ESP-sc-gway.ino 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. // 1-channel LoRa Gateway for ESP8266
  2. // Copyright (c) 2016-2020 Maarten Westenberg
  3. // Author: Maarten Westenberg (mw12554@hotmail.com)
  4. //
  5. // Based on work done by Thomas Telkamp for Raspberry PI 1-ch gateway and many others.
  6. //
  7. // All rights reserved. This program and the accompanying materials
  8. // are made available under the terms of the MIT License
  9. // which accompanies this distribution, and is available at
  10. // https://opensource.org/licenses/mit-license.php
  11. //
  12. // NO WARRANTY OF ANY KIND IS PROVIDED
  13. //
  14. // The protocols and specifications used for this 1ch gateway:
  15. // 1. LoRA Specification version V1.0 and V1.1 for Gateway-Node communication
  16. //
  17. // 2. Semtech Basic communication protocol between Lora gateway and server version 3.0.0
  18. // https://github.com/Lora-net/packet_forwarder/blob/master/PROTOCOL.TXT
  19. //
  20. // Notes:
  21. // - Once call hostbyname() to get IP for services, after that only use IP
  22. // addresses (too many gethost name makes the ESP unstable)
  23. // - Only call yield() in main stream (not for background NTP sync).
  24. //
  25. // ----------------------------------------------------------------------------------------
  26. // The followion file contains most of the definitions
  27. // used in other files. It should be the first file.
  28. #include "configGway.h" // contains the configuration data of GWay
  29. #include "configNode.h" // Contains the personal data of Wifi etc.
  30. #include <Esp.h> // ESP8266 specific IDE functions
  31. #include <string.h>
  32. #include <stdio.h>
  33. #include <sys/types.h>
  34. #include <unistd.h>
  35. #include <fcntl.h>
  36. #include <cstdlib>
  37. #include <sys/time.h>
  38. #include <cstring>
  39. #include <string> // C++ specific string functions
  40. #include <SPI.h> // For the RFM95 bus
  41. #include <TimeLib.h> // http://playground.arduino.cc/code/time
  42. #include <ArduinoJson.h>
  43. #include <FS.h> // ESP8266 Specific
  44. #include <WiFiUdp.h>
  45. #include <pins_arduino.h>
  46. #include <gBase64.h> // https://github.com/adamvr/arduino-base64 (changed the name)
  47. // Local include files
  48. #include "loraModem.h"
  49. #include "loraFiles.h"
  50. #include "oLED.h"
  51. extern "C" {
  52. # include "lwip/err.h"
  53. # include "lwip/dns.h"
  54. }
  55. #if (_GATEWAYNODE==1) || (_LOCALSERVER==1)
  56. # include "AES-128_V10.h"
  57. #endif
  58. // ----------- Specific ESP32 stuff --------------
  59. #if defined (ARDUINO_ARCH_ESP32) || defined(ESP32)
  60. # define ESP32_ARCH 1
  61. //# include <esp_wifi.h>
  62. //# include <WiFi.h>
  63. # include <ESPmDNS.h>
  64. # include <SPIFFS.h>
  65. # if _WIFIMANAGER==1
  66. # define ESP_getChipId() ((uint32_t)ESP.getEfuseMac())
  67. # include <ESP_WiFiManager.h> // Library for ESP WiFi config through an AP
  68. //# include <WebServer.h>
  69. //# include <HttpClient.h>
  70. # endif //_WIFIMANAGER
  71. # if A_SERVER==1
  72. # include <ESP32WebServer.h> // Dedicated Webserver for ESP32
  73. # include <Streaming.h> // http://arduiniana.org/libraries/streaming/
  74. ESP32WebServer server(A_SERVERPORT);
  75. # endif //A_SERVER
  76. # if A_OTA==1
  77. # include <ESP32httpUpdate.h> // Not yet available
  78. # include <ArduinoOTA.h>
  79. # endif //A_OTA
  80. // ----------- Specific ESP8266 stuff --------------
  81. #elif defined(ARDUINO_ARCH_ESP8266)
  82. extern "C" {
  83. # include "user_interface.h"
  84. # include "c_types.h"
  85. }
  86. # include <ESP8266WiFi.h> // Which is specific for ESP8266
  87. # include <ESP8266mDNS.h>
  88. # if A_SERVER==1
  89. # include <ESP8266WebServer.h>
  90. # include <Streaming.h> // http://arduiniana.org/libraries/streaming/
  91. ESP8266WebServer server(A_SERVERPORT);
  92. # endif //A_SERVER
  93. # if A_OTA==1
  94. # include <ESP8266httpUpdate.h>
  95. # include <ArduinoOTA.h>
  96. # endif //A_OTA
  97. # if _WIFIMANAGER==1
  98. # include <ESP_WiFiManager.h> // Library for ESP WiFi config through an AP
  99. # define ESP_getChipId() (ESP.getChipId())
  100. # endif //_WIFIMANAGER
  101. #else
  102. # error "Architecture not supported"
  103. #endif //ESP_ARCH
  104. #include <DNSServer.h> // Local DNSserver
  105. // ----------- Declaration of variables --------------
  106. uint8_t debug=1; // Debug level! 0 is no msgs, 1 normal, 2 extensive
  107. uint8_t pdebug= P_MAIN | P_GUI; // Initially only MAIN and GUI
  108. #if _GATEWAYNODE==1
  109. # if _GPS==1
  110. # include <TinyGPS++.h>
  111. TinyGPSPlus gps;
  112. HardwareSerial sGps(1);
  113. # endif //_GPS
  114. #endif //_GATEWAYNODE
  115. using namespace std;
  116. byte currentMode = 0x81;
  117. bool sx1272 = true; // Actually we use sx1276/RFM95
  118. uint8_t MAC_array[6];
  119. // ----------------------------------------------------------------------------
  120. //
  121. // Configure these values only if necessary!
  122. //
  123. // ----------------------------------------------------------------------------
  124. // Set spreading factor (SF7 - SF12)
  125. sf_t sf = _SPREADING;
  126. sf_t sfi = _SPREADING; // Initial value of SF
  127. // Set location, description and other configuration parameters
  128. // Defined in ESP-sc_gway.h
  129. //
  130. float lat = _LAT; // Configuration specific info...
  131. float lon = _LON;
  132. int alt = _ALT;
  133. char platform[24] = _PLATFORM; // platform definition
  134. char email[40] = _EMAIL; // used for contact email
  135. char description[64]= _DESCRIPTION; // used for free form description
  136. // define servers
  137. IPAddress ntpServer; // IP address of NTP_TIMESERVER
  138. IPAddress ttnServer; // IP Address of thethingsnetwork server
  139. IPAddress thingServer; // Only if we use a second (backup) server
  140. WiFiUDP Udp;
  141. time_t startTime = 0; // The time in seconds since 1970 that the server started. We use this variable since millis() is reset every 50 days...
  142. uint32_t eventTime = 0; // Timing of _event to change value (or not).
  143. uint32_t sendTime = 0; // Time that the last message transmitted
  144. uint32_t doneTime = 0; // Time to expire when CDDONE takes too long
  145. uint32_t statTime = 0; // last time we sent a stat message to server
  146. uint32_t pullTime = 0; // last time we sent a pull_data request to server
  147. #define TX_BUFF_SIZE 1024 // Upstream buffer to send to MQTT
  148. #define RX_BUFF_SIZE 1024 // Downstream received from MQTT
  149. #define STATUS_SIZE 512 // Should(!) be enough based on the static text .. was 1024
  150. #if A_SERVER==1
  151. uint32_t wwwtime = 0;
  152. #endif
  153. #if NTP_INTR==0
  154. uint32_t ntptimer = 0;
  155. #endif
  156. #if _GATEWAYNODE==1
  157. uint16_t frameCount=0; // We write this to SPIFF file
  158. #endif
  159. // Init the indexes of the data we display on the webpage
  160. // We use this for circular buffers
  161. uint16_t iMoni=0;
  162. uint16_t iSeen=0;
  163. uint16_t iSens=0;
  164. // volatile bool inSPI This initial value of mutex is to be free,
  165. // which means that its value is 1 (!)
  166. //
  167. int16_t mutexSPI = 1;
  168. // ----------------------------------------------------------------------------
  169. // FORWARD DECLARATIONS
  170. // These forward declarations are done since other .ino fils are linked by the
  171. // compiler/linker AFTER the main ESP-sc-gway.ino file.
  172. // And espcecially when calling functions with ICACHE_RAM_ATTR the complier
  173. // does not want this.
  174. // Solution can also be to specify less STRICT compile options in Makefile
  175. // ----------------------------------------------------------------------------
  176. void ICACHE_RAM_ATTR Interrupt_0();
  177. void ICACHE_RAM_ATTR Interrupt_1();
  178. int sendPacket(uint8_t *buf, uint8_t length); // _txRx.ino forward
  179. void printIP(IPAddress ipa, const char sep, String & response); // _wwwServer.ino
  180. void setupWWW(); // _wwwServer.ino forward
  181. void mPrint(String txt); // _utils.ino
  182. int getNtpTime(time_t *t); // _utils.ino
  183. int mStat(uint8_t intr, String & response); // _utils.ini
  184. void SerialStat(uint8_t intr); // _utils.ino
  185. void printHexDigit(uint8_t digit, String & response); // _utils.ino
  186. int inDecodes(char * id); // _utils.ino
  187. static void stringTime(time_t t, String & response); // _urils.ino
  188. int initMonitor(struct moniLine *monitor); // _loraFiles.ino
  189. int initConfig(struct espGwayConfig *c); // _loraFiles.ino
  190. int writeSeen(const char *fn, struct nodeSeen *listSeen); // _loraFiles.ino
  191. int readGwayCfg(const char *fn, struct espGwayConfig *c); // _loraFiles.ino
  192. void init_oLED(); // _oLED.ino
  193. void acti_oLED(); // _oLED.ino
  194. void addr_oLED(); // _oLED.ino
  195. void setupOta(char *hostname); // _otaServer.ino
  196. void initLoraModem(); // _loraModem.ino
  197. void rxLoraModem(); // _loraModem.ino
  198. void writeRegister(uint8_t addr, uint8_t value); // _loraModem.ino
  199. void cadScanner(); // _loraModem.ino
  200. void startReceiver(); // _loraModem.ino
  201. void stateMachine(); // _stateMachine.ino
  202. bool connectUdp(); // _udpSemtech.ino
  203. int readUdp(int packetSize); // _udpSemtech.ino
  204. int sendUdp(IPAddress server, int port, uint8_t *msg, int length); // _udpSemtech.ino
  205. void sendstat(); // _udpSemtech.ino
  206. void pullData(); // _udpSemtech.ino
  207. #if _MUTEX==1
  208. void ICACHE_FLASH_ATTR CreateMutux(int *mutex);
  209. bool ICACHE_FLASH_ATTR GetMutex(int *mutex);
  210. void ICACHE_FLASH_ATTR ReleaseMutex(int *mutex);
  211. #endif
  212. // ============================================================================
  213. // MAIN PROGRAM CODE (SETUP AND LOOP)
  214. // ----------------------------------------------------------------------------
  215. // Setup code (one time)
  216. // _state is S_INIT
  217. // ----------------------------------------------------------------------------
  218. void setup() {
  219. char MAC_char[19]; // XXX Unbelievable
  220. MAC_char[18] = 0;
  221. char hostname[12]; // hostname space
  222. # if _DUSB>=1
  223. Serial.begin(_BAUDRATE); // As fast as possible for bus
  224. delay(500);
  225. Serial.flush();
  226. # endif //_DUSB
  227. # if OLED>=1
  228. init_oLED(); // When done display "STARTING" on OLED
  229. # endif //OLED
  230. # if _GPS==1
  231. // Pins are defined in LoRaModem.h together with other pins
  232. sGps.begin(9600, SERIAL_8N1, GPS_TX, GPS_RX); // PIN 12-TX 15-RX
  233. # endif //_GPS
  234. delay(500);
  235. if (SPIFFS.begin()) {
  236. # if _MONITOR>=1
  237. if ((debug>=1) && (pdebug & P_MAIN)) {
  238. mPrint("SPIFFS begin");
  239. }
  240. # endif //_MONITOR
  241. }
  242. else { // SPIFFS not found
  243. if (pdebug & P_MAIN) {
  244. mPrint("SPIFFS.begin: not found, formatting");
  245. }
  246. msg_oLED("FORMAT");
  247. SPIFFS.format();
  248. delay(500);
  249. initConfig(&gwayConfig);
  250. }
  251. // If we set SPIFFS_FORMAT in
  252. # if _SPIFFS_FORMAT>=1
  253. msg_oLED("FORMAT");
  254. SPIFFS.format(); // Normally disabled. Enable only when SPIFFS corrupt
  255. delay(500);
  256. initConfig(&gwayConfig);
  257. if ((debug>=1) && (pdebug & P_MAIN)) {
  258. mPrint("Format SPIFFS Filesystem Done");
  259. }
  260. # endif //_SPIFFS_FORMAT>=1
  261. # if _MONITOR>=1
  262. msg_oLED("MONITOR");
  263. initMonitor(monitor);
  264. # if defined CFG_noassert
  265. mPrint("No Asserts");
  266. # else
  267. mPrint("Do Asserts");
  268. # endif //CFG_noassert
  269. # endif //_MONITOR
  270. delay(500);
  271. // Read the config file for all parameters not set in the setup() or configGway.h file
  272. // This file should be read just after SPIFFS is initializen and before
  273. // other configuration parameters are used.
  274. //
  275. if (readGwayCfg(CONFIGFILE, &gwayConfig) > 0) { // read the Gateway Config
  276. # if _MONITOR>=1
  277. if (debug>=0) {
  278. mPrint("readGwayCfg:: return OK");
  279. }
  280. # endif
  281. }
  282. else {
  283. # if _MONITOR>=1
  284. if (debug>=0) {
  285. mPrint("setup:: readGwayCfg: ERROR readCfgCfg Failed");
  286. }
  287. # endif
  288. };
  289. delay(500);
  290. yield();
  291. # if _WIFIMANAGER==1
  292. msg_oLED("WIFIMGR");
  293. # if MONITOR>=1
  294. mPrint("setup:: WiFiManager");
  295. # endif
  296. delay(500);
  297. wifiMgr();
  298. # endif //_WIFIMANAGER
  299. msg_oLED("WIFI STA");
  300. WiFi.mode(WIFI_STA); // WiFi settings for connections
  301. WiFi.setAutoConnect(true);
  302. WiFi.macAddress(MAC_array);
  303. sprintf(MAC_char,"%02x:%02x:%02x:%02x:%02x:%02x",
  304. MAC_array[0],MAC_array[1],MAC_array[2],MAC_array[3],MAC_array[4],MAC_array[5]);
  305. # if _MONITOR>=1
  306. mPrint("MAC: " + String(MAC_char) + ", len=" + String(strlen(MAC_char)) );
  307. # endif //_MONITOR
  308. // Setup WiFi UDP connection. Give it some time and retry x times. '0' means try forever
  309. while (WlanConnect(0) <= 0) {
  310. # if _MONITOR>=1
  311. if ((debug>=0) && (pdebug & P_MAIN)) {
  312. mPrint("setup:: Error Wifi network connect(0)");
  313. }
  314. # endif //_MONITOR
  315. yield();
  316. }
  317. # if _MONITOR>=1
  318. if ((debug>=1) & ( pdebug & P_MAIN )) {
  319. mPrint("setup:: WlanConnect="+String(WiFi.SSID()) );
  320. }
  321. # endif
  322. // After there is a WiFi router connection, we set the hostname with last 3 bytes of MAC address.
  323. # if defined(ESP32_ARCH)
  324. // ESP32
  325. sprintf(hostname, "%s%02x%02x%02x", "esp32-", MAC_array[3], MAC_array[4], MAC_array[5]);
  326. WiFi.setHostname(hostname);
  327. MDNS.begin(hostname);
  328. # else
  329. //ESP8266
  330. sprintf(hostname, "%s%02x%02x%02x", "esp8266-", MAC_array[3], MAC_array[4], MAC_array[5]);
  331. wifi_station_set_hostname(hostname);
  332. # endif //ESP32_ARCH
  333. # if _MONITOR>=1
  334. if (debug>=0) {
  335. String response = "Host=";
  336. # if defined(ESP32_ARCH)
  337. response += String(WiFi.getHostname());
  338. # else
  339. response += String(wifi_station_get_hostname());
  340. # endif //ESP32_ARCH
  341. response += " WiFi Connected to " + String(WiFi.SSID());
  342. response += " on IP=" + String(WiFi.localIP().toString() );
  343. mPrint(response);
  344. }
  345. # endif //_MONITOR
  346. delay(500);
  347. // If we are here we are connected to WLAN
  348. # if defined(_UDPROUTER)
  349. // So now test the UDP function
  350. if (!connectUdp()) {
  351. # if _MONITOR>=1
  352. mPrint("Error connectUdp");
  353. # endif //_MONITOR
  354. }
  355. # elif defined(_TTNROUTER)
  356. if (!connectTtn()) {
  357. # if _MONITOR>=1
  358. mPrint("Error connectTtn");
  359. # endif //_MONITOR
  360. }
  361. # else
  362. # if _MONITOR>=1
  363. mPrint(F("Setup:: ERROR, No UDP or TCP Connection"));
  364. # endif //_MONITOR
  365. # endif //_UDPROUTER
  366. delay(200);
  367. // Pins are defined and set in loraModem.h
  368. pinMode(pins.ss, OUTPUT);
  369. pinMode(pins.rst, OUTPUT);
  370. pinMode(pins.dio0, INPUT); // This pin is interrupt
  371. pinMode(pins.dio1, INPUT); // This pin is interrupt
  372. //pinMode(pins.dio2, INPUT); // XXX future expansion
  373. // Init the SPI pins
  374. #if defined(ESP32_ARCH)
  375. SPI.begin(SCK, MISO, MOSI, SS);
  376. #else
  377. SPI.begin();
  378. #endif //ESP32_ARCH
  379. delay(500);
  380. // We choose the Gateway ID to be the Ethernet Address of our Gateway card
  381. // display results of getting hardware address
  382. //
  383. # if _MONITOR>=1
  384. if (debug>=0) {
  385. String response= "Gateway ID: ";
  386. printHexDigit(MAC_array[0], response);
  387. printHexDigit(MAC_array[1], response);
  388. printHexDigit(MAC_array[2], response);
  389. printHexDigit(0xFF, response);
  390. printHexDigit(0xFF, response);
  391. printHexDigit(MAC_array[3], response);
  392. printHexDigit(MAC_array[4], response);
  393. printHexDigit(MAC_array[5], response);
  394. response += ", Listening at SF" + String(sf) + " on ";
  395. response += String((double)freqs[gwayConfig.ch].upFreq/1000000) + " MHz.";
  396. mPrint(response);
  397. }
  398. # endif //_MONITOR
  399. // ---------- TIME -------------------------------------
  400. msg_lLED("GET TIME",".");
  401. ntpServer = resolveHost(NTP_TIMESERVER, 15);
  402. if (ntpServer.toString() == "0:0:0:0") { // MMM Experimental
  403. # if _MONITOR>=1
  404. mPrint("setup:: NTP Server not found, found="+ntpServer.toString());
  405. # endif
  406. delay(10000); // Delay 10 seconds
  407. ntpServer = resolveHost(NTP_TIMESERVER, 10);
  408. }
  409. // Set the NTP Time
  410. // As long as the time has not been set we try to set the time.
  411. # if NTP_INTR==1
  412. setupTime(); // Set NTP time host and interval
  413. # else //NTP_INTR
  414. {
  415. // If not using the standard libraries, do manual setting
  416. // of the time. This method works more reliable than the
  417. // interrupt driven method.
  418. String response = ".";
  419. while (timeStatus() == timeNotSet) { // time still 1/1/1970 and 0:00 hrs
  420. time_t newTime;
  421. if (getNtpTime(&newTime)<=0) {
  422. # if _MONITOR>=1
  423. if (debug>=0) {
  424. mPrint("setup:: ERROR Time not set (yet). Time="+String(newTime) );
  425. }
  426. # endif //_MONITOR
  427. response += ".";
  428. msg_lLED("GET TIME",response);
  429. delay(800);
  430. continue;
  431. }
  432. response += ".";
  433. msg_lLED("GET TIME",response);
  434. delay(1000);
  435. setTime(newTime);
  436. }
  437. // When we are here we succeeded in getting the time
  438. startTime = now(); // Time in seconds
  439. # if _MONITOR>=1
  440. if (debug>=0) {
  441. String response= "Time set=";
  442. stringTime(now(),response);
  443. mPrint(response);
  444. }
  445. # endif //_MONITOR
  446. writeGwayCfg(CONFIGFILE, &gwayConfig );
  447. }
  448. # endif //NTP_INTR
  449. delay(100);
  450. // ---------- TTN SERVER -------------------------------
  451. #ifdef _TTNSERVER
  452. ttnServer = resolveHost(_TTNSERVER, 10); // Use DNS to get server IP
  453. if (ttnServer.toString() == "0:0:0:0") { // Experimental
  454. # if _MONITOR>=1
  455. if (debug>=1) {
  456. mPrint("setup:: TTN Server not found");
  457. }
  458. # endif
  459. delay(10000); // Delay 10 seconds
  460. ttnServer = resolveHost(_TTNSERVER, 10);
  461. }
  462. delay(100);
  463. #endif //_TTNSERVER
  464. #ifdef _THINGSERVER
  465. thingServer = resolveHost(_THINGSERVER, 10); // Use DNS to get server IP
  466. delay(100);
  467. #endif //_THINGSERVER
  468. // The Over the Air updates are supported when we have a WiFi connection.
  469. // The NTP time setting does not have to be precise for this function to work.
  470. #if A_OTA==1
  471. setupOta(hostname); // Uses wwwServer
  472. #endif //A_OTA
  473. readSeen(_SEENFILE, listSeen); // read the seenFile records
  474. #if A_SERVER==1
  475. // Setup the webserver
  476. setupWWW();
  477. #endif //A_SERVER
  478. delay(100); // Wait after setup
  479. // Setup and initialise LoRa state machine of _loraModem.ino
  480. _state = S_INIT;
  481. initLoraModem();
  482. if (gwayConfig.cad) {
  483. _state = S_SCAN;
  484. sf = SF7;
  485. cadScanner(); // Always start at SF7
  486. }
  487. else {
  488. _state = S_RX;
  489. rxLoraModem();
  490. }
  491. LoraUp.payLoad[0]= 0;
  492. LoraUp.payLength = 0; // Init the length to 0
  493. // init interrupt handlers, which are shared for GPIO15 / D8,
  494. // we switch on HIGH interrupts
  495. if (pins.dio0 == pins.dio1) {
  496. attachInterrupt(pins.dio0, Interrupt_0, RISING); // Share interrupts
  497. }
  498. // Or in the traditional Comresult case
  499. else {
  500. attachInterrupt(pins.dio0, Interrupt_0, RISING); // Separate interrupts
  501. attachInterrupt(pins.dio1, Interrupt_1, RISING); // Separate interrupts
  502. }
  503. writeConfig(CONFIGFILE, &gwayConfig); // Write config
  504. writeSeen(_SEENFILE, listSeen); // Write the last time record is seen
  505. // activate OLED display
  506. # if OLED>=1
  507. acti_oLED();
  508. addr_oLED();
  509. # endif //OLED
  510. mPrint(" --- Setup() ended, Starting loop() ---");
  511. }//setup
  512. // ----------------------------------------------------------------------------
  513. // LOOP
  514. // This is the main program that is executed time and time again.
  515. // We need to give way to the backend WiFi processing that
  516. // takes place somewhere in the ESP8266 firmware and therefore
  517. // we include yield() statements at important points.
  518. //
  519. // Note: If we spend too much time in user processing functions
  520. // and the backend system cannot do its housekeeping, the watchdog
  521. // function will be executed which means effectively that the
  522. // program crashes.
  523. // We use yield() a lot to avoid ANY watch dog activity of the program.
  524. //
  525. // NOTE2: For ESP make sure not to do large array declarations in loop();
  526. // ----------------------------------------------------------------------------
  527. void loop ()
  528. {
  529. uint32_t uSeconds; // micro seconds
  530. int packetSize;
  531. uint32_t nowSeconds = now();
  532. // check for event value, which means that an interrupt has arrived.
  533. // In this case we handle the interrupt ( e.g. message received)
  534. // in userspace in loop().
  535. //
  536. stateMachine(); // do the state machine
  537. // After a quiet period, make sure we reinit the modem and state machine.
  538. // The interval is in seconds (about 15 seconds) as this re-init
  539. // is a heavy operation.
  540. // So it will kick in if there are not many messages for the gateway.
  541. // Note: Be careful that it does not happen too often in normal operation.
  542. //
  543. if ( ((nowSeconds - statr[0].tmst) > _MSG_INTERVAL ) &&
  544. (msgTime <= statr[0].tmst) )
  545. {
  546. # if _MONITOR>=1
  547. if (( debug>=2 ) && ( pdebug & P_MAIN )) {
  548. String response="";
  549. response += "REINIT:: ";
  550. response += String( _MSG_INTERVAL );
  551. response += (" ");
  552. mStat(0, response);
  553. mPrint(response);
  554. }
  555. # endif //_MONITOR
  556. yield(); // Allow buffer operations to finish
  557. if ((gwayConfig.cad) || (gwayConfig.hop)) {
  558. _state = S_SCAN;
  559. sf = SF7;
  560. cadScanner();
  561. }
  562. else {
  563. _state = S_RX;
  564. rxLoraModem();
  565. }
  566. writeRegister(REG_IRQ_FLAGS_MASK, (uint8_t) 0x00);
  567. writeRegister(REG_IRQ_FLAGS, (uint8_t) 0xFF); // Reset all interrupt flags
  568. msgTime = nowSeconds;
  569. }
  570. #if A_SERVER==1
  571. // Handle the Web server part of this sketch. Mainly used for administration
  572. // and monitoring of the node. This function is important so it is called at the
  573. // start of the loop() function.
  574. yield();
  575. server.handleClient();
  576. #endif //A_SERVER
  577. #if A_OTA==1
  578. // Perform Over the Air (OTA) update if enabled and requested by user.
  579. // It is important to put this function early in loop() as it is
  580. // not called frequently but it should always run when called.
  581. //
  582. yield();
  583. ArduinoOTA.handle();
  584. #endif //A_OTA
  585. // If event is set, we know that we have a (soft) interrupt.
  586. // After all necessary web/OTA services are scanned, we will
  587. // reloop here for timing purposes.
  588. // Do as less yield() as possible.
  589. // XXX 180326
  590. if (_event == 1) {
  591. return;
  592. }
  593. else yield();
  594. // If we are not connected, try to connect.
  595. // We will not read Udp in this loop cycle then
  596. if (WlanConnect(1) < 0) {
  597. # if _MONITOR>=1
  598. if (( debug >= 0 ) && ( pdebug & P_MAIN )) {
  599. mPrint("loop:: ERROR reconnect WLAN");
  600. }
  601. # endif //_MONITOR
  602. yield();
  603. return; // Exit loop if no WLAN connected
  604. } //WlanConnect
  605. // So if we are connected
  606. // Receive UDP PUSH_ACK messages from server. (*2, par. 3.3)
  607. // This is important since the TTN broker will return confirmation
  608. // messages on UDP for every message sent by the gateway. So we have to consume them.
  609. // As we do not know when the server will respond, we test in every loop.
  610. //
  611. else {
  612. while( (packetSize = Udp.parsePacket()) > 0) {
  613. # if _MONITOR>=1
  614. if (debug>=2) {
  615. mPrint("loop:: readUdp calling");
  616. }
  617. # endif //_MONITOR
  618. // DOWNSTREAM
  619. // Packet may be PKT_PUSH_ACK (0x01), PKT_PULL_ACK (0x03) or PKT_PULL_RESP (0x04)
  620. // This command is found in byte 4 (buffer[3])
  621. if (readUdp(packetSize) < 0) {
  622. # if _MONITOR>=1
  623. if ( debug>=0 )
  624. mPrint("readUdp ERROR,down returning < 0");
  625. # endif //_MONITOR
  626. break;
  627. }
  628. // Now we know we succesfully received message from host
  629. // If return value is 0, we received a NTP message,
  630. // otherwise a UDP message with other TTN content
  631. else {
  632. //_event=1; // Could be done double if more messages received
  633. }
  634. }
  635. }
  636. yield(); // on 26/12/2017
  637. // stat PUSH_DATA message (*2, par. 4)
  638. //
  639. if ((nowSeconds - statTime) >= _STAT_INTERVAL) { // Wake up every xx seconds
  640. sendstat(); // Show the status message and send to server
  641. # if _MONITOR>=1
  642. if (( debug>=2 ) && ( pdebug & P_MAIN )) {
  643. mPrint("Send Pushdata sendstat");
  644. }
  645. # endif //_MONITOR
  646. // If the gateway behaves like a node, we do from time to time
  647. // send a node message to the backend server.
  648. // The Gateway node emessage has nothing to do with the STAT_INTERVAL
  649. // message but we schedule it in the same frequency.
  650. //
  651. # if _GATEWAYNODE==1
  652. if (gwayConfig.isNode) {
  653. // Give way to internal some Admin if necessary
  654. yield();
  655. // If the 1ch gateway is a sensor itself, send the sensor values
  656. // could be battery but also other status info or sensor info
  657. if (sensorPacket() < 0) {
  658. # if _MONITOR>=1
  659. if ((debug>=1) || (pdebug & P_MAIN)) {
  660. mPrint("sensorPacket: Error");
  661. }
  662. # endif// _MONITOR
  663. }
  664. }
  665. # endif//_GATEWAYNODE
  666. statTime = nowSeconds;
  667. }
  668. yield();
  669. // send PULL_DATA message (*2, par. 4)
  670. //
  671. nowSeconds = now();
  672. if ((nowSeconds - pullTime) >= _PULL_INTERVAL) { // Wake up every xx seconds
  673. pullData(); // Send PULL_DATA message to server
  674. startReceiver();
  675. pullTime = nowSeconds;
  676. # if _MONITOR>=1
  677. if (( debug>=2) && ( pdebug & P_MAIN )) {
  678. mPrint("ESP-sc-gway:: PULL_DATA message sent");
  679. }
  680. # endif //_MONITOR
  681. }
  682. // If we do our own NTP handling (advisable)
  683. // We do not use the timer interrupt but use the timing
  684. // of the loop() itself which is better for SPI
  685. # if NTP_INTR==0
  686. // Set the time in a manual way. Do not use setSyncProvider
  687. // as this function may collide with SPI and other interrupts
  688. // Note: It can be that we do not receive a time this loop (no worries)
  689. yield();
  690. nowSeconds = now();
  691. if (nowSeconds - ntptimer >= _NTP_INTERVAL) {
  692. yield();
  693. time_t newTime;
  694. if (getNtpTime(&newTime)<=0) {
  695. # if _MONITOR>=1
  696. if (debug>=2) {
  697. mPrint("loop:: WARNING Time not set (yet). Time="+String(newTime) );
  698. }
  699. # endif //_MONITOR
  700. }
  701. else {
  702. setTime(newTime);
  703. if (year(now()) != 1970) {
  704. # if _MONITOR>=1
  705. if ((debug>=1) && (pdebug & P_MAIN)) {
  706. ntptimer = nowSeconds; // Do not when year(now())=="1970" beacause of "FORMAT"
  707. }
  708. # endif
  709. }
  710. }
  711. }
  712. # endif//NTP_INTR
  713. }//loop