Example #1
0
def main():
    global numPRs
    global ticks
    global colorsForNumPRs

    wdt = WDT(timeout=15000)

    while True:
        wdt.feed()
        # print(ticks)

        if wlan.mode() == WLAN.AP:
            drawErrorForTicks(ticks)

            ticks += 1
            time.sleep_ms(13)
            continue

        # about every 10 s:
        if ticks % (800 // 2) == 0:
            print('load colors')
            colorsForNumPRs = loadSettings(select="colors")
            print('getting...')
            getAndPrintPRs()

        drawForTicks(ticks, numPRs)
        ticks += 1
        time.sleep_ms(13)
def wdt():
    from machine import WDT
    from time import sleep
    wdt = WDT(timeout=10000)  #10 seconds of hanging
    while True:
        wdt.feed()
        sleep(1)
Example #3
0
def httpserver(fromcard = False, rootpath = '', watchdog = False):
    global webroot
    #logging.basicConfig(level=logging.ERROR)

    addr = get_address()

    if fromcard:
        from shields import microsd_shield
        sdcard = microsd_shield.MicroSD_Shield()
        sdcard.mount()
        webroot = '/sd/wwwroot'

    if rootpath:
        webroot = rootpath

    #uasyncio.set_debug(1)
    loop = uasyncio.get_event_loop()

    loop.create_task(uasyncio.start_server(serve_content, addr, 80, 20))

    if watchdog:
        from machine import Pin, WDT
        wdt = WDT()
        wdt.feed()
        led = Pin(2, Pin.OUT)
        loop.create_task(heartbeat(wdt, led))
    
    loop.run_forever()
    loop.close()

    if fromcard:
        sdcard.unmount()

#httpserver()
Example #4
0
def main():
    wdt = WDT(timeout=3000)

    homie = HomieDevice(settings)

    homie.add_node(Error())

    # publish device and node properties
    homie.publish_properties()

    # subsribe to topics
    homie.subscribe_topics()

    while True:
        # reset the errors
        homie.errors = 0

        # publish device data
        homie.publish_data()

        # feed wdt if we have no errors
        if not homie.errors:
            wdt.feed()

        utime.sleep(1)
Example #5
0
    async def wdt(self):
        from machine import WDT

        wdt = WDT()
        while True:
            wdt.feed()
            await sleep_ms(WDT_DELAY)
Example #6
0
class WDT(StatusModule):
    """
    A status modue that uses the invocation of the status functions to feed a watchdog timer.
    """
    def __init__(self):
        super(WDT, self).__init__()
        from machine import WDT as PYCOM_WDT
        self.wdt = PYCOM_WDT(timeout=1000*self.config().get("timeout"))

    def feed(self):
        self.wdt.feed()

    def status(self, type):
        self.feed()

    def log(self, level, message):
        self.feed()

    def test(self):
        self.feed()

    def measurement(self, bytearray, json):
        self.feed()

    def get_config_definition():
        return (
            "status_wdt",
            "This module is a watchdog using the status functions as a way too be fed.",
            (
                ("timeout", "60", "Defines how many seconds to wait after the last status message occured until the device is reset.", ConfigFile.VariableType.uint),
            )
        )
Example #7
0
async def heartbeat():
    speed = 1500
    led = Pin(2, Pin.OUT, value=1)
    wdt = WDT()
    while True:
        led.value(led.value() ^ 1)
        wdt.feed()
        await asyncio.sleep_ms(speed)
Example #8
0
class Publish:
    def __init__(self, publish_stack):
        configs = get_configs()

        self.ip = configs['broker_mqtt']['ip']
        self.port = configs['broker_mqtt']['port']
        self.user = configs['broker_mqtt']['user']
        self.password = configs['broker_mqtt']['pass']
        self.topic = bytes(configs['broker_mqtt']['topic'], "utf-8")
        self.uuid = configs['gateway']['uuid']

        self.publish_stack = publish_stack
        self.wdt = WDT(timeout=1000 * 60 * 15)

    def connect(self):
        while True:
            try:
                while self.publish_stack.length() > 0:
                    failed_send = False
                    data = json.loads(self.publish_stack.get())
                    i = 1
                    while i < 9:
                        try:
                            if 'tries' in data:
                                data.update({'tries': data['tries'] + 1})
                            else:
                                data.update({'tries': 1})

                            if not 'gateway' in data:
                                data.update({'gateway': {'uuid': self.uuid}})

                            c = MQTTClient(self.topic, self.ip, self.port,
                                           self.user, self.password)
                            c.connect()
                            c.publish(self.topic, json.dumps(data).encode())
                            c.disconnect()

                            failed_send = False

                            self.wdt.feed()
                            break

                        except Exception:
                            i += 1
                            failed_send = True
                            time.sleep(5)

                    # no persistency for ack answer
                    if failed_send and data['type'] != 'identification':
                        self.publish_stack.write_buffer(json.dumps(data))
                    self.publish_stack.delete()

                # TODO: verify necessity of sleep here
            except Exception as e:
                self.publish_stack.delete()
                log("Publish-connect: {}".format(e))
            time.sleep(5)
Example #9
0
class watchdog(object):
    def __init__(self, wdtimeout):
        #self._wdtimeout = wdtimeout+30000
        print('Timeout', wdtimeout)
        self._watchdog = WDT(timeout=wdtimeout)

    def run(self):
        while True:
            self._watchdog.feed()
            print('reset timeout')
            yield 2
Example #10
0
async def heartbeat():
    await asyncio.sleep(30)
    speed = 125
    led = Pin(LED, Pin.OUT, value=1)
    wdt = WDT()
    while True:
        led(0)
        wdt.feed()
        await asyncio.sleep_ms(speed)
        led(1)
        wdt.feed()
        await asyncio.sleep_ms(speed * 10)
 def start(self, interval=60):
     """
     Begins to publish temperature data on an interval (in seconds).
     This function will not exit! Consider using deep sleep instead.
     :param interval: How often to publish temperature data (60s default)
     :type interval: int
     """
     wdt = WDT()
     while True:
         self.publishTemperature()
         time.sleep(interval)
         wdt.feed()
Example #12
0
  async def relay_loop(self, conns, deadline):
    max_timeout = 5005
    wdt = None
    try:
      if self.uPK.WATCHDOG_TIMEOUT:
        from machine import WDT
        wdt = WDT(timeout=self.uPK.WATCHDOG_TIMEOUT)
        max_timeout = min(max_timeout, self.uPK.WATCHDOG_TIMEOUT // 2)
    except KeyboardInterrupt:
      raise
    except:
      pass

    await fuzzy_sleep_ms()
    try:
      pool = uPageKiteConnPool(conns, self)
      while pool.conns and self.keep_running and time.time() < deadline:
        if wdt:
          wdt.feed()

        self.uPK.GC_COLLECT()
        timeout_ms = min(max(100, (deadline - time.time()) * 1000), max_timeout)
        await fuzzy_sleep_ms()
        if await pool.process_io(self.uPK, int(timeout_ms)) is False:
          raise EofTunnelError('process_io returned False')

        if self.reconfig_flag:
          if self.uPK.info:
            self.uPK.info("Exiting relay_loop early: reconfiguration requested.")
          return False

      # Happy ending!
      return True
    except KeyboardInterrupt:
      raise
    except Exception as e:
      if self.uPK.debug:
        print_exc(e)
        self.uPK.debug('Oops, relay_loop: %s(%s)' % (type(e), e))

    # We've fallen through to our unhappy ending, clean up
    for conn in conns:
      try:
        conn.close()
      except Exception as e:
        if self.uPK.debug:
          self.uPK.debug("Oops, close(%s): %s" % (conn, e))
    return False
Example #13
0
class Clock:
    def __init__(self, led, period=5, max_count=10):
        self._max_count = max_count
        self.__alarm = Timer.Alarm(self._seconds_handler,
                                   period,
                                   periodic=True)
        self._led = led
        self._count = 0
        self._wdt = WDT(timeout=period * 2 *
                        1000)  # enable WDT with a timeout of 2*period seconds

    def _seconds_handler(self, alarm):
        self._count += 1
        print("Timer Alarm called : %s" % str(self._count))
        self._led(1)
        self._wdt.feed()
        if self._count == self._max_count:
            print("Alarm canceled after %s calls" % str(self._max_count))
            alarm.cancel()  # stop counting
Example #14
0
def request(requests):
    s = socket.socket()
    s.setblocking(True)
    p = uselect.poll()
    p.register(
        s,
        uselect.POLLIN | uselect.POLLOUT | uselect.POLLHUP | uselect.POLLERR)

    try:
        wdt = WDT(timeout=10 * 1000)
        s.settimeout(1.0)
        s.connect(socket.getaddrinfo(CTLR_IPADDRESS, 6543)[0][-1])
        logger.info('request: connected to the server...')
        wdt.feed()
        wdt.init(5 * 60 * 1000)
        response = s_handler(p, requests)
        logger.debug('request: finished. response={}'.format(response))
        return response
    except socket.timeout:
        logger.debug('request: Timeout error occurred...')
    except:
        raise
    return
Example #15
0
def main():
    global watchdog

    setup_config()
    setup_connectivity()
    gc.collect()
    setup_sensors()

    watchdog = WDT(timeout=detimotic_conf['watchdog'])

    try:
        while True:
            try:
                for i in range(len(modules)):
                    watchdog.feed()
                    module, last = modules[i]
                    if time.ticks_ms() - last >= module.time():
                        gc.collect()
                        module.loop()
                        modules[i] = (module, time.ticks_ms())
                if time.ticks_ms() - client.last_pingreq >= detimotic_conf['gateway']['ping_freq']:
                    client.ping()
                elif time.ticks_ms() - client.last_pingresp >= 3*detimotic_conf['gateway']['ping_freq']:
                    print('Forcibly reconnecting!')
                    client.disconnect()
                    wlan.disconnect()
                    watchdog.feed()
                    setup_connectivity()
                client.check_msg()
            except MemoryError:
                print('Memory Error!')
    except KeyboardInterrupt:
        print("KB INTERRUPT!")
        client.disconnect()
        wlan.disconnect()
        gc.collect()
        sys.exit(2)
Example #16
0
def mainloop(): #main loop looking for and handling UIDs from chips
    wdt = WDT(timeout=10000)  # enable watchdog with a timeout of 10 seconds
    global taps_pending
    global threadsswitch
    while True:
        uid_send = chipscan()
        if uid_send == "misread":
            negindication()
        elif uid_send == "no_chip":
            negindication()
        elif uid_send == "734D0185":
            setexternalrtc()
        else:
            tap = ("uid"+uid_send+"timestamp"+time_calc())
            chiplog(tap)
            sendlock.acquire()
            taps_pending.append(tap)
            sendlock.release()
            print(tap)
            del tap
            del uid_send
            posindication()
        wdt.feed()
        time.sleep(0.1)
Example #17
0
class Display(object):
    IMG_DIR = '/flash/imgs'

    def __init__(self, debug=False):
        self.cfg = None
        self.rtc = RTC()
        self.debug = debug
        self.battery = Battery()

        # use this pin for debug
        self.wifi_pin = Pin("GP24", mode=Pin.IN, pull=Pin.PULL_UP)

        # Empty WDT object
        self.wdt = None

        if not debug:
            if not self.wifi_pin():
                self.wdt = WDT(timeout=20000)
            self.sd = None
        else:
            from machine import SD
            try:
                self.sd = SD()
                mount(self.sd, '/sd')
                self.logfile = open("/sd/display.log", "a")
            except OSError:
                self.sd = None
                self.logfile = None

        self.epd = EPD()

        self.log("Time left on the alarm: %dms" % self.rtc.alarm_left())

        # Don't flash when we're awake outside of debug
        heartbeat(self.debug)

    def log(self, msg, end='\n'):
        time = "%d, %d, %d, %d, %d, %d" % self.rtc.now()[:-2]
        msg = time + ", " + msg
        if self.logfile:
            self.logfile.write(msg + end)
        print(msg, end=end)

    def feed_wdt(self):
        if self.wdt:
            self.wdt.feed()

    def connect_wifi(self):
        from network import WLAN

        if not self.cfg:
            raise ValueError("Can't initialise wifi, no config")

        self.log('Starting WLAN, attempting to connect to ' + ','.join(self.cfg.wifi.keys()))
        wlan = WLAN(0, WLAN.STA)
        wlan.ifconfig(config='dhcp')
        while not wlan.isconnected():
            nets = wlan.scan()
            for network in nets:
                if network.ssid in self.cfg.wifi.keys():
                    self.log('Connecting to ' + network.ssid)
                    self.feed_wdt() # just in case
                    wlan.connect(ssid=network.ssid, auth=(network.sec, self.cfg.wifi[network.ssid]))
                    while not wlan.isconnected():
                        idle()
                    break

            self.feed_wdt() # just in case
            sleep_ms(2000)

        self.log('Connected as %s' % wlan.ifconfig()[0])

    @staticmethod
    def reset_cause():
        import machine
        val = machine.reset_cause()
        if val == machine.POWER_ON:
            return "power"
        elif val == machine.HARD_RESET:
            return "hard"
        elif val == machine.WDT_RESET:
            return "wdt"
        elif val == machine.DEEPSLEEP_RESET:
            return "sleep"
        elif val == machine.SOFT_RESET:
            return "soft"

    def set_alarm(self, now, json_metadata):
        import json
        json_dict = json.loads(json_metadata)

        # Now we know the time too
        self.rtc = RTC(datetime=now)
        list_int = json_dict["wakeup"][:6]
        time_str = ",".join([str(x) for x in list_int])

        self.log("Setting alarm for " + time_str)
        self.rtc.alarm(time=tuple(list_int))

        if self.rtc.alarm_left() == 0:
            self.log("Alarm failed, setting for +1 hour")
            self.rtc.alarm(time=3600000)

        del json

    def display_file_image(self, file_obj):
        towrite = 15016
        max_chunk = 250
        while towrite > 0:
            c = max_chunk if towrite > max_chunk else towrite
            buff = file_obj.read(c)
            self.epd.upload_image_data(buff, delay_us=2000)
            self.feed_wdt()
            towrite -= c

        self.epd.display_update()

    def display_no_config(self):
        self.log("Displaying no config msg")
        with open(Display.IMG_DIR + '/no_config.bin', 'rb') as pic:
            self.display_file_image(pic)

    def display_low_battery(self):
        self.log("Displaying low battery msg")
        with open(Display.IMG_DIR + '/low_battery.bin', 'rb') as pic:
            self.display_file_image(pic)

    def display_cannot_connect(self):
        self.log("Displaying no server comms msg")
        with open(Display.IMG_DIR + '/no_server.bin', 'rb') as pic:
            self.display_file_image(pic)

    def display_no_wifi(self):
        self.log("Displaying no wifi msg")
        with open(Display.IMG_DIR + '/no_wifi.bin', 'rb') as pic:
            self.display_file_image(pic)

    def check_battery_level(self):
        now_batt = 200
        last_batt = self.battery.battery_raw()
        while now_batt > last_batt:
            sleep_ms(50)
            last_batt = now_batt
            self.feed_wdt()
            now_batt = self.battery.battery_raw()
            self.log("Battery value: %d (%d)" % (self.battery.value(), self.battery.battery_raw()))

        if not self.battery.safe():
            self.log("Battery voltage (%d) low! Turning off" % self.battery.battery_raw())
            self.feed_wdt()
            self.display_low_battery()
            return False
        else:
            self.log("Battery value: %d (%d)" % (self.battery.value(), self.battery.battery_raw()))
        return True

    def run_deepsleep(self):

        if not self.run():
            # RTC wasn't set, try to sleep forever
            self.rtc.alarm(time=2000000000)

        # Set the wakeup (why do it earlier?)
        rtc_i = self.rtc.irq(trigger=RTC.ALARM0, wake=DEEPSLEEP)

        self.log("Going to sleep, waking in %dms" % self.rtc.alarm_left())

        # Close files on the SD card
        if self.sd:
            self.logfile.close()
            self.logfile = None
            unmount('/sd')
            self.sd.deinit()

        # Turn the screen off
        self.epd.disable()

        if not self.wifi_pin():
            # Basically turn off
            deepsleep()
        else:
            self.log("DEBUG MODE: Staying awake")
            pass
            # Do nothing, allow network connections in

    def run(self):

        woken = self.wifi_pin()
        self.epd.enable()

        if not self.check_battery_level():
            return False

        try:
            self.epd.get_sensor_data()
        except ValueError:
            self.log("Can't communicate with display, flashing light and giving up")
            heartbeat(True)
            sleep_ms(15000)
            return True

        if self.rtc.alarm_left() > 0:
            self.log("Woken up but the timer is still running, refreshing screen only")
            self.epd.display_update()
            self.feed_wdt()
            return True

        try:
            self.cfg = Config.load(sd=self.sd)
            self.log("Loaded config")
        except (OSError, ValueError) as e:
            self.log("Failed to load config: " + str(e))
            self.display_no_config()
            try:
                self.connect_wifi()
            except:
                pass # everything

            while True:
                sleep_ms(10)
                self.feed_wdt()

        self.feed_wdt()

        self.connect_wifi()

        content = b''
        try:
            self.log("Connecting to server %s:%d" % (self.cfg.host, self.cfg.port))
            c = Connect(self.cfg.host, self.cfg.port, debug=self.debug)

            self.feed_wdt()

            cause = Display.reset_cause()
            if woken:
                cause = "user"

            self.log("Reset cause: " + cause)

            if len(self.cfg.upload_path) > 0:
                temp = self.epd.get_sensor_data() # we read this already
                c.post(self.cfg.upload_path,
                       battery=self.battery.value(),
                       reset=cause,
                       screen=temp)

            self.log("Fetching metadata from " + self.cfg.metadata_path)
            metadata = c.get_quick(self.cfg.metadata_path, max_length=1024, path_type='json')

            # This will set the time to GMT, not localtime
            self.set_alarm(c.last_fetch_time, metadata)

            self.feed_wdt()
            del metadata
            del self.battery
            self.log("Fetching image from " + self.cfg.image_path)
            self.epd.image_erase_frame_buffer()
            self.feed_wdt()

            length, socket = c.get_object(self.cfg.image_path)

            if length != 15016:
                raise ValueError("Wrong data size for image: %d" % length)

            self.feed_wdt()

        except (RuntimeError, ValueError, OSError) as e:
            self.log("Failed to get remote info: " + str(e))
            self.display_cannot_connect()
            self.rtc.alarm(time=3600000)
            return True

        sleep_ms(1000) # How do we make the write to display more reliable?
        self.feed_wdt()
        self.log("Uploading to display")
        self.display_file_image(socket)
        c.get_object_done() # close off socket

        if self.cfg.src == "sd":
            # If we've got a working config from SD instead of flash
            self.log("Transferring working config")
            Config.transfer()
            self.log("SUCCESS")

        self.log("Finished. Mem free: %d" % gc.mem_free())
        return True
Example #18
0
# Receiver code for Cawthron Institute's mussel farm accelerometer chain
# Author: Kevin Tang
"""
DEFAULT VALUES
MODE: 1 HZ
BAUD RATE: 9600
DATA FRAME: bits=8, parity=None, stop=1, timeout=0
WDT TIMEOUT: 3000ms
ACCELEROMETER RANGE: 2G
ACCELEROMETER FREQUENCY: 10HZ
"""
from machine import I2C, Pin, SPI, UART, WDT
from lis3dh import LIS3DH, LIS3DH_I2C, RANGE_2_G, DATARATE_10_HZ, STANDARD_GRAVITY
from pyb import ADC, RTC
from ds3231_port import DS3231
import time
import os
import sys
import math
global ID
global timer
ID = 0 # Receiver ID (0-9). MAKE SURE TO CHANGE
timer = 1 # By default, sleep value is set to 1s (1 Hz mode)
# Enable Watchdog timer if using battery
global TIMEOUT_VALUE
TIMEOUT_VALUE = 3000
if pyb.Pin.board.USB_VBUS.value() == 0:
  wdt = WDT(timeout = TIMEOUT_VALUE) # enable with a timeout of 3 seconds
if sys.platform == 'pyboard':
  # Initialising pins
Example #19
0
############################################################################
#main execution loop, triggered by awakening from deep sleep

# Get loramac as id to be sent in message
lora_mac = connection.getLoraMac()
lora_id = lora_mac[-6:]                     # only last 6 chars

ledcolor = 'red'                            # first start with color red
(no gps position)

while True:
   # -----------------------------
   gc.collect()

   wdt.feed()                                              # Feed the
WDT to prevent it from resetting the system

   # --------------- start of code executed after awakening
   # led.setLED('green')
   led.setLED(ledcolor)

   # prepare msg to send
   # count_tx = pycom.nvs_get('count_tx')      # retrieve count_tx

   # ----------------------------
   gc.collect()
   wdt.feed()                                  # Feed the WDT to
prevent it from resetting the system

   acc = li.acceleration()                     # read accelerometer
Example #20
0
white = 0x101010

# initialize WDT
wdt = WDT(timeout=5500)  # enable it with a timeout of 5.5 seconds
asleep = .1

wlan = WLAN(mode=WLAN.STA)
wlan.connect(SSID, auth=(WLAN.WPA2, PW), timeout=5000)

while not wlan.isconnected():
    machine.idle()
    pycom.rgbled(red)

print("Connected to Wifi\n")
wdt.feed()  #made it past the WLAN timeout loop error
pycom.rgbled(white)
time.sleep(asleep)

client = MQTTClient("fipy",
                    "io.adafruit.com",
                    user=AIOuser,
                    password=AIOpw,
                    port=8883,
                    ssl=True)

client.set_callback(sub_cb)
client.connect()
time.sleep(asleep)
wdt.feed()  #made it past the WLAN timeout loop error
Example #21
0
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()
        self.wdt = WDT(timeout=50000)

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

        # feed the dog
        self.wdt.feed()

        # 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)
            packet = self.frequency_rounding_fix(packet, self.frequency)
            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 frequency_rounding_fix(self, packet, frequency):
        freq = str(frequency)[0:3] + '.' + str(frequency)[3]

        start = packet.find("freq\":")
        end = packet.find(",", start)

        packet = packet[:start + 7] + freq + packet[end:]

        return packet

    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):
        # feed the dog everytime we pull data
        self.wdt.feed()
        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 _send_down_link_class_c(self, data, datarate, frequency):
        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,
                       device_class=LoRa.CLASS_C)

        self.lora_sock.send(data)
        self._log(
            'Sent downlink packet scheduled on {:.3f}, at {:.3f} Mhz using {}: {}',
            utime.time(), 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:])
                    if "tmst" in data:
                        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)
                    else:
                        self.uplink_alarm = Timer.Alarm(
                            handler=lambda x: self._send_down_link_class_c(
                                ubinascii.a2b_base64(tx_pk["txpk"]["data"]),
                                tx_pk["txpk"]["datr"],
                                int(tx_pk["txpk"]["freq"] * 1000) * 1000),
                            us=50)
                    self._ack_pull_rsp(_token, ack_error)
                    self._log("Pull rsp")
            except usocket.timeout:
                pass
            except OSError as ex:
                if ex.args[0] != 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)))
