示例#1
0
#!/usr/bin/env python
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#

from network import LoRa
import socket
import time

lora = LoRa(mode=LoRa.LORA, frequency=863000000)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setblocking(False)

while True:
    if s.recv(64) == b'Ping':
        s.send('Pong')
    time.sleep(5)
示例#2
0
    def __init__(self, logger):
        """
        Connects to LoRaWAN using OTAA and sets up a ring buffer for storing messages.
        :param logger: status logger
        :type logger: LoggerFactory object
        """

        self.logger = logger
        self.message_limit = int(
            float(config.get_config("fair_access")) /
            (float(config.get_config("air_time")) / 1000))
        self.transmission_date = config.get_config(
            "transmission_date")  # last date when lora was transmitting
        today = time.gmtime()
        date = str(today[0]) + str(today[1]) + str(today[2])
        if self.transmission_date == date:  # if device was last transmitting today
            self.message_count = config.get_config(
                "message_count")  # get number of messages sent today
        else:
            self.message_count = 0  # if device was last transmitting a day or more ago, reset message_count for the day
            self.transmission_date = date
            config.save_config({
                "message_count": self.message_count,
                "transmission_date": date
            })

        regions = {
            "Europe": LoRa.EU868,
            "Asia": LoRa.AS923,
            "Australia": LoRa.AU915,
            "United States": LoRa.US915
        }
        region = regions[config.get_config("region")]

        self.lora = LoRa(mode=LoRa.LORAWAN, region=region, adr=True)

        # create an OTAA authentication parameters
        app_eui = ubinascii.unhexlify(config.get_config("application_eui"))
        app_key = ubinascii.unhexlify(config.get_config("app_key"))

        # join a network using OTAA (Over the Air Activation)
        self.lora.join(activation=LoRa.OTAA,
                       auth=(app_eui, app_key),
                       timeout=0)

        # create a LoRa socket
        self.lora_socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

        # request acknowledgment of data sent
        # self.lora_socket.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, True)

        # do not request acknowledgment of data sent
        self.lora_socket.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED,
                                    False)

        # sets timeout for sending data
        self.lora_socket.settimeout(
            int(config.get_config("lora_timeout")) * 1000)

        # set up callback for receiving downlink messages
        self.lora.callback(trigger=LoRa.RX_PACKET_EVENT,
                           handler=self.lora_recv)

        # initialises circular lora stack to back up data up to about 22.5 days depending on the length of the month
        self.lora_buffer = RingBuffer(self.logger, s.processing_path,
                                      s.lora_file_name,
                                      31 * self.message_limit, 100)

        try:  # this fails if the buffer is empty
            self.check_date()  # remove messages that are over a month old
        except Exception as e:
            pass
示例#3
0
from MPL3115A2 import MPL3115A2, ALTITUDE, PRESSURE
from network import WLAN

wlan = WLAN()
wlan.deinit()

py = Pysense()
si = SI7006A20(py)
lt = LTR329ALS01(py)
li = LIS2HH12(py)

# Disable heartbeat LED
pycom.heartbeat(False)

# Initialize LoRa in LORAWAN mode.
lora = LoRa(mode=LoRa.LORAWAN)
lora.nvram_restore()

# create an OTAA authentication parameters
app_eui = binascii.unhexlify('')
app_key = binascii.unhexlify('')

print("DevEUI: %s" % (binascii.hexlify(lora.mac())))
print("AppEUI: %s" % (binascii.hexlify(app_eui)))
print("AppKey: %s" % (binascii.hexlify(app_key)))

# join a network using OTAA (Over the Air Activation)
if not lora.has_joined():
    lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=10)

# wait until the module has joined the network
示例#4
0
 def Switch_to_LoraRaw(self):
     self.lora.nvram_save()
     self.lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868)
     self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
     self.s.setblocking(False)  #Aquesta instrucció igual sobra
     time.sleep(5)
示例#5
0
import machine

import config

# ------------------------------------------------------------------------------

# Enable LED heartbeat
pycom.heartbeat(True)

# Initialize GPIO
adc = machine.ADC()
temperature_pin = adc.channel(pin='G31')
relay_pin = machine.Pin('G15', mode=machine.Pin.OUT)

# Initialize LoRa in LORAWAN mode.
lora = LoRa(mode=LoRa.LORAWAN, adr=True)

# Welcome message
print("[INFO] @ttncat thermostat example for the LoPy");
print("[INFO] DevEUI: %s" % (ubinascii.hexlify(lora.mac()).decode('ascii')))

