_txRx.ino 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. // 1-channel LoRa Gateway for ESP8266
  2. // Copyright (c) 2016, 2017, 2018, 2019 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[ifreq].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[ifreq].dwnFreq);
  160. //Serial.print(F(", Request=")); Serial.print(freqs[ifreq].dwnFreq);
  161. Serial.print(F(" ->")); Serial.println(LoraDown.fff);
  162. Serial.print(F(" sf =")); Serial.print(atoi(datr+2)); Serial.print(F(" ->")); Serial.println(LoraDown.sfTx);
  163. Serial.print(F(" modu=")); Serial.println(modu);
  164. Serial.print(F(" powe=")); Serial.println(powe);
  165. Serial.print(F(" codr=")); Serial.println(codr);
  166. Serial.print(F(" ipol=")); Serial.println(ipol);
  167. Serial.println();
  168. }
  169. }
  170. # endif // _MONITOR
  171. if (LoraDown.payLength != psize) {
  172. # if _MONITOR>=1
  173. Serial.print(F("sendPacket:: WARNING payLength: "));
  174. Serial.print(LoraDown.payLength);
  175. Serial.print(F(", psize="));
  176. Serial.println(psize);
  177. if (debug>=2) Serial.flush();
  178. # endif //_MONITOR
  179. }
  180. # if _MONITOR>=1
  181. else if (( debug >= 2 ) && ( pdebug & P_TX )) {
  182. Serial.print(F("T Payload="));
  183. for (i=0; i<LoraDown.payLength; i++) {
  184. Serial.print(payLoad[i],HEX);
  185. Serial.print(':');
  186. }
  187. Serial.println();
  188. }
  189. # endif //_MONITOR
  190. // Update downstream statistics
  191. statc.msg_down++;
  192. switch(statr[0].ch) {
  193. case 0: statc.msg_down_0++; break;
  194. case 1: statc.msg_down_1++; break;
  195. case 2: statc.msg_down_2++; break;
  196. }
  197. # if _MONITOR>=1
  198. if (( debug>=2 ) && ( pdebug & P_TX )) {
  199. mPrint("T sendPacket:: fini OK");
  200. }
  201. # endif //_MONITOR
  202. // All data is in Payload and parameters and need to be transmitted.
  203. // The function is called in user-space
  204. _state = S_TX; // _state set to transmit
  205. # if _MONITOR>=1
  206. if ((debug>=1) && ( pdebug & P_TX)) {
  207. mPrint("sendPacket:: STRICT=" + String(_STRICT_1CH) );
  208. }
  209. # endif //_MONITOR
  210. return 1;
  211. }//sendPacket DOWN
  212. // ----------------------------------------------------------------------------
  213. // 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
  214. // Based on the information read from the LoRa transceiver (or fake message)
  215. // build a gateway message to send upstream (to the user somewhere on the web).
  216. //
  217. // parameters:
  218. // tmst: Timestamp to include in the upstream message
  219. // buff_up: The buffer that is generated for upstream
  220. // LoraUP: Structure describing the message received from device
  221. // internal: Boolean value to indicate whether the local sensor is processed
  222. //
  223. // returns:
  224. // buff_index:
  225. // ----------------------------------------------------------------------------
  226. int buildPacket(uint32_t tmst, uint8_t *buff_up, struct LoraUp LoraUp, bool internal)
  227. {
  228. long SNR;
  229. int rssicorr;
  230. int prssi; // packet rssi
  231. char cfreq[12] = {0}; // Character array to hold freq in MHz
  232. //lastTmst = tmst; // Following/according to spec
  233. int buff_index=0;
  234. char b64[256];
  235. uint8_t *message = LoraUp.payLoad;
  236. char messageLength = LoraUp.payLength;
  237. #if _CHECK_MIC==1
  238. unsigned char NwkSKey[16] = _NWKSKEY;
  239. checkMic(message, messageLength, NwkSKey);
  240. #endif // _CHECK_MIC
  241. // Read SNR and RSSI from the register. Note: Not for internal sensors!
  242. // For internal sensor we fake these values as we cannot read a register
  243. if (internal) {
  244. SNR = 12;
  245. prssi = 50;
  246. rssicorr = 157;
  247. }
  248. else {
  249. SNR = LoraUp.snr;
  250. prssi = LoraUp.prssi; // read register 0x1A, packet rssi
  251. rssicorr = LoraUp.rssicorr;
  252. }
  253. #if _STATISTICS >= 1
  254. // Receive statistics, move old statistics down 1 position
  255. // and fill the new top line with the latest received sensor values.
  256. // This works fine for the sensor, EXCEPT when we decode data for _LOCALSERVER
  257. //
  258. for (int m=( MAX_STAT -1); m>0; m--) statr[m]=statr[m-1];
  259. // From now on we can fill statr[0] with sensor data
  260. #if _LOCALSERVER==1
  261. statr[0].datal=0;
  262. int index;
  263. if ((index = inDecodes((char *)(LoraUp.payLoad+1))) >=0 ) {
  264. uint16_t frameCount=LoraUp.payLoad[7]*256 + LoraUp.payLoad[6];
  265. for (int k=0; (k<LoraUp.payLength) && (k<23); k++) {
  266. statr[0].data[k] = LoraUp.payLoad[k+9];
  267. };
  268. // XXX Check that k<23 when leaving the for loop
  269. // XXX or we can not display in statr
  270. uint8_t DevAddr[4];
  271. DevAddr[0]= LoraUp.payLoad[4];
  272. DevAddr[1]= LoraUp.payLoad[3];
  273. DevAddr[2]= LoraUp.payLoad[2];
  274. DevAddr[3]= LoraUp.payLoad[1];
  275. statr[0].datal = encodePacket((uint8_t *)(statr[0].data),
  276. LoraUp.payLength-9-4,
  277. (uint16_t)frameCount,
  278. DevAddr,
  279. decodes[index].appKey,
  280. 0);
  281. }
  282. #endif //_LOCALSERVER
  283. statr[0].tmst = now();
  284. statr[0].ch= ifreq;
  285. statr[0].prssi = prssi - rssicorr;
  286. statr[0].sf = LoraUp.sf;
  287. # if RSSI==1
  288. statr[0].rssi = _rssi - rssicorr;
  289. # endif // RSII
  290. # if _DUSB>=2
  291. if (debug>=0) {
  292. if ((message[4] != 0x26) || (message[1]==0x99)) {
  293. Serial.print(F("addr="));
  294. for (int i=messageLength; i>0; i--) {
  295. if (message[i]<0x10) Serial.print('0');
  296. Serial.print(message[i],HEX);
  297. Serial.print(' ');
  298. }
  299. Serial.println();
  300. }
  301. }
  302. # endif //DUSB
  303. statr[0].node = ( message[1]<<24 | message[2]<<16 | message[3]<<8 | message[4] );
  304. #if _STATISTICS >= 2
  305. // Fill in the statistics that we will also need for the GUI.
  306. // So
  307. switch (statr[0].sf) {
  308. case SF7: statc.sf7++; break;
  309. case SF8: statc.sf8++; break;
  310. case SF9: statc.sf9++; break;
  311. case SF10: statc.sf10++; break;
  312. case SF11: statc.sf11++; break;
  313. case SF12: statc.sf12++; break;
  314. }
  315. #endif // _STATISTICS >= 2
  316. #if _STATISTICS >= 3
  317. if (statr[0].ch == 0) {
  318. statc.msg_ttl_0++; // Increase #message received channel 0
  319. switch (statr[0].sf) {
  320. case SF7: statc.sf7_0++; break;
  321. case SF8: statc.sf8_0++; break;
  322. case SF9: statc.sf9_0++; break;
  323. case SF10: statc.sf10_0++; break;
  324. case SF11: statc.sf11_0++; break;
  325. case SF12: statc.sf12_0++; break;
  326. }
  327. }
  328. else
  329. if (statr[0].ch == 1) {
  330. statc.msg_ttl_1++;
  331. switch (statr[0].sf) {
  332. case SF7: statc.sf7_1++; break;
  333. case SF8: statc.sf8_1++; break;
  334. case SF9: statc.sf9_1++; break;
  335. case SF10: statc.sf10_1++; break;
  336. case SF11: statc.sf11_1++; break;
  337. case SF12: statc.sf12_1++; break;
  338. }
  339. }
  340. else
  341. if (statr[0].ch == 2) {
  342. statc.msg_ttl_2++;
  343. switch (statr[0].sf) {
  344. case SF7: statc.sf7_2++; break;
  345. case SF8: statc.sf8_2++; break;
  346. case SF9: statc.sf9_2++; break;
  347. case SF10: statc.sf10_2++; break;
  348. case SF11: statc.sf11_2++; break;
  349. case SF12: statc.sf12_2++; break;
  350. }
  351. }
  352. #endif //_STATISTICS >= 3
  353. #endif //_STATISTICS >= 2
  354. #if _DUSB>=1
  355. if (( debug>=2 ) && ( pdebug & P_RADIO )){
  356. Serial.print(F("R buildPacket:: pRSSI="));
  357. Serial.print(prssi-rssicorr);
  358. Serial.print(F(" RSSI: "));
  359. Serial.print(_rssi - rssicorr);
  360. Serial.print(F(" SNR: "));
  361. Serial.print(SNR);
  362. Serial.print(F(" Length: "));
  363. Serial.print((int)messageLength);
  364. Serial.print(F(" -> "));
  365. int i;
  366. for (i=0; i< messageLength; i++) {
  367. Serial.print(message[i],HEX);
  368. Serial.print(' ');
  369. }
  370. Serial.println();
  371. yield();
  372. }
  373. #endif // _DUSB
  374. // Show received message status on OLED display
  375. #if OLED>=1
  376. char timBuff[20];
  377. sprintf(timBuff, "%02i:%02i:%02i", hour(), minute(), second());
  378. display.clear();
  379. display.setFont(ArialMT_Plain_16);
  380. display.setTextAlignment(TEXT_ALIGN_LEFT);
  381. // msg_oLED(timBuff, prssi-rssicorr, SNR, message)
  382. display.drawString(0, 0, "Time: " );
  383. display.drawString(40, 0, timBuff);
  384. display.drawString(0, 16, "RSSI: " );
  385. display.drawString(40, 16, String(prssi-rssicorr));
  386. display.drawString(70, 16, ",SNR: " );
  387. display.drawString(110, 16, String(SNR) );
  388. display.drawString(0, 32, "Addr: " );
  389. if (message[4] < 0x10) display.drawString( 40, 32, "0"+String(message[4], HEX)); else display.drawString( 40, 32, String(message[4], HEX));
  390. if (message[3] < 0x10) display.drawString( 61, 32, "0"+String(message[3], HEX)); else display.drawString( 61, 32, String(message[3], HEX));
  391. if (message[2] < 0x10) display.drawString( 82, 32, "0"+String(message[2], HEX)); else display.drawString( 82, 32, String(message[2], HEX));
  392. if (message[1] < 0x10) display.drawString(103, 32, "0"+String(message[1], HEX)); else display.drawString(103, 32, String(message[1], HEX));
  393. display.drawString(0, 48, "LEN: " );
  394. display.drawString(40, 48, String((int)messageLength) );
  395. display.display();
  396. //yield();
  397. #endif //OLED>=1
  398. int j;
  399. // XXX Base64 library is nopad. So we may have to add padding characters until
  400. // message Length is multiple of 4!
  401. // Encode message with messageLength into b64
  402. int encodedLen = base64_enc_len(messageLength); // max 341
  403. # if _MONITOR>=1
  404. if ((debug>=1) && (encodedLen>255) && ( pdebug & P_RADIO )) {
  405. mPrint("R buildPacket:: b64 err, len=" + String(encodedLen));
  406. return(-1);
  407. }
  408. # endif // _MONITOR
  409. base64_encode(b64, (char *) message, messageLength);// max 341
  410. // start composing datagram with the header
  411. uint8_t token_h = (uint8_t)rand(); // random token
  412. uint8_t token_l = (uint8_t)rand(); // random token
  413. // pre-fill the data buffer with fixed fields
  414. buff_up[0] = PROTOCOL_VERSION; // 0x01 still
  415. buff_up[1] = token_h;
  416. buff_up[2] = token_l;
  417. buff_up[3] = PKT_PUSH_DATA; // 0x00
  418. // READ MAC ADDRESS OF ESP8266, and insert 0xFF 0xFF in the middle
  419. buff_up[4] = MAC_array[0];
  420. buff_up[5] = MAC_array[1];
  421. buff_up[6] = MAC_array[2];
  422. buff_up[7] = 0xFF;
  423. buff_up[8] = 0xFF;
  424. buff_up[9] = MAC_array[3];
  425. buff_up[10] = MAC_array[4];
  426. buff_up[11] = MAC_array[5];
  427. buff_index = 12; // 12-byte binary (!) header
  428. // start of JSON structure that will make payload
  429. memcpy((void *)(buff_up + buff_index), (void *)"{\"rxpk\":[", 9);
  430. buff_index += 9;
  431. buff_up[buff_index] = '{';
  432. ++buff_index;
  433. j = snprintf((char *)(buff_up + buff_index), TX_BUFF_SIZE-buff_index, "\"tmst\":%u", tmst);
  434. # if _MONITOR>=1
  435. if ((j<0) && ( debug>=1 ) && ( pdebug & P_RADIO )) {
  436. mPrint("buildPacket:: Error ");
  437. }
  438. # endif //_MONITOR
  439. buff_index += j;
  440. ftoa((double)freqs[ifreq].upFreq / 1000000, cfreq, 6); // XXX This can be done better
  441. j = snprintf((char *)(buff_up + buff_index), TX_BUFF_SIZE-buff_index, ",\"chan\":%1u,\"rfch\":%1u,\"freq\":%s", 0, 0, cfreq);
  442. buff_index += j;
  443. memcpy((void *)(buff_up + buff_index), (void *)",\"stat\":1", 9);
  444. buff_index += 9;
  445. memcpy((void *)(buff_up + buff_index), (void *)",\"modu\":\"LORA\"", 14);
  446. buff_index += 14;
  447. /* Lora datarate & bandwidth, 16-19 useful chars */
  448. switch (LoraUp.sf) {
  449. case SF6:
  450. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF6", 12);
  451. buff_index += 12;
  452. break;
  453. case SF7:
  454. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF7", 12);
  455. buff_index += 12;
  456. break;
  457. case SF8:
  458. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF8", 12);
  459. buff_index += 12;
  460. break;
  461. case SF9:
  462. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF9", 12);
  463. buff_index += 12;
  464. break;
  465. case SF10:
  466. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF10", 13);
  467. buff_index += 13;
  468. break;
  469. case SF11:
  470. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF11", 13);
  471. buff_index += 13;
  472. break;
  473. case SF12:
  474. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF12", 13);
  475. buff_index += 13;
  476. break;
  477. default:
  478. memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF?", 12);
  479. buff_index += 12;
  480. }
  481. memcpy((void *)(buff_up + buff_index), (void *)"BW125\"", 6);
  482. buff_index += 6;
  483. memcpy((void *)(buff_up + buff_index), (void *)",\"codr\":\"4/5\"", 13);
  484. buff_index += 13;
  485. j = snprintf((char *)(buff_up + buff_index), TX_BUFF_SIZE-buff_index, ",\"lsnr\":%li", SNR);
  486. buff_index += j;
  487. j = snprintf((char *)(buff_up + buff_index), TX_BUFF_SIZE-buff_index, ",\"rssi\":%d,\"size\":%u", prssi-rssicorr, messageLength);
  488. buff_index += j;
  489. memcpy((void *)(buff_up + buff_index), (void *)",\"data\":\"", 9);
  490. buff_index += 9;
  491. // Use gBase64 library to fill in the data string
  492. encodedLen = base64_enc_len(messageLength); // max 341
  493. j = base64_encode((char *)(buff_up + buff_index), (char *) message, messageLength);
  494. buff_index += j;
  495. buff_up[buff_index] = '"';
  496. ++buff_index;
  497. // End of packet serialization
  498. buff_up[buff_index] = '}';
  499. ++buff_index;
  500. buff_up[buff_index] = ']';
  501. ++buff_index;
  502. // end of JSON datagram payload */
  503. buff_up[buff_index] = '}';
  504. ++buff_index;
  505. buff_up[buff_index] = 0; // add string terminator, for safety
  506. #if STAT_LOG == 1
  507. // Do statistics logging. In first version we might only
  508. // write part of the record to files, later more
  509. addLog( (unsigned char *)(buff_up), buff_index );
  510. #endif
  511. // When we have the node address and the SF, fill the array
  512. // listSeen with the required data. SEENMAX must be >0 for this to happen.
  513. #if _SEENMAX >= 1
  514. addSeen(listSeen, statr[0] );
  515. #endif
  516. # if _MONITOR>=1
  517. if (( debug>=2 ) && ( pdebug & P_RX )) { // debug: display JSON payload
  518. mPrint("RXPK:: "+String((char *)(buff_up + 12))+"R RXPK:: package length="+String(buff_index));
  519. }
  520. # endif
  521. return(buff_index);
  522. }// buildPacket
  523. // ----------------------------------------------------------------------------
  524. // 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
  525. // Receive a LoRa package over the air, LoRa and deliver to server(s)
  526. //
  527. // Receive a LoRa message and fill the buff_up char buffer.
  528. // returns values:
  529. // - returns the length of string returned in buff_up
  530. // - returns -1 or -2 when no message arrived, depending connection.
  531. //
  532. // This is the "highlevel" read function called by loop(). The receive function
  533. // is started in the _stateMachine.ini file after CDONE event by interrupt
  534. // functions.
  535. // However, the actual read from the buffer (filled by interrupt) is done
  536. // by this function in the main loop() program.
  537. // ----------------------------------------------------------------------------
  538. int receivePacket()
  539. {
  540. uint8_t buff_up[TX_BUFF_SIZE]; // buffer to compose the upstream packet to backend server
  541. long SNR;
  542. uint8_t message[128] = { 0x00 }; // MSG size is 128 bytes for rx
  543. uint8_t messageLength = 0;
  544. // Regular message received, see SX1276 spec table 18
  545. // Next statement could also be a "while" to combine several messages received
  546. // in one UDP message as the Semtech Gateway spec does allow this.
  547. // XXX Not yet supported
  548. // Take the timestamp as soon as possible, to have accurate reception timestamp
  549. // TODO: tmst can jump if micros() overflow.
  550. uint32_t tmst = (uint32_t) micros(); // Only microseconds, rollover in 5X minutes
  551. //lastTmst = tmst; // Following/according to spec
  552. // Handle the physical data read from LoraUp
  553. if (LoraUp.payLength > 0) {
  554. // externally received packet, so last parameter is false (==LoRa external)
  555. int build_index = buildPacket(tmst, buff_up, LoraUp, false);
  556. // REPEATER is a special function where we retransmit received
  557. // message on _ICHANN to _OCHANN.
  558. // Note:: For the moment _OCHANN is not allowed to be same as _ICHANN
  559. #if _REPEATER==1
  560. if (!sendLora(LoraUp.payLoad, LoraUp.payLength)) {
  561. return(-3);
  562. }
  563. #endif
  564. // This is one of the potential problem areas.
  565. // If possible, USB traffic should be left out of interrupt routines
  566. // rxpk PUSH_DATA received from node is rxpk (*2, par. 3.2)
  567. #ifdef _TTNSERVER
  568. if (!sendUdp(ttnServer, _TTNPORT, buff_up, build_index)) {
  569. return(-1); // received a message
  570. }
  571. yield();
  572. #endif
  573. // Use our own defined server or a second well kon server
  574. #ifdef _THINGSERVER
  575. if (!sendUdp(thingServer, _THINGPORT, buff_up, build_index)) {
  576. return(-2); // received a message
  577. }
  578. #endif
  579. #if _LOCALSERVER==1
  580. // Or special case, we do not use a local server to receive
  581. // and decode the server. We use buildPacket() to call decode
  582. // and use statr[0] information to store decoded message
  583. //DecodePayload: para 4.3.1 of Lora 1.1 Spec
  584. // MHDR
  585. // 1 byte Payload[0]
  586. // FHDR
  587. // 4 byte Dev Addr Payload[1-4]
  588. // 1 byte FCtrl Payload[5]
  589. // 2 bytes FCnt Payload[6-7]
  590. // = Optional 0 to 15 bytes Options
  591. // FPort
  592. // 1 bytes, 0x00 Payload[8]
  593. // ------------
  594. // +=9 BYTES HEADER
  595. //
  596. // FRMPayload
  597. // N bytes (Payload )
  598. //
  599. // 4 bytes MIC trailer
  600. int index=0;
  601. if ((index = inDecodes((char *)(LoraUp.payLoad+1))) >=0 ) {
  602. uint8_t DevAddr[4];
  603. DevAddr[0]= LoraUp.payLoad[4];
  604. DevAddr[1]= LoraUp.payLoad[3];
  605. DevAddr[2]= LoraUp.payLoad[2];
  606. DevAddr[3]= LoraUp.payLoad[1];
  607. uint16_t frameCount=LoraUp.payLoad[7]*256 + LoraUp.payLoad[6];
  608. #if _DUSB>=1
  609. if (( debug>=1 ) && ( pdebug & P_RX )) {
  610. Serial.print(F("R receivePacket:: Ind="));
  611. Serial.print(index);
  612. Serial.print(F(", Len="));
  613. Serial.print(LoraUp.payLength);
  614. Serial.print(F(", A="));
  615. for (int i=0; i<4; i++) {
  616. if (DevAddr[i]<0x0F) Serial.print('0');
  617. Serial.print(DevAddr[i],HEX);
  618. //Serial.print(' ');
  619. }
  620. Serial.print(F(", Msg="));
  621. for (int i=0; (i<statr[0].datal) && (i<23); i++) {
  622. if (statr[0].data[i]<0x0F) Serial.print('0');
  623. Serial.print(statr[0].data[i],HEX);
  624. Serial.print(' ');
  625. }
  626. Serial.println();
  627. }
  628. #endif //DUSB
  629. }
  630. # if _MONITOR>=1
  631. else if (( debug>=2 ) && ( pdebug & P_RX )) {
  632. mPrint("receivePacket:: No Index");
  633. }
  634. # endif //DUSB
  635. #endif // _LOCALSERVER
  636. // Reset the message area
  637. LoraUp.payLength = 0;
  638. LoraUp.payLoad[0] = 0x00;
  639. return(build_index);
  640. }
  641. return(0); // failure no message read
  642. }//receivePacket