_txRx.ino 24 KB

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