ESP-sc-gway.ino 26 KB

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