Example #22
0
import time
from machine import WDT

# '''
# test default wdt
wdt0 = WDT(id=0, timeout=3000)
print('into', wdt0)
time.sleep(2)
print(time.ticks_ms())
# 1.test wdt feed
wdt0.feed()
time.sleep(2)
print(time.ticks_ms())
# 2.test wdt stop
wdt0.stop()
print('stop', wdt0)

# 3.wait wdt work
#while True:
#print('idle', time.ticks_ms())
#time.sleep(1)
# '''


# '''
def on_wdt(self):
    print(self.context(), self)
    #self.feed()
    ## release WDT
    #self.stop()
Example #23
0
            self.accumulatedData += sensorValue
            self.readingCount += 1
            if self.readingCount == 5:  # send data every 5min
                data = round((self.accumulatedData / 5),
                             2)  # avg force over the last 5 values
                data = str(self.location + "-" + str(data))
                # print("AVG force - ", data)
                self.sendData(data)
                self.accumulatedData = 0  # clear accumulatedData
                self.readingCount = 0
                return True
        else:
            return False


# Initilise sensors
topLeftSensor = PedalSensor("tLS", 0x0a)
topRightSensor = PedalSensor("tRS", 0x0b)
bottomRightSensor = PedalSensor("bRS", 0x0c)
bottomLeftSensor = PedalSensor("bLS", 0x0d)

