All files lorano.js

100% Statements 641/641
100% Branches 104/104
100% Functions 25/25
100% Lines 641/641

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 6421x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 129x 129x 129x 129x 130x 130x 130x 15x 15x 130x 130x 130x 130x 114x 114x 130x 129x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 127x 127x 127x 127x 127x 126x 126x 126x 126x 65x 65x 65x 65x 61x 61x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 9x 9x 20x 20x 126x 118x 118x 127x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1x 1x 1x 20x 20x 1x 1x 49x 49x 19x 19x 19x 19x 19x 19x 19x 81x 81x 81x 81x 60x 60x 60x 60x 60x 60x 60x 20x 20x 40x 40x 40x 40x 40x 3x 3x 60x 77x 77x 77x 77x 81x 15x 15x 62x 62x 62x 62x 81x 60x 60x 81x 19x 19x 1x 1x 1x 19x 19x 19x 19x 19x 49x 1x 1x 35x 35x 35x 35x 35x 35x 19x 19x 19x 19x 1x 1x 1x 19x 19x 1x 1x 1x 17x 17x 19x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 35x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 32x 32x 32x 32x 35x 35x 1x 1x 31x 31x 31x 35x 4x 4x 4x 35x 35x 1x 1x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 1x 1x 49x 49x 49x 46x 46x 46x 46x 46x 3x 3x 3x 3x 3x 3x 3x 49x 1x 1x 20x 20x 20x 20x 20x 1x 1x 19x 19x 19x 19x 20x 1x 1x 18x 18x 18x 20x 1x 1x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 16x 20x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 20x 1x 1x 40x 40x 40x 40x 40x 40x 40x 2x 2x 2x 40x 40x 1x 1x 1x 1x 37x 37x 40x 2x 2x 2x 35x 35x 35x 40x 2x 2x 2x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 40x 40x 1x 1x 32x 32x 32x 1x 1x 59x 59x 59x 59x 53x 53x 6x 6x 6x 59x 1x 1x 16x 16x 16x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 1x 1x 1x 1x 1x 1x 1x 1x 1x 91x 91x 91x 91x 91x 69x 69x 69x 69x 22x 91x 1x 1x 91x 91x 91x 91x 69x 69x 69x 69x 69x 22x 91x 1x 1x 22x 22x 22x 22x 22x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 32x 32x 32x 32x 16x 16x 16x 32x 1x 1x 1x 1x 64x 64x 64x 64x 64x 64x 320x 320x 320x 320x 1024x 1024x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 1x 1x 1x  
"use strict";
 
process.env.UV_THREADPOOL_SIZE = (process.env.UV_THREADPOOL_SIZE || 4) + 3;
 
const stream = require('stream'),
      crypto = require('crypto'),
      { transaction } = require('objection'),
      aw = require('awaitify-stream'),
      lora_packet = require('lora-packet'),
      PROTOCOL_VERSION = 2,
      pkts = {
          PUSH_DATA: 0,
          PUSH_ACK: 1,
          PULL_DATA: 2,
          PULL_RESP: 3,
          PULL_ACK: 4,
          TX_ACK: 5
      };
 
async function wait_for(link, pkt)
{
    while (true)
    {
        const data = await link.readAsync();
        if (data === null)
        {
            return null;
        }
        if ((data.length >= 4) &&
            (data[0] === PROTOCOL_VERSION) &&
            (data[3] === pkt))
        {
            return data;
        }
    }
}
 
