ESP-sc-gway.ino 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. // 1-channel LoRa Gateway for ESP8266
  2. // Copyright (c) 2016, 2017, 2018, 2019 Maarten Westenberg
  3. // Version 6.1.5
  4. // Date: 2019-12-20
  5. // Author: Maarten Westenberg (mw12554@hotmail.com)
  6. //
  7. // Based on work done by Thomas Telkamp for Raspberry PI 1-ch gateway and many others.
  8. //
  9. // All rights reserved. This program and the accompanying materials
  10. // are made available under the terms of the MIT License
  11. // which accompanies this distribution, and is available at
  12. // https://opensource.org/licenses/mit-license.php
  13. //
  14. // NO WARRANTY OF ANY KIND IS PROVIDED
  15. //
  16. // The protocols and specifications used for this 1ch gateway:
  17. // 1. LoRA Specification version V1.0 and V1.1 for Gateway-Node communication
  18. //
  19. // 2. Semtech Basic communication protocol between Lora gateway and server version 3.0.0
  20. // https://github.com/Lora-net/packet_forwarder/blob/master/PROTOCOL.TXT
  21. //
  22. // Notes:
  23. // - Once call hostbyname() to get IP for services, after that only use IP
  24. // addresses (too many gethost name makes the ESP unstable)
  25. // - Only call yield() in main stream (not for background NTP sync).
  26. //
  27. // ----------------------------------------------------------------------------------------
  28. // The followion file contains most of the definitions
  29. // used in other files. It should be the first file.
  30. #include "configGway.h" // This file contains configuration of GWay
  31. #include "configNode.h" // Contains the AVG data of Wifi etc.
  32. #if defined (ARDUINO_ARCH_ESP32) || defined(ESP32)
  33. #define ESP32_ARCH 1
  34. #endif
  35. #include <Esp.h> // ESP8266 specific IDE functions
  36. #include <string.h>
  37. #include <stdio.h>
  38. #include <sys/types.h>
  39. #include <unistd.h>
  40. #include <fcntl.h>
  41. #include <cstdlib>
  42. #include <sys/time.h>
  43. #include <cstring>
  44. #include <string> // C++ specific string functions
  45. #include <SPI.h> // For the RFM95 bus
  46. #include <TimeLib.h> // http://playground.arduino.cc/code/time
  47. #include <DNSServer.h> // Local DNSserver
  48. #include <ArduinoJson.h>
  49. #include <FS.h> // ESP8266 Specific
  50. #include <WiFiUdp.h>
  51. #include <pins_arduino.h>
  52. #include <gBase64.h> // https://github.com/adamvr/arduino-base64 (changed the name)
  53. // Local include files
  54. #include "loraModem.h"
  55. #include "loraFiles.h"
  56. #include "oLED.h"
  57. extern "C" {
  58. #include "lwip/err.h"
  59. #include "lwip/dns.h"
  60. }
  61. #if _WIFIMANAGER==1
  62. #include <WiFiManager.h> // Library for ESP WiFi config through an AP
  63. #endif
  64. #if (GATEWAYNODE==1) || (_LOCALSERVER==1)
  65. #include "AES-128_V10.h"
  66. #endif
  67. // ----------- Specific ESP32 stuff --------------
  68. #if ESP32_ARCH==1 // IF ESP32
  69. #include "WiFi.h"
  70. #include <ESPmDNS.h>
  71. #include <SPIFFS.h>
  72. #if A_SERVER==1
  73. #include <ESP32WebServer.h> // Dedicated Webserver for ESP32
  74. #include <Streaming.h> // http://arduiniana.org/libraries/streaming/
  75. #endif
  76. #if A_OTA==1
  77. #include <ESP32httpUpdate.h> // Not yet available
  78. #include <ArduinoOTA.h>
  79. #endif//OTA
  80. // ----------- Specific ESP8266 stuff --------------
  81. #else
  82. #include <ESP8266WiFi.h> // Which is specific for ESP8266
  83. #include <ESP8266mDNS.h>
  84. extern "C" {
  85. #include "user_interface.h"
  86. #include "c_types.h"
  87. }
  88. #if A_SERVER==1
  89. #include <ESP8266WebServer.h>
  90. #include <Streaming.h> // http://arduiniana.org/libraries/streaming/
  91. #endif //A_SERVER
  92. #if A_OTA==1
  93. #include <ESP8266httpUpdate.h>
  94. #include <ArduinoOTA.h>
  95. #endif//OTA
  96. #endif//ESP_ARCH
  97. // ----------- Declaration of vars --------------
  98. uint8_t debug=1; // Debug level! 0 is no msgs, 1 normal, 2 extensive
  99. uint8_t pdebug=0xFF; // Allow all patterns for debugging
  100. #if GATEWAYNODE==1
  101. #if _GPS==1
  102. #include <TinyGPS++.h>
  103. TinyGPSPlus gps;
  104. HardwareSerial sGps(1);
  105. #endif //_GPS
  106. #endif //GATEWAYNODE
  107. // You can switch webserver off if not necessary but probably better to leave it in.
  108. #if A_SERVER==1
  109. #if ESP32_ARCH==1
  110. ESP32WebServer server(A_SERVERPORT);
  111. #else
  112. ESP8266WebServer server(A_SERVERPORT);
  113. #endif
  114. #endif
  115. using namespace std;
  116. byte currentMode = 0x81;
  117. bool sx1272 = true; // Actually we use sx1276/RFM95
  118. uint8_t ifreq = 0; // Channel Index
  119. //unsigned long freq = 0;
  120. uint8_t MAC_array[6];
  121. // ----------------------------------------------------------------------------
  122. //
  123. // Configure these values only if necessary!
  124. //
  125. // ----------------------------------------------------------------------------
  126. // Set spreading factor (SF7 - SF12)
  127. sf_t sf = _SPREADING;
  128. sf_t sfi = _SPREADING; // Initial value of SF
  129. // Set location, description and other configuration parameters
  130. // Defined in ESP-sc_gway.h
  131. //
  132. float lat = _LAT; // Configuration specific info...
  133. float lon = _LON;
  134. int alt = _ALT;
  135. char platform[24] = _PLATFORM; // platform definition
  136. char email[40] = _EMAIL; // used for contact email
  137. char description[64]= _DESCRIPTION; // used for free form description
  138. // define servers
  139. IPAddress ntpServer; // IP address of NTP_TIMESERVER
  140. IPAddress ttnServer; // IP Address of thethingsnetwork server
  141. IPAddress thingServer;
  142. WiFiUDP Udp;
  143. time_t startTime = 0; // The time in seconds since 1970 that the server started
  144. // be aware that UTP time has to succeed for meaningful values.
  145. // 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. //uint32_t lastTmst = 0; // Last activity Timer
  152. #if A_SERVER==1
  153. uint32_t wwwtime = 0;
  154. #endif
  155. #if NTP_INTR==0
  156. uint32_t ntptimer = 0;
  157. #endif
  158. #define TX_BUFF_SIZE 1024 // Upstream buffer to send to MQTT
  159. #define RX_BUFF_SIZE 1024 // Downstream received from MQTT
  160. #define STATUS_SIZE 512 // Should(!) be enough based on the static text .. was 1024
  161. #if GATEWAYNODE==1
  162. uint16_t frameCount=0; // We write this to SPIFF file
  163. #endif
  164. // volatile bool inSPI This initial value of mutex is to be free,
  165. // which means that its value is 1 (!)
  166. //
  167. int 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. static void printIP(IPAddress ipa, const char sep, String& response); // _wwwServer.ino
  180. void setupWWW(); // _wwwServer.ino forward
  181. void SerialTime(); // _utils.ino forward
  182. static void mPrint(String txt); // _utils.ino (static void)
  183. int mStat(uint8_t intr, String & response); // _utils.ini
  184. void SerialStat(uint8_t intr); // _utils.ino
  185. void printHexDigit(uint8_t digit); // _utils.ino
  186. int inDecodes(char * id); // _utils.ino
  187. int initMonitor(struct moniLine *monitor); // _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 stateMachine(); // _stateMachine.ino
  197. bool connectUdp(); // _udpSemtech.ino
  198. int readUdp(int packetSize); // _udpSemtech.ino
  199. int sendUdp(IPAddress server, int port, uint8_t *msg, int length); // _udpSemtech.ino
  200. void sendstat(); // _udpSemtech.ino
  201. void pullData(); // _udpSemtech.ino
  202. #if MUTEX==1
  203. // Forward declarations
  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. // DIE is not used actively in the source code apart from resolveHost().
  210. // It is replaced by a Serial.print command so we know that we have a problem
  211. // somewhere.
  212. // There are at least 3 other ways to restart the ESP. Pick one if you want.
  213. // ----------------------------------------------------------------------------
  214. void die(String s)
  215. {
  216. # if _MONITOR>=1
  217. mPrint(s);
  218. # endif
  219. # if _DUSB>=1
  220. Serial.println(s);
  221. if (debug>=2) Serial.flush();
  222. # endif //_DUSB _MONITOR
  223. delay(50);
  224. // system_restart(); // SDK function
  225. // ESP.reset();
  226. abort(); // Within a second
  227. }
  228. // ----------------------------------------------------------------------------
  229. // gway_failed is a function called by ASSERT in configGway.h
  230. //
  231. // ----------------------------------------------------------------------------
  232. void gway_failed(const char *file, uint16_t line) {
  233. #if _DUSB>=1 || _MONITOR>=1
  234. String response="";
  235. response += "Program failed in file: ";
  236. response += String(file);
  237. response += ", line: ";
  238. response += String(line);
  239. mPrint(response);
  240. #endif //_DUSB||_MONITOR
  241. }
  242. // ----------------------------------------------------------------------------
  243. // Convert a float to string for printing
  244. // Parameters:
  245. // f is float value to convert
  246. // p is precision in decimal digits
  247. // val is character array for results
  248. // ----------------------------------------------------------------------------
  249. void ftoa(float f, char *val, int p) {
  250. int j=1;
  251. int ival, fval;
  252. char b[7] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  253. for (int i=0; i< p; i++) { j= j*10; }
  254. ival = (int) f; // Make integer part
  255. fval = (int) ((f- ival)*j); // Make fraction. Has same sign as integer part
  256. if (fval<0) fval = -fval; // So if it is negative make fraction positive again.
  257. // sprintf does NOT fit in memory
  258. if ((f<0) && (ival == 0)) strcat(val, "-");
  259. strcat(val,itoa(ival,b,10)); // Copy integer part first, base 10, null terminated
  260. strcat(val,"."); // Copy decimal point
  261. itoa(fval,b,10); // Copy fraction part base 10
  262. for (int i=0; i<(p-strlen(b)); i++) {
  263. strcat(val,"0"); // first number of 0 of faction?
  264. }
  265. // Fraction can be anything from 0 to 10^p , so can have less digits
  266. strcat(val,b);
  267. }
  268. // ============================================================================
  269. // NTP TIME functions
  270. // ----------------------------------------------------------------------------
  271. // Send the request packet to the NTP server.
  272. //
  273. // ----------------------------------------------------------------------------
  274. int sendNtpRequest(IPAddress timeServerIP) {
  275. const int NTP_PACKET_SIZE = 48; // Fixed size of NTP record
  276. byte packetBuffer[NTP_PACKET_SIZE];
  277. memset(packetBuffer, 0, NTP_PACKET_SIZE); // Zero the buffer.
  278. packetBuffer[0] = 0b11100011; // LI, Version, Mode
  279. packetBuffer[1] = 0; // Stratum, or type of clock
  280. packetBuffer[2] = 6; // Polling Interval
  281. packetBuffer[3] = 0xEC; // Peer Clock Precision
  282. // 8 bytes of zero for Root Delay & Root Dispersion
  283. packetBuffer[12] = 49;
  284. packetBuffer[13] = 0x4E;
  285. packetBuffer[14] = 49;
  286. packetBuffer[15] = 52;
  287. if (!sendUdp( (IPAddress) timeServerIP, (int) 123, packetBuffer, NTP_PACKET_SIZE)) {
  288. gwayConfig.ntpErr++;
  289. gwayConfig.ntpErrTime = now();
  290. return(0);
  291. }
  292. return(1);
  293. }
  294. // ----------------------------------------------------------------------------
  295. // Get the NTP time from one of the time servers
  296. // Note: As this function is called from SyncINterval in the background
  297. // make sure we have no blocking calls in this function
  298. // ----------------------------------------------------------------------------
  299. time_t getNtpTime()
  300. {
  301. gwayConfig.ntps++;
  302. if (!sendNtpRequest(ntpServer)) // Send the request for new time
  303. {
  304. if (pdebug & P_MAIN) {
  305. mPrint("M sendNtpRequest failed");
  306. }
  307. return(0);
  308. }
  309. const int NTP_PACKET_SIZE = 48; // Fixed size of NTP record
  310. byte packetBuffer[NTP_PACKET_SIZE];
  311. memset(packetBuffer, 0, NTP_PACKET_SIZE); // Set buffer cntents to zero
  312. uint32_t beginWait = millis();
  313. delay(10);
  314. while (millis() - beginWait < 1500)
  315. {
  316. int size = Udp.parsePacket();
  317. if ( size >= NTP_PACKET_SIZE ) {
  318. if (Udp.read(packetBuffer, NTP_PACKET_SIZE) < NTP_PACKET_SIZE) {
  319. break;
  320. }
  321. else {
  322. // Extract seconds portion.
  323. unsigned long secs;
  324. secs = packetBuffer[40] << 24;
  325. secs |= packetBuffer[41] << 16;
  326. secs |= packetBuffer[42] << 8;
  327. secs |= packetBuffer[43];
  328. // UTC is 1 TimeZone correction when no daylight saving time
  329. return(secs - 2208988800UL + NTP_TIMEZONES * SECS_IN_HOUR);
  330. }
  331. Udp.flush();
  332. }
  333. delay(100); // Wait 100 millisecs, allow kernel to act when necessary
  334. }
  335. Udp.flush();
  336. // If we are here, we could not read the time from internet
  337. // So increase the counter
  338. gwayConfig.ntpErr++;
  339. gwayConfig.ntpErrTime = now();
  340. # if _MONITOR>=1
  341. if (pdebug & P_MAIN) {
  342. mPrint("getNtpTime:: read failed");
  343. }
  344. # endif //_MONITOR
  345. return(0); // return 0 if unable to get the time
  346. }
  347. // ----------------------------------------------------------------------------
  348. // Set up regular synchronization of NTP server and the local time.
  349. // ----------------------------------------------------------------------------
  350. #if NTP_INTR==1
  351. void setupTime() {
  352. setSyncProvider(getNtpTime);
  353. setSyncInterval(_NTP_INTERVAL);
  354. }
  355. #endif
  356. // ============================================================================
  357. // MAIN PROGRAM CODE (SETUP AND LOOP)
  358. // ----------------------------------------------------------------------------
  359. // Setup code (one time)
  360. // _state is S_INIT
  361. // ----------------------------------------------------------------------------
  362. void setup() {
  363. char MAC_char[19]; // XXX Unbelievable
  364. MAC_char[18] = 0;
  365. # if _DUSB>=1
  366. Serial.begin(_BAUDRATE); // As fast as possible for bus
  367. # endif
  368. delay(500);
  369. #if _MONITOR>=1
  370. initMonitor(monitor);
  371. #endif
  372. #if _GPS==1
  373. // Pins are define in LoRaModem.h together with other pins
  374. sGps.begin(9600, SERIAL_8N1, GPS_TX, GPS_RX);// PIN 12-TX 15-RX
  375. #endif //_GPS
  376. #ifdef ESP32
  377. # if _MONITOR>=1
  378. mPrint("ESP32 defined, freq=" + String(freqs[0].upFreq));
  379. # endif //_MONITOR
  380. #endif //ESP32
  381. #ifdef ARDUINO_ARCH_ESP32
  382. # if _MONITOR>=1
  383. mPrint("ARDUINO_ARCH_ESP32 defined");
  384. # endif //_MONITOR
  385. #endif //ARDUINO_ARCH_ESP32
  386. # if _DUSB>=1
  387. Serial.flush();
  388. # endif //_DUSB
  389. delay(500);
  390. if (SPIFFS.begin()) {
  391. # if _MONITOR>=1
  392. mPrint("SPIFFS init success");
  393. # endif //_MONITOR
  394. }
  395. else {
  396. if (pdebug & P_MAIN) {
  397. mPrint("SPIFFS not found");
  398. }
  399. }
  400. # if _SPIFF_FORMAT>=1
  401. SPIFFS.format(); // Normally disabled. Enable only when SPIFFS corrupt
  402. if ((debug>=1) && (pdebug & P_MAIN)) {
  403. mPrint("Format SPIFFS Filesystem Done");
  404. }
  405. # endif //_SPIFF_FORMAT>=1
  406. delay(500);
  407. // Read the config file for all parameters not set in the setup() or configGway.h file
  408. // This file should be read just after SPIFFS is initializen and before
  409. // other configuration parameters are used.
  410. //
  411. readConfig(CONFIGFILE, &gwayConfig);
  412. readSeen(_SEENFILE, listSeen); // read the seenFile records
  413. # if _MONITOR>=1
  414. mPrint("Assert=");
  415. # if defined CFG_noassert
  416. mPrint("No Asserts");
  417. # else
  418. mPrint("Do Asserts");
  419. # endif //CFG_noassert
  420. # endif //_MONITOR
  421. #if OLED>=1
  422. init_oLED(); // When done display "STARTING" on OLED
  423. #endif //OLED
  424. delay(500);
  425. yield();
  426. WiFi.mode(WIFI_STA);
  427. WiFi.setAutoConnect(true);
  428. //WiFi.begin();
  429. WlanReadWpa(); // Read the last Wifi settings from SPIFFS into memory
  430. WiFi.macAddress(MAC_array);
  431. sprintf(MAC_char,"%02x:%02x:%02x:%02x:%02x:%02x",
  432. MAC_array[0],MAC_array[1],MAC_array[2],MAC_array[3],MAC_array[4],MAC_array[5]);
  433. Serial.print("MAC: ");
  434. Serial.print(MAC_char);
  435. Serial.print(F(", len="));
  436. Serial.println(strlen(MAC_char));
  437. // We start by connecting to a WiFi network, set hostname
  438. char hostname[12];
  439. // Setup WiFi UDP connection. Give it some time and retry x times..
  440. while (WlanConnect(0) <= 0) {
  441. Serial.print(F("Error Wifi network connect "));
  442. Serial.println();
  443. yield();
  444. }
  445. // After there is a WiFi router connection, we can also set the hostname.
  446. #if ESP32_ARCH==1
  447. sprintf(hostname, "%s%02x%02x%02x", "esp32-", MAC_array[3], MAC_array[4], MAC_array[5]);
  448. WiFi.setHostname( hostname );
  449. MDNS.begin(hostname);
  450. #else
  451. sprintf(hostname, "%s%02x%02x%02x", "esp8266-", MAC_array[3], MAC_array[4], MAC_array[5]);
  452. wifi_station_set_hostname( hostname );
  453. #endif //ESP32_ARCH
  454. # if _DUSB>=1
  455. Serial.print(F("Host "));
  456. #if ESP32_ARCH==1
  457. Serial.print(WiFi.getHostname());
  458. #else
  459. Serial.print(wifi_station_get_hostname());
  460. #endif //ESP32_ARCH
  461. Serial.print(F(" WiFi Connected to "));
  462. Serial.print(WiFi.SSID());
  463. Serial.print(F(" on IP="));
  464. Serial.print(WiFi.localIP());
  465. Serial.println();
  466. # endif //_DUSB
  467. delay(500);
  468. // If we are here we are connected to WLAN
  469. #if defined(_UDPROUTER)
  470. // So now test the UDP function
  471. if (!connectUdp()) {
  472. Serial.println(F("Error connectUdp"));
  473. }
  474. #elif defined(_TTNROUTER)
  475. if (!connectTtn()) {
  476. # if _DUSB>=1
  477. Serial.println(F("Error connectTtn"));
  478. # endif //_DUSB
  479. }
  480. #else
  481. # if _MONITOR>=1
  482. mPrint(F("Setup:: ERROR, No UDP or TCP Connection defined"));
  483. # endif //_MONITOR
  484. #endif //_UDPROUTER
  485. delay(200);
  486. // Pins are defined and set in loraModem.h
  487. pinMode(pins.ss, OUTPUT);
  488. pinMode(pins.rst, OUTPUT);
  489. pinMode(pins.dio0, INPUT); // This pin is interrupt
  490. pinMode(pins.dio1, INPUT); // This pin is interrupt
  491. //pinMode(pins.dio2, INPUT); // XXX
  492. // Init the SPI pins
  493. #if ESP32_ARCH==1
  494. SPI.begin(SCK, MISO, MOSI, SS);
  495. #else
  496. SPI.begin();
  497. #endif //ESP32_ARCH==1
  498. delay(500);
  499. // We choose the Gateway ID to be the Ethernet Address of our Gateway card
  500. // display results of getting hardware address
  501. //
  502. # if _DUSB>=1
  503. Serial.print(F("Gateway ID: "));
  504. printHexDigit(MAC_array[0]);
  505. printHexDigit(MAC_array[1]);
  506. printHexDigit(MAC_array[2]);
  507. printHexDigit(0xFF);
  508. printHexDigit(0xFF);
  509. printHexDigit(MAC_array[3]);
  510. printHexDigit(MAC_array[4]);
  511. printHexDigit(MAC_array[5]);
  512. Serial.print(F(", Listening at SF"));
  513. Serial.print(sf);
  514. Serial.print(F(" on "));
  515. Serial.print((double)freqs[ifreq].upFreq/1000000);
  516. Serial.println(" MHz.");
  517. # endif //_DUSB
  518. ntpServer = resolveHost(NTP_TIMESERVER);
  519. # if _MONITOR>=1
  520. if (debug>=1) mPrint("NTP Server found and contacted");
  521. # endif
  522. delay(100);
  523. #ifdef _TTNSERVER
  524. ttnServer = resolveHost(_TTNSERVER); // Use DNS to get server IP
  525. delay(100);
  526. #endif //_TTNSERVER
  527. #ifdef _THINGSERVER
  528. thingServer = resolveHost(_THINGSERVER); // Use DNS to get server IP
  529. delay(100);
  530. #endif //_THINGSERVER
  531. // The Over the Air updates are supported when we have a WiFi connection.
  532. // The NTP time setting does not have to be precise for this function to work.
  533. #if A_OTA==1
  534. setupOta(hostname); // Uses wwwServer
  535. #endif //A_OTA
  536. // Set the NTP Time
  537. // As long as the time has not been set we try to set the time.
  538. #if NTP_INTR==1
  539. setupTime(); // Set NTP time host and interval
  540. #else //NTP_INTR
  541. // If not using the standard libraries, do a manual setting
  542. // of the time. This method works more reliable than the
  543. // interrupt driven method.
  544. //setTime((time_t)getNtpTime());
  545. while (timeStatus() == timeNotSet) {
  546. # if _DUSB>=1 || _MONITOR>=1
  547. if (( debug>=0 ) && ( pdebug & P_MAIN ))
  548. mPrint("setupTime:: Time not set (yet)");
  549. # endif //_DUSB
  550. delay(500);
  551. time_t newTime;
  552. newTime = (time_t)getNtpTime();
  553. if (newTime != 0) setTime(newTime);
  554. }
  555. // When we are here we succeeded in getting the time
  556. startTime = now(); // Time in seconds
  557. # if _DUSB>=1
  558. Serial.print("writeGwayCfg: "); printTime();
  559. Serial.println();
  560. #endif //_DUSB
  561. writeGwayCfg(CONFIGFILE );
  562. #endif //NTP_INTR
  563. #if A_SERVER==1
  564. // Setup the webserver
  565. setupWWW();
  566. #endif //A_SERVER
  567. delay(100); // Wait after setup
  568. // Setup and initialise LoRa state machine of _loraModem.ino
  569. _state = S_INIT;
  570. initLoraModem();
  571. if (_cad) {
  572. _state = S_SCAN;
  573. sf = SF7;
  574. cadScanner(); // Always start at SF7
  575. }
  576. else {
  577. _state = S_RX;
  578. rxLoraModem();
  579. }
  580. LoraUp.payLoad[0]= 0;
  581. LoraUp.payLength = 0; // Init the length to 0
  582. // init interrupt handlers, which are shared for GPIO15 / D8,
  583. // we switch on HIGH interrupts
  584. if (pins.dio0 == pins.dio1) {
  585. //SPI.usingInterrupt(digitalPinToInterrupt(pins.dio0));
  586. attachInterrupt(pins.dio0, Interrupt_0, RISING); // Share interrupts
  587. }
  588. // Or in the traditional Comresult case
  589. else {
  590. //SPI.usingInterrupt(digitalPinToInterrupt(pins.dio0));
  591. //SPI.usingInterrupt(digitalPinToInterrupt(pins.dio1));
  592. attachInterrupt(pins.dio0, Interrupt_0, RISING); // Separate interrupts
  593. attachInterrupt(pins.dio1, Interrupt_1, RISING); // Separate interrupts
  594. }
  595. writeConfig(CONFIGFILE, &gwayConfig); // Write config
  596. writeSeen( _SEENFILE, listSeen); // Write the last time record is seen
  597. // activate OLED display
  598. #if OLED>=1
  599. acti_oLED();
  600. addr_oLED();
  601. #endif //OLED
  602. # if _DUSB>=1
  603. Serial.println(F("--------------------------------------"));
  604. # endif //_DUSB
  605. mPrint("Setup() ended, Starting loop()");
  606. }//setup
  607. // ----------------------------------------------------------------------------
  608. // LOOP
  609. // This is the main program that is executed time and time again.
  610. // We need to give way to the backend WiFi processing that
  611. // takes place somewhere in the ESP8266 firmware and therefore
  612. // we include yield() statements at important points.
  613. //
  614. // Note: If we spend too much time in user processing functions
  615. // and the backend system cannot do its housekeeping, the watchdog
  616. // function will be executed which means effectively that the
  617. // program crashes.
  618. // We use yield() a lot to avoid ANY watch dog activity of the program.
  619. //
  620. // NOTE2: For ESP make sure not to do large array declarations in loop();
  621. // ----------------------------------------------------------------------------
  622. void loop ()
  623. {
  624. uint32_t uSeconds; // micro seconds
  625. int packetSize;
  626. uint32_t nowSeconds = now();
  627. // check for event value, which means that an interrupt has arrived.
  628. // In this case we handle the interrupt ( e.g. message received)
  629. // in userspace in loop().
  630. //
  631. stateMachine(); // do the state machine
  632. // After a quiet period, make sure we reinit the modem and state machine.
  633. // The interval is in seconds (about 15 seconds) as this re-init
  634. // is a heavy operation.
  635. // So it will kick in if there are not many messages for the gateway.
  636. // Note: Be careful that it does not happen too often in normal operation.
  637. //
  638. if ( ((nowSeconds - statr[0].tmst) > _MSG_INTERVAL ) &&
  639. (msgTime <= statr[0].tmst) )
  640. {
  641. # if _MONITOR>=1
  642. if (( debug>=2 ) && ( pdebug & P_MAIN )) {
  643. String response="";
  644. response += "REINIT:: ";
  645. response += String( _MSG_INTERVAL );
  646. response += (" ");
  647. mStat(0, response);
  648. mPrint(response);
  649. }
  650. # endif //_MONITOR
  651. yield(); // Allow buffer operations to finish
  652. if ((_cad) || (_hop)) {
  653. _state = S_SCAN;
  654. sf = SF7;
  655. cadScanner();
  656. }
  657. else {
  658. _state = S_RX;
  659. rxLoraModem();
  660. }
  661. writeRegister(REG_IRQ_FLAGS_MASK, (uint8_t) 0x00);
  662. writeRegister(REG_IRQ_FLAGS, (uint8_t) 0xFF); // Reset all interrupt flags
  663. msgTime = nowSeconds;
  664. }
  665. #if A_SERVER==1
  666. // Handle the Web server part of this sketch. Mainly used for administration
  667. // and monitoring of the node. This function is important so it is called at the
  668. // start of the loop() function.
  669. yield();
  670. server.handleClient();
  671. #endif //A_SERVER
  672. #if A_OTA==1
  673. // Perform Over the Air (OTA) update if enabled and requested by user.
  674. // It is important to put this function early in loop() as it is
  675. // not called frequently but it should always run when called.
  676. //
  677. yield();
  678. ArduinoOTA.handle();
  679. #endif //A_OTA
  680. // If event is set, we know that we have a (soft) interrupt.
  681. // After all necessary web/OTA services are scanned, we will
  682. // reloop here for timing purposes.
  683. // Do as less yield() as possible.
  684. // XXX 180326
  685. if (_event == 1) {
  686. return;
  687. }
  688. else yield();
  689. // If we are not connected, try to connect.
  690. // We will not read Udp in this loop cycle then
  691. if (WlanConnect(1) < 0) {
  692. # if _DUSB>=1 || _MONITOR>=1
  693. if (( debug >= 0 ) && ( pdebug & P_MAIN )) {
  694. mPrint("M ERROR reconnect WLAN");
  695. }
  696. # endif //_DUSB || _MONITOR
  697. yield();
  698. return; // Exit loop if no WLAN connected
  699. }
  700. // So if we are connected
  701. // Receive UDP PUSH_ACK messages from server. (*2, par. 3.3)
  702. // This is important since the TTN broker will return confirmation
  703. // messages on UDP for every message sent by the gateway. So we have to consume them.
  704. // As we do not know when the server will respond, we test in every loop.
  705. //
  706. else {
  707. while( (packetSize = Udp.parsePacket()) > 0) {
  708. # if _MONITOR>=1
  709. if (debug>=2) {
  710. mPrint("loop:: readUdp calling");
  711. }
  712. # endif //_MONITOR
  713. // DOWNSTREAM
  714. // Packet may be PKT_PUSH_ACK (0x01), PKT_PULL_ACK (0x03) or PKT_PULL_RESP (0x04)
  715. // This command is found in byte 4 (buffer[3])
  716. if (readUdp(packetSize) <= 0) {
  717. #if _MONITOR>=1
  718. if ( debug>=0 )
  719. mPrint("readUdp ERROR, retuning <=0");
  720. # endif //_MONITOR
  721. break;
  722. }
  723. // Now we know we succesfully received message from host
  724. else {
  725. //_event=1; // Could be done double if more messages received
  726. }
  727. }
  728. }
  729. yield(); // on 26/12/2017
  730. // stat PUSH_DATA message (*2, par. 4)
  731. //
  732. if ((nowSeconds - statTime) >= _STAT_INTERVAL) { // Wake up every xx seconds
  733. sendstat(); // Show the status message and send to server
  734. # if _MONITOR>=1
  735. if (( debug>=1 ) && ( pdebug & P_MAIN )) {
  736. mPrint("Send sendstat");
  737. }
  738. # endif //_MONITOR
  739. // If the gateway behaves like a node, we do from time to time
  740. // send a node message to the backend server.
  741. // The Gateway node emessage has nothing to do with the STAT_INTERVAL
  742. // message but we schedule it in the same frequency.
  743. //
  744. #if GATEWAYNODE==1
  745. if (gwayConfig.isNode) {
  746. // Give way to internal some Admin if necessary
  747. yield();
  748. // If the 1ch gateway is a sensor itself, send the sensor values
  749. // could be battery but also other status info or sensor info
  750. if (sensorPacket() < 0) {
  751. # if _MONITOR>=1
  752. if ((debug>=1) || (pdebug & P_MAIN)) {
  753. mPrint("sensorPacket: Error");
  754. }
  755. # endif// _MONITOR
  756. }
  757. }
  758. #endif//GATEWAYNODE
  759. statTime = nowSeconds;
  760. }
  761. yield();
  762. // send PULL_DATA message (*2, par. 4)
  763. //
  764. nowSeconds = now();
  765. if ((nowSeconds - pulltime) >= _PULL_INTERVAL) { // Wake up every xx seconds
  766. # if _DUSB>=1 || _MONITOR>=1
  767. if (( debug>=2) && ( pdebug & P_MAIN )) {
  768. mPrint("M PULL");
  769. }
  770. # endif//_DUSB _MONITOR
  771. pullData(); // Send PULL_DATA message to server
  772. startReceiver();
  773. pulltime = nowSeconds;
  774. }
  775. // If we do our own NTP handling (advisable)
  776. // We do not use the timer interrupt but use the timing
  777. // of the loop() itself which is better for SPI
  778. #if NTP_INTR==0
  779. // Set the time in a manual way. Do not use setSyncProvider
  780. // as this function may collide with SPI and other interrupts
  781. yield(); // 26/12/2017
  782. nowSeconds = now();
  783. if (nowSeconds - ntptimer >= _NTP_INTERVAL) {
  784. yield();
  785. time_t newTime;
  786. newTime = (time_t)getNtpTime();
  787. if (newTime != 0) setTime(newTime);
  788. ntptimer = nowSeconds;
  789. }
  790. #endif//NTP_INTR
  791. }//loop