ESP-sc-gway.ino 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  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 gethostbyname() 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 anymore.
  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(const char *s)
  215. {
  216. Serial.println(s);
  217. # if _DUSB>=1 || _MONITOR>=1
  218. if (debug>=2) Serial.flush();
  219. # endif //_DUSB _MONITOR
  220. delay(50);
  221. // system_restart(); // SDK function
  222. // ESP.reset();
  223. abort(); // Within a second
  224. }
  225. // ----------------------------------------------------------------------------
  226. // gway_failed is a function called by ASSERT in configGway.h
  227. //
  228. // ----------------------------------------------------------------------------
  229. void gway_failed(const char *file, uint16_t line) {
  230. #if _DUSB>=1 || _MONITOR>=1
  231. String response="";
  232. response += "Program failed in file: ";
  233. response += String(file);
  234. response += ", line: ";
  235. response += String(line);
  236. mPrint(response);
  237. #endif //_DUSB||_MONITOR
  238. }
  239. // ----------------------------------------------------------------------------
  240. // Convert a float to string for printing
  241. // Parameters:
  242. // f is float value to convert
  243. // p is precision in decimal digits
  244. // val is character array for results
  245. // ----------------------------------------------------------------------------
  246. void ftoa(float f, char *val, int p) {
  247. int j=1;
  248. int ival, fval;
  249. char b[7] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  250. for (int i=0; i< p; i++) { j= j*10; }
  251. ival = (int) f; // Make integer part
  252. fval = (int) ((f- ival)*j); // Make fraction. Has same sign as integer part
  253. if (fval<0) fval = -fval; // So if it is negative make fraction positive again.
  254. // sprintf does NOT fit in memory
  255. if ((f<0) && (ival == 0)) strcat(val, "-");
  256. strcat(val,itoa(ival,b,10)); // Copy integer part first, base 10, null terminated
  257. strcat(val,"."); // Copy decimal point
  258. itoa(fval,b,10); // Copy fraction part base 10
  259. for (int i=0; i<(p-strlen(b)); i++) {
  260. strcat(val,"0"); // first number of 0 of faction?
  261. }
  262. // Fraction can be anything from 0 to 10^p , so can have less digits
  263. strcat(val,b);
  264. }
  265. // ============================================================================
  266. // NTP TIME functions
  267. // ----------------------------------------------------------------------------
  268. // Send the request packet to the NTP server.
  269. //
  270. // ----------------------------------------------------------------------------
  271. int sendNtpRequest(IPAddress timeServerIP) {
  272. const int NTP_PACKET_SIZE = 48; // Fixed size of NTP record
  273. byte packetBuffer[NTP_PACKET_SIZE];
  274. memset(packetBuffer, 0, NTP_PACKET_SIZE); // Zero the buffer.
  275. packetBuffer[0] = 0b11100011; // LI, Version, Mode
  276. packetBuffer[1] = 0; // Stratum, or type of clock
  277. packetBuffer[2] = 6; // Polling Interval
  278. packetBuffer[3] = 0xEC; // Peer Clock Precision
  279. // 8 bytes of zero for Root Delay & Root Dispersion
  280. packetBuffer[12] = 49;
  281. packetBuffer[13] = 0x4E;
  282. packetBuffer[14] = 49;
  283. packetBuffer[15] = 52;
  284. if (!sendUdp( (IPAddress) timeServerIP, (int) 123, packetBuffer, NTP_PACKET_SIZE)) {
  285. gwayConfig.ntpErr++;
  286. gwayConfig.ntpErrTime = now();
  287. return(0);
  288. }
  289. return(1);
  290. }
  291. // ----------------------------------------------------------------------------
  292. // Get the NTP time from one of the time servers
  293. // Note: As this function is called from SyncINterval in the background
  294. // make sure we have no blocking calls in this function
  295. // ----------------------------------------------------------------------------
  296. time_t getNtpTime()
  297. {
  298. gwayConfig.ntps++;
  299. if (!sendNtpRequest(ntpServer)) // Send the request for new time
  300. {
  301. if (pdebug & P_MAIN) {
  302. mPrint("M sendNtpRequest failed");
  303. }
  304. return(0);
  305. }
  306. const int NTP_PACKET_SIZE = 48; // Fixed size of NTP record
  307. byte packetBuffer[NTP_PACKET_SIZE];
  308. memset(packetBuffer, 0, NTP_PACKET_SIZE); // Set buffer cntents to zero
  309. uint32_t beginWait = millis();
  310. delay(10);
  311. while (millis() - beginWait < 1500)
  312. {
  313. int size = Udp.parsePacket();
  314. if ( size >= NTP_PACKET_SIZE ) {
  315. if (Udp.read(packetBuffer, NTP_PACKET_SIZE) < NTP_PACKET_SIZE) {
  316. break;
  317. }
  318. else {
  319. // Extract seconds portion.
  320. unsigned long secs;
  321. secs = packetBuffer[40] << 24;
  322. secs |= packetBuffer[41] << 16;
  323. secs |= packetBuffer[42] << 8;
  324. secs |= packetBuffer[43];
  325. // UTC is 1 TimeZone correction when no daylight saving time
  326. return(secs - 2208988800UL + NTP_TIMEZONES * SECS_IN_HOUR);
  327. }
  328. Udp.flush();
  329. }
  330. delay(100); // Wait 100 millisecs, allow kernel to act when necessary
  331. }
  332. Udp.flush();
  333. // If we are here, we could not read the time from internet
  334. // So increase the counter
  335. gwayConfig.ntpErr++;
  336. gwayConfig.ntpErrTime = now();
  337. # if _MONITOR>=1
  338. if (pdebug & P_MAIN) {
  339. mPrint("getNtpTime:: read failed");
  340. }
  341. # endif //_MONITOR
  342. return(0); // return 0 if unable to get the time
  343. }
  344. // ----------------------------------------------------------------------------
  345. // Set up regular synchronization of NTP server and the local time.
  346. // ----------------------------------------------------------------------------
  347. #if NTP_INTR==1
  348. void setupTime() {
  349. setSyncProvider(getNtpTime);
  350. setSyncInterval(_NTP_INTERVAL);
  351. }
  352. #endif
  353. // ============================================================================
  354. // MAIN PROGRAM CODE (SETUP AND LOOP)
  355. // ----------------------------------------------------------------------------
  356. // Setup code (one time)
  357. // _state is S_INIT
  358. // ----------------------------------------------------------------------------
  359. void setup() {
  360. char MAC_char[19]; // XXX Unbelievable
  361. MAC_char[18] = 0;
  362. # if _DUSB>=1
  363. Serial.begin(_BAUDRATE); // As fast as possible for bus
  364. # endif
  365. delay(500);
  366. #if _MONITOR>=1
  367. initMonitor(monitor);
  368. #endif
  369. #if _GPS==1
  370. // Pins are define in LoRaModem.h together with other pins
  371. sGps.begin(9600, SERIAL_8N1, GPS_TX, GPS_RX);// PIN 12-TX 15-RX
  372. #endif //_GPS
  373. #ifdef ESP32
  374. # if _MONITOR>=1
  375. mPrint("ESP32 defined, freq=" + String(freqs[0].upFreq));
  376. # endif //_MONITOR
  377. #endif //ESP32
  378. #ifdef ARDUINO_ARCH_ESP32
  379. # if _MONITOR>=1
  380. mPrint("ARDUINO_ARCH_ESP32 defined");
  381. # endif //_MONITOR
  382. #endif //ARDUINO_ARCH_ESP32
  383. # if _DUSB>=1
  384. Serial.flush();
  385. # endif //_DUSB
  386. delay(500);
  387. if (SPIFFS.begin()) {
  388. # if _MONITOR>=1
  389. mPrint("SPIFFS init success");
  390. # endif //_MONITOR
  391. }
  392. else {
  393. if (pdebug & P_MAIN) {
  394. mPrint("SPIFFS not found");
  395. }
  396. }
  397. # if _SPIFF_FORMAT>=1
  398. SPIFFS.format(); // Normally disabled. Enable only when SPIFFS corrupt
  399. if ((debug>=1) && (pdebug & P_MAIN)) {
  400. mPrint("Format SPIFFS Filesystem Done");
  401. }
  402. # endif //_SPIFF_FORMAT>=1
  403. delay(500);
  404. // Read the config file for all parameters not set in the setup() or configGway.h file
  405. // This file should be read just after SPIFFS is initializen and before
  406. // other configuration parameters are used.
  407. //
  408. readConfig(CONFIGFILE, &gwayConfig);
  409. readSeen(_SEENFILE, listSeen); // read the seenFile records
  410. # if _MONITOR>=1
  411. mPrint("Assert=");
  412. # if defined CFG_noassert
  413. mPrint("No Asserts");
  414. # else
  415. mPrint("Do Asserts");
  416. # endif //CFG_noassert
  417. # endif //_MONITOR
  418. #if OLED>=1
  419. init_oLED(); // When done display "STARTING" on OLED
  420. #endif //OLED
  421. delay(500);
  422. yield();
  423. WiFi.mode(WIFI_STA);
  424. WiFi.setAutoConnect(true);
  425. //WiFi.begin();
  426. WlanReadWpa(); // Read the last Wifi settings from SPIFFS into memory
  427. WiFi.macAddress(MAC_array);
  428. sprintf(MAC_char,"%02x:%02x:%02x:%02x:%02x:%02x",
  429. MAC_array[0],MAC_array[1],MAC_array[2],MAC_array[3],MAC_array[4],MAC_array[5]);
  430. Serial.print("MAC: ");
  431. Serial.print(MAC_char);
  432. Serial.print(F(", len="));
  433. Serial.println(strlen(MAC_char));
  434. // We start by connecting to a WiFi network, set hostname
  435. char hostname[12];
  436. // Setup WiFi UDP connection. Give it some time and retry x times..
  437. while (WlanConnect(0) <= 0) {
  438. Serial.print(F("Error Wifi network connect "));
  439. Serial.println();
  440. yield();
  441. }
  442. // After there is a WiFi router connection, we can also set the hostname.
  443. #if ESP32_ARCH==1
  444. sprintf(hostname, "%s%02x%02x%02x", "esp32-", MAC_array[3], MAC_array[4], MAC_array[5]);
  445. WiFi.setHostname( hostname );
  446. #else
  447. sprintf(hostname, "%s%02x%02x%02x", "esp8266-", MAC_array[3], MAC_array[4], MAC_array[5]);
  448. wifi_station_set_hostname( hostname );
  449. #endif //ESP32_ARCH
  450. # if _DUSB>=1
  451. Serial.print(F("Host "));
  452. #if ESP32_ARCH==1
  453. Serial.print(WiFi.getHostname());
  454. #else
  455. Serial.print(wifi_station_get_hostname());
  456. #endif //ESP32_ARCH
  457. Serial.print(F(" WiFi Connected to "));
  458. Serial.print(WiFi.SSID());
  459. Serial.print(F(" on IP="));
  460. Serial.print(WiFi.localIP());
  461. Serial.println();
  462. # endif //_DUSB
  463. delay(500);
  464. // If we are here we are connected to WLAN
  465. #if defined(_UDPROUTER)
  466. // So now test the UDP function
  467. if (!connectUdp()) {
  468. Serial.println(F("Error connectUdp"));
  469. }
  470. #elif defined(_TTNROUTER)
  471. if (!connectTtn()) {
  472. # if _DUSB>=1
  473. Serial.println(F("Error connectTtn"));
  474. # endif //_DUSB
  475. }
  476. #else
  477. # if _MONITOR>=1
  478. mPrint(F("Setup:: ERROR, No UDP or TCP Connection defined"));
  479. # endif //_MONITOR
  480. #endif //_UDPROUTER
  481. delay(200);
  482. // Pins are defined and set in loraModem.h
  483. pinMode(pins.ss, OUTPUT);
  484. pinMode(pins.rst, OUTPUT);
  485. pinMode(pins.dio0, INPUT); // This pin is interrupt
  486. pinMode(pins.dio1, INPUT); // This pin is interrupt
  487. //pinMode(pins.dio2, INPUT); // XXX
  488. // Init the SPI pins
  489. #if ESP32_ARCH==1
  490. SPI.begin(SCK, MISO, MOSI, SS);
  491. #else
  492. SPI.begin();
  493. #endif //ESP32_ARCH==1
  494. delay(500);
  495. // We choose the Gateway ID to be the Ethernet Address of our Gateway card
  496. // display results of getting hardware address
  497. //
  498. # if _DUSB>=1
  499. Serial.print(F("Gateway ID: "));
  500. printHexDigit(MAC_array[0]);
  501. printHexDigit(MAC_array[1]);
  502. printHexDigit(MAC_array[2]);
  503. printHexDigit(0xFF);
  504. printHexDigit(0xFF);
  505. printHexDigit(MAC_array[3]);
  506. printHexDigit(MAC_array[4]);
  507. printHexDigit(MAC_array[5]);
  508. Serial.print(F(", Listening at SF"));
  509. Serial.print(sf);
  510. Serial.print(F(" on "));
  511. Serial.print((double)freqs[ifreq].upFreq/1000000);
  512. Serial.println(" MHz.");
  513. # endif //_DUSB
  514. ntpServer = resolveHost(NTP_TIMESERVER);
  515. # if _MONITOR>=1
  516. if (debug>=1) mPrint("NTP Server found and contacted");
  517. # endif
  518. delay(100);
  519. #ifdef _TTNSERVER
  520. ttnServer = resolveHost(_TTNSERVER); // Use DNS to get server IP
  521. delay(100);
  522. #endif //_TTNSERVER
  523. #ifdef _THINGSERVER
  524. thingServer = resolveHost(_THINGSERVER); // Use DNS to get server IP
  525. delay(100);
  526. #endif //_THINGSERVER
  527. // The Over the Air updates are supported when we have a WiFi connection.
  528. // The NTP time setting does not have to be precise for this function to work.
  529. #if A_OTA==1
  530. setupOta(hostname); // Uses wwwServer
  531. #endif //A_OTA
  532. // Set the NTP Time
  533. // As long as the time has not been set we try to set the time.
  534. #if NTP_INTR==1
  535. setupTime(); // Set NTP time host and interval
  536. #else //NTP_INTR
  537. // If not using the standard libraries, do a manual setting
  538. // of the time. This method works more reliable than the
  539. // interrupt driven method.
  540. //setTime((time_t)getNtpTime());
  541. while (timeStatus() == timeNotSet) {
  542. # if _DUSB>=1 || _MONITOR>=1
  543. if (( debug>=0 ) && ( pdebug & P_MAIN ))
  544. mPrint("setupTime:: Time not set (yet)");
  545. # endif //_DUSB
  546. delay(500);
  547. time_t newTime;
  548. newTime = (time_t)getNtpTime();
  549. if (newTime != 0) setTime(newTime);
  550. }
  551. // When we are here we succeeded in getting the time
  552. startTime = now(); // Time in seconds
  553. # if _DUSB>=1
  554. Serial.print("writeGwayCfg: "); printTime();
  555. Serial.println();
  556. #endif //_DUSB
  557. writeGwayCfg(CONFIGFILE );
  558. #endif //NTP_INTR
  559. #if A_SERVER==1
  560. // Setup the webserver
  561. setupWWW();
  562. #endif //A_SERVER
  563. delay(100); // Wait after setup
  564. // Setup and initialise LoRa state machine of _loraModem.ino
  565. _state = S_INIT;
  566. initLoraModem();
  567. if (_cad) {
  568. _state = S_SCAN;
  569. sf = SF7;
  570. cadScanner(); // Always start at SF7
  571. }
  572. else {
  573. _state = S_RX;
  574. rxLoraModem();
  575. }
  576. LoraUp.payLoad[0]= 0;
  577. LoraUp.payLength = 0; // Init the length to 0
  578. // init interrupt handlers, which are shared for GPIO15 / D8,
  579. // we switch on HIGH interrupts
  580. if (pins.dio0 == pins.dio1) {
  581. //SPI.usingInterrupt(digitalPinToInterrupt(pins.dio0));
  582. attachInterrupt(pins.dio0, Interrupt_0, RISING); // Share interrupts
  583. }
  584. // Or in the traditional Comresult case
  585. else {
  586. //SPI.usingInterrupt(digitalPinToInterrupt(pins.dio0));
  587. //SPI.usingInterrupt(digitalPinToInterrupt(pins.dio1));
  588. attachInterrupt(pins.dio0, Interrupt_0, RISING); // Separate interrupts
  589. attachInterrupt(pins.dio1, Interrupt_1, RISING); // Separate interrupts
  590. }
  591. writeConfig(CONFIGFILE, &gwayConfig); // Write config
  592. writeSeen( _SEENFILE, listSeen); // Write the last time record is seen
  593. // activate OLED display
  594. #if OLED>=1
  595. acti_oLED();
  596. addr_oLED();
  597. #endif //OLED
  598. # if _DUSB>=1
  599. Serial.println(F("--------------------------------------"));
  600. # endif //_DUSB
  601. mPrint("Setup() ended, Starting loop()");
  602. }//setup
  603. // ----------------------------------------------------------------------------
  604. // LOOP
  605. // This is the main program that is executed time and time again.
  606. // We need to give way to the backend WiFi processing that
  607. // takes place somewhere in the ESP8266 firmware and therefore
  608. // we include yield() statements at important points.
  609. //
  610. // Note: If we spend too much time in user processing functions
  611. // and the backend system cannot do its housekeeping, the watchdog
  612. // function will be executed which means effectively that the
  613. // program crashes.
  614. // We use yield() a lot to avoid ANY watch dog activity of the program.
  615. //
  616. // NOTE2: For ESP make sure not to do large array declarations in loop();
  617. // ----------------------------------------------------------------------------
  618. void loop ()
  619. {
  620. uint32_t uSeconds; // micro seconds
  621. int packetSize;
  622. uint32_t nowSeconds = now();
  623. // check for event value, which means that an interrupt has arrived.
  624. // In this case we handle the interrupt ( e.g. message received)
  625. // in userspace in loop().
  626. //
  627. stateMachine(); // do the state machine
  628. // After a quiet period, make sure we reinit the modem and state machine.
  629. // The interval is in seconds (about 15 seconds) as this re-init
  630. // is a heavy operation.
  631. // So it will kick in if there are not many messages for the gateway.
  632. // Note: Be careful that it does not happen too often in normal operation.
  633. //
  634. if ( ((nowSeconds - statr[0].tmst) > _MSG_INTERVAL ) &&
  635. (msgTime <= statr[0].tmst) )
  636. {
  637. # if _MONITOR>=1
  638. if (( debug>=2 ) && ( pdebug & P_MAIN )) {
  639. String response="";
  640. response += "REINIT:: ";
  641. response += String( _MSG_INTERVAL );
  642. response += (" ");
  643. mStat(0, response);
  644. mPrint(response);
  645. }
  646. # endif //_MONITOR
  647. yield(); // Allow buffer operations to finish
  648. if ((_cad) || (_hop)) {
  649. _state = S_SCAN;
  650. sf = SF7;
  651. cadScanner();
  652. }
  653. else {
  654. _state = S_RX;
  655. rxLoraModem();
  656. }
  657. writeRegister(REG_IRQ_FLAGS_MASK, (uint8_t) 0x00);
  658. writeRegister(REG_IRQ_FLAGS, (uint8_t) 0xFF); // Reset all interrupt flags
  659. msgTime = nowSeconds;
  660. }
  661. #if A_SERVER==1
  662. // Handle the Web server part of this sketch. Mainly used for administration
  663. // and monitoring of the node. This function is important so it is called at the
  664. // start of the loop() function.
  665. yield();
  666. server.handleClient();
  667. #endif //A_SERVER
  668. #if A_OTA==1
  669. // Perform Over the Air (OTA) update if enabled and requested by user.
  670. // It is important to put this function early in loop() as it is
  671. // not called frequently but it should always run when called.
  672. //
  673. yield();
  674. ArduinoOTA.handle();
  675. #endif //A_OTA
  676. // If event is set, we know that we have a (soft) interrupt.
  677. // After all necessary web/OTA services are scanned, we will
  678. // reloop here for timing purposes.
  679. // Do as less yield() as possible.
  680. // XXX 180326
  681. if (_event == 1) {
  682. return;
  683. }
  684. else yield();
  685. // If we are not connected, try to connect.
  686. // We will not read Udp in this loop cycle then
  687. if (WlanConnect(1) < 0) {
  688. # if _DUSB>=1 || _MONITOR>=1
  689. if (( debug >= 0 ) && ( pdebug & P_MAIN )) {
  690. mPrint("M ERROR reconnect WLAN");
  691. }
  692. # endif //_DUSB || _MONITOR
  693. yield();
  694. return; // Exit loop if no WLAN connected
  695. }
  696. // So if we are connected
  697. // Receive UDP PUSH_ACK messages from server. (*2, par. 3.3)
  698. // This is important since the TTN broker will return confirmation
  699. // messages on UDP for every message sent by the gateway. So we have to consume them.
  700. // As we do not know when the server will respond, we test in every loop.
  701. //
  702. else {
  703. while( (packetSize = Udp.parsePacket()) > 0) {
  704. # if _MONITOR>=1
  705. if (debug>=2) {
  706. mPrint("loop:: readUdp calling");
  707. }
  708. # endif //_MONITOR
  709. // DOWNSTREAM
  710. // Packet may be PKT_PUSH_ACK (0x01), PKT_PULL_ACK (0x03) or PKT_PULL_RESP (0x04)
  711. // This command is found in byte 4 (buffer[3])
  712. if (readUdp(packetSize) <= 0) {
  713. #if _MONITOR>=1
  714. if ( debug>=0 )
  715. mPrint("readUdp ERROR, retuning <=0");
  716. # endif //_MONITOR
  717. break;
  718. }
  719. // Now we know we succesfully received message from host
  720. else {
  721. //_event=1; // Could be done double if more messages received
  722. }
  723. }
  724. }
  725. yield(); // on 26/12/2017
  726. // stat PUSH_DATA message (*2, par. 4)
  727. //
  728. if ((nowSeconds - statTime) >= _STAT_INTERVAL) { // Wake up every xx seconds
  729. sendstat(); // Show the status message and send to server
  730. # if _MONITOR>=1
  731. if (( debug>=1 ) && ( pdebug & P_MAIN )) {
  732. mPrint("Send sendstat");
  733. }
  734. # endif //_MONITOR
  735. // If the gateway behaves like a node, we do from time to time
  736. // send a node message to the backend server.
  737. // The Gateway node emessage has nothing to do with the STAT_INTERVAL
  738. // message but we schedule it in the same frequency.
  739. //
  740. #if GATEWAYNODE==1
  741. if (gwayConfig.isNode) {
  742. // Give way to internal some Admin if necessary
  743. yield();
  744. // If the 1ch gateway is a sensor itself, send the sensor values
  745. // could be battery but also other status info or sensor info
  746. if (sensorPacket() < 0) {
  747. # if _MONITOR>=1
  748. if ((debug>=1) || (pdebug & P_MAIN)) {
  749. mPrint("sensorPacket: Error");
  750. }
  751. # endif// _MONITOR
  752. }
  753. }
  754. #endif//GATEWAYNODE
  755. statTime = nowSeconds;
  756. }
  757. yield();
  758. // send PULL_DATA message (*2, par. 4)
  759. //
  760. nowSeconds = now();
  761. if ((nowSeconds - pulltime) >= _PULL_INTERVAL) { // Wake up every xx seconds
  762. # if _DUSB>=1 || _MONITOR>=1
  763. if (( debug>=2) && ( pdebug & P_MAIN )) {
  764. mPrint("M PULL");
  765. }
  766. # endif//_DUSB _MONITOR
  767. pullData(); // Send PULL_DATA message to server
  768. startReceiver();
  769. pulltime = nowSeconds;
  770. }
  771. // If we do our own NTP handling (advisable)
  772. // We do not use the timer interrupt but use the timing
  773. // of the loop() itself which is better for SPI
  774. #if NTP_INTR==0
  775. // Set the time in a manual way. Do not use setSyncProvider
  776. // as this function may collide with SPI and other interrupts
  777. yield(); // 26/12/2017
  778. nowSeconds = now();
  779. if (nowSeconds - ntptimer >= _NTP_INTERVAL) {
  780. yield();
  781. time_t newTime;
  782. newTime = (time_t)getNtpTime();
  783. if (newTime != 0) setTime(newTime);
  784. ntptimer = nowSeconds;
  785. }
  786. #endif//NTP_INTR
  787. }//loop