# read sensor data every minute
while (True):
    topLeftSensor.tick()
    topRightSensor.tick()
    bottomLeftSensor.tick()
    bottomRightSensor.tick()
    wdt.feed()  # tell watchdog we're stll alive

    time.sleep(60)  # Sleep for a minute
Example #24
0
class Watchdog:
    """The watchdog timer (WDT) is used to restart the system when the
    application crashes and ends up into a non recoverable state. After
    enabling, the application must "feed" the watchdog periodically to
    prevent the timeout from expiring and resetting the system.
    
    https://docs.pycom.io/firmwareapi/pycom/machine/wdt/


    """
    def __init__(self, device=None, settings=None):
        self.device = device
        self.settings = settings
        self.wdt = None
        self.suspended = False

        self.enabled = self.settings.get('main.watchdog.enabled', False)
        self.timeout = self.settings.get('main.watchdog.timeout', 10000)

    def start(self):
        """ """

        if not self.enabled:
            log.info('Skipping watchdog timer (WDT)')
            return

        watchdog_timeout = self.timeout
        log.info('Starting the watchdog timer (WDT) with timeout {}ms'.format(
            watchdog_timeout))

        from machine import WDT
        self.wdt = WDT(timeout=watchdog_timeout)

        # Feed Watchdog once.
        self.feed()

    def resume(self):
        """ """
        log.info('Resuming watchdog')
        self.suspended = False
        self.reconfigure_minimum_timeout(self.timeout)

    def suspend(self):
        """Disabling a started watchdog is not possible, so let's
        just configure it to an ultra large timeout value.


        """
        log.info('Suspending watchdog')
        self.suspended = True
        self.reconfigure_minimum_timeout(999999999)

    def feed(self):
        """ """

        if not self.enabled:
            return

        # When in maintenance mode, try to suspend the watchdog.
        #if self.device.status.maintenance and not self.suspended:
        #    self.stop()

        # Always reconfigure to regular timeout when not in maintenance mode.
        #else:
        #    self.suspended = False
        #    self.wdt.init(self.timeout)

        # Feed the watchdog.
        log.debug('Feeding Watchdog')
        self.wdt.feed()

    def reconfigure_minimum_timeout(self, timeout):
        """

        :param timeout: 

        """
        if not self.enabled:
            return
        if timeout >= self.timeout:
            log.info(
                'Reconfiguring watchdog timeout to {} milliseconds'.format(
                    timeout))
            self.wdt.init(timeout)

    def adjust_for_interval(self, interval):
        """

        :param interval: 

        """
        if self.enabled and not self.suspended:
            watchdog_timeout = self.timeout / 1000.0
            if watchdog_timeout - 2 < interval:
                watchdog_timeout_effective = int((interval + 20) * 1000)
                log.warning(
                    'Reconfiguring original watchdog timeout {} as it is '
                    'smaller or near the configured sleep time {}'.format(
                        watchdog_timeout, interval))
                self.reconfigure_minimum_timeout(watchdog_timeout_effective)
