示例#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)
示例#2
0
def setupWifi(requireAp=True, requireSta=False):
    global ap
    global sta

    try:
        with open('wificonfig.json') as jsonFile:
            cfg = json.load(jsonFile)
        attemptSetup(cfg)
    except Exception as err:
        print("Problem with WIFI configuration", err)

    if (requireAp and (ap == None)) or (requireSta and (sta == None)):
        if (ap == None) and (sta == None):
            print("Neither WIFI AP or Station mode configured using defaults")
            cfg = {}
            attemptSetup(cfg)
        import os
        from machine import WDT
        # Give 5 minutes to configure WIFI before resetting and trying again
        # (handles case where access point happened to be down when this
        # system came up)
        WDT(timeout=300000)
        # No os.path in upython
        if "wificonfigserver.py" in os.listdir():
            from wificonfigserver import runServer
            runServer()
        else:
            # Make an attempt to start up webrepl for
            # file transfer
            import webrepl
            webrepl.start()
示例#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()
示例#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)
示例#5
0
    async def wdt(self):
        from machine import WDT

        wdt = WDT()
        while True:
            wdt.feed()
            await sleep_ms(WDT_DELAY)
def wdt():
    from machine import WDT
    from time import sleep
    wdt = WDT(timeout=10000)  #10 seconds of hanging
    while True:
        wdt.feed()
        sleep(1)
示例#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)
 def __initialise_watchdog(self):
     if self.__conf.get('connection_watchdog', True):
         self.__wifi_lte_watchdog = WDT(
             timeout=constants.__WDT_TIMEOUT_MILLISECONDS
         )
         print('Initialized watchdog for WiFi and LTE connection with timeout {} ms'.format(constants.__WDT_TIMEOUT_MILLISECONDS)) # noqa
     else:
         print('Watchdog for WiFi and LTE was disabled, enable with "connection_watchdog": true in pybytes_config.json') # noqa
    def disconnect(self, keep_wifi=False, force=False):

        if self.__wifi_lte_watchdog is not None:
            self.__wifi_lte_watchdog = WDT(timeout=constants.__WDT_MAX_TIMEOUT_MILLISECONDS)
            print('Watchdog timeout has been increased to {} ms'.format(constants.__WDT_MAX_TIMEOUT_MILLISECONDS)) # noqa

        print_debug(
            1,
            'self.__connection_status={} | self.__network_type={}'.format(
                self.__connection_status, self.__network_type
            )
        )

        if (self.__connection_status == constants.__CONNECTION_STATUS_DISCONNECTED): # noqa
            print_debug(3, "Already disconnected")

        if (constants.__CONNECTION_STATUS_CONNECTED_MQTT_WIFI <= self.__connection_status <= constants.__CONNECTION_STATUS_CONNECTED_MQTT_LTE): # noqa
            print_debug(1, 'MQTT over WIFI||LTE... disconnecting MQTT')
            try:
                self.__connection.disconnect(force=force)
                self.__connection_status = constants.__CONNECTION_STATUS_DISCONNECTED # noqa
            except Exception as e:
                print("Error disconnecting: {}".format(e))

        if (self.__connection_status == constants.__CONNECTION_STATUS_CONNECTED_LORA): # noqa
            print_debug(1, 'Connected over LORA... closing socket and saving nvram') # noqa
            try:
                self.__lora_socket.close()
                self.lora.nvram_save()
            except Exception as e:
                print("Error disconnecting: {}".format(e))

        if (self.__connection_status == constants.__CONNECTION_STATUS_CONNECTED_SIGFOX): # noqa
            print_debug(1, 'Connected over SIGFOX... closing socket')
            try:
                self.__sigfox_socket.close()
            except Exception as e:
                print("Error disconnecting: {}".format(e))

        if (self.__network_type == constants.__NETWORK_TYPE_WIFI and not keep_wifi):
            print_debug(1, 'Connected over WIFI... disconnecting')
            try:
                self.wlan.deinit()
            except Exception as e:
                print("Error disconnecting: {}".format(e))

        if (self.__network_type == constants.__NETWORK_TYPE_LTE):
            print_debug(1, 'Connected over LTE... disconnecting')
            try:
                lte_cfg = self.__conf.get('lte')
                print_debug(1, 'lte.deinit(reset={})'.format(lte_cfg.get('reset', False))) # noqa
                self.lte.deinit(reset=lte_cfg.get('reset', False))
            except Exception as e:
                print("Error disconnecting: {}".format(e))

        self.__network_type = None
        self.__connection_status = constants.__CONNECTION_STATUS_DISCONNECTED
示例#10
0
 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 reconfigure_watchdog(self, timeout_seconds=600):
     try:
         from machine import WDT
         watchdog_timeout = timeout_seconds
         watchdog_timeout_effective = watchdog_timeout * 1000
         wdt = WDT(timeout=watchdog_timeout_effective)
         wdt.init(watchdog_timeout_effective)
         print('INFO:  Reconfigured watchdog to {} seconds'.format(watchdog_timeout))
     except:
         pass
