Ejemplo n.º 1
0
config_start = False
End_discover = False
End_normal = False
power = 2
intent = 1

EnviatGateway = False
neighbours = [[], []]
neighbours_aux = [[], []]
msg = "Config 2"
msg_aux = "Config 2"
rcv_data = False
node_list = ""
msg_alarm_ok = " "

timer_to_send_GTW = Timer.Chrono()
timer_to_send_alarm = Timer.Chrono()
timer_token_ack = Timer.Chrono()
timer_discover_end = Timer.Chrono()
button = machine.Pin(Pin.exp_board.G17, mode=Pin.IN, pull=Pin.PULL_UP)
#timer_to_send_GTW.start()
Hello_received = False

period = 2

counter = 1
i = 0
## Initialize time
rtc = machine.RTC()
#(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
rtc.init((2020, 07, 28, 11, 36))
Ejemplo n.º 2
0
            ComInterface.the_socket.setsockopt(socket.SOL_SIGFOX, socket.SO_RX,
                                               True)

            try:
                # send uplink data
                pycom.rgbled(0x00ffff)  # cyan
                print("Sending with no response at: {}".format(
                    ComInterface.chrono.read()))
                ComInterface.the_socket.send(data)
                print("data sent at: {}: ".format(ComInterface.chrono.read()))
                print('message RSSI: {}'.format(sigfox.rssi()))
                #time.sleep(wait_time)
            except OSError as e:
                print("Error at: {}: ".format(ComInterface.chrono.read()))
                print('Error number {}, {}'.format(e.args[0], e))
                pycom.rgbled(0xff0000)  # red
                if e.args[0] == 11:
                    # Retry Logic
                    print('Error {}, {}'.format(e.args[0], e))
            time.sleep(sleep_after)
            return None


# Init Chrono
chrono = Timer.Chrono()
# Start Time
chrono.start()
ComInterface.initialize(chrono)
ComInterface.send_sigfox(bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), 30,
                         False)
Ejemplo n.º 3
0
from machine import Timer, Pin, PWM
from helpers import *
import _thread
import utime
import adc
from sht1x import SHT1X
from pms5003 import PMS5003, PMSData
import persistence
from datapoint import DataPoint
from ds3231 import DS3231

pycom.heartbeat(False)

VERSION = '0.7.0'

alive_timer = Timer.Chrono()
alive_timer.start()


def tear_down(timer, initial_time_remaining):
    timer.stop()
    elapsed_ms = int(timer.read() * 1000)
    timer.reset()
    time_remaining = initial_time_remaining - elapsed_ms
    print('sleeping for {}ms ({})'.format(time_remaining, ertc.get_time()))

    # deepsleep_pin = Pin('P10', mode=Pin.IN, pull=Pin.PULL_UP)
    # machine.pin_deepsleep_wakeup(pins=[deepsleep_pin], mode=machine.WAKEUP_ALL_LOW, enable_pull=True)
    machine.deepsleep(time_remaining)

Ejemplo n.º 4
0
from network import LoRa
import socket
import time

pycom.wifi_on_boot(False)
Hello_received = False
end_discover = False
CONFIG_MODE = 0
DISCOVER_MODE = 1
LISTEN_MODE = 2
NORMAL_MODE = 3
ALARM_MODE = 4
CHECK = 5
stop_config = False
pycom.wifi_on_boot(False)
timer2 = Timer.Chrono()
timer3 = Timer.Chrono()
timer_read_sensors = Timer.Chrono()
timer_Disc_end = Timer.Chrono()
timer_Disc_end.reset()
timer_read_sensors.reset()
discover_end_ack = False
timer2.reset()
missatge = False
period = 500
pycom.wifi_on_boot(False)

com = comu.Comunication()
com.start_LoraRaw()
#timer=Timer.Chrono()
#timer.reset()
Ejemplo n.º 5
0
import time
from machine import Timer, RTC
import machine
import binascii
import network
import pycom
from network import LTE

from sensors import ds1820, hx711, bme280
import logger
import webserver
from wlanmanager import WLanManager

from config import Config

boottime = Timer.Chrono()
boottime.start()

_config = Config()

_wlan = network.WLAN(id=0)
lte = LTE()

_ds_positions = {
    v: k
    for k, v in _config.get_value('sensors', 'ds1820', 'positions').items()
}

_wm = WLanManager()

