_txRx.ino 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. // 1-channel LoRa Gateway for ESP8266
  2. // Copyright (c) 2016-2020 Maarten Westenberg version for ESP8266
  3. //
  4. // based on work done by Thomas Telkamp for Raspberry PI 1ch gateway
  5. // and many others.
  6. //
  7. // All rights reserved. This program and the accompanying materials
  8. // are made available under the terms of the MIT License
  9. // which accompanies this distribution, and is available at
  10. // https://opensource.org/licenses/mit-license.php
  11. //
  12. // NO WARRANTY OF ANY KIND IS PROVIDED
  13. //
  14. // Author: Maarten Westenberg (mw12554@hotmail.com)
  15. //
  16. // This file contains the LoRa modem specific code enabling to receive
  17. // and transmit packages/messages.
  18. // ========================================================================================
  19. // ----------------------------------------------------------------------------
  20. // DOWN DOWN DOWN DOWN DOWN DOWN DOWN DOWN DOWN DOWN DOWN DOWN DOWN DOWN DOWN
  21. // Send DOWN a LoRa packet over the air to the node. This function does all the
  22. // decoding of the server message and prepares a Payload buffer.
  23. // The payload is actually transmitted by the sendPkt() function.
  24. // This function is used for regular downstream messages and for JOIN_ACCEPT
  25. // messages.
  26. // NOTE: This is not an interrupt function, but is started by loop().
  27. // The _status is set an the end of the function to TX and in _stateMachine
  28. // function the actual transmission function is executed.
  29. // The LoraDown.tmst contains the timestamp that the tranmission should finish.
  30. // ----------------------------------------------------------------------------
  31. int sendPacket(uint8_t *buf, uint8_t length)
  32. {
  33. // Received package with Meta Data (for example):
  34. // codr : "4/5"
  35. // data : "Kuc5CSwJ7/a5JgPHrP29X9K6kf/Vs5kU6g==" // for example
  36. // freq : 868.1 // 868100000 default
  37. // ipol : true/false
  38. // modu : "LORA"
  39. // powe : 14 // Set by default
  40. // rfch : 0 // Set by default
  41. // size : 21
  42. // tmst : 1800642 // for example
  43. // datr : "SF7BW125"
  44. // 12-byte header;
  45. // HDR (1 byte)
  46. //
  47. //
  48. // Data Reply for JOIN_ACCEPT as sent by server:
  49. // AppNonce (3 byte)
  50. // NetID (3 byte)
  51. // DevAddr (4 byte) [ 31..25]:NwkID , [24..0]:NwkAddr
  52. // DLSettings (1 byte)
  53. // RxDelay (1 byte)
  54. // CFList (fill to 16 bytes)
  55. int i=0;
  56. StaticJsonDocument<312> jsonBuffer; // Use of arduinoJson version 6!
  57. char * bufPtr = (char *) (buf);
  58. buf[length] = 0;
  59. # if _MONITOR>=1
  60. if (( debug>=2) && (pdebug & P_TX)) {
  61. mPrint("sendPacket:: " + String((char *)buf) + "< ");
  62. }
  63. # endif //_MONITOR
  64. // Use JSON to decode the string after the first 4 bytes.
  65. // The data for the node is in the "data" field. This function destroys original buffer
  66. auto error = deserializeJson(jsonBuffer, bufPtr);
  67. if (error) {
  68. # if _MONITOR>=1
  69. if (( debug>=1) && (pdebug & P_TX)) {
  70. mPrint("T sendPacket:: ERROR Json Decode: " + String(bufPtr) );
  71. }
  72. # endif //_MONITOR
  73. return(-1);
  74. }
  75. yield();
  76. // Meta Data sent by server (example)
  77. // {"txpk":{"codr":"4/5","data":"YCkEAgIABQABGmIwYX/kSn4Y","freq":868.1,"ipol":true,"modu":"LORA","powe":14,"rfch":0,"size":18,"tmst":1890991792,"datr":"SF7BW125"}}
  78. // Used in the protocol of Gateway:
  79. JsonObject root = jsonBuffer.as<JsonObject>(); // 191111 Avoid Crashes
  80. const char * data = root["txpk"]["data"]; // Downstream Payload
  81. uint8_t psize = root["txpk"]["size"]; // Payload size
  82. bool ipol = root["txpk"]["ipol"];
  83. uint8_t powe = root["txpk"]["powe"]; // power, e.g. 14 or 27
  84. LoraDown.tmst = (uint32_t) root["txpk"]["tmst"].as<unsigned long>();
  85. //const float ff = root["txpk"]["freq"]; // eg 869.525
  86. // Not used in the protocol of Gateway TTN:
  87. const char * datr = root["txpk"]["datr"]; // eg "SF7BW125"
  88. const char * modu = root["txpk"]["modu"]; // =="LORA"
  89. const char * codr = root["txpk"]["codr"]; // e.g. "4/5"
  90. //if (root["txpk"].containsKey("imme") ) {
  91. // const bool imme = root["txpk"]["imme"]; // Immediate Transmit (tmst don't care)
  92. //}
  93. if ( data != NULL ) {
  94. # if _MONITOR>=1
  95. if (( debug>=2 ) && ( pdebug & P_TX )) {
  96. mPrint("sendPacket:: data=" + String(data));
  97. }
  98. # endif //_MONITOR
  99. }
  100. else { // There is data!
  101. # if _MONITOR>=1
  102. if ((debug>=0) && ( pdebug & P_TX )) {
  103. mPrint("sendPacket:: ERROR: data is NULL");
  104. }
  105. # endif //_MONITOR
  106. return(-1);
  107. }
  108. LoraDown.sfTx = atoi(datr+2); // Convert "SF9BW125" or what is received from gateway to number
  109. LoraDown.iiq = (ipol? 0x40: 0x27); // if ipol==true 0x40 else 0x27
  110. LoraDown.crc = 0x00; // switch CRC off for TX
  111. LoraDown.payLength = base64_dec_len((char *) data, strlen(data));// Length of the Payload data
  112. base64_decode((char *) payLoad, (char *) data, strlen(data)); // Fill payload w decoded message
  113. // Compute wait time in microseconds
  114. uint32_t w = (uint32_t) (LoraDown.tmst - micros()); // Wait Time compute
  115. // _STRICT_1CH determines how we will react on downstream messages.
  116. //
  117. // If _STRICT==1, we will answer (in the RX1 timeslot) on the frequency we receive on.
  118. // We will anser in RX2 in rthe time set by _RX2_SF.
  119. // This way, we can better communicate as a single gateway machine
  120. // Otherwise we will answer in RX with RF==12 and use special answer frequency
  121. //
  122. #if _STRICT_1CH == 1
  123. // RX1 is requested frequency
  124. // RX2 is SF _RX2_SF probably SF9
  125. // If possible use RX1 timeslot as this is our frequency.
  126. // Do not use RX2 or JOIN2 as they contain other frequencies
  127. // Wait time RX1
  128. if ((w>1000000) && (w<3000000)) {
  129. LoraDown.tmst-=1000000;
  130. LoraDown.sfTx= sfi; // Take care, TX sf not to be mixed with SCAN
  131. }
  132. // RX2. Is tmst correction necessary
  133. else if ((w>6000000) && (w<7000000)) {
  134. LoraDown.tmst-=500000; // Corrrect the Timestamp
  135. LoraDown.sfTx= _RX2_SF; // Use the RX2 downstream SF (may be dedicated to TTN)
  136. }
  137. LoraDown.powe = 14; // On all freqs except 869.5MHz power is limited
  138. LoraDown.fff = freqs[gwayConfig.ch].dwnFreq; // Use the corresponding Down frequency
  139. #else
  140. // Elif _STRICT_1CH == 0, we will receive messags from the TTN gateway presumably on SF9/869.5MHz
  141. // And since the Gateway is a single channel gateway, and its nodes are probably
  142. // single channel too. They will not listen to that frequency at all.
  143. // Pleae note that this parameter is more for nodes (that cannot change freqs)
  144. // than for gateways.
  145. //
  146. LoraDown.powe = powe;
  147. // convert double frequency (MHz) into uint32_t frequency in Hz.
  148. LoraDown.fff = (uint32_t) ((uint32_t)((ff+0.000035)*1000)) * 1000;
  149. #endif //_STRICT_1CH
  150. LoraDown.payLoad = payLoad;
  151. # if _MONITOR>=1
  152. if (( debug>=1 ) && ( pdebug & P_TX)) {
  153. mPrint("T LoraDown tmst=" + String(LoraDown.tmst));
  154. if ( debug>=2 ) {
  155. Serial.print(F(" Request:: "));
  156. Serial.print(F(" tmst=")); Serial.print(LoraDown.tmst); Serial.print(F(" wait=")); Serial.println(w);
  157. Serial.print(F(" strict=")); Serial.print(_STRICT_1CH);
  158. Serial.print(F(" datr=")); Serial.println(datr);
  159. Serial.print(F(" Rfreq=")); Serial.print(freqs[gwayConfig.ch].dwnFreq);
  160. Serial.print(F(" ->")); Serial.println(LoraDown.fff);
  161. Serial.print(F(" sf =")); Serial.print(atoi(datr+2)); Serial.print(F(" ->")); Serial.println(LoraDown.sfTx);
  162. Serial.print(F(" modu=")); Serial.println(modu);
  163. Serial.print(F(" powe=")); Serial.println(powe);
  164. Serial.print(F(" codr=")); Serial.println(codr);
  165. Serial.print(F(" ipol=")); Serial.println(ipol);
  166. Serial.println();
  167. }
  168. }
  169. # endif // _MONITOR
  170. if (LoraDown.payLength != psize) {
  171. # if _MONITOR>=1
  172. Serial.print(F("sendPacket:: WARNING payLength: "));
  173. Serial.print(LoraDown.payLength);
  174. Serial.print(F(", psize="));
  175. Serial.println(psize);
  176. if (debug>=2) Serial.flush();
  177. # endif //_MONITOR
  178. }
  179. # if _MONITOR>=1
  180. else if (( debug >= 2 ) && ( pdebug & P_TX )) {
  181. Serial.print(F("T Payload="));
  182. for (i=0; i<LoraDown.payLength; i++) {
  183. Serial.print(payLoad[i],HEX);
  184. Serial.print(':');
  185. }
  186. Serial.println();
  187. }
  188. # endif //_MONITOR
  189. // Update downstream statistics
  190. statc.msg_down++;
  191. switch(statr[0].ch) {
  192. case 0: statc.msg_down_0++; break;
  193. case 1: statc.msg_down_1++; break;
  194. case 2: statc.msg_down_2++; break;
  195. }
  196. # if _MONITOR>=1
  197. if (( debug>=2 ) && ( pdebug & P_TX )) {
  198. mPrint("T sendPacket:: fini OK");
  199. }
  200. # endif //_MONITOR
  201. // All data is in Payload and parameters and need to be transmitted.
  202. // The function is called in user-space
  203. _state = S_TX; // _state set to transmit
  204. # if _MONITOR>=1
  205. if ((debug>=1) && ( pdebug & P_TX)) {
  206. mPrint("sendPacket:: STRICT=" + String(_STRICT_1CH) );
  207. }
  208. # endif //_MONITOR
  209. return 1;
  210. }//sendPacket DOWN
  211. // ----------------------------------------------------------------------------
  212. // UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP
  213. // Based on the information read from the LoRa transceiver (or fake message)
  214. // build a gateway message to send upstream (to the user somewhere on the web).
  215. //
  216. // parameters:
  217. // tmst: Timestamp to include in the upstream message
  218. // buff_up: The buffer that is generated for upstream
  219. // LoraUP: Structure describing the message received from device
  220. // internal: Boolean value to indicate whether the local sensor is processed
  221. //
  222. // returns:
  223. // buff_index:
  224. // ----------------------------------------------------------------------------
  225. int buildPacket(uint32_t tmst, uint8_t *buff_up, struct LoraUp LoraUp, bool internal)
  226. {
  227. int32_t SNR;
  228. int16_t rssicorr;
  229. int16_t prssi; // packet rssi
  230. char cfreq[12] = {0}; // Character array to hold freq in MHz
  231. //lastTmst = tmst; // Following/according to spec
  232. int buff_index=0;
  233. char b64[256];
  234. uint8_t *message = LoraUp.payLoad;
  235. char messageLength = LoraUp.payLength;
  236. #if _CHECK_MIC==1
  237. unsigned char NwkSKey[16] = _NWKSKEY;
  238. checkMic(message, messageLength, NwkSKey);
  239. #endif // _CHECK_MIC
  240. // Read SNR and RSSI from the register. Note: Not for internal sensors!
  241. // For internal sensor we fake these values as we cannot read a register
  242. if (internal) {
  243. SNR = 12;
  244. prssi = 50;
  245. rssicorr = 157;
  246. }
  247. else {
  248. SNR = LoraUp.snr;
  249. prssi = LoraUp.prssi; // read register 0x1A, packet rssi
  250. rssicorr = LoraUp.rssicorr;
  251. }
  252. #if _STATISTICS >= 1
  253. // Receive statistics, move old statistics down 1 position
  254. // and fill the new top line with the latest received sensor values.
  255. // This works fine for the sensor, EXCEPT when we decode data for _LOCALSERVER
  256. //
  257. for (int m=( _MAXSTAT -1); m>0; m--) statr[m]=statr[m-1];
  258. // From now on we can fill statr[0] with sensor data
  259. #if _LOCALSERVER==1
  260. statr[0].datal=0;
  261. int index;
  262. if ((index = inDecodes((char *)(LoraUp.payLoad+1))) >=0 ) {
  263. uint16_t frameCount=LoraUp.payLoad[7]*256 + LoraUp.payLoad[6];
  264. for (int k=0; (k<LoraUp.payLength) && (k<23); k++) {
  265. statr[0].data[k] = LoraUp.payLoad[k+9];
  266. };
  267. // XXX Check that k<23 when leaving the for loop
  268. // XXX or we can not display in statr
  269. uint8_t DevAddr[4];
  270. DevAddr[0]= LoraUp.payLoad[4];
  271. DevAddr[1]= LoraUp.payLoad[3];
  272. DevAddr[2]= LoraUp.payLoad[2];
  273. DevAddr[3]= LoraUp.payLoad[1];
  274. statr[0].datal = encodePacket((uint8_t *)(statr[0].data),
  275. LoraUp.payLength-9-4,
  276. (uint16_t)frameCount,
  277. DevAddr,
  278. decodes[index].appKey,
  279. 0);
  280. }
  281. #endif //_LOCALSERVER
  282. statr[0].tmst = now();
  283. statr[0].ch = gwayConfig.ch;
  284. statr[0].prssi = prssi - rssicorr;
  285. statr[0].sf = LoraUp.sf;
  286. # if RSSI==1
  287. statr[0].rssi = _rssi - rssicorr;
  288. # endif // RSII
  289. # if _DUSB>=2
  290. if (debug>=0) {
  291. if ((message[4] != 0x26) || (message[1]==0x99)) {
  292. Serial.print(F("addr="));
  293. for (int i=messageLength; i>0; i--) {
  294. if (message[i]<0x10) Serial.print('0');
  295. Serial.print(message[i],HEX);
  296. Serial.print(' ');
  297. }
  298. Serial.println();
  299. }
  300. }
  301. # endif //DUSB
  302. statr[0].node = ( message[1]<<24 | message[2]<<16 | message[3]<<8 | message[4] );
  303. #if _STATISTICS >= 2
  304. // Fill in the statistics that we will also need for the GUI.
  305. // So
  306. switch (statr[0].sf) {
  307. case SF7: statc.sf7++; break;
  308. case SF8: statc.sf8++; break;
  309. case SF9: statc.sf9++; break;
  310. case SF10: statc.sf10++; break;
  311. case SF11: statc.sf11++; break;
  312. case SF12: statc.sf12++; break;
  313. }
  314. #endif // _STATISTICS >= 2
  315. #if _STATISTICS >= 3
  316. if (statr[0].ch == 0) {
  317. statc.msg_ttl_0++; // Increase #message received channel 0
  318. switch (statr[0].sf) {
  319. case SF7: statc.sf7_0++; break;
  320. case SF8: statc.sf8_0++; break;
  321. case SF9: statc.sf9_0++; break;
  322. case SF10: statc.sf10_0++; break;
  323. case SF11: statc.sf11_0++; break;
  324. case SF12: statc.sf12_0++; break;
  325. }
  326. }
  327. else
  328. if (statr[0].ch == 1) {
  329. statc.msg_ttl_1++;
  330. switch (statr[0].sf) {
  331. case SF7: statc.sf7_1++; break;
  332. case SF8: statc.sf8_1++; break;
  333. case SF9: statc.sf9_1++; break;
  334. case SF10: statc.sf10_1++; break;
  335. case SF11: statc.sf11_1++; break;
  336. case SF12: statc.sf12_1++; break;
  337. }
  338. }
  339. else
  340. if (statr[0].ch == 2) {
  341. statc.msg_ttl_2++;
  342. switch (statr[0].sf) {
  343. case SF7: statc.sf7_2++; break;
  344. case SF8: statc.sf8_2++; break;
  345. case SF9: statc.sf9_2++; break;
  346. case SF10: statc.sf10_2++; break;
  347. case SF11: statc.sf11_2++; break;
  348. case SF12: statc.sf12_2++; break;
  349. }
  350. }
  351. #endif //_STATISTICS >= 3
  352. #endif //_STATISTICS >= 2
  353. #if _MONITOR>=1
  354. if (( debug>=2 ) && ( pdebug & P_RADIO )){
  355. Serial.print(F("R buildPacket:: pRSSI="));
  356. Serial.print(prssi-rssicorr);
  357. Serial.print(F(" RSSI: "));
  358. Serial.print(_rssi - rssicorr);
  359. Serial.print(F(" SNR: "));
  360. Serial.print(SNR);
  361. Serial.print(F(" Length: "));
  362. Serial.print((int)messageLength);
  363. Serial.print(F(" -> "));
  364. int i;
  365. for (i=0; i< messageLength; i++) {
  366. Serial.print(message[i],HEX);
  367. Serial.print(' ');
  368. }
  369. Serial.println();
  370. yield();
  371. }
  372. #endif // _MONITOR
  373. // Show received message status on OLED display
  374. #if OLED>=1
  375. char timBuff[20];
  376. sprintf(timBuff, "%02i:%02i:%02i", hour(), minute(), second());
  377. display.clear();
  378. display.setFont(ArialMT_Plain_16);
  379. display.setTextAlignment(TEXT_ALIGN_LEFT);
  380. display.drawString(0, 0, "Time: " );
  381. display.drawString(40, 0, timBuff);
  382. display.drawString(0, 16, "RSSI: " );
  383. display.drawString(40, 16, String(prssi-rssicorr));
  384. display.drawString(70, 16, ",SNR: " );
  385. display.drawString(110, 16, String(SNR) );
  386. display.drawString(0, 32, "Addr: " );
  387. if (message[4] < 0x10) display.drawString( 40, 32, "0"+String(message[4], HEX)); else display.drawString( 40, 32, String(message[4], HEX));
  388. if (message[3] < 0x10) display.drawString( 61, 32, "0"+String(message[3], HEX)); else display.drawString( 61, 32, String(message[3], HEX));
  389. if (message[2] < 0x10) display.drawString( 82, 32, "0"+String(message[2], HEX)); else display.drawString( 82, 32, String(message[2], HEX));
  390. if (message[1] < 0x10) display.drawString(103, 32, "0"+String(message[1], HEX)); else display.drawString(103, 32, String(message[1], HEX));
  391. display.drawString(0, 48, "LEN: " );
  392. display.drawString(40, 48, String((int)messageLength) );
  393. display.display();
  394. //yield();
  395. #endif //OLED>=1
  396. int j;
  397. // XXX Base64 library is nopad. So we may have to add padding characters until
  398. // message Length is multiple of 4!
  399. // Encode message with messageLength into b64
  400. int encodedLen = base64_enc_len(messageLength); // max 341
  401. # if _MONITOR>=1
  402. if ((debug>=1) && (encodedLen>255) && ( pdebug & P_RADIO )) {
  403. mPrint("R buildPacket:: b64 err, len=" + String(encodedLen));
  404. return(-1);
  405. }
  406. # endif // _MONITOR
  407. base64_encode(b64, (char *) message, messageLength);// max 341
  408. // start composing datagram with the header
  409. uint8_t token_h = (uint8_t)rand(); // random token
  410. uint8_t token_l = (uint8_t)rand(); // random token
  411. // pre-fill the data buffer with fixed fields
  412. buff_up[0] = PROTOCOL_VERSION; // 0x01 still
  413. buff_up[1] = token_h;
  414. buff_up[2] = token_l;
  415. buff_up[3] = PKT_PUSH_DATA; // 0x00
  416. // READ MAC ADDRESS OF ESP8266, and insert 0xFF 0xFF in the middle
  417. buff_up[4] = MAC_array[0];
  418. buff_up[5] = MAC_array[1];
  419. buff_up[6] = MAC_array[2];
  420. buff_up[7] = 0xFF;
  421. buff_up[8] = 0xFF;
  422. buff_up[9] = MAC_array[3];
  423. buff_up[10] = MAC_array[4];
  424. buff_up[11] = MAC_array[5];
  425. buff_index = 12; // 12-byte binary (!) header
  426. // start of JSON structure that will make payload
  427. memcpy((void *)(buff_up + buff_index), (void *)"{\"rxpk\":[", 9);
  428. buff_index += 9;
  429. buff_up[buff_index] = '{';
  430. ++buff_index;
  431. j = snprintf((char *)(buff_up + buff_index), TX_BUFF_SIZE-buff_index, "\"tmst\":%u", tmst);
  432. # if _MONITOR>=1
  433. if ((j<0) && ( debug>=1 ) && ( pdebug & P_RADIO )) {
  434. mPrint("buildPacket:: Error ");
  435. }
  436. # endif //_MONITOR
  437. buff_index += j;
  438. ftoa((double)freqs[gwayConfig.ch].upFreq / 1000000, cfreq, 6); // XXX This can be done better
  439. j = snprintf((char *)(buff_up + buff_index), TX_BUFF_SIZE-buff_index, ",\"chan\":%1u,\"rfch\":%1u,\"freq\":%s", 0, 0, cfreq);
  440. buff_index += j;
  441. memcpy((void *)(buff_up + buff_index), (void *)",\"stat\":1", 9);
  442. buff_index += 9;
  443. memcpy((void *)(buff_up + buff_index), (void *)",\"modu\":\"LORA\"", 14);
  444. buff_index += 14;
  445. /* Lora datarate & bandwidth, 16-19 useful chars */
  446. switch (LoraUp.sf) {
  447. case SF6:
  448. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF6", 12);
  449. buff_index += 12;
  450. break;
  451. case SF7:
  452. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF7", 12);
  453. buff_index += 12;
  454. break;
  455. case SF8:
  456. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF8", 12);
  457. buff_index += 12;
  458. break;
  459. case SF9:
  460. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF9", 12);
  461. buff_index += 12;
  462. break;
  463. case SF10:
  464. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF10", 13);
  465. buff_index += 13;
  466. break;
  467. case SF11:
  468. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF11", 13);
  469. buff_index += 13;
  470. break;
  471. case SF12:
  472. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF12", 13);
  473. buff_index += 13;
  474. break;
  475. default:
  476. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF?", 12);
  477. buff_index += 12;
  478. }
  479. memcpy((void *)(buff_up + buff_index), (void *)"BW125\"", 6); buff_index += 6;
  480. memcpy((void *)(buff_up + buff_index), (void *)",\"codr\":\"4/5\"", 13); buff_index += 13;
  481. buff_index += snprintf((char *)(buff_up + buff_index), TX_BUFF_SIZE-buff_index, ",\"lsnr\":%li", (long)SNR);
  482. buff_index += snprintf((char *)(buff_up + buff_index), TX_BUFF_SIZE-buff_index, ",\"rssi\":%d,\"size\":%u", prssi-rssicorr, messageLength);
  483. memcpy((void *)(buff_up + buff_index), (void *)",\"data\":\"", 9); buff_index += 9;
  484. // Use gBase64 library to fill in the data string
  485. encodedLen = base64_enc_len(messageLength); // max 341
  486. buff_index += base64_encode((char *)(buff_up + buff_index), (char *) message, messageLength);
  487. buff_up[buff_index] = '"';
  488. ++buff_index;
  489. // End of packet serialization
  490. buff_up[buff_index] = '}';
  491. ++buff_index;
  492. buff_up[buff_index] = ']';
  493. ++buff_index;
  494. // end of JSON datagram payload */
  495. buff_up[buff_index] = '}';
  496. ++buff_index;
  497. buff_up[buff_index] = 0; // add string terminator, for safety
  498. // When we have the node address and the SF, fill the listSeen array
  499. // with the required data. _MAXSEEN must be >0 for this to happen.
  500. // statr[0] contains the statistics of the node last seen.
  501. #if _MAXSEEN >= 1
  502. yield(); // MMM May not be necessary
  503. addSeen(listSeen, statr[0] );
  504. #endif
  505. #if _STAT_LOG == 1
  506. // Do statistics logging. In first version we might only
  507. // write part of the record to files, later more
  508. addLog( (unsigned char *)(buff_up), buff_index );
  509. #endif //_STAT_LOG
  510. # if _MONITOR>=1
  511. if (( debug>=2 ) && ( pdebug & P_RX )) { // debug: display JSON payload
  512. mPrint("RXPK:: "+String((char *)(buff_up + 12))+"R RXPK:: package length="+String(buff_index));
  513. }
  514. # endif
  515. return(buff_index);
  516. }// buildPacket
  517. // ----------------------------------------------------------------------------
  518. // UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP UP
  519. // Receive a LoRa package over the air, LoRa and deliver to server(s)
  520. //
  521. // Receive a LoRa message and fill the buff_up char buffer.
  522. // returns values:
  523. // - returns the length of string returned in buff_up
  524. // - returns -1 or -2 when no message arrived, depending connection.
  525. //
  526. // This is the "highlevel" read function called by loop(). The receive function
  527. // is started in the _stateMachine.ini file after CDONE event by interrupt
  528. // functions.
  529. // However, the actual read from the buffer (filled by interrupt) is done
  530. // by this function in the main loop() program.
  531. // ----------------------------------------------------------------------------
  532. int receivePacket()
  533. {
  534. uint8_t buff_up[TX_BUFF_SIZE]; // buffer to compose the upstream packet to backend server
  535. // Regular message received, see SX1276 spec table 18
  536. // Next statement could also be a "while" to combine several messages received
  537. // in one UDP message as the Semtech Gateway spec does allow this.
  538. // XXX Bit ... Not yet supported
  539. // Take the timestamp as soon as possible, to have accurate reception timestamp
  540. // TODO: tmst can jump if micros() overflow.
  541. uint32_t tmst = (uint32_t) micros(); // Only microseconds, rollover in 5X minutes
  542. // Handle the physical data read from LoraUp
  543. if (LoraUp.payLength > 0) {
  544. // externally received packet, so last parameter is false (==LoRa external)
  545. int build_index = buildPacket(tmst, buff_up, LoraUp, false);
  546. // REPEATER is a special function where we retransmit received
  547. // message on _ICHANN to _OCHANN.
  548. // Note:: For the moment _OCHANN is not allowed to be same as _ICHANN
  549. #if _REPEATER==1
  550. if (!sendLora(LoraUp.payLoad, LoraUp.payLength)) {
  551. return(-3);
  552. }
  553. #endif
  554. // This is one of the potential problem areas.
  555. // If possible, USB traffic should be left out of interrupt routines
  556. // rxpk PUSH_DATA received from node is rxpk (*2, par. 3.2)
  557. #ifdef _TTNSERVER
  558. if (!sendUdp(ttnServer, _TTNPORT, buff_up, build_index)) {
  559. return(-1); // received a message
  560. }
  561. yield();
  562. #endif
  563. // Use our own defined server or a second well kon server
  564. #ifdef _THINGSERVER
  565. if (!sendUdp(thingServer, _THINGPORT, buff_up, build_index)) {
  566. return(-2); // received a message
  567. }
  568. #endif
  569. #if _LOCALSERVER==1
  570. // Or special case, we do not use a local server to receive
  571. // and decode the server. We use buildPacket() to call decode
  572. // and use statr[0] information to store decoded message
  573. //DecodePayload: para 4.3.1 of Lora 1.1 Spec
  574. // MHDR
  575. // 1 byte Payload[0]
  576. // FHDR
  577. // 4 byte Dev Addr Payload[1-4]
  578. // 1 byte FCtrl Payload[5]
  579. // 2 bytes FCnt Payload[6-7]
  580. // = Optional 0 to 15 bytes Options
  581. // FPort
  582. // 1 bytes, 0x00 Payload[8]
  583. // ------------
  584. // +=9 BYTES HEADER
  585. //
  586. // FRMPayload
  587. // N bytes (Payload )
  588. //
  589. // 4 bytes MIC trailer
  590. int index=0;
  591. if ((index = inDecodes((char *)(LoraUp.payLoad+1))) >=0 ) {
  592. uint8_t DevAddr[4];
  593. DevAddr[0]= LoraUp.payLoad[4];
  594. DevAddr[1]= LoraUp.payLoad[3];
  595. DevAddr[2]= LoraUp.payLoad[2];
  596. DevAddr[3]= LoraUp.payLoad[1];
  597. //uint16_t frameCount=LoraUp.payLoad[7]*256 + LoraUp.payLoad[6];
  598. #if _DUSB>=1
  599. if (( debug>=1 ) && ( pdebug & P_RX )) {
  600. Serial.print(F("R receivePacket:: Ind="));
  601. Serial.print(index);
  602. Serial.print(F(", Len="));
  603. Serial.print(LoraUp.payLength);
  604. Serial.print(F(", A="));
  605. for (int i=0; i<4; i++) {
  606. if (DevAddr[i]<0x0F) Serial.print('0');
  607. Serial.print(DevAddr[i],HEX);
  608. //Serial.print(' ');
  609. }
  610. Serial.print(F(", Msg="));
  611. for (int i=0; (i<statr[0].datal) && (i<23); i++) {
  612. if (statr[0].data[i]<0x0F) Serial.print('0');
  613. Serial.print(statr[0].data[i],HEX);
  614. Serial.print(' ');
  615. }
  616. Serial.println();
  617. }
  618. #endif //DUSB
  619. }
  620. # if _MONITOR>=1
  621. else if (( debug>=2 ) && ( pdebug & P_RX )) {
  622. mPrint("receivePacket:: No Index");
  623. }
  624. # endif //_MONITOR
  625. #endif // _LOCALSERVER
  626. // Reset the message area
  627. LoraUp.payLength = 0;
  628. LoraUp.payLoad[0] = 0x00;
  629. return(build_index);
  630. }
  631. return(0); // failure no message read
  632. }//receivePacket