ESP-sc-gway.ino 27 KB

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