Example #25
0
def Watchdog():  # 2秒钟内调用喂狗函数,否则系统复位
    global wdt  # 声明全部变量
    if wdt is None:
        wdt = WDT(2)  # 启动看门狗,间隔时长 单位 秒
    wdt.feed()  # 喂狗
Example #26
0
#
# Copyright (c) 2006-2019, RT-Thread Development Team
#
# SPDX-License-Identifier: MIT License
#
# Change Logs:
# Date           Author       Notes
# 2019-06-29     ChenYong     first version
#

from machine import WDT

wdt = WDT(10)  # Create an WDT device object, set the timeout to 10 seconds
wdt.feed(
)  # Perform the "feed dog" operation to clear the watchdog device count during the timout period
# If not executed, the system will restart after the timeout
print("reset system after 10 seconds")
Example #27
0
# available at https://www.pycom.io/opensource/licensing
#
""" LoPy LoRaWAN Nano Gateway example usage """

import config
import time
from nanogateway import NanoGateway
from machine import WDT

if __name__ == '__main__':
    nanogw = NanoGateway(id=config.GATEWAY_ID,
                         frequency=config.LORA_FREQUENCY,
                         datarate=config.LORA_GW_DR,
                         ssid=config.WIFI_SSID,
                         password=config.WIFI_PASS,
                         server=config.SERVER,
                         port=config.PORT,
                         ntp_server=config.NTP,
                         ntp_period=config.NTP_PERIOD_S)

    nanogw.start()
    nanogw._log('You may now press ENTER to enter the REPL')

    wdt = WDT(timeout=15000)

    while True:
        #print("feeding wdt")
        wdt.feed()
        time.sleep(5)
        #input()