/**
 * Creates a Duplex stream (in object mode) which reads and writes to a LoRa radio
 * link.
 *
 * It can perform over-the-air activation of devices it knows about on behalf
 * of your application.
 *
 * Messages received from the radio link are made available to read from the
 * Duplex and have the following properties:
 *
 * - `nwk_addr (Buffer)` - Unique network address of the sending device.
 * - `dev_eui (Buffer)` - Unique global device identifier (IEEE EUI64) of the sending device.
 * - `dev_addr (Buffer)` - Combined identifier of your network (7 most significant bits) and the unique network address of the sending device (i.e. `nwk_addr`, 25 least significant bits).
 * - `payload (Buffer)` - The data which the sending device sent to your application.
 * - `msg (Object)` - The raw packet received by {@link https://github.com/davedoesdev/packet_forwarder_shared|packet_forwarder_shared}. The format is described {@link https://github.com/davedoesdev/packet_forwarder_shared/blob/master/PROTOCOL.TXT|here}.
 * - `packet (Object)` - The decoded packet. Anthony Kirby's excellent {@link https://github.com/anthonykirby/lora-packet|lora-packet} is used to do the decoding.
 * - `reply (Object)` - This contains nearly everything needed to reply to the message. Your application just has to set the payload.
 *   - `header (Object)` - The metadata required by {@link https://github.com/davedoesdev/packet_forwarder_shared|packet_forwarder_shared} to send the reply. See section 6 of {@link https://github.com/davedoesdev/packet_forwarder_shared/blob/master/PROTOCOL.TXT|here}.
 *   - `encoding (Object)` - The fields required by {@link https://github.com/anthonykirby/lora-packet#fromfieldsdata|lora-packet} to encode the reply.
 *   - `payload (undefined)` - Your application must set this property to a Buffer containing the data you want to send back to the device.
 *
 * If your application wants to reply to the message, set `reply.payload` to
 * the data that should be sent and then write `reply` to the Duplex.
 *
 * @param {class} Model - The {@link https://vincit.github.io/objection.js/#models|Objection.js Model class}, or a subclass of it, already {@link https://vincit.github.io/objection.js/#knex|configured for your database using Knex.js}.
 * @param {stream.Duplex} uplink - {@link https://rawgit-gjgjyaqiln.now.sh/davedoesdev/node-lora-comms/master/docs/index.html#lora-commsuplink|lora-comms uplink stream}. Your application must {@link https://rawgit-gjgjyaqiln.now.sh/davedoesdev/node-lora-comms/master/docs/index.html#lora-commsstart|start} the {@link https://github.com/davedoesdev/node-lora-comms|lora-comms} module first and then retrieve the uplink.
 * @param {stream.Duplex} downlink - {@link https://rawgit-gjgjyaqiln.now.sh/davedoesdev/node-lora-comms/master/docs/index.html#lora-commsdownlink|lora-comms downlink stream}. Your application must {@link https://rawgit-gjgjyaqiln.now.sh/davedoesdev/node-lora-comms/master/docs/index.html#lora-commsstart|start} the {@link https://github.com/davedoesdev/node-lora-comms|lora-comms} module first and then retrieve the downlink.
 * @param {Object} options - Configuration options.
 * @param {Buffer} options.appid - 8-byte identifier of your application in the IEEE EUI64 address space. This is also known as the AppEUI and your OTAA devices must use the same value.
 * @param {Buffer} options.netid - 3-byte identifier of your network. The 7 least significant bits must be unique for neighbouring or overlapping networks.
 */
class Link extends stream.Duplex
{
    constructor(Model, uplink, downlink, options)
    {
        // options.appid = AppEUI
        // options.netid = NetId: NwkID (7 LSB), rest chosen by network operator
        // Private NwkId: 000000 or 000001
 
        super(Object.assign({}, options, { objectMode: true }));
 
        this._options = Object.assign(
        {
            // RX1 data rate offset. Just subtracts (see below for data rates).
            // See section 7.1.7 of LoRaWAN spec.
            RX1DRoffset: 0,
            // RX2 data rate. Region-specific. EU:
            // 0 SF12 / 125kHz
            // 1 SF11 / 125kHz
            // 2 SF10 / 125kHz
            // 3 SF9 / 125kHz
            // 4 SF8 / 125kHz
            // 5 SF7 / 125kHz
            // 6 SF7 / 250kHz
            // 7 FSK: 50kbps
            // 8-15 RFU
            RX2DataRate: 0,
            // RxDelay:
            // 7-4 RFU
            // 3-0 Delay in seconds
            RXDelay: 1,
            FCntDownMax: 0xffff
        }, options);
 
        this._knex = Model.knex();
 
        this._ABPDevices = class extends Model {
            static get tableName() { return 'ABPDevices'; };
            static get idColumn() { return 'DevAddr'; };
        };
 
        this._OTAADevices = class extends Model {
            static get tableName() { return 'OTAADevices'; };
            static get idColumn() { return 'NwkAddr'; };
        };
 
        this._OTAAHistory = class extends Model {
            static get tableName() { return 'OTAAHistory'; };
            static get idColumn() { return ['DevEUI', 'DevNonce']; };
        };
 
        this._pending = [];
        this._reading = false;
 
        downlink.on('finish', () =>
        {
            this.end();
        });
 
        this._uplink_out = aw.createWriter(uplink);
        this._downlink_out = aw.createWriter(downlink);
 
        let received_first_pull_data = false;
 
        const ack = (data, _, cb) =>
        {
            (async () =>
            {
                if ((data.length >= 4) && (data[0] === PROTOCOL_VERSION))
                {
                    const type = data[3];
 
                    if (type === pkts.PUSH_DATA)
                    {
                        await this._uplink_out.writeAsync(Buffer.concat([
                            data.slice(0, 3),
                            Buffer.from([pkts.PUSH_ACK])]));
                    }
                    else if (type === pkts.PULL_DATA)
                    {
                        await this._downlink_out.writeAsync(Buffer.concat([
                            data.slice(0, 3),
                            Buffer.from([pkts.PULL_ACK])]));
 
                        // We want to handle further PULL_DATA messages without
                        // the application having to read from downlink.
                        setImmediate(() => this._downlink_in.stream.read(0));
 
                        if (received_first_pull_data)
                        {
                            return cb();
                        }
                        received_first_pull_data = true;
                    }
                }
 
                cb(null, data);
            })();
        };
 
        this._uplink_in = aw.createReader(uplink.pipe(
            new stream.Transform({
                transform: ack,
                highWaterMark: 0,
                objectMode: true
            })));
        this._downlink_in = aw.createReader(downlink.pipe(
            new stream.Transform({
                transform: ack,
                highWaterMark: 0,
                objectMode: true
            })));
 
        (async () =>
        {
            try
            {
                await wait_for(this._downlink_in, pkts.PULL_DATA);
                this.emit('ready');
            }
            catch (ex)
            {
                process.nextTick(() => this.emit('error', ex));
            }
        })();
    }
 