reset_causes = {
Ejemplo n.º 6
0
def start_measurement():
    AP_TIME = 2 * 60
    perf = Timer.Chrono()
    pycom.heartbeat(False)
    pycom.rgbled(0x000000)

    perf.start()

    while boottime.read() < AP_TIME:
        # Measure all enabled sensors
        data = {}
        if ds1820 is not None:
            for rom in ds1820.roms:
                ds1820.start_conversion(rom=rom)
            time.sleep_ms(750)
            for rom in ds1820.roms:
                try:
                    ds_measurement = ds1820.read_temp_async(rom=rom)
                    ds_name = binascii.hexlify(rom).decode('utf-8')
                    if ds_name in _ds_positions:
                        data[_ds_positions[ds_name]] = ds_measurement
                except Exception as e:
                    log("Did not find rom" + str(e))
        if bme280 is not None:
            try:
                (data['t'], data['p'],
                 data['h']) = bme280.read_compensated_data()

                data['p'] = data['p'] / 100  # Pa to mBar
            except Exception:
                log("BME280 not measuring.")
        if hx711 is not None:
            data['weight_kg'] = hx711.get_value(times=5)

        # Log measured values
        perf.start()
        if _csv is not None:
            _csv.add_dict(data)
        if _wlan.mode() == network.WLAN.STA and _wlan.isconnected(
        ) and _beep is not None:
            log("beep")
            _beep.add(data)
        log(data)
        perf.stop()
        time_elapsed = perf.read()
        perf.reset()
        time_until_measurement = measurement_interval - time_elapsed
        log('SecondsO elapsed: {:.2f}s, time until next measurement: {:.2f}s'.
            format(time_elapsed, time_until_measurement))

        # 10 Minuten nach dem Strom an soll der AC da sein.
        log('boottime: ' + str(boottime.read()))
        if machine.reset_cause() != machine.DEEPSLEEP_RESET and boottime.read(
        ) < AP_TIME:
            log('sleep')
            time.sleep_ms(int(abs(time_until_measurement) * 1000))
        else:
            lte.dettach()
            _wlan.deinit()
            log('deepsleep')
            # machine.deepsleep(int(abs(time_until_measurement * 1000)))
            machine.deepsleep(int(abs(10 * 1000)))

    log('Unexpected exited while loop')
    machine.reset()
Ejemplo n.º 7
0
def receive_data():
    global index
    global guard
    global slot
    global packet_size
    lora = LoRa(mode=LoRa.LORA,
                rx_iq=True,
                frequency=freqs[my_sf - 5],
                region=LoRa.EU868,
                power_mode=LoRa.ALWAYS_ON,
                bandwidth=my_bw,
                sf=my_sf)
    lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
    lora_sock.setblocking(False)
    guard = 1000 * guard
    (overall_received, overall_sent) = (0, 0)
    airt = int(airtime_calc(my_sf, 1, packet_size + 2, my_bw_plain) * 1000)
    duty_cycle_limit_slots = math.ceil(100 * airt / (airt + 2 * guard))
    print("duty cycle slots:", duty_cycle_limit_slots)
    print("packet airtime (ms):", airt / 1000)
    print("guard time (ms):", guard / 1000)
    chrono = Timer.Chrono()
    chrono.start()
    i = 1
    while (True):
        print(i, "----------------------------------------------------")
        print("Net size is:", index + 1)
        chrono.reset()
        round_start = chrono.read_us()
        received = 0
        acks = []
        if (int(index) > duty_cycle_limit_slots):
            round_length = math.ceil(int(index) * (airt + 2 * guard))
        else:
            round_length = math.ceil(duty_cycle_limit_slots *
                                     (airt + 2 * guard))
        lora.init(mode=LoRa.LORA,
                  rx_iq=True,
                  region=LoRa.EU868,
                  frequency=freqs[my_sf - 5],
                  power_mode=LoRa.ALWAYS_ON,
                  bandwidth=my_bw,
                  sf=my_sf)
        rec_start = chrono.read_us()
        pycom.rgbled(green)
        while ((chrono.read_us() - round_start) <
               round_length - 66000):  # the following line may take up to 66ms
            recv_pkg = lora_sock.recv(256)
            if (len(recv_pkg) > 2):
                recv_pkg_len = recv_pkg[1]
                recv_pkg_id = recv_pkg[0]
                if (int(recv_pkg_id) <= 35) and (int(recv_pkg_len)
                                                 == int(packet_size)):
                    dev_id, leng, msg = struct.unpack(
                        _LORA_RCV_PKG_FORMAT % recv_pkg_len, recv_pkg)
                    if (len(msg) == packet_size):  # format check
                        received += 1
                        # print('Received from: %d' % dev_id)
                        # print(lora.stats())
                        acks.append(str(int(dev_id)))
                        pycom.rgbled(off)
        print(received, "packets received")
        rec_lasted = chrono.read_us() - rec_start
        if (rec_lasted < round_length):
            print("I'll sleep a bit to align with the round length")
            time.sleep_us(int(round_length - rec_lasted))
        print("Receiving lasted (ms):", (chrono.read_us() - rec_start) / 1000)
        print("...should last (ms):", round_length / 1000)
        proc_t = chrono.read_us()
        ack_msg = ""
        for n in range(int(index) + 1):
            if n in slot:
                id = str(slot[n])
                if id in acks:
                    ack_msg = ack_msg + "1"
                else:
                    ack_msg = ack_msg + "0"
        if (ack_msg != ""):
            ack_msg = str(hex(int(ack_msg, 2)))[2:]
        print("proc time (ms):", (chrono.read_us() - proc_t) / 1000)
        proc_t = chrono.read_us() - proc_t
        if (i % sync_rate == 0):  # SACK
            sync_start = chrono.read_us()
            pycom.rgbled(white)
            time.sleep_us(int(guard * 3 /
                              2))  # let's make it long so all the nodes are up
            lora.init(mode=LoRa.LORA,
                      tx_iq=True,
                      frequency=freqs[my_sf - 5],
                      region=LoRa.EU868,
                      power_mode=LoRa.ALWAYS_ON,
                      bandwidth=my_bw,
                      sf=my_sf,
                      tx_power=14)
            data = str(index + 1) + ":" + str(int(
                proc_t / 1000)) + ":" + ack_msg
            pkg = struct.pack(_LORA_PKG_FORMAT % len(data), MY_ID, len(data),
                              data)
            pycom.rgbled(red)
            lora_sock.send(pkg)
            print("Sent sync: " + data)
            pycom.rgbled(off)
            time.sleep_ms(13)  # node time after sack
            print("sync lasted (ms):", (chrono.read_us() - sync_start) / 1000)
        print("round lasted (ms):", (chrono.read_us() - round_start) / 1000)
        i += 1
Ejemplo n.º 8
0
 def __init__(self):
     self.chrono = Timer.Chrono()
     self.chrono.start()
    #remove all channels 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 ring lopy
    dev_eui = ubinascii.unhexlify(
        '70B3D54990435DFE')  # these settings can be found from TTN
    app_eui = ubinascii.unhexlify('70B3D57ED0028A4F')
    app_key = ubinascii.unhexlify('CE46C01958A612D102F0D106AB415862')

    if not lora.has_joined():
        lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
        pycom.rgbled(green)
        time.sleep(2.5)
    handshk_time = Timer.Chrono()
    handshk_time.start()
    # wait until the module has joined the network
    while not lora.has_joined():
        pycom.rgbled(off)
        time.sleep(0.1)
        pycom.rgbled(red)
        time.sleep(2.4)
        print('Not yet joined...')
    lora.nvram_save()
    handshk_time.stop()
    print("Total handshake time: {0}".format(handshk_time.read()))
    print('Joined!')
    pycom.rgbled(blue)
    # create a LoRa socket
    s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
Ejemplo n.º 10
0
 def __init__(self):
     from machine import Timer
     self.chrono = Timer.Chrono()
     self.chrono.start()
Ejemplo n.º 11
0
    d["lat"] = lat
    d["lon"] = lon
    d["hdop"] = hdop
    d["alt"] = alt
    f.write(json.dumps(d))
    f.write("\n")
    f.close()
    rgb.green(0x88)
    rgb.red(0x88)
    time.sleep(1)
    rgb.green_off()
    rgb.red_off()

rgb = RgbWrapper()  #Setup LED for debug output
sd_en = False       #Whether to try to write to SD card
chrono = Timer.Chrono() #Keep track of time since boot so can  record how long between GPS readings
chrono.start()
last_gps_reading = 0    #When the last GPS reading was taken

try:
    sd = SD()
    os.mount(sd, SD_MOUNT_DIR)
    sd_en = True
    rgb.green(0x88)
    rgb.red(0x88)
    time.sleep(1)
    rgb.green_off()
    rgb.red_off()
except OSError:
    sd_en = False   #Make sure SD card access is disabled
print("SD Card enabled: " + str(sd_en))