Example #28
0
                    j+=1
                if n>=nombre_point:                     print ('beaucoup d\'erreurs capteur n°', i,  end="")
                if j:                                                 lecture_capteur[i]=moyenne/j
                poids_en_gr=((lecture_capteur[i]-tare[i])/mesure[i]*etalon[i])
                print(" n°", i, poids_en_gr,"  ", lecture_capteur[i],  end="" )
                poids_en_gr_total=poids_en_gr+poids_en_gr_total
                trame+=delimiteur+str(lecture_capteur[i])
                i +=1
            numero_trame+=1 
            t=temperatureLopy(GAIN_local,OFFSET_local)                     #mesure de la température du TX***************************************************************************    
            timest = time.localtime()                                                      #on met un timestamp sur la trame
            trame=str(timest)+delimiteur+str(numero_trame)+delimiteur+str(t)+trame+delimiteur+"\n"
            flashWriteData(trame)
            print("poids_en_gr_total", poids_en_gr_total, " Température RX: ", t,  " n° trame: ", numero_trame, '****', trame)
        time.sleep(delai_local)       
        wdt.feed() # feeds  watchgdog



if configuration== 2               : # ON VA CONFIGURER LE TX il y a x capteurs sur le RX; il y a y capteurs sur le TX; 
#trame=label+delimiteur+str(numero_trame)+delimiteur+str(t)+delimiteur+w+{delimiteur+str(lecture_capteur[i])}*nb_capteurs+delimiteur+"\n"        
    lora = LoRa(mode=LoRa.LORA, frequency=c.LORA_FREQUENCY)
    s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
    s.setblocking(False)
    nombre_capteurs=c.nombre_capteurs      #nombre de capteurs sur la balance TX    
    premier_capteur  =c.premier_capteur       #premier_capteur  sur la balance TX
 
    while True:
        alimCapteurs(1)                                         #on alimente les HX711
        if debug:
            pycom.rgbled(c.bleu_pale)             
