_sensor.ino 23 KB

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