_sensor.ino 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. // sensor.ino; 1-channel LoRa Gateway for ESP8266
  2. // Copyright (c) 2016, 2017, 2018, 2019 Maarten Westenberg
  3. //
  4. // All rights reserved. This program and the accompanying materials
  5. // are made available under the terms of the MIT License
  6. // which accompanies this distribution, and is available at
  7. // https://opensource.org/licenses/mit-license.php
  8. //
  9. // NO WARRANTY OF ANY KIND IS PROVIDED
  10. //
  11. // Author: Maarten Westenberg (mw12554@hotmail.com)
  12. //
  13. // This file contains code for using the single channel gateway also as a sensor node.
  14. // Please specify the DevAddr and the AppSKey below (and on your LoRa backend).
  15. // Also you will have to choose what sensors to forward to your application.
  16. //
  17. // Note: disable sensors not used in configGway.h
  18. // - The GPS is included on TTGO T-Beam ESP32 boards by default.
  19. // - The battery sensor works by connecting the VCC pin to A0 analog port
  20. // ============================================================================
  21. #if _GATEWAYNODE==1
  22. #include "LoRaCode.h"
  23. unsigned char DevAddr[4] = _DEVADDR ; // see configGway.h
  24. // Only used by GPS sensor code
  25. #if _GPS==1
  26. // ----------------------------------------------------------------------------
  27. // Smartdelay is a function to delay processing but in the loop get info
  28. // from the GPS device
  29. // ----------------------------------------------------------------------------
  30. static void smartDelay(uint32_t ms)
  31. {
  32. uint32_t start = millis();
  33. do
  34. {
  35. while (sGps.available()) {
  36. gps.encode(sGps.read());
  37. }
  38. yield(); // MMM Maybe avoid crashes
  39. } while (millis() - start < ms);
  40. }
  41. #endif //_GPS
  42. // ----------------------------------------------------------------------------
  43. // LoRaSensors() is a function that puts sensor values in the MACPayload and
  44. // sends these values up to the server. For the server it is impossible to know
  45. // whther or not the message comes from a LoRa node or from the gateway.
  46. //
  47. // The example code below adds a battery value in lCode (encoding protocol) but
  48. // of-course you can add any byte string you wish
  49. //
  50. // Parameters:
  51. // - buf: contains the buffer to put the sensor values in (max==xx);
  52. // Returns:
  53. // - The amount of sensor characters put in the buffer
  54. //
  55. // NOTE: The code in LoRaSensors() is provided as an example only.
  56. // The amount of sensor values as well as their message layout may differ
  57. // for each implementation.
  58. // Also, the message format used by this gateway is LoraCode, a message format
  59. // developed by me for sensor values. Each value is uniquely coded with an
  60. // id and a value, and the total message contains its length (less than 64 bytes)
  61. // and a parity value in byte[0] bit 7.
  62. // ----------------------------------------------------------------------------
  63. static int LoRaSensors(uint8_t *buf) {
  64. # if defined(_LCODE)
  65. # if defined(_RAW)
  66. # error "Only define ONE encoding in configNode.h, _LOCDE or _RAW"
  67. # endif
  68. String response="";
  69. uint8_t tchars = 1;
  70. buf[0] = 0x86; // 134; User code <lCode + len==3 + Parity
  71. # if _MONITOR>=1
  72. if (debug>=0) {
  73. response += "LoRaSensors:: ";
  74. }
  75. # endif //_MONITOR
  76. // GPS sensor is the second server we check for
  77. # if _GPS==1
  78. smartDelay(10); // Use GPS to return fast!
  79. if (millis() > 5000 && gps.charsProcessed() < 10) {
  80. # if _MONITOR>=1
  81. mPrint("ERROR: No GPS data received: check wiring");
  82. # endif //_MONITOR
  83. return(0);
  84. }
  85. // Assuming we have a value, put it in the buf
  86. // The layout of this message is specific to the user,
  87. // so adapt as needed.
  88. // Use lcode to code messages to server
  89. # if _MONITOR>=1
  90. if ((debug>=1) && (pdebug & P_MAIN)){
  91. response += ", Gps lcode:: lat="+String(gps.location.lat())+", lng="+String(gps.location.lng())+", alt="+String(gps.altitude.feet()/3.2808)+", sats="+String(gps.satellites.value());
  92. }
  93. # endif //_MONITOR
  94. tchars += lcode.eGpsL(gps.location.lat(), gps.location.lng(), gps.altitude.value(), gps.satellites.value(), buf + tchars);
  95. # endif //_GPS
  96. # if _BATTERY==1
  97. # if defined(ARDUINO_ARCH_ESP8266) || defined(ESP32)
  98. // For ESP there is no standard battery library
  99. // What we do is to measure GPIO35 pin which has a 100K voltage divider
  100. pinMode(35, INPUT);
  101. float volts=3.3 * analogRead(35) / 4095 * 2; // T_Beam connects to GPIO35
  102. # else
  103. // For ESP8266 no sensor defined
  104. float volts=0;
  105. # endif // ARDUINO_ARCH_ESP8266 || ESP32
  106. # if _MONITOR>=1
  107. if ((debug>=1) && (pdebug & P_MAIN)){
  108. response += "Battery lcode="+String(volts);
  109. }
  110. # endif //_MONITOR
  111. tchars += lcode.eBattery(volts, buf + tchars);
  112. # endif //_BATTERY
  113. // If all sensor data is encoded, we encode the buffer
  114. lcode.eMsg(buf, tchars); // Fill byte 0 with bytecount and Parity
  115. # if _MONITOR>=1
  116. mPrint(response);
  117. # endif //_MONITOR
  118. // Second encoding option is RAW format.
  119. //
  120. // We do not use the lcode format but write all the values to the output
  121. // buffer and we need to get them in sequence out off the buffer.
  122. # elif defined(_RAW)
  123. uint8_t tchars = 0;
  124. // GPS sensor is the second server we check for
  125. # if _GPS==1
  126. smartDelay(10);
  127. if (millis() > 5000 && gps.charsProcessed() < 10) {
  128. # if _MONITOR>=1
  129. mPrint("ERROR: No GPS data received: check wiring");
  130. # endif //_MONITOR
  131. return(0);
  132. }
  133. // Raw coding of LoRa messages to server so add the GPS data raw to the string
  134. # if _MONITOR>=1
  135. if ((debug>=1) && ( pdebug & P_MAIN )){
  136. mPrint("Gps raw:: lat="+String(gps.location.lat())+", lng="+String(gps.location.lng())+", alt="+String(gps.altitude.feet()/3.2808)+", sats="+String(gps.satellites.value()) );
  137. //mPrint("Gps raw:: sizeof double="+String(sizeof(double)) );
  138. }
  139. # endif // _MONITOR
  140. // Length of lat and lng is double
  141. double lat = gps.location.lat();
  142. double lng = gps.location.lng();
  143. double alt = gps.altitude.feet() / 3.2808;
  144. memcpy((buf+tchars), &lat, sizeof(double)); tchars += sizeof(double);
  145. memcpy((buf+tchars), &lng, sizeof(double)); tchars += sizeof(double);
  146. memcpy((buf+tchars), &alt, sizeof(double)); tchars += sizeof(double);
  147. # endif //_GPS
  148. # if _BATTERY==1
  149. # if defined(ARDUINO_ARCH_ESP8266) || defined(ESP32)
  150. // For ESP there is no standard battery library
  151. // What we do is to measure GPIO35 pin which has a 100K voltage divider
  152. pinMode(35, INPUT);
  153. float volts=3.3 * analogRead(35) / 4095 * 2; // T_Beam connects to GPIO35
  154. # else
  155. // For ESP8266 no sensor defined
  156. float volts=0;
  157. # endif // ARDUINO_ARCH_ESP8266 || ESP32
  158. memcpy((buf+tchars), &volts, sizeof(float)); tchars += sizeof(float);
  159. # if _MONITOR>=1
  160. if ((debug>=1) && ( pdebug & P_MAIN )){
  161. mPrint("Battery raw="+String(volts));
  162. }
  163. # endif //_MONITOR
  164. # endif //_BATTERY
  165. // If neither _LCODE or _RAW is defined this is an error
  166. # else
  167. # error "Please define an encoding format as in configNode.h"
  168. # endif
  169. // GENERAL part
  170. # if _DUSB>=1 && _GPS==1
  171. if (( debug>=2 ) && ( pdebug & P_MAIN )) {
  172. Serial.print("GPS sensor");
  173. Serial.print("\tLatitude : ");
  174. Serial.println(gps.location.lat(), 5);
  175. Serial.print("\tLongitude : ");
  176. Serial.println(gps.location.lng(), 4);
  177. Serial.print("\tSatellites: ");
  178. Serial.println(gps.satellites.value());
  179. Serial.print("\tAltitude : ");
  180. Serial.print(gps.altitude.feet() / 3.2808);
  181. Serial.println("M");
  182. Serial.print("\tTime : ");
  183. Serial.print(gps.time.hour());
  184. Serial.print(":");
  185. Serial.print(gps.time.minute());
  186. Serial.print(":");
  187. Serial.println(gps.time.second());
  188. }
  189. # endif //_DUSB _GPS
  190. return(tchars); // return the number of bytes added to payload
  191. }
  192. // ----------------------------------------------------------------------------
  193. // XOR()
  194. // perform x-or function for buffer and key
  195. // Since we do this ONLY for keys and X, Y we know that we need to XOR 16 bytes.
  196. //
  197. // ----------------------------------------------------------------------------
  198. static void mXor(uint8_t *buf, uint8_t *key) {
  199. for (uint8_t i = 0; i < 16; ++i) buf[i] ^= key[i];
  200. }
  201. // ----------------------------------------------------------------------------
  202. // SHIFT-LEFT
  203. // Shift the buffer buf left one bit
  204. // Parameters:
  205. // - buf: An array of uint8_t bytes
  206. // - len: Length of the array in bytes
  207. // ----------------------------------------------------------------------------
  208. static void shift_left(uint8_t * buf, uint8_t len) {
  209. while (len--) {
  210. uint8_t next = len ? buf[1] : 0; // len 0 to 15
  211. uint8_t val = (*buf << 1);
  212. if (next & 0x80) val |= 0x01;
  213. *buf++ = val;
  214. }
  215. }
  216. // ----------------------------------------------------------------------------
  217. // generate_subkey
  218. // RFC 4493, para 2.3
  219. // ----------------------------------------------------------------------------
  220. static void generate_subkey(uint8_t *key, uint8_t *k1, uint8_t *k2) {
  221. memset(k1, 0, 16); // Fill subkey1 with 0x00
  222. // Step 1: Assume k1 is an all zero block
  223. AES_Encrypt(k1,key);
  224. // Step 2: Analyse outcome of Encrypt operation (in k1), generate k1
  225. if (k1[0] & 0x80) {
  226. shift_left(k1,16);
  227. k1[15] ^= 0x87;
  228. }
  229. else {
  230. shift_left(k1,16);
  231. }
  232. // Step 3: Generate k2
  233. for (int i=0; i<16; i++) k2[i]=k1[i];
  234. if (k1[0] & 0x80) { // use k1(==k2) according rfc
  235. shift_left(k2,16);
  236. k2[15] ^= 0x87;
  237. }
  238. else {
  239. shift_left(k2,16);
  240. }
  241. // step 4: Done, return k1 and k2
  242. return;
  243. }
  244. // ----------------------------------------------------------------------------
  245. // MICPACKET()
  246. // Provide a valid MIC 4-byte code (par 2.4 of spec, RFC4493)
  247. // see also https://tools.ietf.org/html/rfc4493
  248. //
  249. // Although our own handler may choose not to interpret the last 4 (MIC) bytes
  250. // of a PHYSPAYLOAD physical payload message of in internal sensor,
  251. // The official TTN (and other) backends will interpret the complete message and
  252. // conclude that the generated message is bogus.
  253. // So we will really simulate internal messages coming from the -1ch gateway
  254. // to come from a real sensor and append 4 MIC bytes to every message that are
  255. // perfectly legimate
  256. // Parameters:
  257. // - data: uint8_t array of bytes = ( MHDR | FHDR | FPort | FRMPayload )
  258. // - len: 8=bit length of data, normally less than 64 bytes
  259. // - FrameCount: 16-bit framecounter
  260. // - dir: 0=up, 1=down
  261. //
  262. // B0 = ( 0x49 | 4 x 0x00 | Dir | 4 x DevAddr | 4 x FCnt | 0x00 | len )
  263. // MIC is cmac [0:3] of ( aes128_cmac(NwkSKey, B0 | Data )
  264. //
  265. // ----------------------------------------------------------------------------
  266. uint8_t micPacket(uint8_t *data, uint8_t len, uint16_t FrameCount, uint8_t * NwkSKey, uint8_t dir) {
  267. //uint8_t NwkSKey[16] = _NWKSKEY;
  268. uint8_t Block_B[16];
  269. uint8_t X[16];
  270. uint8_t Y[16];
  271. // ------------------------------------
  272. // build the B block used by the MIC process
  273. Block_B[0]= 0x49; // 1 byte MIC code
  274. Block_B[1]= 0x00; // 4 byte 0x00
  275. Block_B[2]= 0x00;
  276. Block_B[3]= 0x00;
  277. Block_B[4]= 0x00;
  278. Block_B[5]= dir; // 1 byte Direction
  279. Block_B[6]= DevAddr[3]; // 4 byte DevAddr
  280. Block_B[7]= DevAddr[2];
  281. Block_B[8]= DevAddr[1];
  282. Block_B[9]= DevAddr[0];
  283. Block_B[10]= (FrameCount & 0x00FF); // 4 byte FCNT
  284. Block_B[11]= ((FrameCount >> 8) & 0x00FF);
  285. Block_B[12]= 0x00; // Frame counter upper Bytes
  286. Block_B[13]= 0x00; // These are not used so are 0
  287. Block_B[14]= 0x00; // 1 byte 0x00
  288. Block_B[15]= len; // 1 byte len
  289. // ------------------------------------
  290. // Step 1: Generate the subkeys
  291. //
  292. uint8_t k1[16];
  293. uint8_t k2[16];
  294. generate_subkey(NwkSKey, k1, k2);
  295. // ------------------------------------
  296. // Copy the data to a new buffer which is prepended with Block B0
  297. //
  298. uint8_t micBuf[len+16]; // B0 | data
  299. for (uint8_t i=0; i<16; i++) micBuf[i]=Block_B[i];
  300. for (uint8_t i=0; i<len; i++) micBuf[i+16]=data[i];
  301. // ------------------------------------
  302. // Step 2: Calculate the number of blocks for CMAC
  303. //
  304. uint8_t numBlocks = len/16 + 1; // Compensate for B0 block
  305. if ((len % 16)!=0) numBlocks++; // If we have only a part block, take it all
  306. // ------------------------------------
  307. // Step 3: Calculate padding is necessary
  308. //
  309. uint8_t restBits = len%16; // if numBlocks is not a multiple of 16 bytes
  310. // ------------------------------------
  311. // Step 5: Make a buffer of zeros
  312. //
  313. memset(X, 0, 16);
  314. // ------------------------------------
  315. // Step 6: Do the actual encoding according to RFC
  316. //
  317. for(uint8_t i= 0x0; i < (numBlocks - 1); i++) {
  318. for (uint8_t j=0; j<16; j++) Y[j] = micBuf[(i*16)+j];
  319. mXor(Y, X);
  320. AES_Encrypt(Y, NwkSKey);
  321. for (uint8_t j=0; j<16; j++) X[j] = Y[j];
  322. }
  323. // ------------------------------------
  324. // Step 4: If there is a rest Block, padd it
  325. // Last block. We move step 4 to the end as we need Y
  326. // to compute the last block
  327. //
  328. if (restBits) {
  329. for (uint8_t i=0; i<16; i++) {
  330. if (i< restBits) Y[i] = micBuf[((numBlocks-1)*16)+i];
  331. if (i==restBits) Y[i] = 0x80;
  332. if (i> restBits) Y[i] = 0x00;
  333. }
  334. mXor(Y, k2);
  335. }
  336. else {
  337. for (uint8_t i=0; i<16; i++) {
  338. Y[i] = micBuf[((numBlocks-1)*16)+i];
  339. }
  340. mXor(Y, k1);
  341. }
  342. mXor(Y, X);
  343. AES_Encrypt(Y,NwkSKey);
  344. // ------------------------------------
  345. // Step 7: done, return the MIC size.
  346. // Only 4 bytes are returned (32 bits), which is less than the RFC recommends.
  347. // We return by appending 4 bytes to data, so there must be space in data array.
  348. //
  349. data[len+0]=Y[0];
  350. data[len+1]=Y[1];
  351. data[len+2]=Y[2];
  352. data[len+3]=Y[3];
  353. yield(); // MMM to avoid crashes
  354. return 4;
  355. }
  356. #if _CHECK_MIC==1
  357. // ----------------------------------------------------------------------------
  358. // CHECKMIC
  359. // Function to check the MIC computed for existing messages and for new messages
  360. // Parameters:
  361. // - buf: LoRa buffer to check in bytes, last 4 bytes contain the MIC
  362. // - len: Length of buffer in bytes
  363. // - key: Key to use for MIC. Normally this is the NwkSKey
  364. //
  365. // ----------------------------------------------------------------------------
  366. static void checkMic(uint8_t *buf, uint8_t len, uint8_t *key) {
  367. uint8_t cBuf[len+1];
  368. uint8_t NwkSKey[16] = _NWKSKEY;
  369. # if _MONITOR>=1
  370. if (debug>=2) {
  371. String response = "";
  372. for (int i=0; i<len; i++) {
  373. printHexDigit(buf[i], response);
  374. response += ' ';
  375. }
  376. mPrint("old="+response);
  377. }
  378. # endif //_MONITOR
  379. for (int i=0; i<len-4; i++) {
  380. cBuf[i] = buf[i];
  381. }
  382. len -=4;
  383. uint16_t FrameCount = ( cBuf[7] * 256 ) + cBuf[6];
  384. len += micPacket(cBuf, len, FrameCount, NwkSKey, 0);
  385. if (debug>=2) {
  386. String response = "";
  387. for (int i=0; i<len; i++) {
  388. printHexDigit(cBuf[i],response);
  389. response += " ";
  390. }
  391. mPrint("new="+response);
  392. }
  393. // Mic is only checked, but len is not corrected
  394. }
  395. #endif //_CHECK_MIC
  396. // ----------------------------------------------------------------------------
  397. // SENSORPACKET
  398. // The gateway may also have local sensors that need reporting.
  399. // We will generate a message in gateway-UDP format for upStream messaging
  400. // so that for the backend server it seems like a LoRa node has reported a
  401. // sensor value.
  402. //
  403. // NOTE: We do not need ANY LoRa functions here since we are on the gateway.
  404. // We only need to send a gateway message upstream that looks like a node message.
  405. //
  406. // NOTE:: This function does encrypt the sensorpayload, and the backend
  407. // picks it up fine as decoder thinks it is a MAC message.
  408. //
  409. // Par 4.0 LoraWan spec:
  410. // PHYPayload = ( MHDR | MACPAYLOAD | MIC )
  411. // which is equal to
  412. // ( MHDR | ( FHDR | FPORT | FRMPAYLOAD ) | MIC )
  413. //
  414. // This function makes the totalpackage and calculates MIC
  415. // The maximum size of the message is: 12 + ( 9 + 2 + 64 ) + 4
  416. // So message size should be lass than 128 bytes if Payload is limited to 64 bytes.
  417. //
  418. // return value:
  419. // - On success returns the number of bytes to send
  420. // - On error returns -1
  421. // ----------------------------------------------------------------------------
  422. int sensorPacket() {
  423. uint8_t buff_up[512]; // Declare buffer here to avoid exceptions
  424. uint8_t message[64]={ 0 }; // Payload, init to 0
  425. uint8_t mlength = 0;
  426. uint32_t tmst = micros();
  427. struct LoraUp LUP;
  428. uint8_t NwkSKey[16] = _NWKSKEY;
  429. uint8_t AppSKey[16] = _APPSKEY;
  430. uint8_t DevAddr[4] = _DEVADDR;
  431. // Init the other LoraUp fields
  432. LUP.sf = 8; // Send with SF8
  433. LUP.prssi = -50;
  434. LUP.rssicorr = 139;
  435. LUP.snr = 0;
  436. // In the next few bytes the fake LoRa message must be put
  437. // PHYPayload = MHDR | MACPAYLOAD | MIC
  438. // MHDR, 1 byte
  439. // MIC, 4 bytes
  440. // ------------------------------
  441. // MHDR (Para 4.2), bit 5-7 MType, bit 2-4 RFU, bit 0-1 Major
  442. LUP.payLoad[0] = 0x40; // MHDR 0x40 == unconfirmed up message,
  443. // FRU and major are 0
  444. // -------------------------------
  445. // FHDR consists of 4 bytes addr, 1 byte Fctrl, 2 byte FCnt, 0-15 byte FOpts
  446. // We support ABP addresses only for Gateways
  447. LUP.payLoad[1] = DevAddr[3]; // Last byte[3] of address
  448. LUP.payLoad[2] = DevAddr[2];
  449. LUP.payLoad[3] = DevAddr[1];
  450. LUP.payLoad[4] = DevAddr[0]; // First byte[0] of Dev_Addr
  451. LUP.payLoad[5] = 0x00; // FCtrl is normally 0
  452. LUP.payLoad[6] = frameCount % 0x100; // LSB
  453. LUP.payLoad[7] = frameCount / 0x100; // MSB
  454. // -------------------------------
  455. // FPort, either 0 or 1 bytes. Must be != 0 for non MAC messages such as user payload
  456. //
  457. LUP.payLoad[8] = 0x01; // FPort must not be 0
  458. LUP.payLength = 9;
  459. // FRMPayload; Payload will be AES128 encoded using AppSKey
  460. // See LoRa spec para 4.3.2
  461. // You can add any byte string below based on you personal choice of sensors etc.
  462. //
  463. // Payload bytes in this example are encoded in the LoRaCode(c) format
  464. uint8_t PayLength = LoRaSensors((uint8_t *)(LUP.payLoad + LUP.payLength));
  465. #if _DUSB>=1
  466. if ((debug>=2) && (pdebug & P_RADIO )) {
  467. String response="";
  468. Serial.print(F("old: "));
  469. for (int i=0; i<PayLength; i++) {
  470. Serial.print(LUP.payLoad[i],HEX);
  471. Serial.print(' ');
  472. }
  473. Serial.println();
  474. }
  475. #endif //_DUSB
  476. // we have to include the AES functions at this stage in order to generate LoRa Payload.
  477. uint8_t CodeLength = encodePacket((uint8_t *)(LUP.payLoad + LUP.payLength), PayLength, (uint16_t)frameCount, DevAddr, AppSKey, 0);
  478. #if _DUSB>=1
  479. if ((debug>=2) && (pdebug & P_RADIO )) {
  480. Serial.print(F("new: "));
  481. for (int i=0; i<CodeLength; i++) {
  482. Serial.print(LUP.payLoad[i],HEX);
  483. Serial.print(' ');
  484. }
  485. Serial.println();
  486. }
  487. #endif //_DUSB
  488. LUP.payLength += CodeLength; // length inclusive sensor data
  489. // MIC, Message Integrity Code
  490. // As MIC is used by TTN (and others) we have to make sure that
  491. // framecount is valid and the message is correctly encrypted.
  492. // Note: Until MIC is done correctly, TTN does not receive these messages
  493. // The last 4 bytes are MIC bytes.
  494. //
  495. LUP.payLength += micPacket((uint8_t *)(LUP.payLoad), LUP.payLength, (uint16_t)frameCount, NwkSKey, 0);
  496. #if _DUSB>=1
  497. if ((debug>=2) && (pdebug & P_RADIO )) {
  498. Serial.print(F("mic: "));
  499. for (int i=0; i<LUP.payLength; i++) {
  500. Serial.print(LUP.payLoad[i],HEX);
  501. Serial.print(' ');
  502. }
  503. Serial.println();
  504. }
  505. #endif //_DUSB
  506. // So now our package is ready, and we can send it up through the gateway interface
  507. // Note: Be aware that the sensor message (which is bytes) in message will be
  508. // be expanded if the server expects JSON messages.
  509. // Note2: We fake this sensor message when sending
  510. //
  511. int buff_index = buildPacket(tmst, buff_up, LUP, true);
  512. frameCount++;
  513. statc.msg_ttl++; // XXX Should we count sensor messages as well?
  514. statc.msg_sens++;
  515. switch(gwayConfig.ch) { // MMM remove when possible
  516. case 0: statc.msg_sens_0++; break;
  517. case 1: statc.msg_sens_1++; break;
  518. case 2: statc.msg_sens_2++; break;
  519. }
  520. // In order to save the memory, we only write the framecounter
  521. // to EEPROM every 10 values. It also means that we will invalidate
  522. // 10 value when restarting the gateway.
  523. // NOTE: This means that preferences are NOT saved unless >=10 messages have been received.
  524. //
  525. if ((frameCount % 10)==0) writeGwayCfg(CONFIGFILE, &gwayConfig );
  526. if (buff_index > 512) {
  527. if (debug>0)
  528. mPrint("sensorPacket:: ERROR buffer size too large");
  529. return(-1);
  530. }
  531. #ifdef _TTNSERVER
  532. if (!sendUdp(ttnServer, _TTNPORT, buff_up, buff_index)) {
  533. return(-1);
  534. }
  535. #endif //_TTNSERVER
  536. #ifdef _THINGSERVER
  537. if (!sendUdp(thingServer, _THINGPORT, buff_up, buff_index)) {
  538. return(-1);
  539. }
  540. #endif //_THINGSERVER
  541. #if _DUSB>=1
  542. // If all is right, we should after decoding (which is the same as encoding) get
  543. // the original message back again.
  544. if ((debug>=2) && (pdebug & P_RADIO )) {
  545. CodeLength = encodePacket((uint8_t *)(LUP.payLoad + 9), PayLength, (uint16_t)frameCount-1, DevAddr, AppSKey, 0);
  546. Serial.print(F("rev: "));
  547. for (int i=0; i<CodeLength; i++) {
  548. Serial.print(LUP.payLoad[i],HEX);
  549. Serial.print(' ');
  550. }
  551. Serial.print(F(", addr="));
  552. for (int i=0; i<4; i++) {
  553. Serial.print(DevAddr[i],HEX);
  554. Serial.print(' ');
  555. }
  556. Serial.println();
  557. }
  558. #endif // _DUSB
  559. if (gwayConfig.cad) {
  560. // Set the state to CAD scanning after sending a packet
  561. _state = S_SCAN; // Inititialise scanner
  562. sf = SF7;
  563. cadScanner();
  564. }
  565. else {
  566. // Reset all RX lora stuff
  567. _state = S_RX;
  568. rxLoraModem();
  569. }
  570. return(buff_index);
  571. }
  572. #endif //_GATEWAYNODE==1
  573. #if (_GATEWAYNODE==1) || (_LOCALSERVER==1)
  574. // ----------------------------------------------------------------------------
  575. // ENCODEPACKET
  576. // In Sensor mode, we have to encode the user payload before sending.
  577. // The same applies to decoding packages in the payload for _LOCALSERVER.
  578. // The library files for AES are added to the library directory in AES.
  579. // For the moment we use the AES library made by ideetron as this library
  580. // is also used in the LMIC stack and is small in size.
  581. //
  582. // The function below follows the LoRa spec exactly.
  583. //
  584. // The resulting mumber of Bytes is returned by the functions. This means
  585. // 16 bytes per block, and as we add to the last block we also return 16
  586. // bytes for the last block.
  587. //
  588. // The LMIC code does not do this, so maybe we shorten the last block to only
  589. // the meaningful bytes in the last block. This means that encoded buffer
  590. // is exactly as big as the original message.
  591. //
  592. // NOTE:: Be aware that the LICENSE of the used AES library files
  593. // that we call with AES_Encrypt() is GPL3. It is used as-is,
  594. // but not part of this code.
  595. //
  596. // cmac = aes128_encrypt(K, Block_A[i])
  597. // ----------------------------------------------------------------------------
  598. uint8_t encodePacket(uint8_t *Data, uint8_t DataLength, uint16_t FrameCount, uint8_t *DevAddr, uint8_t *AppSKey, uint8_t Direction) {
  599. #if _DUSB>=1
  600. if (( debug>=2 ) && ( pdebug & P_GUI )) {
  601. Serial.print(F("G encodePacket:: DevAddr="));
  602. for (int i=0; i<4; i++ ) { Serial.print(DevAddr[i],HEX); Serial.print(' '); }
  603. Serial.print(F("G encodePacket:: AppSKey="));
  604. for (int i=0; i<16; i++ ) { Serial.print(AppSKey[i],HEX); Serial.print(' '); }
  605. Serial.println();
  606. }
  607. #endif // _DUSB
  608. //unsigned char AppSKey[16] = _APPSKEY ; // see configGway.h
  609. uint8_t i, j;
  610. uint8_t Block_A[16];
  611. uint8_t bLen=16; // Block length is 16 except for last block in message
  612. uint8_t restLength = DataLength % 16; // We work in blocks of 16 bytes, this is the rest
  613. uint8_t numBlocks = DataLength / 16; // Number of whole blocks to encrypt
  614. if (restLength>0) numBlocks++; // And add block for the rest if any
  615. for(i = 1; i <= numBlocks; i++) {
  616. Block_A[0] = 0x01;
  617. Block_A[1] = 0x00;
  618. Block_A[2] = 0x00;
  619. Block_A[3] = 0x00;
  620. Block_A[4] = 0x00;
  621. Block_A[5] = Direction; // 0 is uplink
  622. Block_A[6] = DevAddr[3]; // Only works for and with ABP
  623. Block_A[7] = DevAddr[2];
  624. Block_A[8] = DevAddr[1];
  625. Block_A[9] = DevAddr[0];
  626. Block_A[10] = (FrameCount & 0x00FF);
  627. Block_A[11] = ((FrameCount >> 8) & 0x00FF);
  628. Block_A[12] = 0x00; // Frame counter upper Bytes
  629. Block_A[13] = 0x00; // These are not used so are 0
  630. Block_A[14] = 0x00;
  631. Block_A[15] = i;
  632. // Encrypt and calculate the S
  633. AES_Encrypt(Block_A, AppSKey);
  634. // Last block? set bLen to rest
  635. if ((i == numBlocks) && (restLength>0)) bLen = restLength;
  636. for(j = 0; j < bLen; j++) {
  637. *Data = *Data ^ Block_A[j];
  638. Data++;
  639. }
  640. }
  641. //return(numBlocks*16); // Do we really want to return all 16 bytes in lastblock
  642. return(DataLength); // or only 16*(numBlocks-1)+bLen;
  643. }
  644. #endif // _GATEWAYNODE || _LOCALSERVER