Example #29
0
class TerkinDevice:
    def __init__(self, name=None, version=None, settings=None):

        self.name = name
        self.version = version
        self.settings = settings

        # Conditionally enable terminal on UART0. Default: False.
        self.terminal = Terminal(self.settings)
        self.terminal.start()

        self.device_id = get_device_id()

        self.networking = None
        self.telemetry = None

        self.wdt = None
        self.rtc = None

        self.status = DeviceStatus()

    @property
    def appname(self):
        return '{} {}'.format(self.name, self.version)

    def start_networking(self):
        log.info('Starting networking')

        from terkin.network import NetworkManager, WiFiException

        self.networking = NetworkManager(device=self, settings=self.settings)

        # Start WiFi.
        try:
            self.networking.start_wifi()

            # Wait for network interface to come up.
            self.networking.wait_for_nic()

            self.status.networking = True

        except WiFiException:
            log.error('Network connectivity not available, WiFi failed')
            self.status.networking = False

        # Start UDP server for pulling device into maintenance mode.
        self.networking.start_modeserver()

        # Initialize LoRa device.
        if self.settings.get('networking.lora.antenna_attached'):
            try:
                self.networking.start_lora()
            except:
                log.exception('Unable to start LoRa subsystem')
        else:
            log.info(
                "[LoRa] Disabling LoRa interface as no antenna has been attached. "
                "ATTENTION: Running LoRa without antenna will wreck your device."
            )

        # Inform about networking status.
        #self.networking.print_status()

    def start_watchdog(self):
        """
        The WDT is used to restart the system when the application crashes and
        ends up into a non recoverable state. After enabling, the application
        must "feed" the watchdog periodically to prevent it from expiring and
        resetting the system.
        """
        # https://docs.pycom.io/firmwareapi/pycom/machine/wdt.html

        if not self.settings.get('main.watchdog.enabled', False):
            log.info('Skipping watchdog timer (WDT)')
            return

        watchdog_timeout = self.settings.get('main.watchdog.timeout', 10000)
        log.info('Starting the watchdog timer (WDT) with timeout {}ms'.format(
            watchdog_timeout))

        from machine import WDT
        self.wdt = WDT(timeout=watchdog_timeout)

        # Feed Watchdog once.
        self.wdt.feed()

    def feed_watchdog(self):
        if self.wdt is not None:
            log.info('Feeding Watchdog')
            self.wdt.feed()

    def start_rtc(self):
        """
        The RTC is used to keep track of the date and time.
        """
        # https://docs.pycom.io/firmwareapi/pycom/machine/rtc.html
        # https://medium.com/@chrismisztur/pycom-uasyncio-installation-94931fc71283
        import time
        from machine import RTC
        self.rtc = RTC()
        # TODO: Use values from configuration settings here.
        self.rtc.ntp_sync("pool.ntp.org", 360)
        while not self.rtc.synced():
            time.sleep_ms(50)
        log.info('RTC: %s', self.rtc.now())

    def run_gc(self):
        """
        Run a garbage collection.
        https://docs.pycom.io/firmwareapi/micropython/gc.html
        """
        import gc
        gc.collect()

    def configure_rgb_led(self):
        """
        https://docs.pycom.io/tutorials/all/rgbled.html
        """
        import pycom

        # Enable or disable heartbeat.
        rgb_led_heartbeat = self.settings.get('main.rgb_led.heartbeat', True)
        pycom.heartbeat(rgb_led_heartbeat)
        pycom.heartbeat_on_boot(rgb_led_heartbeat)

        # Alternative signalling.
        # Todo: Run this in a separate thread in order not to delay execution of main program flow.
        if not rgb_led_heartbeat:
            for _ in range(2):
                pycom.rgbled(0x001100)
                time.sleep(0.15)
                pycom.rgbled(0x000000)
                time.sleep(0.10)

    def power_off_lte_modem(self):
        """
        We don't use LTE yet.

        https://community.hiveeyes.org/t/lte-modem-des-pycom-fipy-komplett-stilllegen/2161
        https://forum.pycom.io/topic/4877/deepsleep-on-batteries/10
        """

        import pycom
        """
        if not pycom.lte_modem_en_on_boot():
            log.info('Skip turning off LTE modem')
            return
        """

        log.info('Turning off LTE modem')
        try:
            from network import LTE

            # Invoking this will cause `LTE.deinit()` to take around 6(!) seconds.
            #log.info('Enabling LTE modem on boot')
            #pycom.lte_modem_en_on_boot(True)

            log.info('Turning off LTE modem on boot')
            pycom.lte_modem_en_on_boot(False)

            log.info('Invoking LTE.deinit()')
            lte = LTE()
            lte.deinit()

        except:
            log.exception('Shutting down LTE modem failed')

    def power_off_bluetooth(self):
        """
        We don't use Bluetooth yet.
        """
        log.info('Turning off Bluetooth')
        try:
            from network import Bluetooth
            bluetooth = Bluetooth()
            bluetooth.deinit()
        except:
            log.exception('Shutting down Bluetooth failed')

    def start_telemetry(self):
        log.info('Starting telemetry')

        self.telemetry = TelemetryManager()

        # Read all designated telemetry targets from configuration settings.
        telemetry_targets = self.settings.get('telemetry.targets')

        # Compute list of all _enabled_ telemetry targets.
        telemetry_candidates = []
        for telemetry_target in telemetry_targets:
            if telemetry_target.get('enabled', False):
                telemetry_candidates.append(telemetry_target)

        # Create adapter objects for each enabled telemetry target.
        for telemetry_target in telemetry_candidates:
            try:
                self.create_telemetry_adapter(telemetry_target)
                self.feed_watchdog()

            except:
                log.exception(
                    'Creating telemetry adapter failed for target: %s',
                    telemetry_target)

    def create_telemetry_adapter(self, telemetry_target):
        # Create adapter object.
        telemetry_adapter = TelemetryAdapter(
            device=self,
            endpoint=telemetry_target['endpoint'],
            address=telemetry_target.get('address'),
            data=telemetry_target.get('data'),
            topology=telemetry_target.get('topology'),
            format=telemetry_target.get('format'),
            content_encoding=telemetry_target.get('encode'),
        )

        # Setup telemetry adapter.
        telemetry_adapter.setup()

        self.telemetry.add_adapter(telemetry_adapter)

    def enable_serial(self):
        # Disable these two lines if you don't want serial access.
        # The Pycom forum tells us that this is already incorporated into
        # more recent firmwares, so this is probably a thing of the past.
        #uart = machine.UART(0, 115200)
        #os.dupterm(uart)
        pass

    def print_bootscreen(self):
        """
        Print bootscreen.

        This contains important details about your device
        and the operating system running on it.
        """

        if not self.settings.get('main.logging.enabled', False):
            return

        # Todo: Maybe refactor to TerkinDatalogger.
        from uio import StringIO
        buffer = StringIO()

        def add(item=''):
            buffer.write(item)
            buffer.write('\n')

        # Program name and version.
        title = '{} {}'.format(self.name, self.version)

        add()
        add('=' * len(title))
        add(title)
        add('=' * len(title))

        # Machine runtime information.
        add('CPU freq     {} MHz'.format(machine.freq() / 1000000))
        add('Device id    {}'.format(self.device_id))
        add()

        # System memory info (in bytes)
        machine.info()
        add()

        # TODO: Python runtime information.
        add('{:8}: {}'.format('Python', sys.version))
        """
        >>> import os; os.uname()
        (sysname='FiPy', nodename='FiPy', release='1.20.0.rc7', version='v1.9.4-2833cf5 on 2019-02-08', machine='FiPy with ESP32', lorawan='1.0.2', sigfox='1.0.1')
        """
        runtime_info = os.uname()
        for key in dir(runtime_info):
            if key == '__class__':
                continue
            value = getattr(runtime_info, key)
            #print('value:', value)
            add('{:8}: {}'.format(key, value))
        add()
        add()

        # Todo: Add program authors, contributors and credits.

        log.info('\n' + buffer.getvalue())

    def power_off(self):
        self.networking.stop()

    def hibernate(self, interval, deepsleep=False):

        #logging.enable_logging()

        if deepsleep:

            # Prepare and invoke deep sleep.
            # https://docs.micropython.org/en/latest/library/machine.html#machine.deepsleep

            log.info('Preparing deep sleep')

            # Set wake up mode.
            self.set_wakeup_mode()

            # Invoke deep sleep.
            log.info('Entering deep sleep for {} seconds'.format(interval))
            self.terminal.stop()
            machine.deepsleep(int(interval * 1000))

        else:

            log.info('Entering light sleep for {} seconds'.format(interval))

            # Invoke light sleep.
            # https://docs.micropython.org/en/latest/library/machine.html#machine.sleep
            # https://docs.micropython.org/en/latest/library/machine.html#machine.lightsleep
            #
            # As "machine.sleep" seems to be a noop on Pycom MicroPython,
            # we will just use the regular "time.sleep" here.
            # machine.sleep(int(interval * 1000))
            time.sleep(interval)

    def resume(self):
        log.info('Reset cause and wakeup reason: %s',
                 MachineResetCause.humanize())

    def set_wakeup_mode(self):

        # Set wake up parameters.
        """
        The arguments are:

        - pins: a list or tuple containing the GPIO to setup for deepsleep wakeup.

        - mode: selects the way the configured GPIOs can wake up the module.
          The possible values are: machine.WAKEUP_ALL_LOW and machine.WAKEUP_ANY_HIGH.

        - enable_pull: if set to True keeps the pull up or pull down resistors enabled
          during deep sleep. If this variable is set to True, then ULP or capacitive touch
          wakeup cannot be used in combination with GPIO wakeup.

        -- https://community.hiveeyes.org/t/deep-sleep-with-fipy-esp32-on-micropython/1792/12

        This will yield a wake up reason like::

            'wakeup_reason': {'code': 1, 'message': 'PIN'}

        """

        # Todo: ``enable_pull`` or not?

        # From documentation.
        # machine.pin_sleep_wakeup(pins=['P8'], mode=machine.WAKEUP_ALL_LOW, enable_pull=True)

        # Let's try.
        #machine.pin_sleep_wakeup(pins=['P8'], mode=machine.WAKEUP_ALL_LOW, enable_pull=False)
        pass