示例#12
0
def init_wdt():
    global timer0, wdt
    wdt = WDT(30)

    period = 5000
    system_log.info(
        "Feeding dog service is running per {} millseconds".format(period))

    timer0 = Timer(Timer.Timer0)
    timer0.start(period=period, mode=timer0.PERIODIC, callback=feed_dog)
示例#13
0
def start(wdt=None):
    freq(80000000)
    #	timer = Timer(2)
    print("iniciando...")
    print(wake_reason())
    if wdt is None:
        wdt = WDT(timeout=240000)
    # Inicializa habilitación de los sensores de material particulado.
    hpma_pin = Pin(16, Pin.OUT)  #Se?al de activaci?n de transistor
    pms_pin = Pin(4, Pin.OUT)  #Se?al de activaci?n de transistor
    #	hpma_pin.value(0)
    #	pms_pin.value(0)

    # Configura buses de comunicación.
    uart = UART(2, baudrate=115200, rx=32, tx=17, timeout=1000)
    uart2 = UART(1, baudrate=9600, rx=33, tx=2, timeout=1000)
    i2c = I2C(sda=Pin(21, Pin.PULL_UP), scl=Pin(22, Pin.PULL_UP), freq=20000)
    spi = SPI(sck=Pin(14), mosi=Pin(13), miso=Pin(15))
    cs = Pin(5, Pin.OUT)

    # Inicia logger. Interfaz para SD.
    logger = Logger(spi=spi, cs=cs)
    logger.success("Estacion inicializada")
    # Sincroniza NTP
    _time.setntp(logger=logger)

    #Crea publicadores
    publishers = []
    for pub in config.publishers(logger):
        publishers.append(
            Publisher(host=pub["host"],
                      token=pub["token"],
                      port=pub["port"],
                      format_=pub["format"],
                      logger=logger,
                      wdt=wdt))
    attr = config.attributes()
    attr["version"] = VERSIONSW
    atrpub = dumps(attr)
    #	print("iniciando timer")
    #	timer.init(period=540000, mode=Timer.PERIODIC, callback=lambda t:readandpublish(None,uart, uart2, i2c, spi, logger, hpma_pin, pms_pin, publishers, atrpub))
    #	print("timer iniciado")
    readandpublish(None, uart, uart2, i2c, spi, logger, hpma_pin, pms_pin,
                   publishers, atrpub)
    # Vuelve a intentar insertar las telemetrias pendientes desde la bd
    freq(240000000)
    for pub in publishers:
        pub.dbPublish(atrpub, uart, uart2, i2c, spi, logger, hpma_pin, pms_pin,
                      publishers)
    logger.success("Ciclo de funcionamiento exitoso")
    logger.close()
    #	state = disable_irq()
    #	timer.deinit()
    return
示例#14
0
    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 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()
示例#16
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)
示例#17
0
def setup():
    global wdt, sd, logger, AP, pin_relay_AP, pin_relay_LED, pin_switch_setupMode, pin_switch_RPi, wdt

    # Logger
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)

    logger.info('===========================')
    logger.info(' Starting CTLR ')
    logger.info('===========================')

    # HW Setup
    wdt = WDT(timeout=20 * 60 * 100)
    sd = SD()
    os.mount(sd, '/sd')

    pin_relay_AP = Pin('P20', mode=Pin.OUT, pull=Pin.PULL_DOWN)
    pin_relay_LED = Pin('P19', mode=Pin.OUT, pull=Pin.PULL_DOWN)
    pin_switch_setupMode = Pin('P9', mode=Pin.IN, pull=Pin.PULL_DOWN)
    pin_switch_RPi = Pin('P7', mode=Pin.OUT, pull=Pin.PULL_DOWN)

    # Network Setup
    # CHANGE AP IN pybytes_config.json!
    pbconfig = pybytes.get_config()
    AP = pbconfig['wifi']['ssid']

    # WIFI Connection
    if AP == 'RUT230_7714':
        pin_relay_AP.value(1)
        wlan = WLAN(mode=WLAN.STA)
        while not wlan.isconnected():
            nets = wlan.scan()
            for net in nets:
                if net.ssid == 'RUT230_7714':
                    pybytes.connect_wifi()
        # # No Internet Case
        # wlan.ifconfig(config=('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8'))
        # wlan.connect('RUT230_7714', auth=(WLAN.WPA2, 'Ei09UrDg'), timeout=5000)
        # while not wlan.isconnected():
        #     machine.idle() # save power while waiting

    socket_svr.setup()
    # _thread.stack_size(16384)
    _thread.start_new_thread(socket_svr.accept_thread, ())

    # UPDATE TIME BY GPS
    logger.info('GPS time fixing start...')
    shmGPSclock.update_RTC_from_GPS()
    socket_svr.var_lock.acquire()
    socket_svr.state = 1
    socket_svr.var_lock.release()
    logger.info('GPS time fixing done...')
    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()
示例#19
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
示例#20
0
    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)