# ------------------------------------------------------------------------------

# join a network using OTAA (Over the Air Activation)
if config.ACTIVATION == LoRa.OTAA:
    app_eui = ubinascii.unhexlify(config.APP_EUI.replace(' ',''))
    app_key = ubinascii.unhexlify(config.APP_KEY.replace(' ',''))
    auth = (app_eui, app_key)

# join a network using ABP (Activation by Personalisation)
else:
示例#6
0
import binascii

# Colors
off = 0x000000
red = 0xff0000
green = 0x00ff00
blue = 0x0000ff

pycom.heartbeat(False)
# Initialise LoRa in LORAWAN mode.
# Please pick the region that matches where you are using the device:
# Asia = LoRa.AS923
# Australia = LoRa.AU915
# Europe = LoRa.EU868
# United States = LoRa.US915
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.US915, tx_power=20, bandwidth = LoRa.BW_500KHZ, sf=7, frequency = 903900000)

def lora_cb(lora):
    events = lora.events()
    if events & LoRa.RX_PACKET_EVENT:
        print('Lora packet received')
    if events & LoRa.TX_PACKET_EVENT:
        print('Lora packet sent')
lora.nvram_erase()
#lora.nvram_restore()
# remove all the channels the gateway doesn't use
for channel in range(16, 72):
    lora.remove_channel(channel)
for channel in range(0,7):
    lora.remove_channel(channel)
#create an OTAA authentication parameters for test lopy
示例#7
0
        if lora_socket is not None:
            frame, port = lora_socket.recvfrom(512)  # longuest frame is +-220
            print(port, frame)
    if events & LoRa.TX_PACKET_EVENT:
        print("tx_time_on_air: {} ms @dr {}",
              lora.stats().tx_time_on_air,
              lora.stats().sftx)


'''
    Main operations: this is sample code for LoRaWAN on AS923
'''

lora = LoRa(mode=LoRa.LORAWAN,
            region=LoRa.AS923,
            device_class=LoRa.CLASS_C,
            adr=False,
            tx_power=20)

# create an OTA authentication params
dev_eui = binascii.unhexlify('0000000000000000')
app_key = binascii.unhexlify(
    'a926e5bb85271f2d')  # not used leave empty loraserver.io
nwk_key = binascii.unhexlify('a926e5bb85271f2da0440f2f4200afe3')

# join a network using OTAA
lora.join(activation=LoRa.OTAA,
          auth=(dev_eui, app_key, nwk_key),
          timeout=0,
          dr=2)  # AS923 always joins at DR2
示例#8
0
from network import LoRa
import socket
import time
import pycom
from machine import Timer
import crypto
from network import WLAN
from network import Bluetooth
import machine



######### Initialize the device #######################
lora = LoRa(mode=LoRa.LORA,power_mode=LoRa.ALWAYS_ON,region=LoRa.EU868)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setblocking(False)
pycom.heartbeat(False)
wlan = WLAN()
wlan.deinit()
bluetooth = Bluetooth()
bluetooth.deinit()



######### Own node's information #####################
my_number=2
source_address='Mac'+str(my_number)
number_of_neighbours=3


######### Initialize the timers #######################
示例#9
0
from network import LoRa
import socket
import time
import utime
import ubinascii
import pycom
import machine

from loramesh import Loramesh

pycom.wifi_on_boot(False)
pycom.heartbeat(False)

lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868, bandwidth=LoRa.BW_125KHZ, sf=7)
MAC = str(ubinascii.hexlify(lora.mac()))[2:-1]
print("LoRa MAC: %s" % MAC)

mesh = Loramesh(lora)

# waiting until it connected to Mesh network and
# it has some valid neighbors
while True:
    mesh.led_state()
    print("%d: State %s, single %s" %
          (time.time(), mesh.cli('state'), mesh.cli('singleton')))
    time.sleep(2)
    if not mesh.is_connected():
        continue

    neigbors = mesh.neighbors_ip()
    if len(neigbors) == 0:
示例#10
0
    def start(self):
        """
        Starts the LoRaWAN nano gateway.
        """

        pycom.heartbeat(False)

        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()

        # setup LTE CATM1 connection
        self.lte = LTE(carrier="verizon")
        self._connect_to_LTE()

        # 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')
示例#11
0
 def __init__(self, region=LoRa.EU868, activation=LoRa.OTAA):
     self.lora = LoRa(mode=LoRa.LORAWAN, region=region)
     # enable testing
     self.lora.compliance_test(True, 0, False)
     self.activation = activation
     self.rejoined = False
