美文网首页LoRa相关LPWAN设计
LoRaWAN网关需求配置

LoRaWAN网关需求配置

作者: 小鱼儿他老汉 | 来源:发表于2018-09-21 20:25 被阅读56次

    需求管理

    从PyCom(比较全)和IBM LMiC两条路径可以观察LoRaWAN网关的设计需求:

    • 激活方式:ABP(Activation By Personalization)/OTAA(OTA Activation)
    • 工作频段:EU433/CN470/CN750/EU868/US915等
    • 空口参数:SF调制度和BW频率宽度,IQ反相与否
    • 数据率:DR Data Rate,CR,Preamble
    • 设备识别:网关设备ID
    • 配网参数:SSID/PSK WiFi
    • 云端参数:主机、端口、TLS证书
    • NTP参数:主机、端口
    • DevEUI:设备识别号
    • AppEUI:应用识别号
    • AppKey:应用秘钥
    • 时间精度:采用NTP授时还是GPS授时,主要是和定位有关联。而且最好采用多基站+TOA/TODA方式来定位。

    Python源码

    """ LoPy LoRaWAN Nano Gateway. Can be used for both EU868 and US915. """
    
    import errno
    import machine
    import ubinascii
    import ujson
    import uos
    import usocket
    import utime
    import _thread
    from micropython import const
    from network import LoRa
    from network import WLAN
    from machine import Timer
    
    
    PROTOCOL_VERSION = const(2)
    
    PUSH_DATA = const(0)
    PUSH_ACK = const(1)
    PULL_DATA = const(2)
    PULL_ACK = const(4)
    PULL_RESP = const(3)
    
    TX_ERR_NONE = 'NONE'
    TX_ERR_TOO_LATE = 'TOO_LATE'
    TX_ERR_TOO_EARLY = 'TOO_EARLY'
    TX_ERR_COLLISION_PACKET = 'COLLISION_PACKET'
    TX_ERR_COLLISION_BEACON = 'COLLISION_BEACON'
    TX_ERR_TX_FREQ = 'TX_FREQ'
    TX_ERR_TX_POWER = 'TX_POWER'
    TX_ERR_GPS_UNLOCKED = 'GPS_UNLOCKED'
    
    UDP_THREAD_CYCLE_MS = const(10)
    
    STAT_PK = {
        'stat': {
            'time': '',
            'lati': 0,
            'long': 0,
            'alti': 0,
            'rxnb': 0,
            'rxok': 0,
            'rxfw': 0,
            'ackr': 100.0,
            'dwnb': 0,
            'txnb': 0
        }
    }
    
    RX_PK = {
        'rxpk': [{
            'time': '',
            'tmst': 0,
            'chan': 0,
            'rfch': 0,
            'freq': 0,
            'stat': 1,
            'modu': 'LORA',
            'datr': '',
            'codr': '4/5',
            'rssi': 0,
            'lsnr': 0,
            'size': 0,
            'data': ''
        }]
    }
    
    TX_ACK_PK = {
        'txpk_ack': {
            'error': ''
        }
    }
    
    
    class NanoGateway:
        """
        Nano gateway class, set up by default for use with TTN, but can be configured
        for any other network supporting the Semtech Packet Forwarder.
        Only required configuration is wifi_ssid and wifi_password which are used for
        connecting to the Internet.
        """
    
        def __init__(self, id, frequency, datarate, ssid, password, server, port, ntp_server='pool.ntp.org', ntp_period=3600):
            self.id = id
            self.server = server
            self.port = port
    
            self.frequency = frequency
            self.datarate = datarate
    
            self.ssid = ssid
            self.password = password
    
            self.ntp_server = ntp_server
            self.ntp_period = ntp_period
    
            self.server_ip = None
    
            self.rxnb = 0
            self.rxok = 0
            self.rxfw = 0
            self.dwnb = 0
            self.txnb = 0
    
            self.sf = self._dr_to_sf(self.datarate)
            self.bw = self._dr_to_bw(self.datarate)
    
            self.stat_alarm = None
            self.pull_alarm = None
            self.uplink_alarm = None
    
            self.wlan = None
            self.sock = None
            self.udp_stop = False
            self.udp_lock = _thread.allocate_lock()
    
            self.lora = None
            self.lora_sock = None
    
            self.rtc = machine.RTC()
    
        def start(self):
            """
            Starts the LoRaWAN nano gateway.
            """
    
            self._log('Starting LoRaWAN nano gateway with id: {}', self.id)
    
            # setup WiFi as a station and connect
            self.wlan = WLAN(mode=WLAN.STA)
            self._connect_to_wifi()
    
            # get a time sync
            self._log('Syncing time with {} ...', self.ntp_server)
            self.rtc.ntp_sync(self.ntp_server, update_period=self.ntp_period)
            while not self.rtc.synced():
                utime.sleep_ms(50)
            self._log("RTC NTP sync complete")
    
            # get the server IP and create an UDP socket
            self.server_ip = usocket.getaddrinfo(self.server, self.port)[0][-1]
            self._log('Opening UDP socket to {} ({}) port {}...', self.server, self.server_ip[0], self.server_ip[1])
            self.sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM, usocket.IPPROTO_UDP)
            self.sock.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
            self.sock.setblocking(False)
    
            # push the first time immediatelly
            self._push_data(self._make_stat_packet())
    
            # create the alarms
            self.stat_alarm = Timer.Alarm(handler=lambda t: self._push_data(self._make_stat_packet()), s=60, periodic=True)
            self.pull_alarm = Timer.Alarm(handler=lambda u: self._pull_data(), s=25, periodic=True)
    
            # start the UDP receive thread
            self.udp_stop = False
            _thread.start_new_thread(self._udp_thread, ())
    
            # initialize the LoRa radio in LORA mode
            self._log('Setting up the LoRa radio at {} Mhz using {}', self._freq_to_float(self.frequency), self.datarate)
            self.lora = LoRa(
                mode=LoRa.LORA,
                frequency=self.frequency,
                bandwidth=self.bw,
                sf=self.sf,
                preamble=8,
                coding_rate=LoRa.CODING_4_5,
                tx_iq=True
            )
    
            # create a raw LoRa socket
            self.lora_sock = usocket.socket(usocket.AF_LORA, usocket.SOCK_RAW)
            self.lora_sock.setblocking(False)
            self.lora_tx_done = False
    
            self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=self._lora_cb)
            self._log('LoRaWAN nano gateway online')
    
        def stop(self):
            """
            Stops the LoRaWAN nano gateway.
            """
    
            self._log('Stopping...')
    
            # send the LoRa radio to sleep
            self.lora.callback(trigger=None, handler=None)
            self.lora.power_mode(LoRa.SLEEP)
    
            # stop the NTP sync
            self.rtc.ntp_sync(None)
    
            # cancel all the alarms
            self.stat_alarm.cancel()
            self.pull_alarm.cancel()
    
            # signal the UDP thread to stop
            self.udp_stop = True
            while self.udp_stop:
                utime.sleep_ms(50)
    
            # disable WLAN
            self.wlan.disconnect()
            self.wlan.deinit()
    
        def _connect_to_wifi(self):
            self.wlan.connect(self.ssid, auth=(None, self.password))
            while not self.wlan.isconnected():
                utime.sleep_ms(50)
            self._log('WiFi connected to: {}', self.ssid)
    
        def _dr_to_sf(self, dr):
            sf = dr[2:4]
            if sf[1] not in '0123456789':
                sf = sf[:1]
            return int(sf)
    
        def _dr_to_bw(self, dr):
            bw = dr[-5:]
            if bw == 'BW125':
                return LoRa.BW_125KHZ
            elif bw == 'BW250':
                return LoRa.BW_250KHZ
            else:
                return LoRa.BW_500KHZ
    
        def _sf_bw_to_dr(self, sf, bw):
            dr = 'SF' + str(sf)
            if bw == LoRa.BW_125KHZ:
                return dr + 'BW125'
            elif bw == LoRa.BW_250KHZ:
                return dr + 'BW250'
            else:
                return dr + 'BW500'
    
        def _lora_cb(self, lora):
            """
            LoRa radio events callback handler.
            """
    
            events = lora.events()
            if events & LoRa.RX_PACKET_EVENT:
                self.rxnb += 1
                self.rxok += 1
                rx_data = self.lora_sock.recv(256)
                stats = lora.stats()
                packet = self._make_node_packet(rx_data, self.rtc.now(), stats.rx_timestamp, stats.sfrx, self.bw, stats.rssi, stats.snr)
                self._push_data(packet)
                self._log('Received packet: {}', packet)
                self.rxfw += 1
            if events & LoRa.TX_PACKET_EVENT:
                self.txnb += 1
                lora.init(
                    mode=LoRa.LORA,
                    frequency=self.frequency,
                    bandwidth=self.bw,
                    sf=self.sf,
                    preamble=8,
                    coding_rate=LoRa.CODING_4_5,
                    tx_iq=True
                    )
    
        def _freq_to_float(self, frequency):
            """
            MicroPython has some inprecision when doing large float division.
            To counter this, this method first does integer division until we
            reach the decimal breaking point. This doesn't completely elimate
            the issue in all cases, but it does help for a number of commonly
            used frequencies.
            """
    
            divider = 6
            while divider > 0 and frequency % 10 == 0:
                frequency = frequency // 10
                divider -= 1
            if divider > 0:
                frequency = frequency / (10 ** divider)
            return frequency
    
        def _make_stat_packet(self):
            now = self.rtc.now()
            STAT_PK["stat"]["time"] = "%d-%02d-%02d %02d:%02d:%02d GMT" % (now[0], now[1], now[2], now[3], now[4], now[5])
            STAT_PK["stat"]["rxnb"] = self.rxnb
            STAT_PK["stat"]["rxok"] = self.rxok
            STAT_PK["stat"]["rxfw"] = self.rxfw
            STAT_PK["stat"]["dwnb"] = self.dwnb
            STAT_PK["stat"]["txnb"] = self.txnb
            return ujson.dumps(STAT_PK)
    
        def _make_node_packet(self, rx_data, rx_time, tmst, sf, bw, rssi, snr):
            RX_PK["rxpk"][0]["time"] = "%d-%02d-%02dT%02d:%02d:%02d.%dZ" % (rx_time[0], rx_time[1], rx_time[2], rx_time[3], rx_time[4], rx_time[5], rx_time[6])
            RX_PK["rxpk"][0]["tmst"] = tmst
            RX_PK["rxpk"][0]["freq"] = self._freq_to_float(self.frequency)
            RX_PK["rxpk"][0]["datr"] = self._sf_bw_to_dr(sf, bw)
            RX_PK["rxpk"][0]["rssi"] = rssi
            RX_PK["rxpk"][0]["lsnr"] = snr
            RX_PK["rxpk"][0]["data"] = ubinascii.b2a_base64(rx_data)[:-1]
            RX_PK["rxpk"][0]["size"] = len(rx_data)
            return ujson.dumps(RX_PK)
    
        def _push_data(self, data):
            token = uos.urandom(2)
            packet = bytes([PROTOCOL_VERSION]) + token + bytes([PUSH_DATA]) + ubinascii.unhexlify(self.id) + data
            with self.udp_lock:
                try:
                    self.sock.sendto(packet, self.server_ip)
                except Exception as ex:
                    self._log('Failed to push uplink packet to server: {}', ex)
    
        def _pull_data(self):
            token = uos.urandom(2)
            packet = bytes([PROTOCOL_VERSION]) + token + bytes([PULL_DATA]) + ubinascii.unhexlify(self.id)
            with self.udp_lock:
                try:
                    self.sock.sendto(packet, self.server_ip)
                except Exception as ex:
                    self._log('Failed to pull downlink packets from server: {}', ex)
    
        def _ack_pull_rsp(self, token, error):
            TX_ACK_PK["txpk_ack"]["error"] = error
            resp = ujson.dumps(TX_ACK_PK)
            packet = bytes([PROTOCOL_VERSION]) + token + bytes([PULL_ACK]) + ubinascii.unhexlify(self.id) + resp
            with self.udp_lock:
                try:
                    self.sock.sendto(packet, self.server_ip)
                except Exception as ex:
                    self._log('PULL RSP ACK exception: {}', ex)
    
        def _send_down_link(self, data, tmst, datarate, frequency):
            """
            Transmits a downlink message over LoRa.
            """
    
            self.lora.init(
                mode=LoRa.LORA,
                frequency=frequency,
                bandwidth=self._dr_to_bw(datarate),
                sf=self._dr_to_sf(datarate),
                preamble=8,
                coding_rate=LoRa.CODING_4_5,
                tx_iq=True
                )
            while utime.ticks_cpu() < tmst:
                pass
            self.lora_sock.send(data)
            self._log(
                'Sent downlink packet scheduled on {:.3f}, at {:.3f} Mhz using {}: {}',
                tmst / 1000000,
                self._freq_to_float(frequency),
                datarate,
                data
            )
    
        def _udp_thread(self):
            """
            UDP thread, reads data from the server and handles it.
            """
    
            while not self.udp_stop:
                try:
                    data, src = self.sock.recvfrom(1024)
                    _token = data[1:3]
                    _type = data[3]
                    if _type == PUSH_ACK:
                        self._log("Push ack")
                    elif _type == PULL_ACK:
                        self._log("Pull ack")
                    elif _type == PULL_RESP:
                        self.dwnb += 1
                        ack_error = TX_ERR_NONE
                        tx_pk = ujson.loads(data[4:])
                        tmst = tx_pk["txpk"]["tmst"]
                        t_us = tmst - utime.ticks_cpu() - 15000
                        if t_us < 0:
                            t_us += 0xFFFFFFFF
                        if t_us < 20000000:
                            self.uplink_alarm = Timer.Alarm(
                                handler=lambda x: self._send_down_link(
                                    ubinascii.a2b_base64(tx_pk["txpk"]["data"]),
                                    tx_pk["txpk"]["tmst"] - 50, tx_pk["txpk"]["datr"],
                                    int(tx_pk["txpk"]["freq"] * 1000) * 1000
                                ), 
                                us=t_us
                            )
                        else:
                            ack_error = TX_ERR_TOO_LATE
                            self._log('Downlink timestamp error!, t_us: {}', t_us)
                        self._ack_pull_rsp(_token, ack_error)
                        self._log("Pull rsp")
                except usocket.timeout:
                    pass
                except OSError as ex:
                    if ex.errno != errno.EAGAIN:
                        self._log('UDP recv OSError Exception: {}', ex)
                except Exception as ex:
                    self._log('UDP recv Exception: {}', ex)
    
                # wait before trying to receive again
                utime.sleep_ms(UDP_THREAD_CYCLE_MS)
    
            # we are to close the socket
            self.sock.close()
            self.udp_stop = False
            self._log('UDP thread stopped')
    
        def _log(self, message, *args):
            """
            Outputs a log message to stdout.
            """
    
            print('[{:>10.3f}] {}'.format(
                utime.ticks_ms() / 1000,
                str(message).format(*args)
                ))
    

    Arduino C++ 源码

    /*******************************************************************************
     *
     * Copyright (c) 2015 Thomas Telkamp
     *
     * All rights reserved. This program and the accompanying materials
     * are made available under the terms of the Eclipse Public License v1.0
     * which accompanies this distribution, and is available at
     * http://www.eclipse.org/legal/epl-v10.html
     *
     *******************************************************************************/
    
    #include <string>
    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <arpa/inet.h>
    #include <string.h>
    #include <iostream>
    #include <cstdlib>
    #include <sys/time.h>
    #include <cstring>
    
    #include <sys/ioctl.h>
    #include <net/if.h>
    
    using namespace std;
    
    #include "base64.h"
    
    #include <wiringPi.h>
    #include <wiringPiSPI.h>
    
    typedef bool boolean;
    typedef unsigned char byte;
    
    static const int CHANNEL = 0;
    
    byte currentMode = 0x81;
    
    char message[256];
    char b64[256];
    
    bool sx1272 = true;
    
    byte receivedbytes;
    
    struct sockaddr_in si_other;
    int s, slen=sizeof(si_other);
    struct ifreq ifr;
    
    uint32_t cp_nb_rx_rcv;
    uint32_t cp_nb_rx_ok;
    uint32_t cp_nb_rx_bad;
    uint32_t cp_nb_rx_nocrc;
    uint32_t cp_up_pkt_fwd;
    
    enum sf_t { SF7=7, SF8, SF9, SF10, SF11, SF12 };
    
    /*******************************************************************************
     *
     * Configure these values!
     *
     *******************************************************************************/
    
    // SX1272 - Raspberry connections
    int ssPin = 6;
    int dio0  = 7;
    int RST   = 0;
    
    // Set spreading factor (SF7 - SF12)
    sf_t sf = SF7;
    
    // Set center frequency
    uint32_t  freq = 868100000; // in Mhz! (868.1)
    
    // Set location
    float lat=0.0;
    float lon=0.0;
    int   alt=0;
    
    /* Informal status fields */
    static char platform[24]    = "Single Channel Gateway";  /* platform definition */
    static char email[40]       = "";                        /* used for contact email */
    static char description[64] = "";                        /* used for free form description */
    
    // define servers
    // TODO: use host names and dns
    #define SERVER1 "54.72.145.119"    // The Things Network: croft.thethings.girovito.nl
    //#define SERVER2 "192.168.1.10"      // local
    #define PORT 1700                   // The port on which to send data
    
    // #############################################
    // #############################################
    
    #define REG_FIFO                    0x00
    #define REG_FIFO_ADDR_PTR           0x0D
    #define REG_FIFO_TX_BASE_AD         0x0E
    #define REG_FIFO_RX_BASE_AD         0x0F
    #define REG_RX_NB_BYTES             0x13
    #define REG_OPMODE                  0x01
    #define REG_FIFO_RX_CURRENT_ADDR    0x10
    #define REG_IRQ_FLAGS               0x12
    #define REG_DIO_MAPPING_1           0x40
    #define REG_DIO_MAPPING_2           0x41
    #define REG_MODEM_CONFIG            0x1D
    #define REG_MODEM_CONFIG2           0x1E
    #define REG_MODEM_CONFIG3           0x26
    #define REG_SYMB_TIMEOUT_LSB        0x1F
    #define REG_PKT_SNR_VALUE           0x19
    #define REG_PAYLOAD_LENGTH          0x22
    #define REG_IRQ_FLAGS_MASK          0x11
    #define REG_MAX_PAYLOAD_LENGTH      0x23
    #define REG_HOP_PERIOD              0x24
    #define REG_SYNC_WORD               0x39
    #define REG_VERSION                 0x42
    
    #define SX72_MODE_RX_CONTINUOS      0x85
    #define SX72_MODE_TX                0x83
    #define SX72_MODE_SLEEP             0x80
    #define SX72_MODE_STANDBY           0x81
    
    #define PAYLOAD_LENGTH              0x40
    
    // LOW NOISE AMPLIFIER
    #define REG_LNA                     0x0C
    #define LNA_MAX_GAIN                0x23
    #define LNA_OFF_GAIN                0x00
    #define LNA_LOW_GAIN                0x20
    
    // CONF REG
    #define REG1                        0x0A
    #define REG2                        0x84
    
    #define SX72_MC2_FSK                0x00
    #define SX72_MC2_SF7                0x70
    #define SX72_MC2_SF8                0x80
    #define SX72_MC2_SF9                0x90
    #define SX72_MC2_SF10               0xA0
    #define SX72_MC2_SF11               0xB0
    #define SX72_MC2_SF12               0xC0
    
    #define SX72_MC1_LOW_DATA_RATE_OPTIMIZE  0x01 // mandated for SF11 and SF12
    
    // FRF
    #define        REG_FRF_MSB              0x06
    #define        REG_FRF_MID              0x07
    #define        REG_FRF_LSB              0x08
    
    #define        FRF_MSB                  0xD9 // 868.1 Mhz
    #define        FRF_MID                  0x06
    #define        FRF_LSB                  0x66
    
    #define BUFLEN 2048  //Max length of buffer
    
    #define PROTOCOL_VERSION  1
    #define PKT_PUSH_DATA 0
    #define PKT_PUSH_ACK  1
    #define PKT_PULL_DATA 2
    #define PKT_PULL_RESP 3
    #define PKT_PULL_ACK  4
    
    #define TX_BUFF_SIZE  2048
    #define STATUS_SIZE   1024
    
    void die(const char *s)
    {
        perror(s);
        exit(1);
    }
    
    void selectreceiver()
    {
        digitalWrite(ssPin, LOW);
    }
    
    void unselectreceiver()
    {
        digitalWrite(ssPin, HIGH);
    }
    
    byte readRegister(byte addr)
    {
        unsigned char spibuf[2];
    
        selectreceiver();
        spibuf[0] = addr & 0x7F;
        spibuf[1] = 0x00;
        wiringPiSPIDataRW(CHANNEL, spibuf, 2);
        unselectreceiver();
    
        return spibuf[1];
    }
    
    void writeRegister(byte addr, byte value)
    {
        unsigned char spibuf[2];
    
        spibuf[0] = addr | 0x80;
        spibuf[1] = value;
        selectreceiver();
        wiringPiSPIDataRW(CHANNEL, spibuf, 2);
    
        unselectreceiver();
    }
    
    
    boolean receivePkt(char *payload)
    {
    
        // clear rxDone
        writeRegister(REG_IRQ_FLAGS, 0x40);
    
        int irqflags = readRegister(REG_IRQ_FLAGS);
    
        cp_nb_rx_rcv++;
    
        //  payload crc: 0x20
        if((irqflags & 0x20) == 0x20)
        {
            printf("CRC error\n");
            writeRegister(REG_IRQ_FLAGS, 0x20);
            return false;
        } else {
    
            cp_nb_rx_ok++;
    
            byte currentAddr = readRegister(REG_FIFO_RX_CURRENT_ADDR);
            byte receivedCount = readRegister(REG_RX_NB_BYTES);
            receivedbytes = receivedCount;
    
            writeRegister(REG_FIFO_ADDR_PTR, currentAddr);
    
            for(int i = 0; i < receivedCount; i++)
            {
                payload[i] = (char)readRegister(REG_FIFO);
            }
        }
        return true;
    }
    
    void SetupLoRa()
    {
        
        digitalWrite(RST, HIGH);
        delay(100);
        digitalWrite(RST, LOW);
        delay(100);
    
        byte version = readRegister(REG_VERSION);
    
        if (version == 0x22) {
            // sx1272
            printf("SX1272 detected, starting.\n");
            sx1272 = true;
        } else {
            // sx1276?
            digitalWrite(RST, LOW);
            delay(100);
            digitalWrite(RST, HIGH);
            delay(100);
            version = readRegister(REG_VERSION);
            if (version == 0x12) {
                // sx1276
                printf("SX1276 detected, starting.\n");
                sx1272 = false;
            } else {
                printf("Unrecognized transceiver.\n");
                //printf("Version: 0x%x\n",version);
                exit(1);
            }
        }
    
        writeRegister(REG_OPMODE, SX72_MODE_SLEEP);
    
        // set frequency
        uint64_t frf = ((uint64_t)freq << 19) / 32000000;
        writeRegister(REG_FRF_MSB, (uint8_t)(frf>>16) );
        writeRegister(REG_FRF_MID, (uint8_t)(frf>> 8) );
        writeRegister(REG_FRF_LSB, (uint8_t)(frf>> 0) );
    
        writeRegister(REG_SYNC_WORD, 0x34); // LoRaWAN public sync word
    
        if (sx1272) {
            if (sf == SF11 || sf == SF12) {
                writeRegister(REG_MODEM_CONFIG,0x0B);
            } else {
                writeRegister(REG_MODEM_CONFIG,0x0A);
            }
            writeRegister(REG_MODEM_CONFIG2,(sf<<4) | 0x04);
        } else {
            if (sf == SF11 || sf == SF12) {
                writeRegister(REG_MODEM_CONFIG3,0x0C);
            } else {
                writeRegister(REG_MODEM_CONFIG3,0x04);
            }
            writeRegister(REG_MODEM_CONFIG,0x72);
            writeRegister(REG_MODEM_CONFIG2,(sf<<4) | 0x04);
        }
    
        if (sf == SF10 || sf == SF11 || sf == SF12) {
            writeRegister(REG_SYMB_TIMEOUT_LSB,0x05);
        } else {
            writeRegister(REG_SYMB_TIMEOUT_LSB,0x08);
        }
        writeRegister(REG_MAX_PAYLOAD_LENGTH,0x80);
        writeRegister(REG_PAYLOAD_LENGTH,PAYLOAD_LENGTH);
        writeRegister(REG_HOP_PERIOD,0xFF);
        writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_BASE_AD));
    
        // Set Continous Receive Mode
        writeRegister(REG_LNA, LNA_MAX_GAIN);  // max lna gain
        writeRegister(REG_OPMODE, SX72_MODE_RX_CONTINUOS);
    
    }
    
    void sendudp(char *msg, int length) {
    
    //send the update
    #ifdef SERVER1
        inet_aton(SERVER1 , &si_other.sin_addr);
        if (sendto(s, (char *)msg, length, 0 , (struct sockaddr *) &si_other, slen)==-1)
        {
            die("sendto()");
        }
    #endif
    
    #ifdef SERVER2
        inet_aton(SERVER2 , &si_other.sin_addr);
        if (sendto(s, (char *)msg, length , 0 , (struct sockaddr *) &si_other, slen)==-1)
        {
            die("sendto()");
        }
    #endif
    }
    
    void sendstat() {
    
        static char status_report[STATUS_SIZE]; /* status report as a JSON object */
        char stat_timestamp[24];
        time_t t;
    
        int stat_index=0;
    
        /* pre-fill the data buffer with fixed fields */
        status_report[0] = PROTOCOL_VERSION;
        status_report[3] = PKT_PUSH_DATA;
    
        status_report[4] = (unsigned char)ifr.ifr_hwaddr.sa_data[0];
        status_report[5] = (unsigned char)ifr.ifr_hwaddr.sa_data[1];
        status_report[6] = (unsigned char)ifr.ifr_hwaddr.sa_data[2];
        status_report[7] = 0xFF;
        status_report[8] = 0xFF;
        status_report[9] = (unsigned char)ifr.ifr_hwaddr.sa_data[3];
        status_report[10] = (unsigned char)ifr.ifr_hwaddr.sa_data[4];
        status_report[11] = (unsigned char)ifr.ifr_hwaddr.sa_data[5];
    
        /* start composing datagram with the header */
        uint8_t token_h = (uint8_t)rand(); /* random token */
        uint8_t token_l = (uint8_t)rand(); /* random token */
        status_report[1] = token_h;
        status_report[2] = token_l;
        stat_index = 12; /* 12-byte header */
    
        /* get timestamp for statistics */
        t = time(NULL);
        strftime(stat_timestamp, sizeof stat_timestamp, "%F %T %Z", gmtime(&t));
    
        int j = snprintf((char *)(status_report + stat_index), STATUS_SIZE-stat_index, "{\"stat\":{\"time\":\"%s\",\"lati\":%.5f,\"long\":%.5f,\"alti\":%i,\"rxnb\":%u,\"rxok\":%u,\"rxfw\":%u,\"ackr\":%.1f,\"dwnb\":%u,\"txnb\":%u,\"pfrm\":\"%s\",\"mail\":\"%s\",\"desc\":\"%s\"}}", stat_timestamp, lat, lon, (int)alt, cp_nb_rx_rcv, cp_nb_rx_ok, cp_up_pkt_fwd, (float)0, 0, 0,platform,email,description);
        stat_index += j;
        status_report[stat_index] = 0; /* add string terminator, for safety */
    
        printf("stat update: %s\n", (char *)(status_report+12)); /* DEBUG: display JSON stat */
    
        //send the update
        sendudp(status_report, stat_index);
    
    }
    
    void receivepacket() {
    
        long int SNR;
        int rssicorr;
    
        if(digitalRead(dio0) == 1)
        {
            if(receivePkt(message)) {
                byte value = readRegister(REG_PKT_SNR_VALUE);
                if( value & 0x80 ) // The SNR sign bit is 1
                {
                    // Invert and divide by 4
                    value = ( ( ~value + 1 ) & 0xFF ) >> 2;
                    SNR = -value;
                }
                else
                {
                    // Divide by 4
                    SNR = ( value & 0xFF ) >> 2;
                }
                
                if (sx1272) {
                    rssicorr = 139;
                } else {
                    rssicorr = 157;
                }
    
                printf("Packet RSSI: %d, ",readRegister(0x1A)-rssicorr);
                printf("RSSI: %d, ",readRegister(0x1B)-rssicorr);
                printf("SNR: %li, ",SNR);
                printf("Length: %i",(int)receivedbytes);
                printf("\n");
    
                int j;
                j = bin_to_b64((uint8_t *)message, receivedbytes, (char *)(b64), 341);
                //fwrite(b64, sizeof(char), j, stdout);
    
                char buff_up[TX_BUFF_SIZE]; /* buffer to compose the upstream packet */
                int buff_index=0;
    
                /* gateway <-> MAC protocol variables */
                //static uint32_t net_mac_h; /* Most Significant Nibble, network order */
                //static uint32_t net_mac_l; /* Least Significant Nibble, network order */
    
                /* pre-fill the data buffer with fixed fields */
                buff_up[0] = PROTOCOL_VERSION;
                buff_up[3] = PKT_PUSH_DATA;
    
                /* process some of the configuration variables */
                //net_mac_h = htonl((uint32_t)(0xFFFFFFFF & (lgwm>>32)));
                //net_mac_l = htonl((uint32_t)(0xFFFFFFFF &  lgwm  ));
                //*(uint32_t *)(buff_up + 4) = net_mac_h;
                //*(uint32_t *)(buff_up + 8) = net_mac_l;
    
                buff_up[4] = (unsigned char)ifr.ifr_hwaddr.sa_data[0];
                buff_up[5] = (unsigned char)ifr.ifr_hwaddr.sa_data[1];
                buff_up[6] = (unsigned char)ifr.ifr_hwaddr.sa_data[2];
                buff_up[7] = 0xFF;
                buff_up[8] = 0xFF;
                buff_up[9] = (unsigned char)ifr.ifr_hwaddr.sa_data[3];
                buff_up[10] = (unsigned char)ifr.ifr_hwaddr.sa_data[4];
                buff_up[11] = (unsigned char)ifr.ifr_hwaddr.sa_data[5];
    
                /* start composing datagram with the header */
                uint8_t token_h = (uint8_t)rand(); /* random token */
                uint8_t token_l = (uint8_t)rand(); /* random token */
                buff_up[1] = token_h;
                buff_up[2] = token_l;
                buff_index = 12; /* 12-byte header */
    
                // TODO: tmst can jump is time is (re)set, not good.
                struct timeval now;
                gettimeofday(&now, NULL);
                uint32_t tmst = (uint32_t)(now.tv_sec*1000000 + now.tv_usec);
    
                /* start of JSON structure */
                memcpy((void *)(buff_up + buff_index), (void *)"{\"rxpk\":[", 9);
                buff_index += 9;
                buff_up[buff_index] = '{';
                ++buff_index;
                j = snprintf((char *)(buff_up + buff_index), TX_BUFF_SIZE-buff_index, "\"tmst\":%u", tmst);
                buff_index += j;
                j = snprintf((char *)(buff_up + buff_index), TX_BUFF_SIZE-buff_index, ",\"chan\":%1u,\"rfch\":%1u,\"freq\":%.6lf", 0, 0, (double)freq/1000000);
                buff_index += j;
                memcpy((void *)(buff_up + buff_index), (void *)",\"stat\":1", 9);
                buff_index += 9;
                memcpy((void *)(buff_up + buff_index), (void *)",\"modu\":\"LORA\"", 14);
                buff_index += 14;
                /* Lora datarate & bandwidth, 16-19 useful chars */
                switch (sf) {
                case SF7:
                    memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF7", 12);
                    buff_index += 12;
                    break;
                case SF8:
                    memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF8", 12);
                    buff_index += 12;
                    break;
                case SF9:
                    memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF9", 12);
                    buff_index += 12;
                    break;
                case SF10:
                    memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF10", 13);
                    buff_index += 13;
                    break;
                case SF11:
                    memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF11", 13);
                    buff_index += 13;
                    break;
                case SF12:
                    memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF12", 13);
                    buff_index += 13;
                    break;
                default:
                    memcpy((void *)(buff_up + buff_index), (void *)",\"datr\":\"SF?", 12);
                    buff_index += 12;
                }
                memcpy((void *)(buff_up + buff_index), (void *)"BW125\"", 6);
                buff_index += 6;
                memcpy((void *)(buff_up + buff_index), (void *)",\"codr\":\"4/5\"", 13);
                buff_index += 13;
                j = snprintf((char *)(buff_up + buff_index), TX_BUFF_SIZE-buff_index, ",\"lsnr\":%li", SNR);
                buff_index += j;
                j = snprintf((char *)(buff_up + buff_index), TX_BUFF_SIZE-buff_index, ",\"rssi\":%d,\"size\":%u", readRegister(0x1A)-rssicorr, receivedbytes);
                buff_index += j;
                memcpy((void *)(buff_up + buff_index), (void *)",\"data\":\"", 9);
                buff_index += 9;
                j = bin_to_b64((uint8_t *)message, receivedbytes, (char *)(buff_up + buff_index), 341);
                buff_index += j;
                buff_up[buff_index] = '"';
                ++buff_index;
    
                /* End of packet serialization */
                buff_up[buff_index] = '}';
                ++buff_index;
                buff_up[buff_index] = ']';
                ++buff_index;
                /* end of JSON datagram payload */
                buff_up[buff_index] = '}';
                ++buff_index;
                buff_up[buff_index] = 0; /* add string terminator, for safety */
    
                printf("rxpk update: %s\n", (char *)(buff_up + 12)); /* DEBUG: display JSON payload */
    
                //send the messages
                sendudp(buff_up, buff_index);
    
                fflush(stdout);
    
            } // received a message
    
        } // dio0=1
    }
    
    int main () {
    
        struct timeval nowtime;
        uint32_t lasttime;
    
        wiringPiSetup () ;
        pinMode(ssPin, OUTPUT);
        pinMode(dio0, INPUT);
        pinMode(RST, OUTPUT);
    
        //int fd = 
        wiringPiSPISetup(CHANNEL, 500000);
        //cout << "Init result: " << fd << endl;
    
        SetupLoRa();
    
        if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
        {
            die("socket");
        }
        memset((char *) &si_other, 0, sizeof(si_other));
        si_other.sin_family = AF_INET;
        si_other.sin_port = htons(PORT);
    
        ifr.ifr_addr.sa_family = AF_INET;
        strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);  // can we rely on eth0?
        ioctl(s, SIOCGIFHWADDR, &ifr);
    
        /* display result */
        printf("Gateway ID: %.2x:%.2x:%.2x:ff:ff:%.2x:%.2x:%.2x\n",
               (unsigned char)ifr.ifr_hwaddr.sa_data[0],
               (unsigned char)ifr.ifr_hwaddr.sa_data[1],
               (unsigned char)ifr.ifr_hwaddr.sa_data[2],
               (unsigned char)ifr.ifr_hwaddr.sa_data[3],
               (unsigned char)ifr.ifr_hwaddr.sa_data[4],
               (unsigned char)ifr.ifr_hwaddr.sa_data[5]);
    
        printf("Listening at SF%i on %.6lf Mhz.\n", sf,(double)freq/1000000);
        printf("------------------\n");
    
        while(1) {
    
            receivepacket();
    
            gettimeofday(&nowtime, NULL);
            uint32_t nowseconds = (uint32_t)(nowtime.tv_sec);
            if (nowseconds - lasttime >= 30) {
                lasttime = nowseconds;
                sendstat();
                cp_nb_rx_rcv = 0;
                cp_nb_rx_ok = 0;
                cp_up_pkt_fwd = 0;
            }
            delay(1);
        }
    
        return (0);
    
    }
    
    

    相关文章

      网友评论

        本文标题:LoRaWAN网关需求配置

        本文链接:https://www.haomeiwen.com/subject/pzmznftx.html