hello world

Fork of lmic_MOTE_L152RC by Semtech

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers lmic.cpp Source File

lmic.cpp

Go to the documentation of this file.
00001 /*******************************************************************************
00002  * Copyright (c) 2014-2015 IBM Corporation.
00003  * All rights reserved. This program and the accompanying materials
00004  * are made available under the terms of the Eclipse Public License v1.0
00005  * which accompanies this distribution, and is available at
00006  * http://www.eclipse.org/legal/epl-v10.html
00007  *
00008  * Contributors:
00009  *    IBM Zurich Research Lab - initial API, implementation and documentation
00010  *******************************************************************************/
00011 
00012 //! \file
00013 #include "lmic.h"
00014 #include "debug.h"  // tmp wbr
00015 
00016 #if !defined(MINRX_SYMS)
00017 #define MINRX_SYMS 5
00018 #endif // !defined(MINRX_SYMS)
00019 #define PAMBL_SYMS 8
00020 #define PAMBL_FSK  5
00021 #define PRERX_FSK  1
00022 #define RXLEN_FSK  (1+5+2)
00023 
00024 #define BCN_INTV_osticks       sec2osticks(BCN_INTV_sec)
00025 #define TXRX_GUARD_osticks     ms2osticks(TXRX_GUARD_ms)
00026 #define JOIN_GUARD_osticks     ms2osticks(JOIN_GUARD_ms)
00027 #define DELAY_DNW1_osticks     sec2osticks(DELAY_DNW1)
00028 #define DELAY_DNW2_osticks     sec2osticks(DELAY_DNW2)
00029 #define DELAY_JACC1_osticks    sec2osticks(DELAY_JACC1)
00030 #define DELAY_JACC2_osticks    sec2osticks(DELAY_JACC2)
00031 #define DELAY_EXTDNW2_osticks  sec2osticks(DELAY_EXTDNW2)
00032 #define BCN_RESERVE_osticks    ms2osticks(BCN_RESERVE_ms)
00033 #define BCN_GUARD_osticks      ms2osticks(BCN_GUARD_ms)
00034 #define BCN_WINDOW_osticks     ms2osticks(BCN_WINDOW_ms)
00035 #define AIRTIME_BCN_osticks    us2osticks(AIRTIME_BCN)
00036 #if defined(CFG_eu868)
00037 #define DNW2_SAFETY_ZONE       ms2osticks(3000)
00038 #endif
00039 #if defined(CFG_us915)
00040 #define DNW2_SAFETY_ZONE       ms2osticks(750)
00041 #endif
00042 
00043 // Special APIs - for development or testing
00044 #define isTESTMODE() 0
00045 
00046 DEFINE_LMIC;
00047 DECL_ON_LMIC_EVENT;
00048 
00049 
00050 // Fwd decls.
00051 static void engineUpdate(void);
00052 static void startScan (void);
00053 
00054 
00055 // ================================================================================
00056 // BEG OS - default implementations for certain OS suport functions
00057 
00058 #if !defined(HAS_os_calls)
00059 
00060 #if !defined(os_rlsbf2)
00061 u2_t os_rlsbf2 (xref2cu1_t buf) {
00062     return (u2_t)(buf[0] | (buf[1]<<8));
00063 }
00064 #endif
00065 
00066 #if !defined(os_rlsbf4)
00067 u4_t os_rlsbf4 (xref2cu1_t buf) {
00068     return (u4_t)(buf[0] | (buf[1]<<8) | ((u4_t)buf[2]<<16) | ((u4_t)buf[3]<<24));
00069 }
00070 #endif
00071 
00072 
00073 #if !defined(os_rmsbf4)
00074 u4_t os_rmsbf4 (xref2cu1_t buf) {
00075     return (u4_t)(buf[3] | (buf[2]<<8) | ((u4_t)buf[1]<<16) | ((u4_t)buf[0]<<24));
00076 }
00077 #endif
00078 
00079 
00080 #if !defined(os_wlsbf2)
00081 void os_wlsbf2 (xref2u1_t buf, u2_t v) {
00082     buf[0] = v;
00083     buf[1] = v>>8;
00084 }
00085 #endif
00086 
00087 #if !defined(os_wlsbf4)
00088 void os_wlsbf4 (xref2u1_t buf, u4_t v) {
00089     buf[0] = v;
00090     buf[1] = v>>8;
00091     buf[2] = v>>16;
00092     buf[3] = v>>24;
00093 }
00094 #endif
00095 
00096 #if !defined(os_wmsbf4)
00097 void os_wmsbf4 (xref2u1_t buf, u4_t v) {
00098     buf[3] = v;
00099     buf[2] = v>>8;
00100     buf[1] = v>>16;
00101     buf[0] = v>>24;
00102 }
00103 #endif
00104 
00105 #if !defined(os_getBattLevel)
00106 u1_t os_getBattLevel (void) {
00107     return MCMD_DEVS_BATT_NOINFO;
00108 }
00109 #endif
00110 
00111 #if !defined(os_crc16)
00112 // New CRC-16 CCITT(XMODEM) checksum for beacons:
00113 u2_t os_crc16 (xref2u1_t data, uint len) {
00114     u2_t remainder = 0;
00115     u2_t polynomial = 0x1021;
00116     for( uint i = 0; i < len; i++ ) {
00117         remainder ^= data[i] << 8;
00118         for( u1_t bit = 8; bit > 0; bit--) {
00119             if( (remainder & 0x8000) )
00120                 remainder = (remainder << 1) ^ polynomial;
00121             else 
00122                 remainder <<= 1;
00123         }
00124     }
00125     return remainder;
00126 }
00127 #endif
00128 
00129 #endif // !HAS_os_calls
00130 
00131 // END OS - default implementations for certain OS suport functions
00132 // ================================================================================
00133 
00134 // ================================================================================
00135 // BEG AES
00136 
00137 static void micB0 (u4_t devaddr, u4_t seqno, int dndir, int len) {
00138     os_clearMem(AESaux,16);
00139     AESaux[0]  = 0x49;
00140     AESaux[5]  = dndir?1:0;
00141     AESaux[15] = len;
00142     os_wlsbf4(AESaux+ 6,devaddr);
00143     os_wlsbf4(AESaux+10,seqno);
00144 }
00145 
00146 
00147 static int aes_verifyMic (xref2cu1_t key, u4_t devaddr, u4_t seqno, int dndir, xref2u1_t pdu, int len) {
00148     micB0(devaddr, seqno, dndir, len);
00149     os_copyMem(AESkey,key,16);
00150     return os_aes(AES_MIC, pdu, len) == os_rmsbf4(pdu+len);
00151 }
00152 
00153 
00154 static void aes_appendMic (xref2cu1_t key, u4_t devaddr, u4_t seqno, int dndir, xref2u1_t pdu, int len) {
00155     micB0(devaddr, seqno, dndir, len);
00156     os_copyMem(AESkey,key,16);
00157     // MSB because of internal structure of AES
00158     os_wmsbf4(pdu+len, os_aes(AES_MIC, pdu, len));
00159 }
00160 
00161 
00162 static void aes_appendMic0 (xref2u1_t pdu, int len) {
00163     os_getDevKey(AESkey);
00164     os_wmsbf4(pdu+len, os_aes(AES_MIC|AES_MICNOAUX, pdu, len));  // MSB because of internal structure of AES
00165 }
00166 
00167 
00168 static int aes_verifyMic0 (xref2u1_t pdu, int len) {
00169     os_getDevKey(AESkey);
00170     return os_aes(AES_MIC|AES_MICNOAUX, pdu, len) == os_rmsbf4(pdu+len);
00171 }
00172 
00173 
00174 static void aes_encrypt (xref2u1_t pdu, int len) {
00175     os_getDevKey(AESkey);
00176     os_aes(AES_ENC, pdu, len);
00177 }
00178 
00179 
00180 static void aes_cipher (xref2cu1_t key, u4_t devaddr, u4_t seqno, int dndir, xref2u1_t payload, int len) {
00181     if( len <= 0 )
00182         return;
00183     os_clearMem(AESaux, 16);
00184     AESaux[0] = AESaux[15] = 1; // mode=cipher / dir=down / block counter=1
00185     AESaux[5] = dndir?1:0;
00186     os_wlsbf4(AESaux+ 6,devaddr);
00187     os_wlsbf4(AESaux+10,seqno);
00188     os_copyMem(AESkey,key,16);
00189     os_aes(AES_CTR, payload, len);
00190 }
00191 
00192 
00193 static void aes_sessKeys (u2_t devnonce, xref2cu1_t artnonce, xref2u1_t nwkkey, xref2u1_t artkey) {
00194     os_clearMem(nwkkey, 16);
00195     nwkkey[0] = 0x01;
00196     os_copyMem(nwkkey+1, artnonce, LEN_ARTNONCE+LEN_NETID);
00197     os_wlsbf2(nwkkey+1+LEN_ARTNONCE+LEN_NETID, devnonce);
00198     os_copyMem(artkey, nwkkey, 16);
00199     artkey[0] = 0x02;
00200 
00201     os_getDevKey(AESkey);
00202     os_aes(AES_ENC, nwkkey, 16);
00203     os_getDevKey(AESkey);
00204     os_aes(AES_ENC, artkey, 16);
00205 }
00206 
00207 // END AES
00208 // ================================================================================
00209 
00210 
00211 // ================================================================================
00212 // BEG LORA
00213 
00214 #if defined(CFG_eu868) // ========================================
00215 
00216 #define maxFrameLen(dr) ((dr)<=DR_SF9 ? maxFrameLens[(dr)] : 0xFF)
00217 const u1_t maxFrameLens [] = { 64,64,64,123 };
00218 
00219 const u1_t _DR2RPS_CRC[] = {
00220     ILLEGAL_RPS,
00221     (u1_t)MAKERPS(SF12, BW125, CR_4_5, 0, 0),
00222     (u1_t)MAKERPS(SF11, BW125, CR_4_5, 0, 0),
00223     (u1_t)MAKERPS(SF10, BW125, CR_4_5, 0, 0),
00224     (u1_t)MAKERPS(SF9,  BW125, CR_4_5, 0, 0),
00225     (u1_t)MAKERPS(SF8,  BW125, CR_4_5, 0, 0),
00226     (u1_t)MAKERPS(SF7,  BW125, CR_4_5, 0, 0),
00227     (u1_t)MAKERPS(SF7,  BW250, CR_4_5, 0, 0),
00228     (u1_t)MAKERPS(FSK,  BW125, CR_4_5, 0, 0),
00229     ILLEGAL_RPS
00230 };
00231 
00232 static const s1_t TXPOWLEVELS[] = {
00233     20, 14, 11, 8, 5, 2, 0,0, 0,0,0,0, 0,0,0,0
00234 };
00235 #define pow2dBm(mcmd_ladr_p1) (TXPOWLEVELS[(mcmd_ladr_p1&MCMD_LADR_POW_MASK)>>MCMD_LADR_POW_SHIFT])
00236 
00237 #elif defined(CFG_us915) // ========================================
00238 
00239 #define maxFrameLen(dr) ((dr)<=DR_SF11CR ? maxFrameLens[(dr)] : 0xFF)
00240 //const u1_t maxFrameLens [] = { 24,66,142,255,255,255,255,255,  66,142 };
00241 
00242 const u1_t _DR2RPS_CRC[] = {
00243     ILLEGAL_RPS,
00244     MAKERPS(SF10, BW125, CR_4_5, 0, 0),
00245     MAKERPS(SF9 , BW125, CR_4_5, 0, 0),
00246     MAKERPS(SF8 , BW125, CR_4_5, 0, 0),
00247     MAKERPS(SF7 , BW125, CR_4_5, 0, 0),
00248     MAKERPS(SF8 , BW500, CR_4_5, 0, 0),
00249     ILLEGAL_RPS ,
00250     ILLEGAL_RPS ,
00251     ILLEGAL_RPS ,
00252     MAKERPS(SF12, BW500, CR_4_5, 0, 0),
00253     MAKERPS(SF11, BW500, CR_4_5, 0, 0),
00254     MAKERPS(SF10, BW500, CR_4_5, 0, 0),
00255     MAKERPS(SF9 , BW500, CR_4_5, 0, 0),
00256     MAKERPS(SF8 , BW500, CR_4_5, 0, 0),
00257     MAKERPS(SF7 , BW500, CR_4_5, 0, 0),
00258     ILLEGAL_RPS
00259 };
00260 
00261 #define pow2dBm(mcmd_ladr_p1) ((s1_t)(30 - (((mcmd_ladr_p1)&MCMD_LADR_POW_MASK)<<1)))
00262 
00263 #endif // ================================================
00264 
00265 static const u1_t SENSITIVITY[7][3] = {
00266     // ------------bw----------
00267     // 125kHz    250kHz    500kHz
00268     { 141-109,  141-109, 141-109 },  // FSK
00269     { 141-127,  141-124, 141-121 },  // SF7
00270     { 141-129,  141-126, 141-123 },  // SF8
00271     { 141-132,  141-129, 141-126 },  // SF9
00272     { 141-135,  141-132, 141-129 },  // SF10
00273     { 141-138,  141-135, 141-132 },  // SF11
00274     { 141-141,  141-138, 141-135 }   // SF12
00275 };
00276 
00277 int getSensitivity (rps_t rps) {
00278     return -141 + SENSITIVITY[getSf(rps)][getBw(rps)];
00279 }
00280 
00281 ostime_t calcAirTime (rps_t rps, u1_t plen) {
00282     u1_t bw = getBw(rps);  // 0,1,2 = 125,250,500kHz
00283     u1_t sf = getSf(rps);  // 0=FSK, 1..6 = SF7..12
00284     if( sf == FSK ) {
00285         return (plen+/*preamble*/5+/*syncword*/3+/*len*/1+/*crc*/2) * /*bits/byte*/8
00286             * (s4_t)OSTICKS_PER_SEC / /*kbit/s*/50000;
00287     }
00288     u1_t sfx = 4*(sf+(7-SF7));
00289     u1_t q = sfx - (sf >= SF11 ? 8 : 0);
00290     int tmp = 8*plen - sfx + 28 + (getNocrc(rps)?0:16) - (getIh(rps)?20:0);
00291     if( tmp > 0 ) {
00292         tmp = (tmp + q - 1) / q;
00293         tmp *= getCr(rps)+5;
00294         tmp += 8;
00295     } else {
00296         tmp = 8;
00297     }
00298     tmp = (tmp<<2) + /*preamble*/49 /* 4 * (8 + 4.25) */;
00299     // bw = 125000 = 15625 * 2^3
00300     //      250000 = 15625 * 2^4
00301     //      500000 = 15625 * 2^5
00302     // sf = 7..12
00303     //
00304     // osticks =  tmp * OSTICKS_PER_SEC * 1<<sf / bw
00305     //
00306     // 3 => counter reduced divisor 125000/8 => 15625
00307     // 2 => counter 2 shift on tmp
00308     sfx = sf+(7-SF7) - (3+2) - bw;
00309     int div = 15625;
00310     if( sfx > 4 ) {
00311         // prevent 32bit signed int overflow in last step
00312         div >>= sfx-4;
00313         sfx = 4;
00314     }
00315     // Need 32bit arithmetic for this last step
00316     return (((ostime_t)tmp << sfx) * OSTICKS_PER_SEC + div/2) / div;
00317 }
00318 
00319 extern inline rps_t updr2rps (dr_t dr);
00320 extern inline rps_t dndr2rps (dr_t dr);
00321 extern inline int isFasterDR (dr_t dr1, dr_t dr2);
00322 extern inline int isSlowerDR (dr_t dr1, dr_t dr2);
00323 extern inline dr_t  incDR    (dr_t dr);
00324 extern inline dr_t  decDR    (dr_t dr);
00325 extern inline dr_t  assertDR (dr_t dr);
00326 extern inline dr_t  validDR  (dr_t dr);
00327 extern inline dr_t  lowerDR  (dr_t dr, u1_t n);
00328 
00329 extern inline sf_t  getSf    (rps_t params);
00330 extern inline rps_t setSf    (rps_t params, sf_t sf);
00331 extern inline bw_t  getBw    (rps_t params);
00332 extern inline rps_t setBw    (rps_t params, bw_t cr);
00333 extern inline cr_t  getCr    (rps_t params);
00334 extern inline rps_t setCr    (rps_t params, cr_t cr);
00335 extern inline int   getNocrc (rps_t params);
00336 extern inline rps_t setNocrc (rps_t params, int nocrc);
00337 extern inline int   getIh    (rps_t params);
00338 extern inline rps_t setIh    (rps_t params, int ih);
00339 extern inline rps_t makeRps  (sf_t sf, bw_t bw, cr_t cr, int ih, int nocrc);
00340 extern inline int   sameSfBw (rps_t r1, rps_t r2);
00341 
00342 // END LORA
00343 // ================================================================================
00344 
00345 
00346 // Adjust DR for TX retries
00347 //  - indexed by retry count
00348 //  - return steps to lower DR
00349 static const u1_t DRADJUST[2+TXCONF_ATTEMPTS] = {
00350     // normal frames - 1st try / no retry
00351     0,
00352     // confirmed frames
00353     0,0,1,0,1,0,1,0,0
00354 };
00355 
00356 
00357 // Table below defines the size of one symbol as
00358 //   symtime = 256us * 2^T(sf,bw)
00359 // 256us is called one symunit. 
00360 //                 SF:                                  
00361 //      BW:      |__7___8___9__10__11__12
00362 //      125kHz   |  2   3   4   5   6   7
00363 //      250kHz   |  1   2   3   4   5   6
00364 //      500kHz   |  0   1   2   3   4   5
00365 //  
00366 // Times for half symbol per DR
00367 // Per DR table to minimize rounding errors
00368 static const ostime_t DR2HSYM_osticks[] = {
00369 #if defined(CFG_eu868)
00370 #define dr2hsym(dr) (DR2HSYM_osticks[(dr)])
00371     us2osticksRound(128<<7),  // DR_SF12
00372     us2osticksRound(128<<6),  // DR_SF11
00373     us2osticksRound(128<<5),  // DR_SF10
00374     us2osticksRound(128<<4),  // DR_SF9
00375     us2osticksRound(128<<3),  // DR_SF8
00376     us2osticksRound(128<<2),  // DR_SF7
00377     us2osticksRound(128<<1),  // DR_SF7B
00378     us2osticksRound(80)       // FSK -- not used (time for 1/2 byte)
00379 #elif defined(CFG_us915)
00380 #define dr2hsym(dr) (DR2HSYM_osticks[(dr)&7])  // map DR_SFnCR -> 0-6
00381     us2osticksRound(128<<5),  // DR_SF10   DR_SF12CR
00382     us2osticksRound(128<<4),  // DR_SF9    DR_SF11CR
00383     us2osticksRound(128<<3),  // DR_SF8    DR_SF10CR
00384     us2osticksRound(128<<2),  // DR_SF7    DR_SF9CR
00385     us2osticksRound(128<<1),  // DR_SF8C   DR_SF8CR
00386     us2osticksRound(128<<0)   // ------    DR_SF7CR
00387 #endif
00388 };
00389 
00390 
00391 static ostime_t calcRxWindow (u1_t secs, dr_t dr) {
00392     ostime_t rxoff, err;
00393     if( secs==0 ) {
00394         // aka 128 secs (next becaon)
00395         rxoff = LMIC.drift;
00396         err = LMIC.lastDriftDiff;
00397     } else {
00398         // scheduled RX window within secs into current beacon period
00399         rxoff = (LMIC.drift * (ostime_t)secs) >> BCN_INTV_exp;
00400         err = (LMIC.lastDriftDiff * (ostime_t)secs) >> BCN_INTV_exp;
00401     }
00402     u1_t rxsyms = MINRX_SYMS;
00403     err += (ostime_t)LMIC.maxDriftDiff * LMIC.missedBcns;
00404     LMIC.rxsyms = MINRX_SYMS + (err / dr2hsym(dr));
00405 
00406     return (rxsyms-PAMBL_SYMS) * dr2hsym(dr) + rxoff;
00407 }
00408 
00409 
00410 // Setup beacon RX parameters assuming we have an error of ms (aka +/-(ms/2))
00411 static void calcBcnRxWindowFromMillis (u1_t ms, bit_t ini) {
00412     if( ini ) {
00413         LMIC.drift = 0;
00414         LMIC.maxDriftDiff = 0;
00415         LMIC.missedBcns = 0;
00416         LMIC.bcninfo.flags |= BCN_NODRIFT|BCN_NODDIFF;
00417     }
00418     ostime_t hsym = dr2hsym(DR_BCN);
00419     LMIC.bcnRxsyms = MINRX_SYMS + ms2osticksCeil(ms) / hsym;
00420     LMIC.bcnRxtime = LMIC.bcninfo.txtime + BCN_INTV_osticks - (LMIC.bcnRxsyms-PAMBL_SYMS) * hsym;
00421 }
00422 
00423 
00424 // Setup scheduled RX window (ping/multicast slot)
00425 static void rxschedInit (xref2rxsched_t rxsched) {
00426     os_clearMem(AESkey,16);
00427     os_clearMem(LMIC.frame+8,8);
00428     os_wlsbf4(LMIC.frame, LMIC.bcninfo.time);
00429     os_wlsbf4(LMIC.frame+4, LMIC.devaddr);
00430     os_aes(AES_ENC,LMIC.frame,16);
00431     u1_t intvExp = rxsched->intvExp;
00432     ostime_t off = os_rlsbf2(LMIC.frame) & (0x0FFF >> (7 - intvExp)); // random offset (slot units)
00433     rxsched->rxbase = (LMIC.bcninfo.txtime +
00434                        BCN_RESERVE_osticks +
00435                        ms2osticks(BCN_SLOT_SPAN_ms * off)); // random offset osticks
00436     rxsched->slot   = 0;
00437     rxsched->rxtime = rxsched->rxbase - calcRxWindow(/*secs BCN_RESERVE*/2+(1<<intvExp),rxsched->dr);
00438     rxsched->rxsyms = LMIC.rxsyms;
00439 }
00440 
00441 
00442 static bit_t rxschedNext (xref2rxsched_t rxsched, ostime_t cando) {
00443   again:
00444     if( rxsched->rxtime - cando >= 0 )
00445         return 1;
00446     u1_t slot;
00447     if( (slot=rxsched->slot) >= 128 )
00448         return 0;
00449     u1_t intv = 1<<rxsched->intvExp;
00450     if( (rxsched->slot = (slot += (intv))) >= 128 )
00451         return 0;
00452     rxsched->rxtime = rxsched->rxbase
00453         + ((BCN_WINDOW_osticks * (ostime_t)slot) >> BCN_INTV_exp)
00454         - calcRxWindow(/*secs BCN_RESERVE*/2+slot+intv,rxsched->dr);
00455     rxsched->rxsyms = LMIC.rxsyms;
00456     goto again;
00457 }
00458 
00459 
00460 static ostime_t rndDelay (u1_t secSpan) {
00461     u2_t r = os_getRndU2();
00462     ostime_t delay = r;
00463     if( delay > OSTICKS_PER_SEC )
00464         delay = r % (u2_t)OSTICKS_PER_SEC;
00465     if( secSpan > 0 )
00466         delay += ((u1_t)r % secSpan) * OSTICKS_PER_SEC;
00467     return delay;
00468 }
00469 
00470 
00471 static void txDelay (ostime_t reftime, u1_t secSpan) {
00472     reftime += rndDelay(secSpan);
00473     if( LMIC.globalDutyRate == 0  ||  (reftime - LMIC.globalDutyAvail) > 0 ) {
00474         LMIC.globalDutyAvail = reftime;
00475         LMIC.opmode |= OP_RNDTX;
00476     }
00477 }
00478 
00479 
00480 static void setDrJoin (u1_t reason, u1_t dr) {
00481     EV(drChange, INFO, (e_.reason    = reason,
00482                         e_.deveui    = MAIN::CDEV->getEui(),
00483                         e_.dr        = dr|DR_PAGE,
00484                         e_.txpow     = LMIC.adrTxPow,
00485                         e_.prevdr    = LMIC.datarate|DR_PAGE,
00486                         e_.prevtxpow = LMIC.adrTxPow));
00487     LMIC.datarate = dr;
00488     DO_DEVDB(LMIC.datarate,datarate);
00489 }
00490 
00491 
00492 static void setDrTxpow (u1_t reason, u1_t dr, s1_t pow) {
00493     EV(drChange, INFO, (e_.reason    = reason,
00494                         e_.deveui    = MAIN::CDEV->getEui(),
00495                         e_.dr        = dr|DR_PAGE,
00496                         e_.txpow     = pow,
00497                         e_.prevdr    = LMIC.datarate|DR_PAGE,
00498                         e_.prevtxpow = LMIC.adrTxPow));
00499     
00500     if( pow != KEEP_TXPOW ) {
00501         LMIC.adrTxPow = pow;
00502         if (pow < LMIC.txpow_limit)
00503             LMIC.txpow = pow;
00504     }
00505     if( LMIC.datarate != dr ) {
00506         LMIC.datarate = dr;
00507         DO_DEVDB(LMIC.datarate,datarate);
00508         LMIC.opmode |= OP_NEXTCHNL;
00509     }
00510 }
00511 
00512 
00513 void LMIC_stopPingable (void) {
00514     LMIC.opmode &= ~(OP_PINGABLE|OP_PINGINI);
00515 }
00516 
00517 
00518 void LMIC_setPingable (u1_t intvExp) {
00519     // Change setting
00520     LMIC.ping.intvExp = (intvExp & 0x7);
00521     LMIC.opmode |= OP_PINGABLE;
00522     // App may call LMIC_enableTracking() explicitely before
00523     // Otherwise tracking is implicitly enabled here
00524     if( (LMIC.opmode & (OP_TRACK|OP_SCAN)) == 0  &&  LMIC.bcninfoTries == 0 )
00525         LMIC_enableTracking(0);
00526 }
00527 
00528 
00529 #if defined(CFG_eu868)
00530 // ================================================================================
00531 //
00532 // BEG: EU868 related stuff
00533 //
00534 enum { NUM_DEFAULT_CHANNELS=6 };
00535 static const u4_t iniChannelFreq[12] = {
00536     // Join frequencies and duty cycle limit (0.1%)
00537     EU868_F1|BAND_MILLI, EU868_J4|BAND_MILLI,
00538     EU868_F2|BAND_MILLI, EU868_J5|BAND_MILLI,
00539     EU868_F3|BAND_MILLI, EU868_J6|BAND_MILLI,
00540     // Default operational frequencies
00541     EU868_F1|BAND_CENTI, EU868_F2|BAND_CENTI, EU868_F3|BAND_CENTI,
00542     EU868_F4|BAND_MILLI, EU868_F5|BAND_MILLI, EU868_F6|BAND_DECI
00543 };
00544 
00545 static void initDefaultChannels (bit_t join) {
00546     os_clearMem(&LMIC.channelFreq, sizeof(LMIC.channelFreq));
00547     os_clearMem(&LMIC.channelDrMap, sizeof(LMIC.channelDrMap));
00548     os_clearMem(&LMIC.bands, sizeof(LMIC.bands));
00549 
00550     LMIC.channelMap = 0x3F;
00551     u1_t su = join ? 0 : 6;
00552     for( u1_t fu=0; fu<6; fu++,su++ ) {
00553         LMIC.channelFreq[fu]  = iniChannelFreq[su];
00554         LMIC.channelDrMap[fu] = DR_RANGE_MAP(DR_SF12,DR_SF7);
00555     }
00556     if( !join ) {
00557         LMIC.channelDrMap[5] = DR_RANGE_MAP(DR_SF12,DR_SF7);
00558         LMIC.channelDrMap[1] = DR_RANGE_MAP(DR_SF12,DR_FSK);
00559     }
00560 
00561     LMIC.bands[BAND_MILLI].txcap    = 1000;  // 0.1%
00562     LMIC.bands[BAND_MILLI].txpow    = 14;
00563     LMIC.bands[BAND_MILLI].lastchnl = os_getRndU1() % MAX_CHANNELS;
00564     LMIC.bands[BAND_CENTI].txcap    = 100;   // 1%
00565     LMIC.bands[BAND_CENTI].txpow    = 14;
00566     LMIC.bands[BAND_CENTI].lastchnl = os_getRndU1() % MAX_CHANNELS;
00567     LMIC.bands[BAND_DECI ].txcap    = 10;    // 10%
00568     LMIC.bands[BAND_DECI ].txpow    = 27;
00569     LMIC.bands[BAND_CENTI].lastchnl = os_getRndU1() % MAX_CHANNELS;
00570     LMIC.bands[BAND_MILLI].avail = 
00571     LMIC.bands[BAND_CENTI].avail =
00572     LMIC.bands[BAND_DECI ].avail = os_getTime();
00573 }
00574 
00575 bit_t LMIC_setupBand (u1_t bandidx, s1_t txpow, u2_t txcap) {
00576     if( bandidx > BAND_AUX ) return 0;
00577     band_t* b = &LMIC.bands[bandidx];
00578     b->txpow = txpow;
00579     b->txcap = txcap;
00580     b->avail = os_getTime();
00581     b->lastchnl = os_getRndU1() % MAX_CHANNELS;
00582     return 1;
00583 }
00584 
00585 bit_t LMIC_setupChannel (u1_t chidx, u4_t freq, u2_t drmap, s1_t band) {
00586     if( chidx >= MAX_CHANNELS )
00587         return 0;
00588     if( band == -1 ) {
00589         if( freq >= 869400000 && freq <= 869650000 )
00590             freq |= BAND_DECI;   // 10% 27dBm
00591         else if( (freq >= 868000000 && freq <= 868600000) ||
00592                  (freq >= 869700000 && freq <= 870000000)  )
00593             freq |= BAND_CENTI;  // 1% 14dBm 
00594         else 
00595             freq |= BAND_MILLI;  // 0.1% 14dBm
00596     } else {
00597         if( band > BAND_AUX ) return 0;
00598         freq = (freq&~3) | band;
00599     }
00600     LMIC.channelFreq [chidx] = freq;
00601     LMIC.channelDrMap[chidx] = drmap==0 ? DR_RANGE_MAP(DR_SF12,DR_SF7) : drmap;
00602     LMIC.channelMap |= 1<<chidx;  // enabled right away
00603     return 1;
00604 }
00605 
00606 void LMIC_disableChannel (u1_t channel) {
00607     LMIC.channelFreq[channel] = 0;
00608     LMIC.channelDrMap[channel] = 0;
00609     LMIC.channelMap &= ~(1<<channel);
00610 }
00611 
00612 static u4_t convFreq (xref2u1_t ptr) {
00613     u4_t freq = (os_rlsbf4(ptr-1) >> 8) * 100;
00614     if( freq < EU868_FREQ_MIN || freq > EU868_FREQ_MAX )
00615         freq = 0;
00616     return freq;
00617 }
00618 
00619 static u1_t mapChannels (u1_t chpage, u2_t chmap) {
00620     // Bad page, disable all channel, enable non-existent
00621     if( chpage != 0 || chmap==0 || (chmap & ~LMIC.channelMap) != 0 )
00622         return 0;  // illegal input
00623     for( u1_t chnl=0; chnl<MAX_CHANNELS; chnl++ ) {
00624         if( (chmap & (1<<chnl)) != 0 && LMIC.channelFreq[chnl] == 0 )
00625             chmap &= ~(1<<chnl); // ignore - channel is not defined
00626     }
00627     LMIC.channelMap = chmap;
00628     return 1;
00629 }
00630 
00631 
00632 static void updateTx (ostime_t txbeg) {
00633     u4_t freq = LMIC.channelFreq[LMIC.txChnl];
00634     // Update global/band specific duty cycle stats
00635     ostime_t airtime = calcAirTime(LMIC.rps, LMIC.dataLen);
00636     // Update channel/global duty cycle stats
00637     xref2band_t band = &LMIC.bands[freq & 0x3];
00638     LMIC.freq  = freq & ~(u4_t)3;
00639     LMIC.txpow = band->txpow;
00640     band->avail = txbeg + airtime * band->txcap;
00641     if( LMIC.globalDutyRate != 0 )
00642         LMIC.globalDutyAvail = txbeg + (airtime<<LMIC.globalDutyRate);
00643 }
00644 
00645 static ostime_t nextTx (ostime_t now) {
00646     u1_t bmap=0xF;
00647     do {
00648         ostime_t mintime = now + /*10h*/36000*OSTICKS_PER_SEC;
00649         u1_t band=0;
00650         for( u1_t bi=0; bi<4; bi++ ) {
00651             if( (bmap & (1<<bi)) && mintime - LMIC.bands[bi].avail > 0 )
00652                 mintime = LMIC.bands[band = bi].avail;
00653         }
00654         // Find next channel in given band
00655         u1_t chnl = LMIC.bands[band].lastchnl;
00656         for( u1_t ci=0; ci<MAX_CHANNELS; ci++ ) {
00657             if( (chnl = (chnl+1)) >= MAX_CHANNELS )
00658                 chnl -=  MAX_CHANNELS;
00659             if( (LMIC.channelMap & (1<<chnl)) != 0  &&  // channel enabled
00660                 (LMIC.channelDrMap[chnl] & (1<<(LMIC.datarate&0xF))) != 0  &&
00661                 band == (LMIC.channelFreq[chnl] & 0x3) ) { // in selected band
00662                 LMIC.txChnl = LMIC.bands[band].lastchnl = chnl;
00663                 return mintime;
00664             }
00665         }
00666         if( (bmap &= ~(1<<band)) == 0 ) {
00667             // No feasible channel  found!
00668             return mintime;
00669         }
00670     } while(1);
00671 }
00672 
00673 
00674 static void setBcnRxParams (void) {
00675     LMIC.dataLen = 0;
00676     LMIC.freq = LMIC.channelFreq[LMIC.bcnChnl] & ~(u4_t)3;
00677     LMIC.rps  = setIh(setNocrc(dndr2rps((dr_t)DR_BCN),1),LEN_BCN);
00678 }
00679 
00680 #define setRx1Params() /*LMIC.freq/rps remain unchanged*/
00681 
00682 static void initJoinLoop (void) {       // eu868
00683     LMIC.txChnl = os_getRndU1() % 6;
00684     LMIC.adrTxPow = 14;
00685     setDrJoin(DRCHG_SET, DR_SF7);
00686     initDefaultChannels(1);
00687     ASSERT((LMIC.opmode & OP_NEXTCHNL)==0);
00688     LMIC.txend = LMIC.bands[BAND_MILLI].avail + rndDelay(8);
00689 }
00690 
00691 
00692 static ostime_t nextJoinState (void) {
00693     u1_t failed = 0;
00694 
00695     // Try 869.x and then 864.x with same DR
00696     // If both fail try next lower datarate
00697     if( ++LMIC.txChnl == 6 )
00698         LMIC.txChnl = 0;
00699     if( (++LMIC.txCnt & 1) == 0 ) {
00700         // Lower DR every 2nd try (having tried 868.x and 864.x with the same DR)
00701         if( LMIC.datarate == DR_SF12 )
00702             failed = 1; // we have tried all DR - signal EV_JOIN_FAILED
00703         else
00704             setDrJoin(DRCHG_NOJACC, decDR((dr_t)LMIC.datarate));
00705     }
00706     // Clear NEXTCHNL because join state engine controls channel hopping
00707     LMIC.opmode &= ~OP_NEXTCHNL;
00708     // Move txend to randomize synchronized concurrent joins.
00709     // Duty cycle is based on txend.
00710     ostime_t time = os_getTime();
00711     if( time - LMIC.bands[BAND_MILLI].avail < 0 )
00712         time = LMIC.bands[BAND_MILLI].avail;
00713     LMIC.txend = time +
00714         (isTESTMODE()
00715          // Avoid collision with JOIN ACCEPT @ SF12 being sent by GW (but we missed it)
00716          ? DNW2_SAFETY_ZONE
00717          // Otherwise: randomize join (street lamp case):
00718          // SF12:255, SF11:127, .., SF7:8secs
00719          : DNW2_SAFETY_ZONE+rndDelay(255>>LMIC.datarate));
00720     // 1 - triggers EV_JOIN_FAILED event
00721     return failed;
00722 }
00723 
00724 //
00725 // END: EU868 related stuff
00726 //
00727 // ================================================================================
00728 #elif defined(CFG_us915)
00729 // ================================================================================
00730 //
00731 // BEG: US915 related stuff
00732 //
00733 
00734 
00735 static void initDefaultChannels (void)
00736 {
00737 #ifdef CHNL_HYBRID
00738         int idx = CHNL_HYBRID >> 1;
00739         LMIC.channelMap[0] = 0x0000;
00740         LMIC.channelMap[1] = 0x0000;
00741         LMIC.channelMap[2] = 0x0000;
00742         LMIC.channelMap[3] = 0x0000;
00743         if (CHNL_HYBRID & 1)
00744             LMIC.channelMap[idx] = 0xff00;
00745         else
00746             LMIC.channelMap[idx] = 0x00ff;
00747             
00748         LMIC.channelMap[4] = 1 << CHNL_HYBRID;
00749         LMIC.txpow_limit = 20;
00750 #else
00751     for( u1_t i=0; i<4; i++ )
00752         LMIC.channelMap[i] = 0xFFFF;
00753     LMIC.channelMap[4] = 0x00FF;
00754     
00755     LMIC.txpow_limit = 30;
00756 #endif
00757 
00758     LMIC.txpow = LMIC.txpow_limit;
00759     LMIC.adrTxPow = LMIC.txpow_limit;
00760 }
00761 
00762 static u4_t convFreq (xref2u1_t ptr) {
00763     u4_t freq = (os_rlsbf4(ptr-1) >> 8) * 100;
00764     if( freq < US915_FREQ_MIN || freq > US915_FREQ_MAX )
00765         freq = 0;
00766     return freq;
00767 }
00768 
00769 bit_t LMIC_setupChannel (u1_t chidx, u4_t freq, u2_t drmap, s1_t band) {
00770     if( chidx < 72 || chidx >= 72+MAX_XCHANNELS )
00771         return 0; // channels 0..71 are hardwired
00772     chidx -= 72;
00773     LMIC.xchFreq[chidx] = freq;
00774     LMIC.xchDrMap[chidx] = drmap==0 ? DR_RANGE_MAP(DR_SF10,DR_SF8C) : drmap;
00775     LMIC.channelMap[chidx>>4] |= (1<<(chidx&0xF));
00776     return 1;
00777 }
00778 
00779 void LMIC_disableChannel (u1_t channel) {
00780     if( channel < 72+MAX_XCHANNELS )
00781         LMIC.channelMap[channel/4] &= ~(1<<(channel&0xF));
00782 }
00783 
00784 static u1_t mapChannels (u1_t chpage, u2_t chmap) {
00785     if( chpage == MCMD_LADR_CHP_125ON || chpage == MCMD_LADR_CHP_125OFF ) {
00786         u2_t en125 = chpage == MCMD_LADR_CHP_125ON ? 0xFFFF : 0x0000;
00787         for( u1_t u=0; u<4; u++ )
00788             LMIC.channelMap[u] = en125;
00789         LMIC.channelMap[64/16] = chmap;
00790     } else {
00791         if( chpage >= (72+MAX_XCHANNELS+15)/16 )
00792             return 0;
00793         LMIC.channelMap[chpage] = chmap;
00794     }
00795     return 1;
00796 }
00797 
00798 static void updateTx (ostime_t txbeg) {
00799     u1_t chnl = LMIC.txChnl;
00800 #ifdef JOIN_REQ_DEBUG    
00801     printf("chnl%d ", chnl);
00802 #endif /* JOIN_REQ_DEBUG */  
00803     if( chnl < 64 ) {
00804         LMIC.freq = US915_125kHz_UPFBASE + chnl*US915_125kHz_UPFSTEP;
00805 #ifdef JOIN_REQ_DEBUG
00806     printf("%d (125khz)\r\n", LMIC.freq);
00807 #endif /* JOIN_REQ_DEBUG */    
00808         return;
00809     }
00810     
00811     /* using 500KHz channel */
00812     if (LMIC.txpow_limit >= 26)
00813         LMIC.txpow = 26;
00814     else
00815         LMIC.txpow = LMIC.txpow_limit;
00816         
00817     if( chnl < 64+8 ) {
00818         LMIC.freq = US915_500kHz_UPFBASE + (chnl-64)*US915_500kHz_UPFSTEP;
00819 #ifdef JOIN_REQ_DEBUG
00820     printf("%d (500k)\r\n", LMIC.freq);
00821 #endif /* JOIN_REQ_DEBUG */            
00822     } else {
00823         ASSERT(chnl < 64+8+MAX_XCHANNELS);
00824         LMIC.freq = LMIC.xchFreq[chnl-72];
00825 #ifdef JOIN_REQ_DEBUG
00826     printf("%d (x)\r\n", LMIC.freq);
00827 #endif /* JOIN_REQ_DEBUG */           
00828     }
00829 
00830     // Update global duty cycle stats
00831     if( LMIC.globalDutyRate != 0 ) {
00832         ostime_t airtime = calcAirTime(LMIC.rps, LMIC.dataLen);
00833         LMIC.globalDutyAvail = txbeg + (airtime<<LMIC.globalDutyRate);
00834     }
00835 }
00836 
00837 int count_bits(u2_t v)
00838 {
00839     int c;
00840     
00841     for (c = 0; v; c++) {
00842         v &= v - 1; // clear the last significant bit set
00843     }
00844 
00845     return c;
00846 }
00847 
00848 // US does not have duty cycling - return now as earliest TX time
00849 #define nextTx(now) (_nextTx(),(now))
00850 static void _nextTx (void) {
00851     u1_t prev_ch = LMIC.txChnl;
00852     u1_t tries = 0;
00853     u1_t en_cnt;
00854     
00855     if( LMIC.datarate >= DR_SF8C ) { // 500kHz
00856 #ifdef CHNL_HYBRID
00857         LMIC.txChnl = 1 << CHNL_HYBRID; // only one channel possible
00858 #else
00859         en_cnt = count_bits(LMIC.channelMap[4]);
00860         do {
00861             do {
00862                 LMIC.chRnd = os_getRndU1() & 7;
00863                 if (++tries > 48)
00864                     return;
00865             } while ( !(LMIC.channelMap[4] & (1 << LMIC.chRnd)) );
00866             LMIC.txChnl = 64 + LMIC.chRnd;
00867             if (en_cnt < 2)
00868                 prev_ch = LMIC.txChnl + 1;  // not enough enabled, skip the following test
00869                 
00870         } while (prev_ch == LMIC.txChnl);
00871 #endif
00872     } else { // 125kHz
00873 #ifdef CHNL_HYBRID
00874         u1_t idx = CHNL_HYBRID >> 1;
00875         en_cnt = count_bits(LMIC.channelMap[idx]);
00876         do {
00877             do {
00878                 LMIC.chRnd = os_getRndU1() & 15;
00879                 if (++tries > 96)
00880                     return;
00881             } while ( !(LMIC.channelMap[idx] & (1 << LMIC.chRnd)) );
00882             LMIC.txChnl = (idx << 4) + LMIC.chRnd;
00883             if (en_cnt < 2)
00884                 prev_ch = LMIC.txChnl + 1;  // not enough enabled, skip the following test
00885                             
00886         } while (prev_ch == LMIC.txChnl);
00887 #else
00888         en_cnt = count_bits(LMIC.channelMap[0]);
00889         en_cnt += count_bits(LMIC.channelMap[1]);
00890         en_cnt += count_bits(LMIC.channelMap[2]);
00891         en_cnt += count_bits(LMIC.channelMap[3]);
00892         do {
00893             do {
00894                 LMIC.chRnd = os_getRndU1() & 63;
00895             } while ( !(LMIC.channelMap[LMIC.chRnd >> 4] & (1 << (LMIC.chRnd & 15))) );
00896             LMIC.txChnl = LMIC.chRnd;
00897             if (en_cnt < 2)
00898                 prev_ch = LMIC.txChnl + 1;  // not enough enabled, skip the following test
00899                 
00900         } while (prev_ch == LMIC.txChnl);
00901 #endif
00902     }
00903 }
00904 
00905 static void setBcnRxParams (void) {
00906     LMIC.dataLen = 0;
00907     LMIC.freq = US915_500kHz_DNFBASE + LMIC.bcnChnl * US915_500kHz_DNFSTEP;
00908     LMIC.rps  = setIh(setNocrc(dndr2rps((dr_t)DR_BCN),1),LEN_BCN);
00909 }
00910 
00911 #define setRx1Params() {                                                \
00912     LMIC.freq = US915_500kHz_DNFBASE + (LMIC.txChnl & 0x7) * US915_500kHz_DNFSTEP; \
00913     if( /* TX datarate */LMIC.dndr < DR_SF8C )                          \
00914         LMIC.dndr += DR_SF10CR - DR_SF10;                               \
00915     else if( LMIC.dndr == DR_SF8C )                                     \
00916         LMIC.dndr = DR_SF7CR;                                           \
00917     LMIC.rps = dndr2rps(LMIC.dndr);                                     \
00918 }
00919 
00920 static void initJoinLoop (void) {
00921     LMIC.chRnd = 0;
00922     LMIC.txChnl = 0;
00923     LMIC.joinBlockChnl = 0;
00924     LMIC.joinBlock = 0;
00925     LMIC.datarate = DR_SF10;
00926     LMIC.adrTxPow = LMIC.txpow_limit;
00927     ASSERT((LMIC.opmode & OP_NEXTCHNL)==0);
00928     LMIC.txend = os_getTime();
00929     setDrJoin(DRCHG_SET, DR_SF7);
00930 }
00931 
00932 static ostime_t nextJoinState (void) {
00933     u1_t failed = 0;
00934     
00935 #if 0
00936     // Try the following:
00937     //   SF7/8/9/10  on a random channel 0..63
00938     //   SF8C        on a random channel 64..71
00939     //
00940     if( LMIC.datarate != DR_SF8C ) {
00941         _nextTx();
00942         setDrJoin(DRCHG_SET, DR_SF8C);
00943     } else {
00944         _nextTx();
00945         s1_t dr = DR_SF7 - ++LMIC.txCnt;
00946         if( dr < DR_SF10 ) {
00947             dr = DR_SF10;
00948             failed = 1; // All DR exhausted - signal failed
00949         }
00950         setDrJoin(DRCHG_SET, dr);
00951     }
00952 #endif /* #if 0 */
00953 
00954     if( LMIC.datarate == DR_SF8C ) {
00955         // attempted 500khz channel, try 125khz channel in next block
00956         LMIC.datarate = DR_SF10;
00957         if (++LMIC.joinBlock == 8) {
00958             LMIC.joinBlock = 0;
00959             if (++LMIC.joinBlockChnl == 8)
00960                 LMIC.joinBlockChnl = 0;
00961         }
00962         LMIC.txChnl = (LMIC.joinBlock << 3) + LMIC.joinBlockChnl;
00963     } else {
00964         // attempted 125khz channel, try 500khz channel
00965         LMIC.datarate = DR_SF8C;
00966         LMIC.txChnl = LMIC.joinBlock + 64;
00967     }
00968 #ifdef JOIN_REQ_DEBUG
00969     printf("njs blk%d, dr%d, txChnl%d ", LMIC.joinBlock, LMIC.datarate, LMIC.txChnl); // crlf in updateTx()
00970 #endif /* JOIN_REQ_DEBUG */
00971     
00972     LMIC.opmode &= ~OP_NEXTCHNL;
00973     LMIC.txend = os_getTime() +
00974         (isTESTMODE()
00975          // Avoid collision with JOIN ACCEPT being sent by GW (but we missed it - GW is still busy)
00976          ? DNW2_SAFETY_ZONE
00977          // Otherwise: randomize join (street lamp case):
00978          // SF10:16, SF9=8,..SF8C:1secs
00979          : rndDelay(16>>LMIC.datarate));
00980     // 1 - triggers EV_JOIN_FAILED event
00981     return failed;
00982 }
00983 
00984 //
00985 // END: US915 related stuff
00986 //
00987 // ================================================================================
00988 #else
00989 #error Unsupported frequency band!
00990 #endif
00991 
00992 
00993 static void runEngineUpdate (xref2osjob_t osjob) {
00994     engineUpdate();
00995 }
00996 
00997 
00998 static void reportEvent (ev_t ev) {
00999     EV(devCond, INFO, (e_.reason = EV::devCond_t::LMIC_EV,
01000                        e_.eui    = MAIN::CDEV->getEui(),
01001                        e_.info   = ev));
01002     ON_LMIC_EVENT(ev);
01003     engineUpdate();
01004 }
01005 
01006 
01007 static void runReset (xref2osjob_t osjob) {
01008     // Disable session
01009     LMIC_reset();
01010     LMIC_startJoining();
01011     reportEvent(EV_RESET);
01012 }
01013 
01014 static void stateJustJoined (void) {
01015     LMIC.seqnoDn     = LMIC.seqnoUp = 0;
01016     LMIC.rejoinCnt   = 0;
01017     LMIC.dnConf      = LMIC.adrChanged = LMIC.ladrAns = LMIC.devsAns = 0;
01018     LMIC.moreData    = LMIC.dn2Ans = LMIC.snchAns = LMIC.dutyCapAns = 0;
01019     LMIC.pingSetAns  = 0;
01020     LMIC.upRepeat    = 0;
01021     LMIC.adrAckReq   = LINK_CHECK_INIT;
01022     LMIC.dn2Dr       = DR_DNW2;
01023     LMIC.dn2Freq     = FREQ_DNW2;
01024     LMIC.bcnChnl     = CHNL_BCN;
01025     LMIC.ping.freq   = FREQ_PING;
01026     LMIC.ping.dr     = DR_PING;
01027 }
01028 
01029 
01030 // ================================================================================
01031 // Decoding frames
01032 
01033 
01034 // Decode beacon  - do not overwrite bcninfo unless we have a match!
01035 static int decodeBeacon (void) {
01036     ASSERT(LMIC.dataLen == LEN_BCN); // implicit header RX guarantees this
01037     xref2u1_t d = LMIC.frame;
01038     if(
01039 #ifdef CFG_eu868
01040         d[OFF_BCN_CRC1] != (u1_t)os_crc16(d,OFF_BCN_CRC1)
01041 #elif defined(CFG_us915)
01042         os_rlsbf2(&d[OFF_BCN_CRC1]) != os_crc16(d,OFF_BCN_CRC1)
01043 #endif
01044         )
01045         return 0;   // first (common) part fails CRC check
01046     // First set of fields is ok
01047     u4_t bcnnetid = os_rlsbf4(&d[OFF_BCN_NETID]) & 0xFFFFFF;
01048     if( bcnnetid != LMIC.netid )
01049         return -1;  // not the beacon we're looking for
01050 
01051     LMIC.bcninfo.flags &= ~(BCN_PARTIAL|BCN_FULL);
01052     // Match - update bcninfo structure
01053     LMIC.bcninfo.snr    = LMIC.snr;
01054     LMIC.bcninfo.rssi   = LMIC.rssi;
01055     LMIC.bcninfo.txtime = LMIC.rxtime - AIRTIME_BCN_osticks;
01056     LMIC.bcninfo.time   = os_rlsbf4(&d[OFF_BCN_TIME]);
01057     LMIC.bcninfo.flags |= BCN_PARTIAL;
01058 
01059     // Check 2nd set
01060     if( os_rlsbf2(&d[OFF_BCN_CRC2]) != os_crc16(d,OFF_BCN_CRC2) )
01061         return 1;
01062     // Second set of fields is ok
01063     LMIC.bcninfo.lat    = (s4_t)os_rlsbf4(&d[OFF_BCN_LAT-1]) >> 8; // read as signed 24-bit
01064     LMIC.bcninfo.lon    = (s4_t)os_rlsbf4(&d[OFF_BCN_LON-1]) >> 8; // ditto
01065     LMIC.bcninfo.info   = d[OFF_BCN_INFO];
01066     LMIC.bcninfo.flags |= BCN_FULL;
01067     return 2;
01068 }
01069 
01070 
01071 static bit_t decodeFrame (void) {
01072     xref2u1_t d = LMIC.frame;
01073     u1_t hdr    = d[0];
01074     u1_t ftype  = hdr & HDR_FTYPE;
01075     int  dlen   = LMIC.dataLen;
01076     if( dlen < OFF_DAT_OPTS+4 ||
01077         (hdr & HDR_MAJOR) != HDR_MAJOR_V1 ||
01078         (ftype != HDR_FTYPE_DADN  &&  ftype != HDR_FTYPE_DCDN) ) {
01079         // Basic sanity checks failed
01080         EV(specCond, WARN, (e_.reason = EV::specCond_t::UNEXPECTED_FRAME,
01081                             e_.eui    = MAIN::CDEV->getEui(),
01082                             e_.info   = dlen < 4 ? 0 : os_rlsbf4(&d[dlen-4]),
01083                             e_.info2  = hdr + (dlen<<8)));
01084       norx:
01085         LMIC.dataLen = 0;
01086         return 0;
01087     }
01088     // Validate exact frame length
01089     // Note: device address was already read+evaluated in order to arrive here.
01090     int  fct   = d[OFF_DAT_FCT];
01091     u4_t addr  = os_rlsbf4(&d[OFF_DAT_ADDR]);
01092     u4_t seqno = os_rlsbf2(&d[OFF_DAT_SEQNO]);
01093     int  olen  = fct & FCT_OPTLEN;
01094     int  ackup = (fct & FCT_ACK) != 0 ? 1 : 0;   // ACK last up frame
01095     int  poff  = OFF_DAT_OPTS+olen;
01096     int  pend  = dlen-4;  // MIC
01097 
01098     if( addr != LMIC.devaddr ) {
01099         EV(specCond, WARN, (e_.reason = EV::specCond_t::ALIEN_ADDRESS,
01100                             e_.eui    = MAIN::CDEV->getEui(),
01101                             e_.info   = addr,
01102                             e_.info2  = LMIC.devaddr));
01103         goto norx;
01104     }
01105     if( poff > pend ) {
01106         EV(specCond, ERR, (e_.reason = EV::specCond_t::CORRUPTED_FRAME,
01107                            e_.eui    = MAIN::CDEV->getEui(),
01108                            e_.info   = 0x1000000 + (poff-pend) + (fct<<8) + (dlen<<16)));
01109         goto norx;
01110     }
01111 
01112     int port = -1;
01113     int replayConf = 0;
01114 
01115     if( pend > poff )
01116         port = d[poff++];
01117 
01118     seqno = LMIC.seqnoDn + (u2_t)(seqno - LMIC.seqnoDn);
01119 
01120     if( !aes_verifyMic(LMIC.nwkKey, LMIC.devaddr, seqno, /*dn*/1, d, pend) ) {
01121         EV(spe3Cond, ERR, (e_.reason = EV::spe3Cond_t::CORRUPTED_MIC,
01122                            e_.eui1   = MAIN::CDEV->getEui(),
01123                            e_.info1  = Base::lsbf4(&d[pend]),
01124                            e_.info2  = seqno,
01125                            e_.info3  = LMIC.devaddr));
01126         goto norx;
01127     }
01128     if( seqno < LMIC.seqnoDn ) {
01129         if( (s4_t)seqno > (s4_t)LMIC.seqnoDn ) {
01130             EV(specCond, INFO, (e_.reason = EV::specCond_t::DNSEQNO_ROLL_OVER,
01131                                 e_.eui    = MAIN::CDEV->getEui(),
01132                                 e_.info   = LMIC.seqnoDn, 
01133                                 e_.info2  = seqno));
01134             goto norx;
01135         }
01136         if( seqno != LMIC.seqnoDn-1 || !LMIC.dnConf || ftype != HDR_FTYPE_DCDN ) {
01137             EV(specCond, INFO, (e_.reason = EV::specCond_t::DNSEQNO_OBSOLETE,
01138                                 e_.eui    = MAIN::CDEV->getEui(),
01139                                 e_.info   = LMIC.seqnoDn, 
01140                                 e_.info2  = seqno));
01141             goto norx;
01142         }
01143         // Replay of previous sequence number allowed only if
01144         // previous frame and repeated both requested confirmation
01145         replayConf = 1;
01146     }
01147     else {
01148         if( seqno > LMIC.seqnoDn ) {
01149             EV(specCond, INFO, (e_.reason = EV::specCond_t::DNSEQNO_SKIP,
01150                                 e_.eui    = MAIN::CDEV->getEui(),
01151                                 e_.info   = LMIC.seqnoDn, 
01152                                 e_.info2  = seqno));
01153         }
01154         LMIC.seqnoDn = seqno+1;  // next number to be expected
01155         DO_DEVDB(LMIC.seqnoDn,seqnoDn);
01156         // DN frame requested confirmation - provide ACK once with next UP frame
01157         LMIC.dnConf = (ftype == HDR_FTYPE_DCDN ? FCT_ACK : 0);
01158     }
01159 
01160     if( LMIC.dnConf || (fct & FCT_MORE) )
01161         LMIC.opmode |= OP_POLL;
01162 
01163     // We heard from network
01164     LMIC.adrChanged = LMIC.rejoinCnt = 0;
01165     if( LMIC.adrAckReq != LINK_CHECK_OFF )
01166         LMIC.adrAckReq = LINK_CHECK_INIT;
01167 
01168     // Process OPTS
01169     int m = LMIC.rssi - RSSI_OFF - getSensitivity(LMIC.rps);
01170     LMIC.margin = m < 0 ? 0 : m > 254 ? 254 : m;
01171 
01172     xref2u1_t opts = &d[OFF_DAT_OPTS];
01173     int oidx = 0;
01174     while( oidx < olen ) {
01175         switch( opts[oidx] ) {
01176         case MCMD_LCHK_ANS: {
01177             //int gwmargin = opts[oidx+1];
01178             //int ngws = opts[oidx+2];
01179             oidx += 3;
01180             continue;
01181         }
01182         case MCMD_LADR_REQ: {
01183             u1_t p1     = opts[oidx+1];            // txpow + DR
01184             u2_t chmap  = os_rlsbf2(&opts[oidx+2]);// list of enabled channels
01185             u1_t chpage = opts[oidx+4] & MCMD_LADR_CHPAGE_MASK;     // channel page
01186             u1_t uprpt  = opts[oidx+4] & MCMD_LADR_REPEAT_MASK;     // up repeat count
01187             oidx += 5;
01188 
01189             LMIC.ladrAns = 0x80 |     // Include an answer into next frame up
01190                 MCMD_LADR_ANS_POWACK | MCMD_LADR_ANS_CHACK | MCMD_LADR_ANS_DRACK;
01191             if( !mapChannels(chpage, chmap) )
01192                 LMIC.ladrAns &= ~MCMD_LADR_ANS_CHACK;
01193             dr_t dr = (dr_t)(p1>>MCMD_LADR_DR_SHIFT);
01194             if( !validDR(dr) ) {
01195                 LMIC.ladrAns &= ~MCMD_LADR_ANS_DRACK;
01196                 EV(specCond, ERR, (e_.reason = EV::specCond_t::BAD_MAC_CMD,
01197                                    e_.eui    = MAIN::CDEV->getEui(),
01198                                    e_.info   = Base::lsbf4(&d[pend]),
01199                                    e_.info2  = Base::msbf4(&opts[oidx-4])));
01200             }
01201             if( (LMIC.ladrAns & 0x7F) == (MCMD_LADR_ANS_POWACK | MCMD_LADR_ANS_CHACK | MCMD_LADR_ANS_DRACK) ) {
01202                 // Nothing went wrong - use settings
01203                 LMIC.upRepeat = uprpt;
01204                 setDrTxpow(DRCHG_NWKCMD, dr, pow2dBm(p1));
01205             }
01206             LMIC.adrChanged = 1;  // Trigger an ACK to NWK
01207             continue;
01208         }
01209         case MCMD_DEVS_REQ: {
01210             LMIC.devsAns = 1;
01211             oidx += 1;
01212             continue;
01213         }
01214         case MCMD_DN2P_SET: {
01215             dr_t dr = (dr_t)(opts[oidx+1] & 0x0F);
01216             u4_t freq = convFreq(&opts[oidx+2]);
01217             oidx += 5;
01218             LMIC.dn2Ans = 0x80;   // answer pending
01219             if( validDR(dr) )
01220                 LMIC.dn2Ans |= MCMD_DN2P_ANS_DRACK;
01221             if( freq != 0 )
01222                 LMIC.dn2Ans |= MCMD_DN2P_ANS_CHACK;
01223             if( LMIC.dn2Ans == (0x80|MCMD_DN2P_ANS_DRACK|MCMD_DN2P_ANS_CHACK) ) {
01224                 LMIC.dn2Dr = dr;
01225                 LMIC.dn2Freq = freq;
01226                 DO_DEVDB(LMIC.dn2Dr,dn2Dr);
01227                 DO_DEVDB(LMIC.dn2Freq,dn2Freq);
01228             }
01229             continue;
01230         }
01231         case MCMD_DCAP_REQ: {
01232             u1_t cap = opts[oidx+1];
01233             oidx += 2;
01234             // A value cap=0xFF means device is OFF unless enabled again manually.
01235             if( cap==0xFF )
01236                 LMIC.opmode |= OP_SHUTDOWN;  // stop any sending
01237             LMIC.globalDutyRate  = cap & 0xF;
01238             LMIC.globalDutyAvail = os_getTime();
01239             DO_DEVDB(cap,dutyCap);
01240             LMIC.dutyCapAns = 1;
01241             continue;
01242         }
01243         case MCMD_SNCH_REQ: {
01244             u1_t chidx = opts[oidx+1];  // channel
01245             u4_t freq  = convFreq(&opts[oidx+2]); // freq
01246             u1_t drs   = opts[oidx+5];  // datarate span
01247             LMIC.snchAns = 0x80;
01248             if( freq != 0 && LMIC_setupChannel(chidx, freq, DR_RANGE_MAP(drs&0xF,drs>>4), -1) )
01249                 LMIC.snchAns |= MCMD_SNCH_ANS_DRACK|MCMD_SNCH_ANS_FQACK;
01250             oidx += 6;
01251             continue;
01252         }
01253         case MCMD_PING_SET: {
01254             u4_t freq = convFreq(&opts[oidx+1]);
01255             oidx += 4;
01256             u1_t flags = 0x80;
01257             if( freq != 0 ) {
01258                 flags |= MCMD_PING_ANS_FQACK;
01259                 LMIC.ping.freq = freq;
01260                 DO_DEVDB(LMIC.ping.intvExp, pingIntvExp);
01261                 DO_DEVDB(LMIC.ping.freq, pingFreq);
01262                 DO_DEVDB(LMIC.ping.dr, pingDr);
01263             }
01264             LMIC.pingSetAns = flags;
01265             continue;
01266         }
01267         case MCMD_BCNI_ANS: {
01268             // Ignore if tracking already enabled
01269             if( (LMIC.opmode & OP_TRACK) == 0 ) {
01270                 LMIC.bcnChnl = opts[oidx+3];
01271                 // Enable tracking - bcninfoTries
01272                 LMIC.opmode |= OP_TRACK;
01273                 // Cleared later in txComplete handling - triggers EV_BEACON_FOUND
01274                 ASSERT(LMIC.bcninfoTries!=0);
01275                 // Setup RX parameters
01276                 LMIC.bcninfo.txtime = (LMIC.rxtime
01277                                        + ms2osticks(os_rlsbf2(&opts[oidx+1]) * MCMD_BCNI_TUNIT)
01278                                        + ms2osticksCeil(MCMD_BCNI_TUNIT/2)
01279                                        - BCN_INTV_osticks);
01280                 LMIC.bcninfo.flags = 0;  // txtime above cannot be used as reference (BCN_PARTIAL|BCN_FULL cleared)
01281                 calcBcnRxWindowFromMillis(MCMD_BCNI_TUNIT,1);  // error of +/-N ms 
01282 
01283                 EV(lostFrame, INFO, (e_.reason  = EV::lostFrame_t::MCMD_BCNI_ANS,
01284                                      e_.eui     = MAIN::CDEV->getEui(),
01285                                      e_.lostmic = Base::lsbf4(&d[pend]),
01286                                      e_.info    = (LMIC.missedBcns |
01287                                                    (osticks2us(LMIC.bcninfo.txtime + BCN_INTV_osticks
01288                                                                - LMIC.bcnRxtime) << 8)),
01289                                      e_.time    = MAIN::CDEV->ostime2ustime(LMIC.bcninfo.txtime + BCN_INTV_osticks)));
01290             }
01291             oidx += 4;
01292             continue;
01293         }
01294         }
01295         EV(specCond, ERR, (e_.reason = EV::specCond_t::BAD_MAC_CMD,
01296                            e_.eui    = MAIN::CDEV->getEui(),
01297                            e_.info   = Base::lsbf4(&d[pend]),
01298                            e_.info2  = Base::msbf4(&opts[oidx])));
01299         break;
01300     }
01301     if( oidx != olen ) {
01302         EV(specCond, ERR, (e_.reason = EV::specCond_t::CORRUPTED_FRAME,
01303                            e_.eui    = MAIN::CDEV->getEui(),
01304                            e_.info   = 0x1000000 + (oidx) + (olen<<8)));
01305     }
01306 
01307     if( !replayConf ) {
01308         // Handle payload only if not a replay
01309         // Decrypt payload - if any
01310         if( port >= 0  &&  pend-poff > 0 )
01311             aes_cipher(port <= 0 ? LMIC.nwkKey : LMIC.artKey, LMIC.devaddr, seqno, /*dn*/1, d+poff, pend-poff);
01312 
01313         EV(dfinfo, DEBUG, (e_.deveui  = MAIN::CDEV->getEui(),
01314                            e_.devaddr = LMIC.devaddr,
01315                            e_.seqno   = seqno,
01316                            e_.flags   = (port < 0 ? EV::dfinfo_t::NOPORT : 0) | EV::dfinfo_t::DN,
01317                            e_.mic     = Base::lsbf4(&d[pend]),
01318                            e_.hdr     = d[LORA::OFF_DAT_HDR],
01319                            e_.fct     = d[LORA::OFF_DAT_FCT],
01320                            e_.port    = port,
01321                            e_.plen    = dlen,
01322                            e_.opts.length = olen,
01323                            memcpy(&e_.opts[0], opts, olen)));
01324     } else {
01325         EV(specCond, INFO, (e_.reason = EV::specCond_t::DNSEQNO_REPLAY,
01326                             e_.eui    = MAIN::CDEV->getEui(),
01327                             e_.info   = Base::lsbf4(&d[pend]),
01328                             e_.info2  = seqno));
01329     }
01330 
01331     if( // NWK acks but we don't have a frame pending
01332         (ackup && LMIC.txCnt == 0) ||
01333         // We sent up confirmed and we got a response in DNW1/DNW2
01334         // BUT it did not carry an ACK - this should never happen
01335         // Do not resend and assume frame was not ACKed.
01336         (!ackup && LMIC.txCnt != 0) ) {
01337         EV(specCond, ERR, (e_.reason = EV::specCond_t::SPURIOUS_ACK,
01338                            e_.eui    = MAIN::CDEV->getEui(),
01339                            e_.info   = seqno,
01340                            e_.info2  = ackup));
01341     }
01342 
01343     if( LMIC.txCnt != 0 ) // we requested an ACK
01344         LMIC.txrxFlags |= ackup ? TXRX_ACK : TXRX_NACK;
01345 
01346     if( port < 0 ) {
01347         LMIC.txrxFlags |= TXRX_NOPORT;
01348         LMIC.dataBeg = poff;
01349         LMIC.dataLen = 0;
01350     } else {
01351         LMIC.txrxFlags |= TXRX_PORT;
01352         LMIC.dataBeg = poff;
01353         LMIC.dataLen = pend-poff;
01354     }
01355     return 1;
01356 }
01357 
01358 
01359 // ================================================================================
01360 // TX/RX transaction support
01361 
01362 
01363 static void setupRx2 (void) {
01364     LMIC.txrxFlags = TXRX_DNW2;
01365     LMIC.rps = dndr2rps(LMIC.dn2Dr);
01366     LMIC.freq = LMIC.dn2Freq;
01367     LMIC.dataLen = 0;
01368     os_radio(RADIO_RX);
01369 }
01370 
01371 
01372 static void schedRx2 (ostime_t delay, osjobcb_t func) {
01373     // Add 1.5 symbols we need 5 out of 8. Try to sync 1.5 symbols into the preamble.
01374     LMIC.rxtime = LMIC.txend + delay + (PAMBL_SYMS-MINRX_SYMS)*dr2hsym(LMIC.dn2Dr);
01375     os_setTimedCallback(&LMIC.osjob, LMIC.rxtime - RX_RAMPUP, func);
01376 }
01377 
01378 static void setupRx1 (osjobcb_t func) {
01379     LMIC.txrxFlags = TXRX_DNW1;
01380     // Turn LMIC.rps from TX over to RX
01381     LMIC.rps = setNocrc(LMIC.rps,1);
01382     LMIC.dataLen = 0;
01383     LMIC.osjob.func = func;
01384     os_radio(RADIO_RX);
01385 }
01386 
01387 
01388 // Called by HAL once TX complete and delivers exact end of TX time stamp in LMIC.rxtime
01389 static void txDone (ostime_t delay, osjobcb_t func) {
01390     if( (LMIC.opmode & (OP_TRACK|OP_PINGABLE|OP_PINGINI)) == (OP_TRACK|OP_PINGABLE) ) {
01391         rxschedInit(&LMIC.ping);    // note: reuses LMIC.frame buffer!
01392         LMIC.opmode |= OP_PINGINI;
01393     }
01394     // Change RX frequency / rps (US only) before we increment txChnl
01395     setRx1Params();
01396     // LMIC.rxsyms carries the TX datarate (can be != LMIC.datarate [confirm retries etc.])
01397     // Setup receive - LMIC.rxtime is preloaded with 1.5 symbols offset to tune
01398     // into the middle of the 8 symbols preamble.
01399 #if defined(CFG_eu868)
01400     if( /* TX datarate */LMIC.rxsyms == DR_FSK ) {
01401         LMIC.rxtime = LMIC.txend + delay - PRERX_FSK*us2osticksRound(160);
01402         LMIC.rxsyms = RXLEN_FSK;
01403     }
01404     else
01405 #endif
01406     {
01407         LMIC.rxtime = LMIC.txend + delay + (PAMBL_SYMS-MINRX_SYMS)*dr2hsym(LMIC.dndr);
01408         LMIC.rxsyms = MINRX_SYMS;
01409     }
01410     os_setTimedCallback(&LMIC.osjob, LMIC.rxtime - RX_RAMPUP, func);
01411 }
01412 
01413 
01414 // ======================================== Join frames
01415 
01416 
01417 static void onJoinFailed (xref2osjob_t osjob) {
01418     // Notify app - must call LMIC_reset() to stop joining
01419     // otherwise join procedure continues.
01420     reportEvent(EV_JOIN_FAILED);
01421 }
01422 
01423 
01424 static bit_t processJoinAccept (void) {
01425     ASSERT(LMIC.txrxFlags != TXRX_DNW1 || LMIC.dataLen != 0);
01426     ASSERT((LMIC.opmode & OP_TXRXPEND)!=0);
01427 
01428     if( LMIC.dataLen == 0 ) {
01429       nojoinframe:
01430         if( (LMIC.opmode & OP_JOINING) == 0 ) {
01431             ASSERT((LMIC.opmode & OP_REJOIN) != 0);
01432             // REJOIN attempt for roaming
01433             LMIC.opmode &= ~(OP_REJOIN|OP_TXRXPEND);
01434             if( LMIC.rejoinCnt < 10 )
01435                 LMIC.rejoinCnt++;
01436             reportEvent(EV_REJOIN_FAILED);
01437             return 1;
01438         }
01439         LMIC.opmode &= ~OP_TXRXPEND;
01440         ostime_t delay = nextJoinState();
01441         EV(devCond, DEBUG, (e_.reason = EV::devCond_t::NO_JACC,
01442                             e_.eui    = MAIN::CDEV->getEui(),
01443                             e_.info   = LMIC.datarate|DR_PAGE,
01444                             e_.info2  = osticks2ms(delay)));
01445         // Build next JOIN REQUEST with next engineUpdate call
01446         // Optionally, report join failed.
01447         // Both after a random/chosen amount of ticks.
01448         os_setTimedCallback(&LMIC.osjob, os_getTime()+delay,
01449                             (delay&1) != 0
01450                             ? FUNC_ADDR(onJoinFailed)      // one JOIN iteration done and failed
01451                             : FUNC_ADDR(runEngineUpdate)); // next step to be delayed
01452         return 1;
01453     }
01454     u1_t hdr  = LMIC.frame[0];
01455     u1_t dlen = LMIC.dataLen;
01456     u4_t mic  = os_rlsbf4(&LMIC.frame[dlen-4]); // safe before modified by encrypt!
01457     if( (dlen != LEN_JA && dlen != LEN_JAEXT)
01458         || (hdr & (HDR_FTYPE|HDR_MAJOR)) != (HDR_FTYPE_JACC|HDR_MAJOR_V1) ) {
01459         EV(specCond, ERR, (e_.reason = EV::specCond_t::UNEXPECTED_FRAME,
01460                            e_.eui    = MAIN::CDEV->getEui(),
01461                            e_.info   = dlen < 4 ? 0 : mic,
01462                            e_.info2  = hdr + (dlen<<8)));
01463       badframe:
01464         printf("pja badframe dlen:%d, hdr:%02x\r\n", dlen, hdr);
01465         if( (LMIC.txrxFlags & TXRX_DNW1) != 0 )
01466             return 0;
01467         goto nojoinframe;
01468     }
01469     aes_encrypt(LMIC.frame+1, dlen-1);
01470     if( !aes_verifyMic0(LMIC.frame, dlen-4) ) {
01471         EV(specCond, ERR, (e_.reason = EV::specCond_t::JOIN_BAD_MIC,
01472                            e_.info   = mic));
01473         goto badframe;
01474     }
01475 
01476     u4_t addr = os_rlsbf4(LMIC.frame+OFF_JA_DEVADDR);
01477     LMIC.devaddr = addr;
01478     LMIC.netid = os_rlsbf4(&LMIC.frame[OFF_JA_NETID]) & 0xFFFFFF;
01479 
01480 #if defined(CFG_eu868)
01481     initDefaultChannels(0);
01482     if( dlen > LEN_JA ) {
01483         dlen = OFF_CFLIST;
01484         for( u1_t chidx=3; chidx<8; chidx++, dlen+=3 ) {
01485             u4_t freq = convFreq(&LMIC.frame[dlen]);
01486             if( freq )
01487                 LMIC_setupChannel(chidx, freq, 0, -1);
01488         }
01489     }
01490 #elif defined(CFG_us915)
01491 #ifdef JA_DEBUG
01492     debug_buf(LMIC.frame, dlen);
01493 #endif /* JA_DEBUG */
01494     /*                                                     11 12  13 14  15 16  17 18  19 1a  1b 1c  1d 1e 1f  20 */
01495     /* 20 27 2a b1 01 00 00 d0 44 76 03 00 00 0c c5 59 6c, xx xx, xx xx, xx xx, xx xx, xx xx, xx xx, xx xx xx, xx */
01496     /*  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f 10,  {0} ,  {1} ,  {2} ,  {3} ,  {4} ,  {5} ,   res   , type */
01497     /* join accept: [0] to [16], CFList: [17] to [32] */
01498     if (dlen == LEN_JAEXT) {
01499 #ifdef JA_DEBUG        
01500         printf("cflistType:%d\r\n", LMIC.frame[32]);
01501 #endif /* JA_DEBUG */
01502         if (LMIC.frame[32] == 1) {
01503             u2_t *u2_ptr = (u2_t *)&LMIC.frame[17]; // LoRaWAN is little endian
01504             for (u1_t idx = 0; idx < 5; idx++)
01505                 LMIC.channelMap[idx] = u2_ptr[idx];
01506 #ifdef JA_DEBUG                
01507             for (u1_t idx = 0; idx < 5; idx++)
01508                 printf("%d map %04x\r\n", idx, LMIC.channelMap[idx]);
01509 #endif /* JA_DEBUG */                
01510         }
01511     }
01512 #endif /* CFG_us915 */
01513 
01514     // already incremented when JOIN REQ got sent off
01515     aes_sessKeys(LMIC.devNonce-1, &LMIC.frame[OFF_JA_ARTNONCE], LMIC.nwkKey, LMIC.artKey);
01516     DO_DEVDB(LMIC.netid,   netid);
01517     DO_DEVDB(LMIC.devaddr, devaddr);
01518     DO_DEVDB(LMIC.nwkKey,  nwkkey);
01519     DO_DEVDB(LMIC.artKey,  artkey);
01520 
01521     EV(joininfo, INFO, (e_.arteui  = MAIN::CDEV->getArtEui(),
01522                         e_.deveui  = MAIN::CDEV->getEui(),
01523                         e_.devaddr = LMIC.devaddr,
01524                         e_.oldaddr = oldaddr,
01525                         e_.nonce   = LMIC.devNonce-1,
01526                         e_.mic     = mic,
01527                         e_.reason  = ((LMIC.opmode & OP_REJOIN) != 0
01528                                       ? EV::joininfo_t::REJOIN_ACCEPT
01529                                       : EV::joininfo_t::ACCEPT)));
01530     
01531     ASSERT((LMIC.opmode & (OP_JOINING|OP_REJOIN))!=0);
01532     if( (LMIC.opmode & OP_REJOIN) != 0 ) {
01533         // Lower DR every try below current UP DR
01534         LMIC.datarate = lowerDR(LMIC.datarate, LMIC.rejoinCnt);
01535     }
01536     LMIC.opmode &= ~(OP_JOINING|OP_TRACK|OP_REJOIN|OP_TXRXPEND|OP_PINGINI) | OP_NEXTCHNL;
01537     stateJustJoined();
01538     reportEvent(EV_JOINED);
01539     return 1;
01540 }
01541 
01542 
01543 static void processRx2Jacc (xref2osjob_t osjob) {
01544     if( LMIC.dataLen == 0 )
01545         LMIC.txrxFlags = 0;  // nothing in 1st/2nd DN slot
01546     processJoinAccept();
01547 }
01548 
01549 
01550 static void setupRx2Jacc (xref2osjob_t osjob) {
01551     LMIC.osjob.func = FUNC_ADDR(processRx2Jacc);
01552     setupRx2();
01553 }
01554 
01555 
01556 static void processRx1Jacc (xref2osjob_t osjob) {
01557     if( LMIC.dataLen == 0 || !processJoinAccept() )
01558         schedRx2(DELAY_JACC2_osticks, FUNC_ADDR(setupRx2Jacc));
01559 }
01560 
01561 
01562 static void setupRx1Jacc (xref2osjob_t osjob) {
01563     setupRx1(FUNC_ADDR(processRx1Jacc));
01564 }
01565 
01566 
01567 static void jreqDone (xref2osjob_t osjob) {
01568     txDone(DELAY_JACC1_osticks, FUNC_ADDR(setupRx1Jacc));
01569 }
01570 
01571 // ======================================== Data frames
01572 
01573 // Fwd decl.
01574 static bit_t processDnData(void);
01575 
01576 static void processRx2DnDataDelay (xref2osjob_t osjob) {
01577     processDnData();
01578 }
01579 
01580 static void processRx2DnData (xref2osjob_t osjob) {
01581     if( LMIC.dataLen == 0 ) {
01582         LMIC.txrxFlags = 0;  // nothing in 1st/2nd DN slot
01583         // Delay callback processing to avoid up TX while gateway is txing our missed frame! 
01584         // Since DNW2 uses SF12 by default we wait 3 secs.
01585         os_setTimedCallback(&LMIC.osjob,
01586                             (os_getTime() + DNW2_SAFETY_ZONE + rndDelay(2)),
01587                             processRx2DnDataDelay);
01588         return;
01589     }
01590     processDnData();
01591 }
01592 
01593 
01594 static void setupRx2DnData (xref2osjob_t osjob) {
01595     LMIC.osjob.func = FUNC_ADDR(processRx2DnData);
01596     setupRx2();
01597 }
01598 
01599 
01600 static void processRx1DnData (xref2osjob_t osjob) {
01601     if( LMIC.dataLen == 0 || !processDnData() )
01602         schedRx2(DELAY_DNW2_osticks, FUNC_ADDR(setupRx2DnData));
01603 }
01604 
01605 
01606 static void setupRx1DnData (xref2osjob_t osjob) {
01607     setupRx1(FUNC_ADDR(processRx1DnData));
01608 }
01609 
01610 
01611 static void updataDone (xref2osjob_t osjob) {
01612     txDone(DELAY_DNW1_osticks, FUNC_ADDR(setupRx1DnData));
01613 }
01614 
01615 // ======================================== 
01616 
01617 
01618 static void buildDataFrame (void) {
01619     bit_t txdata = ((LMIC.opmode & (OP_TXDATA|OP_POLL)) != OP_POLL);
01620     u1_t dlen = txdata ? LMIC.pendTxLen : 0;
01621 
01622     // Piggyback MAC options
01623     // Prioritize by importance
01624     int  end = OFF_DAT_OPTS;
01625     if( (LMIC.opmode & (OP_TRACK|OP_PINGABLE)) == (OP_TRACK|OP_PINGABLE) ) {
01626         // Indicate pingability in every UP frame
01627         LMIC.frame[end] = MCMD_PING_IND;
01628         LMIC.frame[end+1] = LMIC.ping.dr | (LMIC.ping.intvExp<<4);
01629         end += 2;
01630     }
01631     if( LMIC.dutyCapAns ) {
01632         LMIC.frame[end] = MCMD_DCAP_ANS;
01633         end += 1;
01634         LMIC.dutyCapAns = 0;
01635     }
01636     if( LMIC.dn2Ans ) {
01637         LMIC.frame[end+0] = MCMD_DN2P_ANS;
01638         LMIC.frame[end+1] = LMIC.dn2Ans & ~MCMD_DN2P_ANS_RFU;
01639         end += 2;
01640         LMIC.dn2Ans = 0;
01641     }
01642     if( LMIC.devsAns ) {  // answer to device status
01643         LMIC.frame[end+0] = MCMD_DEVS_ANS;
01644         LMIC.frame[end+1] = LMIC.margin;
01645         LMIC.frame[end+2] = os_getBattLevel();
01646         end += 3;
01647         LMIC.devsAns = 0;
01648     }
01649     if( LMIC.ladrAns ) {  // answer to ADR change
01650         LMIC.frame[end+0] = MCMD_LADR_ANS;
01651         LMIC.frame[end+1] = LMIC.ladrAns & ~MCMD_LADR_ANS_RFU;
01652         end += 2;
01653         LMIC.ladrAns = 0;
01654     }
01655     if( LMIC.bcninfoTries > 0 ) {
01656         LMIC.frame[end] = MCMD_BCNI_REQ;
01657         end += 1;
01658     }
01659     if( LMIC.adrChanged ) {
01660         if( LMIC.adrAckReq < 0 )
01661             LMIC.adrAckReq = 0;
01662         LMIC.adrChanged = 0;
01663     }
01664     if( LMIC.pingSetAns != 0 ) {
01665         LMIC.frame[end+0] = MCMD_PING_ANS;
01666         LMIC.frame[end+1] = LMIC.pingSetAns & ~MCMD_PING_ANS_RFU;
01667         end += 2;
01668         LMIC.pingSetAns = 0;
01669     }
01670     if( LMIC.snchAns ) {
01671         LMIC.frame[end+0] = MCMD_SNCH_ANS;
01672         LMIC.frame[end+1] = LMIC.snchAns & ~MCMD_SNCH_ANS_RFU;
01673         end += 2;
01674         LMIC.snchAns = 0;
01675     }
01676     ASSERT(end <= OFF_DAT_OPTS+16);
01677 
01678     u1_t flen = end + (txdata ? 5+dlen : 4);
01679     if( flen > MAX_LEN_FRAME ) {
01680         // Options and payload too big - delay payload
01681         txdata = 0;
01682         flen = end+4;
01683     }
01684     LMIC.frame[OFF_DAT_HDR] = HDR_FTYPE_DAUP | HDR_MAJOR_V1;
01685     LMIC.frame[OFF_DAT_FCT] = (LMIC.dnConf | LMIC.adrEnabled
01686                               | (LMIC.adrAckReq >= 0 ? FCT_ADRARQ : 0)
01687                               | (end-OFF_DAT_OPTS));
01688     os_wlsbf4(LMIC.frame+OFF_DAT_ADDR,  LMIC.devaddr);
01689 
01690     if( LMIC.txCnt == 0 ) {
01691         LMIC.seqnoUp += 1;
01692         //printf("seqnoUp inc %d\r\n", LMIC.seqnoUp);
01693         DO_DEVDB(LMIC.seqnoUp,seqnoUp);
01694     } else {
01695         EV(devCond, INFO, (e_.reason = EV::devCond_t::RE_TX,
01696                            e_.eui    = MAIN::CDEV->getEui(),
01697                            e_.info   = LMIC.seqnoUp-1,
01698                            e_.info2  = ((LMIC.txCnt+1) |
01699                                         (DRADJUST[LMIC.txCnt+1] << 8) |
01700                                         ((LMIC.datarate|DR_PAGE)<<16))));
01701     }
01702     os_wlsbf2(LMIC.frame+OFF_DAT_SEQNO, LMIC.seqnoUp-1);
01703 
01704     // Clear pending DN confirmation
01705     LMIC.dnConf = 0;
01706 
01707     if( txdata ) {
01708         if( LMIC.pendTxConf ) {
01709             // Confirmed only makes sense if we have a payload (or at least a port)
01710             LMIC.frame[OFF_DAT_HDR] = HDR_FTYPE_DCUP | HDR_MAJOR_V1;
01711             if( LMIC.txCnt == 0 ) LMIC.txCnt = 1;
01712         }
01713         LMIC.frame[end] = LMIC.pendTxPort;
01714         os_copyMem(LMIC.frame+end+1, LMIC.pendTxData, dlen);
01715         aes_cipher(LMIC.pendTxPort==0 ? LMIC.nwkKey : LMIC.artKey,
01716                    LMIC.devaddr, LMIC.seqnoUp-1,
01717                    /*up*/0, LMIC.frame+end+1, dlen);
01718     }
01719     aes_appendMic(LMIC.nwkKey, LMIC.devaddr, LMIC.seqnoUp-1, /*up*/0, LMIC.frame, flen-4);
01720 
01721     EV(dfinfo, DEBUG, (e_.deveui  = MAIN::CDEV->getEui(),
01722                        e_.devaddr = LMIC.devaddr,
01723                        e_.seqno   = LMIC.seqnoUp-1,
01724                        e_.flags   = (LMIC.pendTxPort < 0 ? EV::dfinfo_t::NOPORT : EV::dfinfo_t::NOP),
01725                        e_.mic     = Base::lsbf4(&LMIC.frame[flen-4]),
01726                        e_.hdr     = LMIC.frame[LORA::OFF_DAT_HDR],
01727                        e_.fct     = LMIC.frame[LORA::OFF_DAT_FCT],
01728                        e_.port    = LMIC.pendTxPort,
01729                        e_.plen    = txdata ? dlen : 0,
01730                        e_.opts.length = end-LORA::OFF_DAT_OPTS,
01731                        memcpy(&e_.opts[0], LMIC.frame+LORA::OFF_DAT_OPTS, end-LORA::OFF_DAT_OPTS)));
01732     LMIC.dataLen = flen;
01733 }
01734 
01735 
01736 // Callback from HAL during scan mode or when job timer expires.
01737 static void onBcnRx (xref2osjob_t job) {
01738     // If we arrive via job timer make sure to put radio to rest.
01739     os_radio(RADIO_RST);
01740     os_clearCallback(&LMIC.osjob);
01741     if( LMIC.dataLen == 0 ) {
01742         // Nothing received - timeout
01743         LMIC.opmode &= ~(OP_SCAN | OP_TRACK);
01744         reportEvent(EV_SCAN_TIMEOUT);
01745         return;
01746     }
01747     if( decodeBeacon() <= 0 ) {
01748         // Something is wrong with the beacon - continue scan
01749         LMIC.dataLen = 0;
01750         os_radio(RADIO_RXON);
01751         os_setTimedCallback(&LMIC.osjob, LMIC.bcninfo.txtime, FUNC_ADDR(onBcnRx));
01752         return;
01753     }
01754     // Found our 1st beacon
01755     // We don't have a previous beacon to calc some drift - assume
01756     // an max error of 13ms = 128sec*100ppm which is roughly +/-100ppm
01757     calcBcnRxWindowFromMillis(13,1);
01758     LMIC.opmode &= ~OP_SCAN;          // turn SCAN off
01759     LMIC.opmode |=  OP_TRACK;         // auto enable tracking
01760     reportEvent(EV_BEACON_FOUND);    // can be disabled in callback
01761 }
01762 
01763 
01764 // Enable receiver to listen to incoming beacons
01765 // netid defines when scan stops (any or specific beacon)
01766 // This mode ends with events: EV_SCAN_TIMEOUT/EV_SCAN_BEACON
01767 // Implicitely cancels any pending TX/RX transaction.
01768 // Also cancels an onpoing joining procedure.
01769 static void startScan (void) {
01770     ASSERT(LMIC.devaddr!=0 && (LMIC.opmode & OP_JOINING)==0);
01771     if( (LMIC.opmode & OP_SHUTDOWN) != 0 )
01772         return;
01773     // Cancel onging TX/RX transaction
01774     LMIC.txCnt = LMIC.dnConf = LMIC.bcninfo.flags = 0;
01775     LMIC.opmode = (LMIC.opmode | OP_SCAN) & ~(OP_TXRXPEND);
01776     setBcnRxParams();
01777     LMIC.rxtime = LMIC.bcninfo.txtime = os_getTime() + sec2osticks(BCN_INTV_sec+1);
01778     os_setTimedCallback(&LMIC.osjob, LMIC.rxtime, FUNC_ADDR(onBcnRx));
01779     os_radio(RADIO_RXON);
01780 }
01781 
01782 
01783 bit_t LMIC_enableTracking (u1_t tryBcnInfo) {
01784     if( (LMIC.opmode & (OP_SCAN|OP_TRACK|OP_SHUTDOWN)) != 0 )
01785         return 0;  // already in progress or failed to enable
01786     // If BCN info requested from NWK then app has to take are
01787     // of sending data up so that MCMD_BCNI_REQ can be attached.
01788     if( (LMIC.bcninfoTries = tryBcnInfo) == 0 )
01789         startScan();
01790     return 1;  // enabled
01791 }
01792 
01793 
01794 void LMIC_disableTracking (void) {
01795     LMIC.opmode &= ~(OP_SCAN|OP_TRACK);
01796     LMIC.bcninfoTries = 0;
01797     engineUpdate();
01798 }
01799 
01800 
01801 // ================================================================================
01802 //
01803 // Join stuff
01804 //
01805 // ================================================================================
01806 
01807 static void buildJoinRequest (u1_t ftype) {
01808     // Do not use pendTxData since we might have a pending
01809     // user level frame in there. Use RX holding area instead.
01810     xref2u1_t d = LMIC.frame;
01811     d[OFF_JR_HDR] = ftype;
01812     os_getArtEui(d + OFF_JR_ARTEUI);
01813     os_getDevEui(d + OFF_JR_DEVEUI);
01814     os_wlsbf2(d + OFF_JR_DEVNONCE, LMIC.devNonce);
01815     aes_appendMic0(d, OFF_JR_MIC);
01816 
01817     EV(joininfo,INFO,(e_.deveui  = MAIN::CDEV->getEui(),
01818                       e_.arteui  = MAIN::CDEV->getArtEui(),
01819                       e_.nonce   = LMIC.devNonce,
01820                       e_.oldaddr = LMIC.devaddr,
01821                       e_.mic     = Base::lsbf4(&d[LORA::OFF_JR_MIC]),
01822                       e_.reason  = ((LMIC.opmode & OP_REJOIN) != 0
01823                                     ? EV::joininfo_t::REJOIN_REQUEST
01824                                     : EV::joininfo_t::REQUEST)));
01825     LMIC.dataLen = LEN_JR;
01826     LMIC.devNonce++;
01827     DO_DEVDB(LMIC.devNonce,devNonce);
01828 }
01829 
01830 static void startJoining (xref2osjob_t osjob) {
01831     reportEvent(EV_JOINING);
01832 }
01833 
01834 // Start join procedure if not already joined.
01835 bit_t LMIC_startJoining (void) {
01836     if( LMIC.devaddr == 0 ) {
01837         // There should be no TX/RX going on
01838         ASSERT((LMIC.opmode & (OP_POLL|OP_TXRXPEND)) == 0);
01839         // Lift any previous duty limitation
01840         LMIC.globalDutyRate = 0;
01841         // Cancel scanning
01842         LMIC.opmode &= ~(OP_SCAN|OP_REJOIN|OP_LINKDEAD|OP_NEXTCHNL);
01843         // Setup state
01844         LMIC.rejoinCnt = LMIC.txCnt = LMIC.pendTxConf = 0;
01845         initJoinLoop();
01846         LMIC.opmode |= OP_JOINING;
01847         // reportEvent will call engineUpdate which then starts sending JOIN REQUESTS
01848         os_setCallback(&LMIC.osjob, FUNC_ADDR(startJoining));
01849         return 1;
01850     }
01851     return 0; // already joined
01852 }
01853 
01854 
01855 // ================================================================================
01856 //
01857 //
01858 //
01859 // ================================================================================
01860 
01861 static void processPingRx (xref2osjob_t osjob) {
01862     if( LMIC.dataLen != 0 ) {
01863         LMIC.txrxFlags = TXRX_PING;
01864         if( decodeFrame() ) {
01865             reportEvent(EV_RXCOMPLETE);
01866             return;
01867         }
01868     }
01869     // Pick next ping slot
01870     engineUpdate();
01871 }
01872 
01873 
01874 static bit_t processDnData (void) {
01875     ASSERT((LMIC.opmode & OP_TXRXPEND)!=0);
01876 
01877     if( LMIC.dataLen == 0 ) {
01878       norx:
01879         if( LMIC.txCnt != 0 ) {
01880             if( LMIC.txCnt < TXCONF_ATTEMPTS ) {
01881                 LMIC.txCnt += 1;
01882                 setDrTxpow(DRCHG_NOACK, lowerDR(LMIC.datarate, DRADJUST[LMIC.txCnt]), KEEP_TXPOW);
01883                 // Schedule another retransmission
01884                 txDelay(LMIC.rxtime, RETRY_PERIOD_secs);
01885                 LMIC.opmode &= ~OP_TXRXPEND;
01886                 engineUpdate();
01887                 return 1;
01888             }
01889             LMIC.txrxFlags = TXRX_NACK | TXRX_NOPORT;
01890         } else {
01891             // Nothing received - implies no port
01892             LMIC.txrxFlags = TXRX_NOPORT;
01893         }
01894         if( LMIC.adrAckReq != LINK_CHECK_OFF )
01895             LMIC.adrAckReq += 1;
01896         LMIC.dataBeg = LMIC.dataLen = 0;
01897       txcomplete:
01898         LMIC.opmode &= ~(OP_TXDATA|OP_TXRXPEND);
01899         if( (LMIC.txrxFlags & (TXRX_DNW1|TXRX_DNW2|TXRX_PING)) != 0  &&  (LMIC.opmode & OP_LINKDEAD) != 0 ) {
01900             LMIC.opmode &= ~OP_LINKDEAD;
01901             reportEvent(EV_LINK_ALIVE);
01902         }
01903         reportEvent(EV_TXCOMPLETE);
01904         // If we haven't heard from NWK in a while although we asked for a sign
01905         // assume link is dead - notify application and keep going
01906         if( LMIC.adrAckReq > LINK_CHECK_DEAD ) {
01907             // We haven't heard from NWK for some time although we
01908             // asked for a response for some time - assume we're disconnected. Lower DR one notch.
01909             EV(devCond, ERR, (e_.reason = EV::devCond_t::LINK_DEAD,
01910                               e_.eui    = MAIN::CDEV->getEui(),
01911                               e_.info   = LMIC.adrAckReq));
01912             setDrTxpow(DRCHG_NOADRACK, decDR((dr_t)LMIC.datarate), KEEP_TXPOW);
01913             LMIC.adrAckReq = LINK_CHECK_CONT;
01914             LMIC.opmode |= OP_REJOIN|OP_LINKDEAD;
01915             reportEvent(EV_LINK_DEAD);
01916         }
01917         // If this falls to zero the NWK did not answer our MCMD_BCNI_REQ commands - try full scan
01918         if( LMIC.bcninfoTries > 0 ) {
01919             if( (LMIC.opmode & OP_TRACK) != 0 ) {
01920                 reportEvent(EV_BEACON_FOUND);
01921                 LMIC.bcninfoTries = 0;
01922             }
01923             else if( --LMIC.bcninfoTries == 0 ) {
01924                 startScan();   // NWK did not answer - try scan
01925             }
01926         }
01927         return 1;
01928     }
01929     if( !decodeFrame() ) {
01930         if( (LMIC.txrxFlags & TXRX_DNW1) != 0 )
01931             return 0;
01932         goto norx;
01933     }
01934     goto txcomplete;
01935 }
01936 
01937 
01938 static void processBeacon (xref2osjob_t osjob) {
01939     ostime_t lasttx = LMIC.bcninfo.txtime;   // save here - decodeBeacon might overwrite
01940     u1_t flags = LMIC.bcninfo.flags;
01941     ev_t ev;
01942 
01943     if( LMIC.dataLen != 0 && decodeBeacon() >= 1 ) {
01944         ev = EV_BEACON_TRACKED;
01945         if( (flags & (BCN_PARTIAL|BCN_FULL)) == 0 ) {
01946             // We don't have a previous beacon to calc some drift - assume
01947             // an max error of 13ms = 128sec*100ppm which is roughly +/-100ppm
01948             calcBcnRxWindowFromMillis(13,0);
01949             goto rev;
01950         }
01951         // We have a previous BEACON to calculate some drift
01952         s2_t drift = BCN_INTV_osticks - (LMIC.bcninfo.txtime - lasttx);
01953         if( LMIC.missedBcns > 0 ) {
01954             drift = LMIC.drift + (drift - LMIC.drift) / (LMIC.missedBcns+1);
01955         }
01956         if( (LMIC.bcninfo.flags & BCN_NODRIFT) == 0 ) {
01957             s2_t diff = LMIC.drift - drift;
01958             if( diff < 0 ) diff = -diff;
01959             LMIC.lastDriftDiff = diff;
01960             if( LMIC.maxDriftDiff < diff )
01961                 LMIC.maxDriftDiff = diff;
01962             LMIC.bcninfo.flags &= ~BCN_NODDIFF;
01963         }
01964         LMIC.drift = drift;
01965         LMIC.missedBcns = LMIC.rejoinCnt = 0;
01966         LMIC.bcninfo.flags &= ~BCN_NODRIFT;
01967         EV(devCond,INFO,(e_.reason = EV::devCond_t::CLOCK_DRIFT,
01968                          e_.eui    = MAIN::CDEV->getEui(),
01969                          e_.info   = drift,
01970                          e_.info2  = /*occasion BEACON*/0));
01971         ASSERT((LMIC.bcninfo.flags & (BCN_PARTIAL|BCN_FULL)) != 0);
01972     } else {
01973         ev = EV_BEACON_MISSED;
01974         LMIC.bcninfo.txtime += BCN_INTV_osticks - LMIC.drift;
01975         LMIC.bcninfo.time   += BCN_INTV_sec;
01976         LMIC.missedBcns++;
01977         // Delay any possible TX after surmised beacon - it's there although we missed it
01978         txDelay(LMIC.bcninfo.txtime + BCN_RESERVE_osticks, 4);
01979         if( LMIC.missedBcns > MAX_MISSED_BCNS )
01980             LMIC.opmode |= OP_REJOIN;  // try if we can roam to another network
01981         if( LMIC.bcnRxsyms > MAX_RXSYMS ) {
01982             LMIC.opmode &= ~(OP_TRACK|OP_PINGABLE|OP_PINGINI|OP_REJOIN);
01983             reportEvent(EV_LOST_TSYNC);
01984             return;
01985         }
01986     }
01987     LMIC.bcnRxtime = LMIC.bcninfo.txtime + BCN_INTV_osticks - calcRxWindow(0,DR_BCN);
01988     LMIC.bcnRxsyms = LMIC.rxsyms;    
01989   rev:
01990 #ifdef CFG_us915
01991     LMIC.bcnChnl = (LMIC.bcnChnl+1) & 7;
01992 #endif
01993     if( (LMIC.opmode & OP_PINGINI) != 0 )
01994         rxschedInit(&LMIC.ping);  // note: reuses LMIC.frame buffer!
01995     reportEvent(ev);
01996 }
01997 
01998 
01999 static void startRxBcn (xref2osjob_t osjob) {
02000     LMIC.osjob.func = FUNC_ADDR(processBeacon);
02001     os_radio(RADIO_RX);
02002 }
02003 
02004 
02005 static void startRxPing (xref2osjob_t osjob) {
02006     LMIC.osjob.func = FUNC_ADDR(processPingRx);
02007     os_radio(RADIO_RX);
02008 }
02009 
02010 
02011 // Decide what to do next for the MAC layer of a device
02012 static void engineUpdate (void) {
02013     // Check for ongoing state: scan or TX/RX transaction
02014     if( (LMIC.opmode & (OP_SCAN|OP_TXRXPEND|OP_SHUTDOWN)) != 0 ) 
02015         return;
02016 
02017     if( LMIC.devaddr == 0 && (LMIC.opmode & OP_JOINING) == 0 ) {
02018         LMIC_startJoining();
02019         return;
02020     }
02021 
02022     ostime_t now    = os_getTime();
02023     ostime_t rxtime = 0;
02024     ostime_t txbeg  = 0;
02025 
02026     if( (LMIC.opmode & OP_TRACK) != 0 ) {
02027         // We are tracking a beacon
02028         ASSERT( now + RX_RAMPUP - LMIC.bcnRxtime <= 0 );
02029         rxtime = LMIC.bcnRxtime - RX_RAMPUP;
02030     }
02031 
02032     if( (LMIC.opmode & (OP_JOINING|OP_REJOIN|OP_TXDATA|OP_POLL)) != 0 ) {
02033         // Need to TX some data...
02034         // Assuming txChnl points to channel which first becomes available again.
02035         bit_t jacc = ((LMIC.opmode & (OP_JOINING|OP_REJOIN)) != 0 ? 1 : 0);
02036         // Find next suitable channel and return availability time
02037         if( (LMIC.opmode & OP_NEXTCHNL) != 0 ) {
02038             txbeg = LMIC.txend = nextTx(now);
02039             LMIC.opmode &= ~OP_NEXTCHNL;
02040         } else {
02041             txbeg = LMIC.txend;
02042         }
02043         // Delayed TX or waiting for duty cycle?
02044         if( (LMIC.globalDutyRate != 0 || (LMIC.opmode & OP_RNDTX) != 0)  &&  (txbeg - LMIC.globalDutyAvail) < 0 )
02045             txbeg = LMIC.globalDutyAvail;
02046         // If we're tracking a beacon...
02047         // then make sure TX-RX transaction is complete before beacon
02048         if( (LMIC.opmode & OP_TRACK) != 0 &&
02049             txbeg + (jacc ? JOIN_GUARD_osticks : TXRX_GUARD_osticks) - rxtime > 0 ) {
02050             // Not enough time to complete TX-RX before beacon - postpone after beacon.
02051             // In order to avoid clustering of postponed TX right after beacon randomize start!
02052             txDelay(rxtime + BCN_RESERVE_osticks, 16);
02053             txbeg = 0;
02054             goto checkrx;
02055         }
02056         // Earliest possible time vs overhead to setup radio
02057         if( txbeg - (now + TX_RAMPUP) < 0 ) {
02058             // We could send right now!
02059         txbeg = now;
02060             dr_t txdr = (dr_t)LMIC.datarate;
02061             if( jacc ) {
02062                 u1_t ftype;
02063                 if( (LMIC.opmode & OP_REJOIN) != 0 ) {
02064                     txdr = lowerDR(txdr, LMIC.rejoinCnt);
02065                     ftype = HDR_FTYPE_REJOIN;
02066                 } else {
02067                     ftype = HDR_FTYPE_JREQ;
02068                 }
02069                 buildJoinRequest(ftype);
02070                 LMIC.osjob.func = FUNC_ADDR(jreqDone);
02071             } else {
02072                 if( LMIC.seqnoDn >= 0xFFFFFF80 ) {
02073                     // Imminent roll over - proactively reset MAC
02074                     EV(specCond, INFO, (e_.reason = EV::specCond_t::DNSEQNO_ROLL_OVER,
02075                                         e_.eui    = MAIN::CDEV->getEui(),
02076                                         e_.info   = LMIC.seqnoDn, 
02077                                         e_.info2  = 0));
02078                     // Device has to react! NWK will not roll over and just stop sending.
02079                     // Thus, we have N frames to detect a possible lock up.
02080                   reset:
02081                     os_setCallback(&LMIC.osjob, FUNC_ADDR(runReset));
02082                     return;
02083                 }
02084                 if( (LMIC.txCnt==0 && LMIC.seqnoUp == 0xFFFFFFFF) ) {
02085                     // Roll over of up seq counter
02086                     EV(specCond, ERR, (e_.reason = EV::specCond_t::UPSEQNO_ROLL_OVER,
02087                                        e_.eui    = MAIN::CDEV->getEui(),
02088                                        e_.info2  = LMIC.seqnoUp));
02089                     // Do not run RESET event callback from here!
02090                     // App code might do some stuff after send unaware of RESET.
02091                     goto reset;
02092                 }
02093                 buildDataFrame();
02094                 LMIC.osjob.func = FUNC_ADDR(updataDone);
02095             }
02096             LMIC.rps    = setCr(updr2rps(txdr), (cr_t)LMIC.errcr);
02097             LMIC.dndr   = txdr;  // carry TX datarate (can be != LMIC.datarate) over to txDone/setupRx1
02098             LMIC.opmode = (LMIC.opmode & ~(OP_POLL|OP_RNDTX)) | OP_TXRXPEND | OP_NEXTCHNL;
02099             updateTx(txbeg);
02100             os_radio(RADIO_TX);
02101             return;
02102         }
02103         // Cannot yet TX
02104         if( (LMIC.opmode & OP_TRACK) == 0 )
02105             goto txdelay; // We don't track the beacon - nothing else to do - so wait for the time to TX
02106         // Consider RX tasks
02107         if( txbeg == 0 ) // zero indicates no TX pending
02108             txbeg += 1;  // TX delayed by one tick (insignificant amount of time)
02109     } else {
02110         // No TX pending - no scheduled RX
02111         if( (LMIC.opmode & OP_TRACK) == 0 )
02112             return;
02113     }
02114 
02115     // Are we pingable?
02116   checkrx:
02117     if( (LMIC.opmode & OP_PINGINI) != 0 ) {
02118         // One more RX slot in this beacon period?
02119         if( rxschedNext(&LMIC.ping, now+RX_RAMPUP) ) {
02120             if( txbeg != 0  &&  (txbeg - LMIC.ping.rxtime) < 0 )
02121                 goto txdelay;
02122             LMIC.rxsyms  = LMIC.ping.rxsyms;
02123             LMIC.rxtime  = LMIC.ping.rxtime;
02124             LMIC.freq    = LMIC.ping.freq;
02125             LMIC.rps     = dndr2rps(LMIC.ping.dr);
02126             LMIC.dataLen = 0;
02127             ASSERT(LMIC.rxtime - now+RX_RAMPUP >= 0 );
02128             os_setTimedCallback(&LMIC.osjob, LMIC.rxtime - RX_RAMPUP, FUNC_ADDR(startRxPing));
02129             return;
02130         }
02131         // no - just wait for the beacon
02132     }
02133 
02134     if( txbeg != 0  &&  (txbeg - rxtime) < 0 )
02135         goto txdelay;
02136 
02137     setBcnRxParams();
02138     LMIC.rxsyms = LMIC.bcnRxsyms;
02139     LMIC.rxtime = LMIC.bcnRxtime;
02140     if( now - rxtime >= 0 ) {
02141         LMIC.osjob.func = FUNC_ADDR(processBeacon);
02142         os_radio(RADIO_RX);
02143         return;
02144     }
02145     os_setTimedCallback(&LMIC.osjob, rxtime, FUNC_ADDR(startRxBcn));
02146     return;
02147 
02148   txdelay:
02149     EV(devCond, INFO, (e_.reason = EV::devCond_t::TX_DELAY,
02150                        e_.eui    = MAIN::CDEV->getEui(),
02151                        e_.info   = osticks2ms(txbeg-now),
02152                        e_.info2  = LMIC.seqnoUp-1));
02153     os_setTimedCallback(&LMIC.osjob, txbeg-TX_RAMPUP, FUNC_ADDR(runEngineUpdate));
02154 }
02155 
02156 
02157 void LMIC_setAdrMode (bit_t enabled) {
02158     LMIC.adrEnabled = enabled ? FCT_ADREN : 0;
02159 }
02160 
02161 
02162 //  Should we have/need an ext. API like this?
02163 void LMIC_setDrTxpow (dr_t dr, s1_t txpow) {
02164     setDrTxpow(DRCHG_SET, dr, txpow);
02165 }
02166 
02167 
02168 void LMIC_shutdown (void) {
02169     os_clearCallback(&LMIC.osjob);
02170     os_radio(RADIO_RST);
02171     LMIC.opmode |= OP_SHUTDOWN;
02172 }
02173 
02174 
02175 void LMIC_reset (void) {
02176     EV(devCond, INFO, (e_.reason = EV::devCond_t::LMIC_EV,
02177                        e_.eui    = MAIN::CDEV->getEui(),
02178                        e_.info   = EV_RESET));
02179     os_radio(RADIO_RST);
02180     os_clearCallback(&LMIC.osjob);
02181 
02182     os_clearMem((xref2u1_t)&LMIC,SIZEOFEXPR(LMIC));
02183     LMIC.devaddr      =  0;
02184     LMIC.devNonce     =  os_getRndU2();
02185     LMIC.opmode       =  OP_NONE;
02186     LMIC.errcr        =  CR_4_5;
02187     LMIC.adrEnabled   =  0; /* FCT_ADREN */
02188     LMIC.dn2Dr        =  DR_DNW2;   // we need this for 2nd DN window of join accept
02189     LMIC.dn2Freq      =  FREQ_DNW2; // ditto
02190     LMIC.ping.freq    =  FREQ_PING; // defaults for ping
02191     LMIC.ping.dr      =  DR_PING;   // ditto
02192     LMIC.ping.intvExp =  0xFF;
02193 #if defined(CFG_us915)
02194     initDefaultChannels();
02195 #endif
02196     DO_DEVDB(LMIC.devaddr,      devaddr);
02197     DO_DEVDB(LMIC.devNonce,     devNonce);
02198     DO_DEVDB(LMIC.dn2Dr,        dn2Dr);
02199     DO_DEVDB(LMIC.dn2Freq,      dn2Freq);
02200     DO_DEVDB(LMIC.ping.freq,    pingFreq);
02201     DO_DEVDB(LMIC.ping.dr,      pingDr);
02202     DO_DEVDB(LMIC.ping.intvExp, pingIntvExp);
02203 }
02204 
02205 
02206 void LMIC_init (void) {
02207     LMIC.opmode = OP_SHUTDOWN;
02208 }
02209 
02210 
02211 void LMIC_clrTxData (void) {
02212     LMIC.opmode &= ~(OP_TXDATA|OP_TXRXPEND|OP_POLL);
02213     LMIC.pendTxLen = 0;
02214     if( (LMIC.opmode & (OP_JOINING|OP_SCAN)) != 0 ) // do not interfere with JOINING
02215         return;
02216     os_clearCallback(&LMIC.osjob);
02217     os_radio(RADIO_RST);
02218     engineUpdate();
02219 }
02220 
02221 
02222 void LMIC_setTxData (void) {
02223     LMIC.opmode |= OP_TXDATA;
02224     if( (LMIC.opmode & OP_JOINING) == 0 )
02225         LMIC.txCnt = 0;             // cancel any ongoing TX/RX retries
02226     engineUpdate();
02227 }
02228 
02229 
02230 //
02231 int LMIC_setTxData2 (u1_t port, xref2u1_t data, u1_t dlen, u1_t confirmed) {
02232     if( dlen > SIZEOFEXPR(LMIC.pendTxData) )
02233         return -2;
02234     if( data != (xref2u1_t)0 )
02235         os_copyMem(LMIC.pendTxData, data, dlen);
02236     LMIC.pendTxConf = confirmed;
02237     LMIC.pendTxPort = port;
02238     LMIC.pendTxLen  = dlen;
02239     LMIC_setTxData();
02240     return 0;
02241 }
02242 
02243 
02244 // Send a payload-less message to signal device is alive
02245 void LMIC_sendAlive (void) {
02246     LMIC.opmode |= OP_POLL;
02247     engineUpdate();
02248 }
02249 
02250 
02251 // Check if other networks are around.
02252 void LMIC_tryRejoin (void) {
02253     LMIC.opmode |= OP_REJOIN;
02254     engineUpdate();
02255 }
02256 
02257 //! \brief Setup given session keys
02258 //! and put the MAC in a state as if 
02259 //! a join request/accept would have negotiated just these keys.
02260 //! It is crucial that the combinations `devaddr/nwkkey` and `devaddr/artkey`
02261 //! are unique within the network identified by `netid`.
02262 //! NOTE: on Harvard architectures when session keys are in flash:
02263 //!  Caller has to fill in LMIC.{nwk,art}Key  before and pass {nwk,art}Key are NULL
02264 //! \param netid a 24 bit number describing the network id this device is using
02265 //! \param devaddr the 32 bit session address of the device. It is strongly recommended
02266 //!    to ensure that different devices use different numbers with high probability.
02267 //! \param nwkKey  the 16 byte network session key used for message integrity.
02268 //!     If NULL the caller has copied the key into `LMIC.nwkKey` before.
02269 //! \param artKey  the 16 byte application router session key used for message confidentiality.
02270 //!     If NULL the caller has copied the key into `LMIC.artKey` before.
02271 void LMIC_setSession (u4_t netid, devaddr_t devaddr, xref2u1_t nwkKey, xref2u1_t artKey) {
02272     LMIC.netid = netid;
02273     LMIC.devaddr = devaddr;
02274     if( nwkKey != (xref2u1_t)0 )
02275         os_copyMem(LMIC.nwkKey, nwkKey, 16);
02276     if( artKey != (xref2u1_t)0 )
02277         os_copyMem(LMIC.artKey, artKey, 16);
02278     
02279 #if defined(CFG_eu868)
02280     initDefaultChannels(0);
02281 #endif
02282  
02283     LMIC.opmode &= ~(OP_JOINING|OP_TRACK|OP_REJOIN|OP_TXRXPEND|OP_PINGINI);
02284     LMIC.opmode |= OP_NEXTCHNL;
02285     stateJustJoined();
02286     DO_DEVDB(LMIC.netid,   netid);
02287     DO_DEVDB(LMIC.devaddr, devaddr);
02288     DO_DEVDB(LMIC.nwkKey,  nwkkey);
02289     DO_DEVDB(LMIC.artKey,  artkey);
02290     DO_DEVDB(LMIC.seqnoUp, seqnoUp);
02291     DO_DEVDB(LMIC.seqnoDn, seqnoDn);
02292 }
02293 
02294 // Enable/disable link check validation.
02295 // LMIC sets the ADRACKREQ bit in UP frames if there were no DN frames
02296 // for a while. It expects the network to provide a DN message to prove
02297 // connectivity with a span of UP frames. If this no such prove is coming
02298 // then the datarate is lowered and a LINK_DEAD event is generated.
02299 // This mode can be disabled and no connectivity prove (ADRACKREQ) is requested
02300 // nor is the datarate changed.
02301 // This must be called only if a session is established (e.g. after EV_JOINED)
02302 void LMIC_setLinkCheckMode (bit_t enabled) {
02303     LMIC.adrChanged = 0;
02304     LMIC.adrAckReq = enabled ? LINK_CHECK_INIT : LINK_CHECK_OFF;
02305 }
02306 
02307 void LMIC_reverse_memcpy(u1_t *dst, const u1_t *src, size_t n)
02308 {
02309     size_t i;
02310 
02311     for (i=0; i < n; ++i)
02312         dst[n-1-i] = src[i];    
02313 }
02314