示例#12
0
import machine
import socket
import ubinascii

pir = Pin('P4', mode=Pin.IN, pull=None)

# unique id (last 4 of mac) for message
id = ubinascii.hexlify(machine.unique_id()).decode()[8:12]

# type of sensor
type = "pir"

# creat lora socket
lora = LoRa(mode=LoRa.LORA,
            region=LoRa.US915,
            frequency=902000000,
            tx_power=20,
            sf=12,
            power_mode=LoRa.TX_ONLY)

sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 3)


# Note change in activity or continued state.
def activity_generator():
    '''This function will check for PIR motion activity'''

    pir_state = pir()

    while True:
        if pir() != pir_state:
示例#13
0



# Initialise LoRa in LORAWAN mode.
# Please pick the region that matches where you are using the device:
# Asia = LoRa.AS923
# Australia = LoRa.AU915
# Europe = LoRa.EU868
# United States = LoRa.US915
#lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.US915)

#Above code bypassed because I needed to manually select the correct frequencies to work properly in the US.
#Otherwise, it wanted to send to 64 channels randomly and 88% would be to inactive channels for that region
print('Initialize LoRa')
lora = LoRa(mode=LoRa.LORAWAN, public=1,  adr=0, tx_retries=0)
print('Remove default channels')
for i in range(0, 71):
    lora.remove_channel(i)
print('Removed default channels')
time.sleep(1)
    
    # Set US ISM 915 channel plan for TTN US
lora.add_channel(0, frequency=903900000, dr_min=0, dr_max=3)
lora.add_channel(1, frequency=904100000, dr_min=0, dr_max=3)
lora.add_channel(2, frequency=904300000, dr_min=0, dr_max=3)
lora.add_channel(3, frequency=904500000, dr_min=0, dr_max=3)
lora.add_channel(4, frequency=904700000, dr_min=0, dr_max=3)
lora.add_channel(5, frequency=904900000, dr_min=0, dr_max=3)
lora.add_channel(6, frequency=905100000, dr_min=0, dr_max=3)
lora.add_channel(7, frequency=905300000, dr_min=0, dr_max=3)
# Colors
off = 0x000000
red = 0xff0000
green = 0x00ff00
blue = 0x0000ff
#colors = ["off", "red", "green", "blue"]
colors = [off, red, green, blue]

# Turn off hearbeat LED
pycom.heartbeat(False)

# Initialize LoRaWAN radio
#lora = LoRa(mode=LoRa.LORAWAN)
lora = LoRa(mode=LoRa.LORAWAN,
            region=LoRa.AU915,
            adr=False,
            tx_retries=0,
            device_class=LoRa.CLASS_A)

# Set network keys
app_eui = binascii.unhexlify('70B3D57ED000EF92')
app_key = binascii.unhexlify('47D97E33D867DA5ACFE358F7BD75522B')

# remove some channels
for i in range(16, 65):
    lora.remove_channel(i)
for i in range(66, 72):
    lora.remove_channel(i)

# Join the network
lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
示例#15
0
import pycom
import socket
from machine import UART
from network import LoRa

import config

pycom.heartbeat(False)
uart = UART(1, baudrate=config.serial_baud)
lora = LoRa(mode=LoRa.LORA, frequency=config.lora_frequency, tx_power=14)
lora_socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
lora_socket.setblocking(False)

print('Program started, listening on Serial port 1, transmitting on LoRa')
while True:
    incomming = uart.read(5)
    if incomming == None:
        continue
    buffer = incomming.decode('utf-8')
    print("Sending:'{0}'".format(buffer))
    lora_socket.send(buffer)
示例#16
0
import time
import socket
from machine import Pin, Timer
from network import LoRa

lora = LoRa(mode=LoRa.LORA,
            frequency=868300000,
            bandwidth=LoRa.BW_125KHZ,
            tx_power=14,
            sf=12)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

echo1 = Pin('G22', mode=Pin.IN)
trigger1 = Pin('G17', mode=Pin.OUT)

echo2 = Pin('G16', mode=Pin.IN)
trigger2 = Pin('G15', mode=Pin.OUT)

echo3 = Pin('G14', mode=Pin.IN)
trigger3 = Pin('G13', mode=Pin.OUT)