    _read()
    {
        if (this._reading) { return; }
        this._reading = true;
        (async () =>
        {
            try
            {
                while (true)
                {
                    // Process each message we last read
                    let msg;
                    while ((msg = this._pending.shift()) !== undefined)
                    {
                        // Decode message data
                        const data = Buffer.from(msg.data, 'base64');
                        const decoded = lora_packet.fromWire(data);
                        
                        // OTAA join
                        if (decoded.isJoinRequestMessage())
                        {
                            await this._join(msg, decoded);
                        }
                        // Data
                        else if (decoded.isDataMessage() &&
                                 (decoded.getDir() === 'up') &&
                                 !await this._data(msg, decoded))
                        {
                            return;
                        }
                    }
 
                    // Read incoming packet
                    const packet = await wait_for(this._uplink_in, pkts.PUSH_DATA);
                    if (packet === null)
                    {
                        return this.push(null);
                    }
 
                    // Parse packet data (JSON-encoded by shared pkt forwarder)
                    const payload = JSON.parse(packet.slice(12));
                    if (payload.rxpk)
                    {
                        this._pending = payload.rxpk;
                    }
                }
            }
            catch (ex)
            {
                this.emit('error', ex);
            }
            finally
            {
                this._reading = false;
            }
        })();
    }
 
    _write(data, _, cb)
    {
        (async () =>
        {
            try
            {
                const encoded = data.encoded || await transaction(this._knex, async trx =>
                {
                    const device = await this._device(data.encoding.DevAddr, trx);
                    if (!device)
                    {
                        // we don't know this device
                        throw new Error('unknown device');
                    }
                    if (!device.NwkSKey || !device.AppSKey)
                    {
                        // can't be abp because abp keys aren't nullable
                        throw new Error('device not joined');
                    }
 
                    if (device.FCntDown > this._options.FCntDownMax)
                    {
                        throw new Error('send frame count exceeded');
                    }
 
                    await this._patch_device(
                        device, { FCntDown: device.FCntDown + 1 }, trx);
 
                    return lora_packet.fromFields(Object.assign(
                    {
                        payload: data.payload,
                        FCnt: device.FCntDown
                    }, data.encoding), device.AppSKey, device.NwkSKey);
                });
 
                const payload = encoded.getPHYPayload();
 
                const header = Buffer.alloc(4);
                header[0] = PROTOCOL_VERSION;
                crypto.randomFillSync(header, 1, 2);
                header[3] = pkts.PULL_RESP;
 
                const txpk = Object.assign(
                {
                    data: payload.toString('base64'),
                    size: payload.length
                }, data.header);
 
                await this._downlink_out.writeAsync(Buffer.concat([
                    header,
                    Buffer.from(JSON.stringify({txpk: txpk}))]));
 
                const tx_ack = await wait_for(this._downlink_in, pkts.TX_ACK);
                if ((tx_ack !== null) &&
                    ((tx_ack[1] !== header[1]) ||
                     (tx_ack[2] !== header[2])))
                {
                    throw new Error('TX_ACK token mismatch');
                }
 
                cb();
            }
            catch (ex)
            {
                cb(ex);
            }
        })();
    }
 