示例#21
0
    def __init__(self):
        self.wdt = WDT()
        self.adc = ADC(0)
        self.auto_tim = Timer(1)
        self.publish_tim = Timer(2)
        self.ping_fail = 0
        self.ping_mqtt = 0
        self.light_state = 0
        self.light_intensity = 0
        self.sensor_interrupt = 0
        self.button_interrupt = 0
        self.current_color = [255, 255, 255]
        self.auto_human = config.AUTO_HUMAN
        self.auto_sound = config.AUTO_SOUND
        self.auto_light = config.AUTO_LIGHT
        self.light_status = {
            "state": "OFF",
            "brightness": 100,
            "color": {
                "r": 255,
                "g": 255,
                "b": 255
            },
            "effetc": ""
        }

        self.np = NeoPixel(Pin(config.WS2812_PIN, Pin.OUT), config.WS2812_BIT)

        self.mqtt_client = MQTTClient(client_id=config.DEVICE_NAME,
                                      server=config.MQTT_SERVER,
                                      port=config.MQTT_PORT,
                                      user=config.MQTT_USER,
                                      password=config.MQTT_PASSWD,
                                      keepalive=60)
        self.mqtt_client.set_callback(self.sub_callback)
        self.mqtt_client.set_last_will(config.AVAILABILITY_TOPIC, "offline")

        self.human_sensor_1 = Pin(config.HUMAN_SENSOR_PIN_1, Pin.IN,
                                  Pin.PULL_UP)
        self.human_sensor_2 = Pin(config.HUMAN_SENSOR_PIN_2, Pin.IN,
                                  Pin.PULL_UP)
        self.human_sensor_3 = Pin(config.HUMAN_SENSOR_PIN_3, Pin.IN,
                                  Pin.PULL_UP)
        self.sound_sensor = Pin(config.SOUND_SENSOR_PIN, Pin.IN, Pin.PULL_UP)
        self.button = Pin(config.BUTTON_PIN, Pin.IN, Pin.PULL_UP)
示例#22
0
    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()
示例#23
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
示例#24
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)
示例#25
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)
示例#26
0
    def __init__(self):
        a = 0
        while a <= 10:
            a = a + 1
            print("REINICIO\n")

        self.timer = Timer(0)
        self.timer.init(period=1200000,
                        mode=Timer.PERIODIC,
                        callback=handleInterrupt)  #Reset cada 20 mins
        self.wdt = WDT(
            timeout=100000
        )  #Watchdog configurado para que si no se alimenta en 100 seg realimente
        self.p13 = Pin(13, Pin.IN)  #Pin para interrumpir el main

        self.mac = ubinascii.hexlify(network.WLAN().config('mac'),
                                     ':').decode()
        print("Esto es la mac:", self.mac)

        # Scan for 10s (at 100% duty cycle)
        self.bt = BLE()

        self.lista_id = []
        self.lista_rssi = []
示例#27
0
    def start(self):
        WDT(True)
        self.ntp_sync()
        if self.deepsleep():
            loop = uasyncio.get_event_loop()
            for module_type in self.modules:
                if module_type == 'rtc':
                    loop.run_until_complete(
                        self.modules['rtc'].adjust_time(once=True))
                    machine.resetWDT()
                elif module_type == 'climate':
                    loop.run_until_complete(
                        self.modules['climate'].read(once=True))
                    machine.resetWDT()
                    if self.online():
                        loop.run_until_complete(
                            self.post_sensor_data(once=True))
                        machine.resetWDT()
                    if self.modules['climate'].light:
                        loop.run_until_complete(
                            self.modules['climate'].adjust_light(once=True))
                        machine.resetWDT()
                if self.online():
                    if self.id.get('updates'):
                        loop.run_until_complete(self.check_updates(once=True))
                        machine.resetWDT()
                    if not self.id.get('disable_software_updates'):
                        loop.run_until_complete(
                            self.task_check_software_updates(once=True))
                        machine.resetWDT()
                if self.deepsleep():
                    if self._network:
                        self._network.off()
                    machine.deepsleep(self.deepsleep() * 60000)

        self.start_async()
示例#28
0
import time
import machine
from umqttsimple import MQTTClient
from machine import ADC
from machine import Pin
from machine import WDT

wdt = WDT()  # enable it with a timeout of 2s
analog = ADC(0)  # create ADC object on ADC pin
GPIO5_D1 = Pin(5, Pin.OUT)
GPIO5_D1.on()

mqtt_server = 'mqtt.by'
mqtt_port = 1883
mqtt_user = '******'
mqtt_password = '******'
client_id = 'wifiRelay'
topic_prefix = b'/user/valik/'
topic_sub = topic_prefix + b'krd/zal/clickRelay'
topic_pub = topic_prefix + b'krd/zal/status'

# Complete project details at https://RandomNerdTutorials.com


def sub_cb(topic, msg):
    print((topic, msg))
    if topic == topic_sub:
        if msg == b'0':
            if status != 1024:
                print('forced turn off')
                GPIO5_D1.off()
示例#29
0
"""
Reset script for the cc3200 boards
This is needed to force the board to reboot
with the default WLAN AP settings
"""

from machine import WDT
import time
import os

mch = os.uname().machine
if not "LaunchPad" in mch and not "WiPy" in mch:
    raise Exception("Board not supported!")

wdt = WDT(timeout=1000)
print(wdt)
time.sleep_ms(900)
示例#30
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()