Example #30
0
def go(deviceid, config, wlconfig, loops=25):
    """
    Every single board deployment must have this function accepting these
    exact arguments.  Only way to ensure a non-maddening structure!
    """
    # Set up our last ditch hang preventer
    dogfood = 60000
    wdt = WDT(timeout=dogfood)
    print("Watchdog set for %.2f seconds" % (dogfood / 1000.))

    # Unpack the things
    knownaps = config['knownaps']
    dbconfig = config['dbconfig']
    wlan = wlconfig['wlan']
    wconfig = wlconfig['wconfig']

    # Indicate our WiFi connection status
    ledIndicator = utils.shinyThing(pin=4, inverted=False, startBlink=True)
    if wlan.isconnected() is True:
        ledIndicator.off()
    else:
        utils.blinken(ledIndicator, 0.25, 10)
        ledIndicator.on()

    # Set up the onewire stuff
    dsPin = Pin(21)
    ow = onewire.OneWire(dsPin)
    ds = ds18x20.DS18X20(ow)

    loopCounter = 0
    while loopCounter < loops:
        # Feed the dog. We'll do this a bunch since wifi can be slow
        wdt.feed()
        print("\nFed the dog")
        print("Starting loop %d of %d" % (loopCounter + 1, loops))
        print("Checking WiFi status ...")
        # Attempt to connect to one of the strongest of knownaps
        wlan, wconfig = uwifi.checkWifiStatus(knownaps,
                                              wlan=wlan,
                                              conf=wconfig,
                                              repl=False)

        # Try to store the connection information
        wdt.feed()
        print("Fed the dog")
        sV = utils.postNetConfig(wlan, dbconfig, tagname=deviceid)

        # We only should attempt a measurement if the wifi is good, so
        #   keep this all in the conditional!
        if wlan.isconnected() is True:
            # If the network config dropped out suddenly, sV will be false.
            #   That lets us skip the rest so we can get a WiFi status check
            #   sooner rather than later
            if sV is True:
                wdt.feed()
                print("Fed the dog")
                doDS18x(ds, dbconfig, led=ledIndicator)

        gc.collect()
        # Print some memory statistics so I can watch for problems
        micropython.mem_info()
        print("Sleeping (and feeding the dog) ...\n")
        for sc in range(0, 60):
            if sc % 10 == 0 and sc != 0:
                print("\n")
            else:
                print(".", end='')
            time.sleep(1)
            wdt.feed()

        loopCounter += 1

    # Since we're at the end of our rope here, drop the hammer and reset
    print("Resetting in 5 seconds ...")
    time.sleep(5)
    reset()