p_blue_light = Pin('G23', mode=Pin.OUT)
p_red_light = Pin('G24', mode=Pin.OUT)
p_green_light = Pin('G11', mode=Pin.OUT)
'''
b_pin = Pin('G22', mode=Pin.OUT)
a_pin = Pin('G17', mode=Pin.OUT)
f_pin = Pin('G16', mode=Pin.OUT)
g_pin = Pin('G15', mode=Pin.OUT)
e_pin = Pin('G14', mode=Pin.OUT)
d_pin = Pin('G13', mode=Pin.OUT)
示例#17
0
文件: send.py 项目: Wquarks/LoRa
from network import LoRa  #pour être en mode LoRa
import socket  #pour envoyer des trames
import time  # pour la gestion du timer

print('start')

lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868, preamble=20, sf=12)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setblocking(True)
i = 0  #i permet d’identifier le numero de trame et donc les trame perdu

while True:
    msg = str(i) + "abcdefghijklmnopqrstuvwxyz0123456789"  #chaine à envoyer
    s.send(msg)  # envoie du message
    print(msg)  # visulisation de celui-ci si on est branché à un PC
    i += 1
    time.sleep(2)  # temps d’attente
示例#18
0
        if lora.has_joined():
            flash_led_to(GREEN)
            print('LoRa Joined')
            return True
        else:
            flash_led_to(RED)
            print('LoRa Not Joined')
            return False

    else:
        return True

pycom.heartbeat(False) # Disable the heartbeat LED

# Getting the LoRa MAC
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.AS923)
print("Device LoRa MAC:", binascii.hexlify(lora.mac()))

flash_led_to(YELLOW)
# joining TTN
join_lora(True)

py = Pysense()
tempHum = SI7006A20(py)
ambientLight = LTR329ALS01(py)

# create a LoRa socket
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

#    s.setsockopt(socket.SOL_LORA, socket.SO_DR, 0)
s.setsockopt(socket.SOL_LORA, socket.SO_DR, config.LORA_NODE_DR)
示例#19
0
    return (send_pkg)


def LoRaSend(val, ch):
    sl = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
    sl.setblocking(True)
    sl.send(encrypt(SITE + mac() + '/' + ch + '&' +
                    val))  # Send on LoRa Network & wait Reply
    sl.setblocking(False)
    try:
        pycom.nvs_set('num', pycom.nvs_get('num') + 1)
    except:
        pycom.nvs_set('num', 0)
    print("Sent", ch)


lora = LoRa(mode=LoRa.LORA, region=LoRa.AU915, power_mode=LoRa.TX_ONLY)
sl = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

msgID = str(pycom.nvs_get('num'))
string = '{"val":' + str(
    sensorVals[0]) + ',"msgID":' + str(msgID) + ',"volt":' + str(voltage) + '}'
LoRaSend(string, str(1))
utime.sleep(0.1)
string = '{"val":' + str(sensorVals[1]) + ',"msgID":' + str(
    pycom.nvs_get('num')) + '}'
LoRaSend(string, str(2))

gc.collect()
machine.deepsleep(3600000)
示例#20
0
from dth import DTH

print("starting")

pycom.heartbeat(False)

th = DTH("P23", 1)
time.sleep(2)

adc = ADC()
adc.vref_to_pin("P22")
adc.vref(1100)
adc_c = adc.channel(pin="P16", attn=ADC.ATTN_11DB)


lora = LoRa(mode=LoRa.LORA, region=LoRa.US915)
lora.init(
    tx_power=14,
    sf=7,
    frequency=915000000,
    coding_rate=LoRa.CODING_4_5,
    bandwidth=LoRa.BW_125KHZ,
    power_mode=LoRa.TX_ONLY,
)


s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

cnt = 0
node = "lopy4_1"
示例#21
0
    def __init__(bandwidth=0,
                 sf=7,
                 buffersize=64,
                 preamble=8,
                 fichier='azer.txt',
                 power=14,
                 coding=1,
                 timeout=0.5,
                 maxretry=10):

        # fichier='azer.txt'
        # buffersize=64
        #buffersize=64 #taille  du  buffer  de récéption
        # lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868, bandwidth=LoRa.BW_500KHZ,preamble=5, sf=7)#définition dun truc
        lora = LoRa(mode=LoRa.LORA,
                    region=LoRa.EU868,
                    bandwidth=bandwidth,
                    preamble=preamble,
                    sf=sf,
                    tx_power=power,
                    coding_rate=coding)  #définition dun truc
        s = socket.socket(
            socket.AF_LORA,
            socket.SOCK_RAW)  #définition d'un socket réseaux de type lora
        print(lora.stats())
        print("bandwidth=" + str(bandwidth) + "preamble=" + str(preamble) +
              "sf=" + str(sf) + "tx_power=" + str(power) + "coding_rate=" +
              str(coding))
        print("bandtith" + str(lora.bandwidth()) + "preamble" +
              str(lora.preamble()) + "sf" + str(lora.sf()) + "tx_power" +
              str(lora.tx_power()) + "coding_rate" + str(lora.coding_rate()))

        # #ne pouvant avoir une résolution en  dessou de  la  seconde  sans passer  par des  tick ces mort
        # ltime=int()
        # def crono():
        # 	global ltime
        # 	b=time.time()
        # 	out=b-ltime
        # 	ltime=b
        # 	return out

        #fonction  permetant de vider  le buffer  qui peut poser  des soucis RArement mais  ça peut vite  être contrégniant dans le cas échéant
        def purge():
            #purger les  sockete
            s.setblocking(False)
            purgetemp = s.recv(buffersize)
            while purgetemp != b'':
                purgetemp = s.recv(buffersize)
            s.setblocking(True)

        #declaration
        startAt = 0
        nbtrame = 0
        indexManque = []
        indexRecieve = []
        stVarIndex = ""
        tVarIndex = ""
        playloadsize = 0  #autodetect

        arrayStat = []

        def unboxing(rawtram):

            #on verifie si on peut umpack la trame
            try:  #"H"+str(buffersize-2)
                unpackted = unpack(
                    stVarIndex + "s", rawtram
                )  #on stoque la data qui est dans un  tuple dans une variable

            except ValueError:  #OSError
                print("Unboxing: raw: " + str(rawtram))
            else:
                #pour le premier tour  on empege une division par zero
                totaltemp = time.time() - startAt
                if totaltemp == 0:
                    totaltemp = 1
                totaldata = (len(indexRecieve) + 1) * int(playloadsize)

                # arrayStat.append((unpackted[0], (totaldata/totaltemp), time.time(), gps.coord,lora.stats()[1], lora.stats()[2]))
                print("Unboxing: chunk " + str(unpackted[0]) + " Download: " +
                      str((len(indexRecieve) + 1) / nbtrame * 100) +
                      "% débit moyen: " + str(totaldata / totaltemp) +
                      "octée/s " + "position: " + str(gps.coord) +
                      " power reçus " + str(lora.stats()[1]) + "dBm, SNR: " +
                      str(lora.stats()[2]) + "dB ",
                      end='')

                #pour  verifier si  un  packet DOUBLON OU est malformer  on verifi  que l'index  existe  bien
                if unpackted[0] in indexManque:
                    #on vérifie si ces bien une trame  de data
                    #try  plus nécésaire ?
                    try:
                        #on archive le packet recus
                        indexRecieve.append(unpackted)
                        #caclule en%  des trame perdu #####peut être  opti
                        print("packet  perdu  " +
                              str(lostpacket(unpackted[0])) + "%")
                        #on  suprime  le  packet  de la  liste de  packet a  renvoiller
                        indexManque.remove(unpackted[0])
                    except ValueError:
                        #debug value
                        print("List des  packet a receptioner ",
                              str(indexManque))
                        # print("liste des packet déja  receptioner", str(indexRecieve))
                        print("chunk  a  suprimer :", unpackted[0])
                        print("packet unpackted", str(unpackted))
                        print("raw packet", str(rawtram))
                else:
                    #ajouter un compteur pour dire  q'uon a un packet  corrompu  pour les  packet  perdu !!
                    print(
                        "Unboxing: BAD INDEX Duplicate Packet or Malformed  packet ?"
                    )

        #définition d'une fonction d'aquitement
        def sendACK(vara):
            s.settimeout(timeout)
            i = 0
            while True:
                i += 1
                s.send(vara)
                print("ACK Envoit: " + str(vara))
                try:
                    retour = s.recv(buffersize)
                    #print("ack Reçus")
                    break
                except OSError as socket:
                    print("ACK timeout n° ", i)
                    time.sleep(0.1)
                    if (i == maxretry):
                        exit("connexion  perdu")
            #s.setblocking(True)
            return retour

        def sendACKvrf(data, match):
            while True:
                mydata = sendACK(data)
                if (type(match) == bytes):
                    if mydata == match:
                        break
                    else:
                        print("ACKvfr attendue :  ", match, "is byte  reçus",
                              mydata)
                if (type(match) == str):
                    if mydata == match.encode():
                        break
                    else:
                        print("ACKvfr attendue :  ", match.encode(),
                              "  is str  reçus", mydata)
            return True

        #fonction qui  va  calculer  les   packet perdu
        def lostpacket(id):
            indexlost = indexManque.index(id)
            for a in range(len(indexRecieve)):
                if (indexRecieve[a][0] == id):
                    indexadd = a
                    break
            #trame perdu +  trame  reception  =  nombre trame  totale
            totaltramesend = indexadd + indexlost + 1
            #raport  de perte
            return (indexlost + 1) / totaltramesend * 100

        def writeTo(name):
            # global indexRecieve #ABON ?
            #on essay suprime le fichier si il existe
            #flmee de  chercherune fonction  de  test  si  le fichier existe avant  de le suprimer
            name = str(name)
            try:
                #on  essaye  de le supprimer
                os.remove(name)
                print("fichier supprimer")
            except OSError as e:
                print("fichier inéxistant")

            #on  va  ouvrire  le fichiuer
            with open(
                    name, 'w'
            ) as fout:  #création de du fichier data.txt sur le module si il n'est pas present, ou sinon on l'ouvre en mode ajout de data.
                #on va  parser notre  tableaux de  tuple
                for truc in indexRecieve:
                    #on  va selecioner  la  2eme valeur de  notre tuple  (les data)
                    fout.write(truc[1])
                    # on referme le fichier proprement
            fout.close()

        print("Attente Trame Datalenght")
        #purge le buffer au  cas ou
        purge()

        s.settimeout(10)  ##EXPERIMENTAL POUR PAS BLOQUER
        #pour définire nbtrame  on va  accepter que les  trame  étant sur 1 octée en Long
        varnul = 0
        while True:
            try:
                nbtrame = unpack('L3s32s', s.recv(buffersize))
                if nbtrame[1] == b'OwO':
                    checksum = nbtrame[2]
                    nbtrame = nbtrame[0]
                    break
            except Exception as e:
                print("INITIALISATION: nombretrame err : Trame Non  attendue",
                      str(nbtrame))
                varnul += 1
                if (varnul == maxretry):
                    exit("connexion  perdu")
        print("nombre de trame", str(nbtrame))

        s.settimeout(timeout)

        #on déduit le type de  variable a  utiliser en fonction du  nombre de trame total
        if nbtrame < 256:
            tVarIndex = "B"
            stVarIndex = "B" + str(buffersize - 1)
            playloadsize = str(buffersize - 1)
        elif (nbtrame < 65536):
            tVarIndex = "H"
            stVarIndex = "H" + str(buffersize - 2)
            playloadsize = str(buffersize - 1)
        else:
            tVarIndex = "L"
            stVarIndex = "L" + str(buffersize - 4)
            playloadsize = str(buffersize - 1)

        #génération d'un  tableaux qui contien toute les trame
        for number in range(int(nbtrame)):
            indexManque.append(number)

        print("envoit d'un  ackitement")
        #Unboxing de la premierre trame de donnée qui fait office d'ackitment
        purge()
        startAt = time.time()
        unboxing(sendACK(str(nbtrame)))

        print("démarage reception")
        startAt = time.time()
        #je  demande explicitement d'écouter j'usqua se que je  recois une trame
        s.setblocking(True)
        while True:

            #tant que l'éméteur veux envoiller des donnée
            while True:
                #je  reçois ma trame
                ##experimentale
                s.settimeout(10)  ##
                trame = s.recv(buffersize)
                s.settimeout(timeout)  ##

                #quand l'éméteur  a fini ENvoit de  stop pour  passer a la partie suivante
                if trame == b'STOP':
                    print("fin de flux reçus  !")
                    #s.send("OK")
                    break
                #sinon on traite la trame normalement
                else:
                    #on va traiter la  trame  recus
                    unboxing(trame)

            print("Packet perdu" + str(
                len(indexManque) /
                (len(indexRecieve) + len(indexManque)) * 100) + "%")

            #si il  n'y a plus de trame manquante
            if (len(indexManque) == 0):
                print("plus de trame manquante.")
                #sendACK("STOP")
                #on va indiquer a l'éméteur que ces fini
                s.send("STOP")
                #on sort de toute mes boucle  affain  de  passer a  au  trie  des data
                break

            print("trame perdu/restant:")
            print(indexManque)

            #Envoit des trame a  retransmetre
            #+ ajout de la premierre trame reçus (data)

            #on copy explicitement le  précédant tableaux dans un  nouveaux
            indexManquetosend = indexManque.copy()

            time.sleep(0.250)

            #tant qu'il reste des trame dans la liste TEMPORAIRE des trame qui  manque
            while len(indexManquetosend):
                #vieux conmpeur
                i = 0
                #on initialise ma future  trame en déclarant que ça serat du  binaire
                temp = b''

                #je  crée  une  trame  qui  sera  égale  a la taille  du buffer ou inferieure  tant qu'il  me   reste des valeur  a y metre
                ##	  i<(buffersize/2) #mieux ? ###########################
                while i < 32 and len(indexManquetosend):
                    #je rajoute de nouveaux Idex de trame  manquante  a ma trame  éxistante
                    temp += pack('H', indexManquetosend[0])
                    #je  suprime  la valeur  ajouter
                    indexManquetosend.pop(0)
                    i += 1
                #je  m'assurt  que l'éméteur a  bien recus la  trame  qu'il  a recus  est qu'il n'es pas  perdu  [utile quand je chercherer a débusquer les trame  malformer]
                sendACKvrf(
                    temp, "indexOKforNext"
                )  #######a la place de indexOk peut metre un ckecksum
                print("INDEXE echangée  " + str(i) + " liste des chunck")
            #on envoit a  l'éméteur un  signial  indiquant qu'il n'y a plus  de  trame a  envoiller est on verifi qu'il  est bien sincro

            print("on STOP la l'émition")
            sendACKvrf("STOPliste", "indexFIN")
            print("liste  trame manquante bien  réceptioner"
                  )  ##  ligne 160  et  163 redondante ?
            print(indexManque)
            #on envoit une  trame  pour  trigguer l'éméteur pour qu'il  passe  en  mode émition  et on traite  la premierre valeur reçus
            ###metre  un  time  out a  l'éméteur

            #on commence  la  reception qqd  on est  sur d'avoir  du  binaire
            tmpp = b'indexFIN'
            while tmpp == b'indexFIN':
                print(tmpp)  #debug
                tmpp = sendACK("GO")
                print(tmpp)  #debug
            unboxing(tmpp)

            print("début de la rerectption")
####

        print("récéption terminer:")

        purge()
        s.setblocking(False)
        s.send("FinTransmition")
        s.send("FinTransmition")
        s.send("FinTransmition")

        stopAt = time.time()

        print("trie:")
        #on va trier  en fonction  du  1er élémenet du tuple du tableaux
        indexRecieve.sort(key=itemgetter(0))
        #print(indexRecieve)

        datafile = b''
        for truc in indexRecieve:
            if (truc[1] == b''):
                break
            datafile += truc[1]
        print("durée du transfer:",
              str(stopAt - startAt), "seconde débit moyen de",
              str(len(datafile) / (stopAt - startAt)), "octée/s")
        m = hashlib.sha256()
        m.update(datafile)

        print("################")
        if checksum == m.digest():
            print("Fichier intègre !")
        else:
            print("/!\ bad checksum ! /!\ ")
        print("################")

        print("Phase écriture:")

        writeTo(fichier)

        # print("durée du transfer:",str(stopAt-startAt),"débit moyen de", str(os.stat("imgOut.txt")[5]/(stopAt-startAt)))

        print("transfer  terminer")

        print(str(indexRecieve))
示例#22
0
def lora_erase():
    lora = LoRa(mode=LoRa.LORAWAN)
    lora.nvram_erase()
示例#23
0
si = SI7006A20(py)

# Disable Hearbeat
pycom.heartbeat(False)
pycom.rgbled(0x331000)  # red

# Initialise LoRa in LORAWAN mode.
# Please pick the region that matches where you are using the device:
# Asia = LoRa.AS923
# Australia = LoRa.AU915
# Europe = LoRa.EU868
# United States = LoRa.US915

# Setup Temeprature

lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868, bandwidth=LoRa.BW_250KHZ)

# create an OTAA authentication parameters, change them to the provided credentials
app_eui = ubinascii.unhexlify('70B3D57ED003AFB6')
app_key = ubinascii.unhexlify('73802D693E0BF2E835756B7B1977F7F0')
#uncomment to use LoRaWAN application provided dev_eui
#dev_eui = ubinascii.unhexlify('70B3D549938EA1EE')

# join a network using OTAA (Over the Air Activation)
#uncomment below to use LoRaWAN application provided dev_eui
lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
#lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0)

# wait until the module has joined the network
while not lora.has_joined():
    time.sleep(2.5)
示例#24
0
def get_device_eui():
    lora = LoRa(mode=LoRa.LORAWAN)
    print(ubinascii.hexlify(lora.mac()).upper().decode("utf-8"))
示例#25
0
#
# Copyright (c) 2016, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#

from network import LoRa
import binascii
import pycom

EXPECTED_MAC_ADDRESS = b"{MAC_ADDRESS}"

lora = LoRa(mode=LoRa.LORA)

if binascii.hexlify(lora.mac()) == EXPECTED_MAC_ADDRESS:
    pycom.heartbeat(False)
    pycom.rgbled(0x008000)   # green
    print('Test OK')
    while True:
        pass
else:
    print('Test failed')
示例#26
0
def t3_publication(topic, msg):
	print (topic, ';', msg)
	pycom.rgbled(0xff00)

UNIQUE_ID = machine.unique_id()
MQTT_BROKER = "192.168.2.68"
MQTT_PORT = 1883
MQTT_TOPIC = "iot-2/type/lopy/id/lopy2/evt/evento1/fmt/json"
mqtt_client = MQTTClient(UNIQUE_ID, MQTT_BROKER, port=MQTT_PORT)
mqtt_client.settimeout = settimeout
mqtt_client.set_callback(t3_publication)
mqtt_client.connect()

_LORA_PKG_ACK_FORMAT = "BBB"
_LORA_PKG_FORMAT = "BB%ds"
lora = LoRa(mode=LoRa.LORA, rx_iq=True)
lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
lora_sock.setblocking(False)
print("NANO GATEWAY RUNNING!!!")
while (True):
    recv_pkg = lora_sock.recv(512)
    print(recv_pkg)
    time.sleep(5)
    if (len(recv_pkg) > 2):
        recv_pkg_len = recv_pkg[1]
        device_id, pkg_len, msg = struct.unpack(_LORA_PKG_FORMAT % recv_pkg_len, recv_pkg)
        print(msg)
        #mqtt_client.publish("lopytopic", json.dumps(msg))
        mqtt_client.publish(MQTT_TOPIC, json.dumps(msg))
        
        ack_pkg = struct.pack(_LORA_PKG_ACK_FORMAT, device_id, 1, 200)
示例#27
0
ow = OneWire(Pin('P10'))
temp = DS18X20(ow)

# A basic package header, B: 1 byte for the deviceId, B: 1 byte for the pkg size
_LORA_PKG_FORMAT = "BB%ds"
_LORA_PKG_ACK_FORMAT = "BBB"
DEVICE_ID = 0x01

pycom.heartbeat(False)  # disable the blue blinking
# Open a Lora Socket, use tx_iq to avoid listening to our own messages
# Please pick the region that matches where you are using the device:
# Asia = LoRa.AS923
# Australia = LoRa.AU915
# Europe = LoRa.EU868
# United States = LoRa.US915
lora = LoRa(mode=LoRa.LORA, tx_iq=True, region=LoRa.US915)
lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
lora_sock.setblocking(False)
print("Simple Lora raw Node")
pycom.rgbled(0x000022)
while (True):
    temp.start_conversion()
    time.sleep(1)
    print(temp.read_temp_async())
    # Package send containing a simple string
    msg = "Device 1 Here"
    n = {'t': temp.read_temp_async(), 'id': 'd01'}
    msg = json.dumps(n)
    pkg = struct.pack(_LORA_PKG_FORMAT % len(msg), DEVICE_ID, len(msg), msg)
    lora_sock.send(pkg)
    print(pkg)
示例#28
0
"""
Semplice ping-pong fra due LoPy in frequenza "locale"
--INVIO
"""

from network import LoRa
import socket
import time
import pycom

# Setup del socket
lora = LoRa(mode=LoRa.LORA, frequency=868000000)  # 868 MHz
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setblocking(False)

a = 0
while True:
    time.sleep(5)
    o = 'Ping-{}'.format(a)
    s.send(o)
    print(o)
    a += 1
示例#29
0
import time
import ubinascii
import pycom
import json
pycom.heartbeat(False)

with open('config.json') as f:
    config = json.load(f)

# Initialise LoRa in LORAWAN mode.
# Please pick the region that matches where you are using the device:
# Asia = LoRa.AS923
# Australia = LoRa.AU915
# Europe = LoRa.EU868
# United States = LoRa.US915
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)

#print("DevEUI: " + ubinascii.hexlify(lora.mac()).decode('utf-8').upper())

# create an OTAA authentication parameters

app_eui = ubinascii.unhexlify(config['APP_EUI']) ## app key
app_key = ubinascii.unhexlify(config['APP_KEY'])


def connect_lora():
    # join a network using OTAA (Over the Air Activation)
    lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)

    while not lora.has_joined():
        print('Not yet joined...')
示例#30
0
 def __init__(self, mode=LoRa.LORAWAN):
     super().__init__()
     self.socket = None
     self.lora = LoRa(mode=mode)