ESP-sc-gway.ino 24 KB

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