Example #31
0
    client.connect()
    client.subscribe(topic_sub)
    print('Connected to %s MQTT broker, subscribed to %s topic' %
          (mqtt_server, topic_sub))
    return client


def restart_and_reconnect():
    print('Failed to connect to MQTT broker. Reconnecting...')
    time.sleep(10)
    machine.reset()


try:
    client = connect_and_subscribe()
except OSError as e:
    restart_and_reconnect()

while True:
    try:
        client.check_msg()

        status = analog.read()
        msg = b'OFF' if status == 1024 else b'ON'
        client.publish(topic_pub, msg)
        time.sleep(1)  #sec
        wdt.feed()  # wathdog
        print(msg)

    except OSError as e:
        restart_and_reconnect()
Example #32
0
            self.blynk.lcd_write(7, 0, 1, config.SERIAL)
            self._send_coins()
            self.time = 0

        c_coins =[self.coins[2].count, self.coins[3].count]
        if self.prev_coins != c_coins:
            self.prev_coins = c_coins
            self.leds.coin_in()
            self._send_coins()

wdt = WDT(timeout=WDT_TIMEOUT)

wlan = WLAN(mode=WLAN.STA)
connect_to_wlan(wlan) # the WDT will reset if this takes more than 15s

wdt.feed()

# set the current time (mandatory to validate certificates)
RTC(datetime=(2015, 12, 12, 11, 30, 0, 0, None))

# initialize Blynk with SSL enabled
blynk = BlynkLib.Blynk(BLYNK_AUTH, wdt=False, ssl=True)

# register the main task
s_task = MainTask(blynk, wdt, MAIN_TASK_PERIOD, COIN_INPUTS[config.COIN_10_CENT],
                                                COIN_INPUTS[config.COIN_20_CENT],
                                                COIN_INPUTS[config.COIN_50_CENT],
                                                COIN_INPUTS[config.COIN_1_EUR],
                                                COIN_INPUTS[config.COIN_2_EUR],
                                                COIN_INPUTS[config.EUR_TOTAL],
                                                COIN_INPUTS[config.ALARM])