    _header(msg, delay)
    {
        return {
            tmst: msg.tmst + delay,
            freq: msg.freq,
            rfch: 0, // only 0 can transmit
            modu: msg.modu,
            datr: msg.datr,
            codr: msg.codr,
            ipol: true
        };
    }
 
    async _patch_device(device, data, trx)
    {
        if (device.NwkAddr)
        {
            await this._OTAADevices
                .query(trx)
                .patch(data)
                .where('NwkAddr', device.NwkAddr);
        }
        else
        {
            await this._ABPDevices
                .query(trx)
                .patch(data)
                .where('DevAddr', device.DevAddr);
        }
    }
 
    async _join(msg, decoded)
    {
        // Check OTAA join request is for this app
        const buffers = decoded.getBuffers();
        if (!buffers.AppEUI.equals(this._options.appid))
        {
            return;
        }
 
        // Check if we know this device
        const device = await this._deveui_to_otaa_device(buffers.DevEUI);
        if (!device)
        {
            return;
        }
 
        // Verify request
        if (!lora_packet.verifyMIC(decoded, null, device.AppKey))
        {
            return this.emit('verify_mic_failed', device, decoded);
        }
 
        // Check for replay
        try
        {
            await this._OTAAHistory
                .query()
                .insert(
                {
                    DevEUI: buffers.DevEUI,
                    DevNonce: buffers.DevNonce
                });
        }
        catch (ex)
        {
            return this.emit('join_replay', device, decoded, ex);
        }
 
        // Make AppNonce
        const app_nonce = crypto.randomBytes(3);
 
        // Make NwkSKey
        const nwk_skey = this._skey(device.AppKey,
                                    0x01,
                                    app_nonce,
                                    buffers.DevNonce);
 
        // Make AppSKey
        const app_skey = this._skey(device.AppKey,
                                    0x02,
                                    app_nonce,
                                    buffers.DevNonce);
 
        // Make DevAddr
        const dev_addr = this.nwk_addr_to_dev_addr(device.NwkAddr);
        
        // Allow subclass to customise Join Accept message
        const data = await this._join_data(
        {
            msg: msg,
            packet: decoded,
            nwk_addr: device.NwkAddr,
            dev_eui: device.DevEUI,
            dev_addr: dev_addr,
            reply: {
                header: this._header(msg, 5000000), // JOIN_ACCEPT_DELAY1 (5s)
                encoding: {
                    MType: 'Join Accept',
                    AppNonce: app_nonce,
                    NetID: this._options.netid,
                    DevAddr: dev_addr,
                    // DLSettings:
                    // 7 RFU (reserved)
                    // 6-4 RX1DRoffset
                    // 3-0 RX2 data rate (same as LinkADRReq in spec)
                    DLSettings: (this._options.RX1DRoffset << 4) |
                                this._options.RX2DataRate,
                    RXDelay: this._options.RXDelay
                    // CFList (optional, none given here):
                    // Frequences of channels 4-8
                    // Each 3 bytes (24 bit, freq in Hz / 100), unused is 0
                    // Followed by 1 RFU byte
                }
            }
        });
 
        // Encode Join Accept message
        data.encoded = lora_packet.fromFields(
            data.encoding, app_skey, nwk_skey, device.AppKey);
 
        // Save keys
        await this._OTAADevices
            .query()
            .patch(
            {
                NwkSKey: nwk_skey,
                AppSKey: app_skey,
                FCntUp: 0,
                FCntDown: 0
            })
            .where('NwkAddr', device.NwkAddr);
 
        // Send Join Accept message
        this.write(data);
    }
 
    async _data(msg, decoded)
    {
        return await transaction(this._knex, async trx =>
        {
            const buffers = decoded.getBuffers();
            const device = await this._device(buffers.DevAddr, trx);
            if (!device)
            {
                // we don't know this device
                return true;
            }
            if (!device.NwkSKey || !device.AppSKey)
            {
                // can't be abp because abp keys aren't nullable
                this.emit('not_joined', device, decoded);
                return true;
            }
 
            if (!lora_packet.verifyMIC(decoded, device.NwkSKey))
            {
                this.emit('verify_mic_failed', device, decoded);
                return true;
            }
 
            const fcnt = decoded.getFCnt();
            if (fcnt < device.FCntUp)
            {
                this.emit('data_replay', device, decoded);
                return true;
            }
 
            await this._patch_device(device, { FCntUp: fcnt + 1 }, trx)
 
            return this.push(
            {
                msg: msg,
                packet: decoded,
                nwk_addr: device.NwkAddr,
                dev_eui: device.DevEUI,
                dev_addr: buffers.DevAddr,
                payload: lora_packet.decrypt(decoded, device.AppSKey, device.NwkSKey),
                reply: {
                    header: this._header(msg, 1000000), // RECEIVE_DELAY1 (1s)
                    encoding: {
                        MType: 'Unconfirmed Data Down',
                        DevAddr: buffers.DevAddr,
                        FCtrl: {
                            ADR: false,
                            ADRACKReq: false,
                            ACK: decoded.getMType() === 'Confirmed Data Up',
                            FPending: false
                        },
                        FPort: 1
                    }
                }
            });
        });
    }
 
