ESP-sc-gway.ino 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  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. // The followion file contains most of the definitions
  29. // used in other files. It should be the first file.
  30. #include "ESP-sc-gway.h" // This file contains configuration of GWay
  31. #if defined (ARDUINO_ARCH_ESP32) || defined(ESP32)
  32. #define ESP32_ARCH 1
  33. #endif
  34. #include <Esp.h> // ESP8266 specific IDE functions
  35. #include <string.h>
  36. #include <stdio.h>
  37. #include <sys/types.h>
  38. #include <unistd.h>
  39. #include <fcntl.h>
  40. #include <cstdlib>
  41. #include <sys/time.h>
  42. #include <cstring>
  43. #include <string> // C++ specific string functions
  44. #include <SPI.h> // For the RFM95 bus
  45. #include <TimeLib.h> // http://playground.arduino.cc/code/time
  46. #include <DNSServer.h> // Local DNSserver
  47. #include <ArduinoJson.h>
  48. #include <FS.h> // ESP8266 Specific
  49. #include <WiFiUdp.h>
  50. #include <pins_arduino.h>
  51. #include <gBase64.h> // https://github.com/adamvr/arduino-base64 (changed the name)
  52. // Local include files
  53. #include "loraModem.h"
  54. #include "loraFiles.h"
  55. #include "sensor.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. void setupWWW(); // _wwwServer.ino forward
  180. static void printIP(IPAddress ipa, const char sep, String& response); // _wwwServer.ino
  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 ESP-sc-gway.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); // Zeroise 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(100);
  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. Serial.println(F("SPIFFS init success"));
  376. }
  377. else {
  378. }
  379. #endif
  380. #if _SPIFF_FORMAT>=1
  381. #if DUSB>=1
  382. if (( debug >= 0 ) && ( pdebug & P_MAIN )) {
  383. Serial.println(F("M Format Filesystem ... "));
  384. }
  385. #endif
  386. SPIFFS.format(); // Normally disabled. Enable only when SPIFFS corrupt
  387. #if DUSB>=1
  388. if (( debug >= 0 ) && ( pdebug & P_MAIN )) {
  389. Serial.println(F("Done"));
  390. }
  391. #endif
  392. #endif
  393. Serial.print(F("Assert="));
  394. #if defined CFG_noassert
  395. Serial.println(F("No Asserts"));
  396. #else
  397. Serial.println(F("Do Asserts"));
  398. #endif
  399. #if OLED>=1
  400. init_oLED(); // When done display "STARTING" on OLED
  401. #endif
  402. delay(500);
  403. yield();
  404. #if DUSB>=1
  405. if (debug>=1) {
  406. Serial.print(F("debug="));
  407. Serial.println(debug);
  408. yield();
  409. }
  410. #endif
  411. WiFi.mode(WIFI_STA);
  412. WiFi.setAutoConnect(true);
  413. //WiFi.begin();
  414. WlanReadWpa(); // Read the last Wifi settings from SPIFFS into memory
  415. WiFi.macAddress(MAC_array);
  416. sprintf(MAC_char,"%02x:%02x:%02x:%02x:%02x:%02x",
  417. MAC_array[0],MAC_array[1],MAC_array[2],MAC_array[3],MAC_array[4],MAC_array[5]);
  418. Serial.print("MAC: ");
  419. Serial.print(MAC_char);
  420. Serial.print(F(", len="));
  421. Serial.println(strlen(MAC_char));
  422. // We start by connecting to a WiFi network, set hostname
  423. char hostname[12];
  424. // Setup WiFi UDP connection. Give it some time and retry x times..
  425. while (WlanConnect(0) <= 0) {
  426. Serial.print(F("Error Wifi network connect "));
  427. Serial.println();
  428. yield();
  429. }
  430. // After there is a WiFi router connection, we can also set the hostname.
  431. #if ESP32_ARCH==1
  432. sprintf(hostname, "%s%02x%02x%02x", "esp32-", MAC_array[3], MAC_array[4], MAC_array[5]);
  433. WiFi.setHostname( hostname );
  434. #else
  435. sprintf(hostname, "%s%02x%02x%02x", "esp8266-", MAC_array[3], MAC_array[4], MAC_array[5]);
  436. wifi_station_set_hostname( hostname );
  437. #endif
  438. Serial.print(F("Host "));
  439. #if ESP32_ARCH==1
  440. Serial.print(WiFi.getHostname());
  441. #else
  442. Serial.print(wifi_station_get_hostname());
  443. #endif
  444. Serial.print(F(" WiFi Connected to "));
  445. Serial.print(WiFi.SSID());
  446. Serial.print(F(" on IP="));
  447. Serial.print(WiFi.localIP());
  448. Serial.println();
  449. delay(500);
  450. // If we are here we are connected to WLAN
  451. #if defined(_UDPROUTER)
  452. // So now test the UDP function
  453. if (!connectUdp()) {
  454. Serial.println(F("Error connectUdp"));
  455. }
  456. #elif defined(_TTNROUTER)
  457. if (!connectTtn()) {
  458. Serial.println(F("Error connectTtn"));
  459. }
  460. #else
  461. Serial.print(F("Setup:: No UDP or TCP Connection defined"));
  462. #endif
  463. delay(200);
  464. // Pins are defined and set in loraModem.h
  465. pinMode(pins.ss, OUTPUT);
  466. pinMode(pins.rst, OUTPUT);
  467. pinMode(pins.dio0, INPUT); // This pin is interrupt
  468. pinMode(pins.dio1, INPUT); // This pin is interrupt
  469. //pinMode(pins.dio2, INPUT);
  470. // Init the SPI pins
  471. #if ESP32_ARCH==1
  472. SPI.begin(SCK, MISO, MOSI, SS);
  473. #else
  474. SPI.begin();
  475. #endif
  476. delay(500);
  477. // We choose the Gateway ID to be the Ethernet Address of our Gateway card
  478. // display results of getting hardware address
  479. //
  480. Serial.print("Gateway ID: ");
  481. printHexDigit(MAC_array[0]);
  482. printHexDigit(MAC_array[1]);
  483. printHexDigit(MAC_array[2]);
  484. printHexDigit(0xFF);
  485. printHexDigit(0xFF);
  486. printHexDigit(MAC_array[3]);
  487. printHexDigit(MAC_array[4]);
  488. printHexDigit(MAC_array[5]);
  489. Serial.print(", Listening at SF");
  490. Serial.print(sf);
  491. Serial.print(" on ");
  492. Serial.print((double)freqs[ifreq].upFreq/1000000);
  493. Serial.println(" MHz.");
  494. if (!WiFi.hostByName(NTP_TIMESERVER, ntpServer)) // Get IP address of Timeserver
  495. {
  496. die("Setup:: ERROR hostByName NTP");
  497. };
  498. delay(100);
  499. #ifdef _TTNSERVER
  500. if (!WiFi.hostByName(_TTNSERVER, ttnServer)) // Use DNS to get server IP once
  501. {
  502. die("Setup:: ERROR hostByName TTN");
  503. };
  504. delay(100);
  505. #endif
  506. #ifdef _THINGSERVER
  507. if (!WiFi.hostByName(_THINGSERVER, thingServer))
  508. {
  509. die("Setup:: ERROR hostByName THING");
  510. }
  511. delay(100);
  512. #endif
  513. // The Over the Air updates are supported when we have a WiFi connection.
  514. // The NTP time setting does not have to be precise for this function to work.
  515. #if A_OTA==1
  516. setupOta(hostname); // Uses wwwServer
  517. #endif
  518. // Set the NTP Time
  519. // As long as the time has not been set we try to set the time.
  520. #if NTP_INTR==1
  521. setupTime(); // Set NTP time host and interval
  522. #else
  523. // If not using the standard libraries, do a manual setting
  524. // of the time. This method works more reliable than the
  525. // interrupt driven method.
  526. //setTime((time_t)getNtpTime());
  527. while (timeStatus() == timeNotSet) {
  528. #if DUSB>=1
  529. if (( debug>=0 ) && ( pdebug & P_MAIN ))
  530. Serial.println(F("M setupTime:: Time not set (yet)"));
  531. #endif
  532. delay(500);
  533. time_t newTime;
  534. newTime = (time_t)getNtpTime();
  535. if (newTime != 0) setTime(newTime);
  536. }
  537. // When we are here we succeeded in getting the time
  538. startTime = now(); // Time in seconds
  539. #if DUSB>=1
  540. Serial.print("Time: "); printTime();
  541. Serial.println();
  542. #endif
  543. writeGwayCfg(CONFIGFILE );
  544. #if DUSB>=1
  545. Serial.println(F("Gateway configuration saved"));
  546. #endif
  547. #endif //NTP_INTR
  548. #if A_SERVER==1
  549. // Setup the webserver
  550. setupWWW();
  551. #endif
  552. delay(100); // Wait after setup
  553. // Setup and initialise LoRa state machine of _loramModem.ino
  554. _state = S_INIT;
  555. initLoraModem();
  556. if (_cad) {
  557. _state = S_SCAN;
  558. sf = SF7;
  559. cadScanner(); // Always start at SF7
  560. }
  561. else {
  562. _state = S_RX;
  563. rxLoraModem();
  564. }
  565. LoraUp.payLoad[0]= 0;
  566. LoraUp.payLength = 0; // Init the length to 0
  567. // init interrupt handlers, which are shared for GPIO15 / D8,
  568. // we switch on HIGH interrupts
  569. if (pins.dio0 == pins.dio1) {
  570. //SPI.usingInterrupt(digitalPinToInterrupt(pins.dio0));
  571. attachInterrupt(pins.dio0, Interrupt_0, RISING); // Share interrupts
  572. }
  573. // Or in the traditional Comresult case
  574. else {
  575. //SPI.usingInterrupt(digitalPinToInterrupt(pins.dio0));
  576. //SPI.usingInterrupt(digitalPinToInterrupt(pins.dio1));
  577. attachInterrupt(pins.dio0, Interrupt_0, RISING); // Separate interrupts
  578. attachInterrupt(pins.dio1, Interrupt_1, RISING); // Separate interrupts
  579. }
  580. writeConfig( CONFIGFILE, &gwayConfig); // Write config
  581. // activate OLED display
  582. #if OLED>=1
  583. acti_oLED();
  584. addr_oLED();
  585. #endif
  586. Serial.println(F("--------------------------------------"));
  587. }//setup
  588. // ----------------------------------------------------------------------------
  589. // LOOP
  590. // This is the main program that is executed time and time again.
  591. // We need to give way to the backend WiFi processing that
  592. // takes place somewhere in the ESP8266 firmware and therefore
  593. // we include yield() statements at important points.
  594. //
  595. // Note: If we spend too much time in user processing functions
  596. // and the backend system cannot do its housekeeping, the watchdog
  597. // function will be executed which means effectively that the
  598. // program crashes.
  599. // We use yield() a lot to avoid ANY watch dog activity of the program.
  600. //
  601. // NOTE2: For ESP make sure not to do large array declarations in loop();
  602. // ----------------------------------------------------------------------------
  603. void loop ()
  604. {
  605. uint32_t uSeconds; // micro seconds
  606. int packetSize;
  607. uint32_t nowSeconds = now();
  608. // check for event value, which means that an interrupt has arrived.
  609. // In this case we handle the interrupt ( e.g. message received)
  610. // in userspace in loop().
  611. //
  612. stateMachine(); // do the state machine
  613. // After a quiet period, make sure we reinit the modem and state machine.
  614. // The interval is in seconds (about 15 seconds) as this re-init
  615. // is a heavy operation.
  616. // SO it will kick in if there are not many messages for the gateway.
  617. // Note: Be careful that it does not happen too often in normal operation.
  618. //
  619. if ( ((nowSeconds - statr[0].tmst) > _MSG_INTERVAL ) &&
  620. (msgTime <= statr[0].tmst) )
  621. {
  622. #if DUSB>=1
  623. if (( debug>=1 ) && ( pdebug & P_MAIN )) {
  624. Serial.print("M REINIT:: ");
  625. Serial.print( _MSG_INTERVAL );
  626. Serial.print(F(" "));
  627. SerialStat(0);
  628. }
  629. #endif
  630. // startReceiver() ??
  631. if ((_cad) || (_hop)) {
  632. _state = S_SCAN;
  633. sf = SF7;
  634. cadScanner();
  635. }
  636. else {
  637. _state = S_RX;
  638. rxLoraModem();
  639. }
  640. writeRegister(REG_IRQ_FLAGS_MASK, (uint8_t) 0x00);
  641. writeRegister(REG_IRQ_FLAGS, (uint8_t) 0xFF); // Reset all interrupt flags
  642. msgTime = nowSeconds;
  643. }
  644. #if A_SERVER==1
  645. // Handle the Web server part of this sketch. Mainly used for administration
  646. // and monitoring of the node. This function is important so it is called at the
  647. // start of the loop() function.
  648. yield();
  649. server.handleClient();
  650. #endif
  651. #if A_OTA==1
  652. // Perform Over the Air (OTA) update if enabled and requested by user.
  653. // It is important to put this function early in loop() as it is
  654. // not called frequently but it should always run when called.
  655. //
  656. yield();
  657. ArduinoOTA.handle();
  658. #endif
  659. // If event is set, we know that we have a (soft) interrupt.
  660. // After all necessary web/OTA services are scanned, we will
  661. // reloop here for timing purposes.
  662. // Do as less yield() as possible.
  663. // XXX 180326
  664. if (_event == 1) {
  665. return;
  666. }
  667. else yield();
  668. // If we are not connected, try to connect.
  669. // We will not read Udp in this loop cycle then
  670. if (WlanConnect(1) < 0) {
  671. #if DUSB>=1
  672. if (( debug >= 0 ) && ( pdebug & P_MAIN ))
  673. Serial.println(F("M ERROR reconnect WLAN"));
  674. #endif
  675. yield();
  676. return; // Exit loop if no WLAN connected
  677. }
  678. // So if we are connected
  679. // Receive UDP PUSH_ACK messages from server. (*2, par. 3.3)
  680. // This is important since the TTN broker will return confirmation
  681. // messages on UDP for every message sent by the gateway. So we have to consume them.
  682. // As we do not know when the server will respond, we test in every loop.
  683. //
  684. else {
  685. while( (packetSize = Udp.parsePacket()) > 0) {
  686. #if DUSB>=2
  687. Serial.println(F("loop:: readUdp calling"));
  688. #endif
  689. // DOWNSTREAM
  690. // Packet may be PKT_PUSH_ACK (0x01), PKT_PULL_ACK (0x03) or PKT_PULL_RESP (0x04)
  691. // This command is found in byte 4 (buffer[3])
  692. if (readUdp(packetSize) <= 0) {
  693. #if DUSB>=1
  694. if (( debug>0 ) && ( pdebug & P_MAIN ))
  695. Serial.println(F("M readUdp error"));
  696. #endif
  697. break;
  698. }
  699. // Now we know we succesfully received message from host
  700. else {
  701. //_event=1; // Could be done double if more messages received
  702. }
  703. }
  704. }
  705. yield(); // XXX 26/12/2017
  706. // stat PUSH_DATA message (*2, par. 4)
  707. //
  708. if ((nowSeconds - statTime) >= _STAT_INTERVAL) { // Wake up every xx seconds
  709. #if DUSB>=1
  710. if (( debug>=1 ) && ( pdebug & P_MAIN )) {
  711. Serial.print(F("M STAT:: ..."));
  712. Serial.flush();
  713. }
  714. #endif
  715. sendstat(); // Show the status message and send to server
  716. #if DUSB>=1
  717. if (( debug>=1 ) && ( pdebug & P_MAIN )) {
  718. Serial.println(F(" done"));
  719. if (debug>=2) Serial.flush();
  720. }
  721. #endif
  722. // If the gateway behaves like a node, we do from time to time
  723. // send a node message to the backend server.
  724. // The Gateway node emessage has nothing to do with the STAT_INTERVAL
  725. // message but we schedule it in the same frequency.
  726. //
  727. #if GATEWAYNODE==1
  728. if (gwayConfig.isNode) {
  729. // Give way to internal some Admin if necessary
  730. yield();
  731. // If the 1ch gateway is a sensor itself, send the sensor values
  732. // could be battery but also other status info or sensor info
  733. if (sensorPacket() < 0) {
  734. #if DUSB>=1
  735. Serial.println(F("sensorPacket: Error"));
  736. #endif
  737. }
  738. }
  739. #endif
  740. statTime = nowSeconds;
  741. }
  742. yield();
  743. // send PULL_DATA message (*2, par. 4)
  744. //
  745. nowSeconds = now();
  746. if ((nowSeconds - pulltime) >= _PULL_INTERVAL) { // Wake up every xx seconds
  747. #if DUSB>=1
  748. if (( debug>=2) && ( pdebug & P_MAIN )) {
  749. Serial.println(F("M PULL"));
  750. if (debug>=1) Serial.flush();
  751. }
  752. #endif
  753. pullData(); // Send PULL_DATA message to server
  754. startReceiver();
  755. pulltime = nowSeconds;
  756. }
  757. // If we do our own NTP handling (advisable)
  758. // We do not use the timer interrupt but use the timing
  759. // of the loop() itself which is better for SPI
  760. #if NTP_INTR==0
  761. // Set the time in a manual way. Do not use setSyncProvider
  762. // as this function may collide with SPI and other interrupts
  763. yield(); // 26/12/2017
  764. nowSeconds = now();
  765. if (nowSeconds - ntptimer >= _NTP_INTERVAL) {
  766. yield();
  767. time_t newTime;
  768. newTime = (time_t)getNtpTime();
  769. if (newTime != 0) setTime(newTime);
  770. ntptimer = nowSeconds;
  771. }
  772. #endif
  773. }//loop