ESP-sc-gway.ino 25 KB

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