_sensor.ino 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. // sensor.ino; 1-channel LoRa Gateway for ESP8266
  2. // Copyright (c) 2016-2020 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. 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. 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 V="+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. void mXor(uint8_t *buf, uint8_t *key)
  199. {
  200. for (uint8_t i = 0; i < 16; ++i) buf[i] ^= key[i];
  201. }
  202. // ----------------------------------------------------------------------------
  203. // SHIFT-LEFT
  204. // Shift the buffer buf left one bit
  205. // Parameters:
  206. // - buf: An array of uint8_t bytes
  207. // - len: Length of the array in bytes
  208. // ----------------------------------------------------------------------------
  209. void shift_left(uint8_t * buf, uint8_t len)
  210. {
  211. while (len--) {
  212. uint8_t next = len ? buf[1] : 0; // len 0 to 15
  213. uint8_t val = (*buf << 1);
  214. if (next & 0x80) val |= 0x01;
  215. *buf++ = val;
  216. }
  217. }
  218. // ----------------------------------------------------------------------------
  219. // generate_subkey
  220. // RFC 4493, para 2.3
  221. // -----------------------------------------------------------------------------
  222. void generate_subkey(uint8_t *key, uint8_t *k1, uint8_t *k2)
  223. {
  224. memset(k1, 0, 16); // Fill subkey1 with 0x00
  225. // Step 1: Assume k1 is an all zero block
  226. AES_Encrypt(k1,key);
  227. // Step 2: Analyse outcome of Encrypt operation (in k1), generate k1
  228. if (k1[0] & 0x80) {
  229. shift_left(k1,16);
  230. k1[15] ^= 0x87;
  231. }
  232. else {
  233. shift_left(k1,16);
  234. }
  235. // Step 3: Generate k2
  236. for (int i=0; i<16; i++) k2[i]=k1[i];
  237. if (k1[0] & 0x80) { // use k1(==k2) according rfc
  238. shift_left(k2,16);
  239. k2[15] ^= 0x87;
  240. }
  241. else {
  242. shift_left(k2,16);
  243. }
  244. // step 4: Done, return k1 and k2
  245. return;
  246. }
  247. // ----------------------------------------------------------------------------
  248. // MICPACKET()
  249. // Provide a valid MIC 4-byte code (par 2.4 of spec, RFC4493)
  250. // see also https://tools.ietf.org/html/rfc4493
  251. //
  252. // Although our own handler may choose not to interpret the last 4 (MIC) bytes
  253. // of a PHYSPAYLOAD physical payload message of in internal sensor,
  254. // The official TTN (and other) backends will interpret the complete message and
  255. // conclude that the generated message is bogus.
  256. // So we will really simulate internal messages coming from the -1ch gateway
  257. // to come from a real sensor and append 4 MIC bytes to every message that are
  258. // perfectly legimate
  259. // Parameters:
  260. // - data: uint8_t array of bytes = ( MHDR | FHDR | FPort | FRMPayload )
  261. // - len: 8=bit length of data, normally less than 64 bytes
  262. // - FrameCount: 16-bit framecounter
  263. // - dir: 0=up, 1=down
  264. //
  265. // B0 = ( 0x49 | 4 x 0x00 | Dir | 4 x DevAddr | 4 x FCnt | 0x00 | len )
  266. // MIC is cmac [0:3] of ( aes128_cmac(NwkSKey, B0 | Data )
  267. //
  268. // ----------------------------------------------------------------------------
  269. uint8_t micPacket(uint8_t *data, uint8_t len, uint16_t FrameCount, uint8_t * NwkSKey, uint8_t dir)
  270. {
  271. //uint8_t NwkSKey[16] = _NWKSKEY;
  272. uint8_t Block_B[16];
  273. uint8_t X[16];
  274. uint8_t Y[16];
  275. // ------------------------------------
  276. // build the B block used by the MIC process
  277. Block_B[0]= 0x49; // 1 byte MIC code
  278. Block_B[1]= 0x00; // 4 byte 0x00
  279. Block_B[2]= 0x00;
  280. Block_B[3]= 0x00;
  281. Block_B[4]= 0x00;
  282. Block_B[5]= dir; // 1 byte Direction
  283. Block_B[6]= DevAddr[3]; // 4 byte DevAddr
  284. Block_B[7]= DevAddr[2];
  285. Block_B[8]= DevAddr[1];
  286. Block_B[9]= DevAddr[0];
  287. Block_B[10]= (FrameCount & 0x00FF); // 4 byte FCNT
  288. Block_B[11]= ((FrameCount >> 8) & 0x00FF);
  289. Block_B[12]= 0x00; // Frame counter upper Bytes
  290. Block_B[13]= 0x00; // These are not used so are 0
  291. Block_B[14]= 0x00; // 1 byte 0x00
  292. Block_B[15]= len; // 1 byte len
  293. // ------------------------------------
  294. // Step 1: Generate the subkeys
  295. //
  296. uint8_t k1[16];
  297. uint8_t k2[16];
  298. generate_subkey(NwkSKey, k1, k2);
  299. // ------------------------------------
  300. // Copy the data to a new buffer which is prepended with Block B0
  301. //
  302. uint8_t micBuf[len+16]; // B0 | data
  303. for (uint8_t i=0; i<16; i++) micBuf[i]=Block_B[i];
  304. for (uint8_t i=0; i<len; i++) micBuf[i+16]=data[i];
  305. // ------------------------------------
  306. // Step 2: Calculate the number of blocks for CMAC
  307. //
  308. uint8_t numBlocks = len/16 + 1; // Compensate for B0 block
  309. if ((len % 16)!=0) numBlocks++; // If we have only a part block, take it all
  310. // ------------------------------------
  311. // Step 3: Calculate padding is necessary
  312. //
  313. uint8_t restBits = len%16; // if numBlocks is not a multiple of 16 bytes
  314. // ------------------------------------
  315. // Step 5: Make a buffer of zeros
  316. //
  317. memset(X, 0, 16);
  318. // ------------------------------------
  319. // Step 6: Do the actual encoding according to RFC
  320. //
  321. for(uint8_t i= 0x0; i < (numBlocks - 1); i++) {
  322. for (uint8_t j=0; j<16; j++) Y[j] = micBuf[(i*16)+j];
  323. mXor(Y, X);
  324. AES_Encrypt(Y, NwkSKey);
  325. for (uint8_t j=0; j<16; j++) X[j] = Y[j];
  326. }
  327. // ------------------------------------
  328. // Step 4: If there is a rest Block, padd it
  329. // Last block. We move step 4 to the end as we need Y
  330. // to compute the last block
  331. //
  332. if (restBits) {
  333. for (uint8_t i=0; i<16; i++) {
  334. if (i< restBits) Y[i] = micBuf[((numBlocks-1)*16)+i];
  335. if (i==restBits) Y[i] = 0x80;
  336. if (i> restBits) Y[i] = 0x00;
  337. }
  338. mXor(Y, k2);
  339. }
  340. else {
  341. for (uint8_t i=0; i<16; i++) {
  342. Y[i] = micBuf[((numBlocks-1)*16)+i];
  343. }
  344. mXor(Y, k1);
  345. }
  346. mXor(Y, X);
  347. AES_Encrypt(Y,NwkSKey);
  348. // ------------------------------------
  349. // Step 7: done, return the MIC size.
  350. // Only 4 bytes are returned (32 bits), which is less than the RFC recommends.
  351. // We return by appending 4 bytes to data, so there must be space in data array.
  352. //
  353. data[len+0]=Y[0];
  354. data[len+1]=Y[1];
  355. data[len+2]=Y[2];
  356. data[len+3]=Y[3];
  357. yield(); // MMM to avoid crashes
  358. return 4;
  359. }
  360. #if _CHECK_MIC==1
  361. // ----------------------------------------------------------------------------
  362. // CHECKMIC
  363. // Function to check the MIC computed for existing messages and for new messages
  364. // Parameters:
  365. // - buf: LoRa buffer to check in bytes, last 4 bytes contain the MIC
  366. // - len: Length of buffer in bytes
  367. // - key: Key to use for MIC. Normally this is the NwkSKey
  368. //
  369. // ----------------------------------------------------------------------------
  370. void checkMic(uint8_t *buf, uint8_t len, uint8_t *key)
  371. {
  372. uint8_t cBuf[len+1];
  373. uint8_t NwkSKey[16] = _NWKSKEY;
  374. # if _MONITOR>=1
  375. if (debug>=2) {
  376. String response = "";
  377. for (int i=0; i<len; i++) {
  378. printHexDigit(buf[i], response);
  379. response += ' ';
  380. }
  381. mPrint("old="+response);
  382. }
  383. # endif //_MONITOR
  384. for (int i=0; i<len-4; i++) {
  385. cBuf[i] = buf[i];
  386. }
  387. len -=4;
  388. uint16_t FrameCount = ( cBuf[7] * 256 ) + cBuf[6];
  389. len += micPacket(cBuf, len, FrameCount, NwkSKey, 0);
  390. if (debug>=2) {
  391. String response = "";
  392. for (int i=0; i<len; i++) {
  393. printHexDigit(cBuf[i],response);
  394. response += " ";
  395. }
  396. mPrint("new="+response);
  397. }
  398. // Mic is only checked, but len is not corrected
  399. }
  400. #endif //_CHECK_MIC
  401. // ----------------------------------------------------------------------------
  402. // SENSORPACKET
  403. // The gateway may also have local sensors that need reporting.
  404. // We will generate a message in gateway-UDP format for upStream messaging
  405. // so that for the backend server it seems like a LoRa node has reported a
  406. // sensor value.
  407. //
  408. // NOTE: We do not need ANY LoRa functions here since we are on the gateway.
  409. // We only need to send a gateway message upstream that looks like a node message.
  410. //
  411. // NOTE:: This function does encrypt the sensorpayload, and the backend
  412. // picks it up fine as decoder thinks it is a MAC message.
  413. //
  414. // Par 4.0 LoraWan spec:
  415. // PHYPayload = ( MHDR | MACPAYLOAD | MIC )
  416. // which is equal to
  417. // ( MHDR | ( FHDR | FPORT | FRMPAYLOAD ) | MIC )
  418. //
  419. // This function makes the totalpackage and calculates MIC
  420. // The maximum size of the message is: 12 + ( 9 + 2 + 64 ) + 4
  421. // So message size should be lass than 128 bytes if Payload is limited to 64 bytes.
  422. //
  423. // return value:
  424. // - On success returns the number of bytes to send
  425. // - On error returns -1
  426. // ----------------------------------------------------------------------------
  427. int sensorPacket() {
  428. uint8_t buff_up[512]; // Declare buffer here to avoid exceptions
  429. uint8_t message[64]={ 0 }; // Payload, init to 0
  430. uint8_t mlength = 0;
  431. uint32_t tmst = micros();
  432. struct LoraUp LUP;
  433. uint8_t NwkSKey[16] = _NWKSKEY;
  434. uint8_t AppSKey[16] = _APPSKEY;
  435. uint8_t DevAddr[4] = _DEVADDR;
  436. // Init the other LoraUp fields
  437. LUP.sf = 8; // Send with SF8
  438. LUP.prssi = -50;
  439. LUP.rssicorr = 139;
  440. LUP.snr = 0;
  441. // In the next few bytes the fake LoRa message must be put
  442. // PHYPayload = MHDR | MACPAYLOAD | MIC
  443. // MHDR, 1 byte
  444. // MIC, 4 bytes
  445. // ------------------------------
  446. // MHDR (Para 4.2), bit 5-7 MType, bit 2-4 RFU, bit 0-1 Major
  447. LUP.payLoad[0] = 0x40; // MHDR 0x40 == unconfirmed up message,
  448. // FRU and major are 0
  449. // -------------------------------
  450. // FHDR consists of 4 bytes addr, 1 byte Fctrl, 2 byte FCnt, 0-15 byte FOpts
  451. // We support ABP addresses only for Gateways
  452. LUP.payLoad[1] = DevAddr[3]; // Last byte[3] of address
  453. LUP.payLoad[2] = DevAddr[2];
  454. LUP.payLoad[3] = DevAddr[1];
  455. LUP.payLoad[4] = DevAddr[0]; // First byte[0] of Dev_Addr
  456. LUP.payLoad[5] = 0x00; // FCtrl is normally 0
  457. LUP.payLoad[6] = frameCount % 0x100; // LSB
  458. LUP.payLoad[7] = frameCount / 0x100; // MSB
  459. // -------------------------------
  460. // FPort, either 0 or 1 bytes. Must be != 0 for non MAC messages such as user payload
  461. //
  462. LUP.payLoad[8] = 0x01; // FPort must not be 0
  463. LUP.payLength = 9;
  464. // FRMPayload; Payload will be AES128 encoded using AppSKey
  465. // See LoRa spec para 4.3.2
  466. // You can add any byte string below based on you personal choice of sensors etc.
  467. //
  468. // Payload bytes in this example are encoded in the LoRaCode(c) format
  469. uint8_t PayLength = LoRaSensors((uint8_t *)(LUP.payLoad + LUP.payLength));
  470. #if _DUSB>=1
  471. if ((debug>=2) && (pdebug & P_RADIO )) {
  472. String response="";
  473. Serial.print(F("old: "));
  474. for (int i=0; i<PayLength; i++) {
  475. Serial.print(LUP.payLoad[i],HEX);
  476. Serial.print(' ');
  477. }
  478. Serial.println();
  479. }
  480. #endif //_DUSB
  481. // we have to include the AES functions at this stage in order to generate LoRa Payload.
  482. uint8_t CodeLength = encodePacket((uint8_t *)(LUP.payLoad + LUP.payLength), PayLength, (uint16_t)frameCount, DevAddr, AppSKey, 0);
  483. #if _DUSB>=1
  484. if ((debug>=2) && (pdebug & P_RADIO )) {
  485. Serial.print(F("new: "));
  486. for (int i=0; i<CodeLength; i++) {
  487. Serial.print(LUP.payLoad[i],HEX);
  488. Serial.print(' ');
  489. }
  490. Serial.println();
  491. }
  492. #endif //_DUSB
  493. LUP.payLength += CodeLength; // length inclusive sensor data
  494. // MIC, Message Integrity Code
  495. // As MIC is used by TTN (and others) we have to make sure that
  496. // framecount is valid and the message is correctly encrypted.
  497. // Note: Until MIC is done correctly, TTN does not receive these messages
  498. // The last 4 bytes are MIC bytes.
  499. //
  500. LUP.payLength += micPacket((uint8_t *)(LUP.payLoad), LUP.payLength, (uint16_t)frameCount, NwkSKey, 0);
  501. #if _DUSB>=1
  502. if ((debug>=2) && (pdebug & P_RADIO )) {
  503. Serial.print(F("mic: "));
  504. for (int i=0; i<LUP.payLength; i++) {
  505. Serial.print(LUP.payLoad[i],HEX);
  506. Serial.print(' ');
  507. }
  508. Serial.println();
  509. }
  510. #endif //_DUSB
  511. // So now our package is ready, and we can send it up through the gateway interface
  512. // Note: Be aware that the sensor message (which is bytes) in message will be
  513. // be expanded if the server expects JSON messages.
  514. // Note2: We fake this sensor message when sending
  515. //
  516. int buff_index = buildPacket(tmst, buff_up, LUP, true);
  517. frameCount++;
  518. statc.msg_ttl++; // XXX Should we count sensor messages as well?
  519. statc.msg_sens++;
  520. switch(gwayConfig.ch) { // MMM remove when possible
  521. case 0: statc.msg_sens_0++; break;
  522. case 1: statc.msg_sens_1++; break;
  523. case 2: statc.msg_sens_2++; break;
  524. }
  525. // In order to save the memory, we only write the framecounter
  526. // to EEPROM every 10 values. It also means that we will invalidate
  527. // 10 value when restarting the gateway.
  528. // NOTE: This means that preferences are NOT saved unless >=10 messages have been received.
  529. //
  530. if ((frameCount % 10)==0) writeGwayCfg(CONFIGFILE, &gwayConfig );
  531. if (buff_index > 512) {
  532. if (debug>0)
  533. mPrint("sensorPacket:: ERROR buffer size too large");
  534. return(-1);
  535. }
  536. #ifdef _TTNSERVER
  537. if (!sendUdp(ttnServer, _TTNPORT, buff_up, buff_index)) {
  538. return(-1);
  539. }
  540. #endif //_TTNSERVER
  541. #ifdef _THINGSERVER
  542. if (!sendUdp(thingServer, _THINGPORT, buff_up, buff_index)) {
  543. return(-1);
  544. }
  545. #endif //_THINGSERVER
  546. #if _DUSB>=1
  547. // If all is right, we should after decoding (which is the same as encoding) get
  548. // the original message back again.
  549. if ((debug>=2) && (pdebug & P_RADIO )) {
  550. CodeLength = encodePacket((uint8_t *)(LUP.payLoad + 9), PayLength, (uint16_t)frameCount-1, DevAddr, AppSKey, 0);
  551. Serial.print(F("rev: "));
  552. for (int i=0; i<CodeLength; i++) {
  553. Serial.print(LUP.payLoad[i],HEX);
  554. Serial.print(' ');
  555. }
  556. Serial.print(F(", addr="));
  557. for (int i=0; i<4; i++) {
  558. Serial.print(DevAddr[i],HEX);
  559. Serial.print(' ');
  560. }
  561. Serial.println();
  562. }
  563. #endif // _DUSB
  564. if (gwayConfig.cad) {
  565. // Set the state to CAD scanning after sending a packet
  566. _state = S_SCAN; // Inititialise scanner
  567. sf = SF7;
  568. cadScanner();
  569. }
  570. else {
  571. // Reset all RX lora stuff
  572. _state = S_RX;
  573. rxLoraModem();
  574. }
  575. return(buff_index);
  576. }
  577. #endif //_GATEWAYNODE==1
  578. #if (_GATEWAYNODE==1) || (_LOCALSERVER==1)
  579. // ----------------------------------------------------------------------------
  580. // ENCODEPACKET
  581. // In Sensor mode, we have to encode the user payload before sending.
  582. // The same applies to decoding packages in the payload for _LOCALSERVER.
  583. // The library files for AES are added to the library directory in AES.
  584. // For the moment we use the AES library made by ideetron as this library
  585. // is also used in the LMIC stack and is small in size.
  586. //
  587. // The function below follows the LoRa spec exactly.
  588. //
  589. // The resulting mumber of Bytes is returned by the functions. This means
  590. // 16 bytes per block, and as we add to the last block we also return 16
  591. // bytes for the last block.
  592. //
  593. // The LMIC code does not do this, so maybe we shorten the last block to only
  594. // the meaningful bytes in the last block. This means that encoded buffer
  595. // is exactly as big as the original message.
  596. //
  597. // NOTE:: Be aware that the LICENSE of the used AES library files
  598. // that we call with AES_Encrypt() is GPL3. It is used as-is,
  599. // but not part of this code.
  600. //
  601. // cmac = aes128_encrypt(K, Block_A[i])
  602. // ----------------------------------------------------------------------------
  603. uint8_t encodePacket(uint8_t *Data, uint8_t DataLength, uint16_t FrameCount, uint8_t *DevAddr, uint8_t *AppSKey, uint8_t Direction)
  604. {
  605. #if _DUSB>=1
  606. if (( debug>=2 ) && ( pdebug & P_GUI )) {
  607. Serial.print(F("G encodePacket:: DevAddr="));
  608. for (int i=0; i<4; i++ ) { Serial.print(DevAddr[i],HEX); Serial.print(' '); }
  609. Serial.print(F("G encodePacket:: AppSKey="));
  610. for (int i=0; i<16; i++ ) { Serial.print(AppSKey[i],HEX); Serial.print(' '); }
  611. Serial.println();
  612. }
  613. #endif // _DUSB
  614. //unsigned char AppSKey[16] = _APPSKEY ; // see configGway.h
  615. uint8_t i, j;
  616. uint8_t Block_A[16];
  617. uint8_t bLen=16; // Block length is 16 except for last block in message
  618. uint8_t restLength = DataLength % 16; // We work in blocks of 16 bytes, this is the rest
  619. uint8_t numBlocks = DataLength / 16; // Number of whole blocks to encrypt
  620. if (restLength>0) numBlocks++; // And add block for the rest if any
  621. for(i = 1; i <= numBlocks; i++) {
  622. Block_A[0] = 0x01;
  623. Block_A[1] = 0x00;
  624. Block_A[2] = 0x00;
  625. Block_A[3] = 0x00;
  626. Block_A[4] = 0x00;
  627. Block_A[5] = Direction; // 0 is uplink
  628. Block_A[6] = DevAddr[3]; // Only works for and with ABP
  629. Block_A[7] = DevAddr[2];
  630. Block_A[8] = DevAddr[1];
  631. Block_A[9] = DevAddr[0];
  632. Block_A[10] = (FrameCount & 0x00FF);
  633. Block_A[11] = ((FrameCount >> 8) & 0x00FF);
  634. Block_A[12] = 0x00; // Frame counter upper Bytes
  635. Block_A[13] = 0x00; // These are not used so are 0
  636. Block_A[14] = 0x00;
  637. Block_A[15] = i;
  638. // Encrypt and calculate the S
  639. AES_Encrypt(Block_A, AppSKey);
  640. // Last block? set bLen to rest
  641. if ((i == numBlocks) && (restLength>0)) bLen = restLength;
  642. for(j = 0; j < bLen; j++) {
  643. *Data = *Data ^ Block_A[j];
  644. Data++;
  645. }
  646. }
  647. //return(numBlocks*16); // Do we really want to return all 16 bytes in lastblock
  648. return(DataLength); // or only 16*(numBlocks-1)+bLen;
  649. }
  650. #endif // _GATEWAYNODE || _LOCALSERVER