    _skey(app_key, type, app_nonce, dev_nonce)
    {
        return Link.skey(this._options.netid, app_key, type, app_nonce, dev_nonce);
    }
 
    async _device(dev_addr, trx)
    {
        const device = await this._dev_addr_to_otaa_device(dev_addr, trx);
        if (device)
        {
            return device;
        }
        return await this._ABPDevices
                        .query(trx)
                        .findById(dev_addr);
    }
 
    async _join_data(data)
    {
        return data.reply;
    }
 
    /**
     * Combines the unique address of a device with the network identifier
     * configured for this {@link #link|link} (`options.netid`).
     *
     * @param {Buffer} nwk_addr - Device address within the network.
     * @returns {Buffer} - 25 lsb: `nwk_addr`; 7 msb: the 7 lsb of `options.netid`.
     */
    nwk_addr_to_dev_addr(nwk_addr)
    {
        const dev_addr = Buffer.from(nwk_addr);
        // 7 msb of DevAddr match 7 lsb of netid (NwkID)
        dev_addr[0] &= 0x1;
        dev_addr[0] |= (this._options.netid[2] & 0x7f) << 1;
        return dev_addr;
    }
 
    /**
     * Checks if the supplied device address is on the network configured
     * for this {@link #link|link} (`options.netid`).
     *
     * @param {Buffer} dev_addr - Combined device and network address.
     * @returns {Buffer|null} - If the device is on the configured network then the 25 lsb of `dev_addr` otherwise `null`.
     */
    dev_addr_to_nwk_addr(dev_addr)
    {
        // Check if from OTAA device on this network
        // (7 msb of DevAddr match 7 lsb of netid (NwkID))
        if ((dev_addr[0] >> 1) === (this._options.netid[2] & 0x7f))
        {
            const nwk_addr = Buffer.from(dev_addr);
            nwk_addr[0] &= 0x01;
            return nwk_addr
        }
        return null;
    }
 
    async _dev_addr_to_otaa_device(dev_addr, trx)
    {
        const nwk_addr = this.dev_addr_to_nwk_addr(dev_addr);
        if (nwk_addr)
        {
            // OTAA device
            return await this._OTAADevices
                        .query(trx)
                        .findById(nwk_addr);
        }
        return null;
    }
 
    async _deveui_to_otaa_device(deveui)
    {
        return await this._OTAADevices 
                    .query()
                    .findOne('DevEUI', deveui);
    }
 
    /**
     * If the supplied device address is on the network configured
     * for this {@link #link|link} (`options.netid`) then return its unique
     * global device ID (IEEE EUI64).
     *
     * @param {Buffer} dev_addr - Combined device and network address.
     * @returns {Buffer|null} - If the device is on the configured network then its IEEE EUI64 ID otherwise `null`.
     */
    async dev_addr_to_deveui(dev_addr)
    {
        const device = await this._dev_addr_to_otaa_device(dev_addr)
        if (device)
        {
            return device.DevEUI;
        }
        return null;
    }
}
 
// For testing
Link.skey = function (netid, app_key, type, app_nonce, dev_nonce)
{
    const cipher = crypto.createCipheriv('aes-128-ecb', app_key, '');
    cipher.setAutoPadding(false);
 
    const skey = [];
    const update = buf =>
    {
        // The octet order for all multi-octet fields is little endian
        for (let i = buf.length - 1; i >= 0; i -= 1)
        {
            skey.push(cipher.update(buf.slice(i, i + 1)));
        }
    };
 
    update(Buffer.from([type]));
    update(app_nonce);
    update(netid);
    update(dev_nonce);
    update(Buffer.alloc(7));
    skey.push(cipher.final());
 
    return Buffer.concat(skey);
};
 
exports.Link = Link;