Пример #1
0
 def oflush(self, n=255):
     t = 5000
     while t:
         self.i2c.readfrom_into(self.i2c_addr + 1, self.buf1)
         r = self.buf1[0]
         if r >= n:
             return
         t -= 1
         machine.idle()
     raise OSError(uerrno.ETIMEDOUT)
Пример #2
0
def connect_to_wlan(wlan):
    # try connecting to wifi until succeeding
    while True:
        try:
            wlan.connect(WIFI_SSID, auth=WIFI_AUTH, timeout=7500)
            while not wlan.isconnected():
                machine.idle()
            return
        except OSError:
            pass
Пример #3
0
def connect_wifi(cfg=None):
    if not cfg:
        from config import Config
        cfg = Config.load(debug=True)

    from network import WLAN
    import machine

    print('Starting WLAN, attempting to connect to ' + cfg.wifi_ssid)
    wlan = WLAN(0, WLAN.STA)
    wlan.ifconfig(config='dhcp')
    wlan.connect(ssid=cfg.wifi_ssid, auth=(WLAN.WPA2, cfg.wifi_key))
    while not wlan.isconnected():
        machine.idle()
    print('Connected')
Пример #4
0
    def send_command(self, ins, p1, p2, data=None, expected=None):

        # These command variables are always sent
        cmd = struct.pack('3B', ins, p1, p2)

        # Looks like data is only sent with the length (Lc)
        if data:
            assert len(data) <= 251 # Thus speaks the datasheet
            cmd += struct.pack('B', len(data))
            cmd += data

        # Expected data is either not present at all, 0 for null-terminated, or a number for fixed
        if expected is not None:
            cmd += struct.pack('B', expected)

        if self.debug:
            print("Sending: " + hexlify(cmd).decode())

        self.spi.write(cmd)

        # Wait for a little while
        time.sleep_us(15) # This should take at most 14.5us
        while self.tc_busy_bar() == 0:
            machine.idle()

        # Request a response
        if expected is not None:
            if expected > 0:
                result_bytes = self.spi.read(2 + expected)
            else:
                result_bytes = self.spi.read(EPD.MAX_READ)
                strlen = result_bytes.find(b'\x00')
                result_bytes = result_bytes[:strlen] + result_bytes[strlen+1:strlen+3]
        else:
            result_bytes = self.spi.read(2)

        if self.debug:
            print("Received: " + hexlify(result_bytes).decode())

        (result,) = struct.unpack_from('>H', result_bytes[-2:])

        if result != EPD.SW_NORMAL_PROCESSING:
            raise ValueError("Bad result code: 0x%x" % result)

        return result_bytes[:-2]
Пример #5
0
    def read(self):
        # wait for the device being ready
        while self.pOUT() == 1:
            idle()

        # shift in data, and gain & channel info
        result = 0
        for j in range(24 + self.GAIN):
            state = disable_irq()
            self.pSCK(True)
            self.pSCK(False)
            enable_irq(state)
            result = (result << 1) | self.pOUT()

        # shift back the extra bits
        result >>= self.GAIN

        # check sign
        if result > 0x7fffff:
            result -= 0x1000000

        return result
Пример #6
0
    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])
Пример #7
0
import machine
from network import WLAN
wlan = WLAN() # get current object, without changing the mode

if machine.reset_cause() != machine.SOFT_RESET:
    wlan.init(mode=WLAN.STA)
    # configuration below MUST match your home router settings!!
    wlan.ifconfig(config=('192.168.178.107', '255.255.255.0', '192.168.178.1', '8.8.8.8'))

if not wlan.isconnected():
    # change the line below to match your network ssid, security and password
    wlan.connect('mywifi', auth=(WLAN.WPA2, 'mywifikey'), timeout=5000)
    while not wlan.isconnected():
        machine.idle() # save power while waiting
Пример #8
0
def flash_wait_not_busy():
    while stm.mem32[stm.FLASH + stm.FLASH_SR] & 1 << 16:
        machine.idle()
Пример #9
0
bt.deinit()

print('Switching off LoRa')
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868, power_mode=LoRa.SLEEP)

if (uos.uname().sysname == 'FiPy'):

     # print('Switching off LTE')
     # lte = network.LTE()
     # quit = False
     # while quit == False:
     #     try:
     #         lte.deinit()
     #     except uosError:
     #         print('  Exception occured, retrying...')
     #         pass
     #     else:
     #         quit = True

     print('Switching off Sigfox')
     sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ1)

print('Switching off RGB Led')
pycom.rgbled(0x000000)

print('===============================================================================')

print('Now entering idle mode... ')
while True:
    machine.idle()# Nothing
Пример #10
0
####################################
Пример #11
0
def wait_connection():
    sta_if = network.WLAN(network.STA_IF)
    while not sta_if.isconnected():
        machine.idle()
Пример #12
0
 def enable(self):
     self.tc_en_bar.value(0) # Power up
     time.sleep_ms(5)
     while self.tc_busy_bar() == 0:
         machine.idle() # will it wake up here?
Пример #13
0
def runLoop():
    motor_H.off()
    motor_V.off()
    while True:
        blynk.run()
        machine.idle()
Пример #14
0
    def connect_station(self, network):

        network_name = network['ssid']

        log.info('WiFi STA: Prepare connecting to network "{}"'.format(
            network_name))

        auth_mode = self.get_auth_mode(network_name)

        log.info(
            'WiFi STA: Attempt connecting to network "{}" with auth mode "{}"'.
            format(network_name, auth_mode))

        password = network['password']

        # TODO: Optionally, configure hostname.
        # https://docs.micropython.org/en/latest/library/network.WLAN.html
        # https://github.com/pycom/pycom-micropython-sigfox/pull/165
        # https://forum.pycom.io/topic/3326/new-firmware-release-v1-18-0
        if 'dhcp_hostname' in network:
            if hasattr(self.station, 'config'):
                log.ingo('WiFi STA: Using dhcp_hostname "{}"'.format(
                    network['dhcp_hostname']))
                self.station.config(dhcp_hostname=network['dhcp_hostname'])
            else:
                log.error('Could not set hostname on older MicroPython')

        # Optionally, configure static IP address.
        if 'ifconfig' in network:
            log.info(
                'WiFi STA: Using static network configuration "{}"'.format(
                    network_name))
            self.station.ifconfig(config=network['ifconfig'])

        # Obtain timeout value.
        network_timeout = network.get('timeout', 15.0)

        # Set interval how often to poll for WiFi connectivity.
        network_poll_interval = 800

        # Connect to WiFi station.
        log.info(
            'WiFi STA: Starting connection to "{}" with timeout of {} seconds'.
            format(network_name, network_timeout))
        self.station.connect(network_name, (auth_mode, password),
                             timeout=int(network_timeout * 1000))

        # Wait for station network to arrive.
        # ``isconnected()`` returns True when connected to a WiFi access point *and* having a valid IP address.
        retries = int(network_timeout * network_poll_interval)
        while not self.station.isconnected() and retries > 0:

            log.info(
                'WiFi STA: Waiting for network "{}".'.format(network_name))
            retries -= 1

            # Save power while waiting.
            machine.idle()

            # Feed watchdog.
            self.manager.device.feed_watchdog()

            # Don't busy-wait.
            time.sleep_ms(network_poll_interval)

        if not self.station.isconnected():
            raise WiFiException(
                'WiFi STA: Unable to connect to "{}"'.format(network_name))

        # Inform about networking status.
        self.print_short_status()
        self.print_address_status()

        return True
    def start_real(self):
        """
        https://docs.pycom.io/tutorials/all/wlan.html
        https://github.com/pycom/pydocs/blob/master/firmwareapi/pycom/network/wlan.md
        """

        #if machine.reset_cause() == machine.SOFT_RESET:
        #   print("WiFi STA: Network connection after SOFT_RESET.")
        #    self.print_short_status()
        #    # Inform about networking status.
        #    self.print_address_status()
        #    return True

        # Save the default ssid and auth for restoring AP mode later
        #original_ssid = self.station.ssid()
        #original_auth = self.station.auth()

        # Inform about networking status.
        self.print_address_status()

        # Setup network interface.
        log.info("WiFi STA+AP: Starting interface")
        self.station.mode(WLAN.STA_AP)
        self.station.init()

        # Check WiFi connectivity.
        if self.is_connected():

            log.info(
                "WiFi STA: Network connection already established, will skip scanning and resume connectivity."
            )
            self.print_short_status()

            # Give system some breath.
            time.sleep(0.25)

            # Inform about networking status.
            self.print_short_status()
            self.print_address_status()

            return True

        # Prepare information about known WiFi networks.
        networks_known = frozenset(
            [station['ssid'] for station in self.stations])

        # Attempt to connect to known/configured networks.
        attempt = 0
        while True:

            delay = 1

            if self.is_connected():
                attempt = 0

            else:
                log.info(
                    "WiFi STA: Connecting to configured networks: %s. Attempt: #%s",
                    list(networks_known), attempt + 1)
                try:
                    self.connect_stations(networks_known)

                except:
                    log.exception(
                        'WiFi STA: Connecting to configured networks "{}" failed'
                        .format(list(networks_known)))
                    delay = backoff_time(attempt, minimum=1, maximum=600)
                    log.info('WiFi STA: Retrying in {} seconds'.format(delay))

                attempt += 1

            machine.idle()
            time.sleep(delay)

        # Todo: Reenable WiFi AP mode in the context of an "initial configuration" mode.
        """
Пример #16
0
def runLoop():
    while True:
        blynk.run()
        machine.idle()
Пример #17
0
def wait_for_event(event, timeout_ms):
    t0 = time.ticks_ms()
    while last_event != event and time.ticks_diff(time.ticks_ms(), t0) < timeout_ms:
        machine.idle()
Пример #18
0
def start_transmissions(_pkts):
    global lora
    global index
    global lora_sock
    global active_tx
    global active_rx
    global chrono
    global my_slot
    global proc_gw
    global AppSKey
    global succeeded
    global retrans
    global dropped
    global join_start
    global guard
    global sack_rcv
    global msg
    global sack_bytes
    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))
    proc_and_switch = 12000 # time for preparing the packet and switch radio mode (us)
    if (int(MY_ID) == 22 or int(MY_ID) == 34): # fipy nodes switch faster
        proc_and_switch = 10000
    chrono.reset()
    if (my_slot == -1):
        join_start = chrono.read_us()
        join_request(my_sf)
    else:
        sync()
    repeats = 0
    clock_correct = 0
    sync_slot = int(airtime_calc(my_sf,1,sack_bytes+2,my_bw_plain)*1000+guard+proc_gw)
    clocks = [sync_slot]
    print("-----")
    print("MY SLOT:", my_slot)
    print("Net size:", index)
    print("Time on air (ms):", airt/1000)
    print("Guard time (ms):", guard/1000)
    print("Duty cycle slots:", duty_cycle_limit_slots)
    print("SACK slot length (ms):", sync_slot/1000)
    print("Gw processing time (ms):", int(proc_gw/1000))
    print("Time after SACK rec (ms):", (chrono.read_us()-sack_rcv)/1000)
    # send data
    i = 1
    (succeeded, retrans, dropped, active_rx, active_tx) = (0, 0, 0, 0.0, 0.0)
    print("S T A R T")
    while(i <= _pkts): # stop after pkts # of packets
        print(i, "----------------------------------------------------")
        chrono.reset()
        start = chrono.read_us()
        pycom.rgbled(green)
        print("starting a new round at (ms):", start/1000)
        # calculate the time until the sack packet
        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))
        round_length += proc_gw # gw proc+switch time (us)
        t = int(my_slot*(airt + 2*guard) + guard - proc_and_switch) # sleep time before transmission
        print("sleep time (ms):", t/1000)
        pycom.rgbled(off)
        time.sleep_us(t)
        _thread.start_new_thread(generate_msg, ())
        pycom.rgbled(red)
        on_time = chrono.read_us()
        lora.init(mode=LoRa.LORA, tx_iq=True, region=LoRa.EU868, frequency=freqs[my_sf-5], power_mode=LoRa.TX_ONLY, bandwidth=my_bw, sf=my_sf, tx_power=14)
        pkg = struct.pack(_LORA_PKG_FORMAT % len(msg), MY_ID, len(msg), msg)
        print("Sending packet of", len(pkg), "bytes at (ms):", (chrono.read_us()-start)/1000)
        lora_sock.send(pkg)
        # print(lora.stats())
        pycom.rgbled(off)
        lora.power_mode(LoRa.SLEEP)
        active_tx += (chrono.read_us() - on_time)
        t = int(round_length - (chrono.read_us() - start) - clock_correct)
        if t < 0:
            t = 0
            print("cannot align clock!")
        print("sleep time after data (s):", t/1e6, "/ clock correction (ms):", clock_correct/1000)
        machine.idle()
        time.sleep_us(t)
        sync_start = chrono.read_us()
        if (i % sync_rate == 0): # SACK
            rec = 0
            sack_rcv = 0
            acks = ""
            lora_sock.setblocking(False)
            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)
            print("started sync slot at (ms):", (sync_start)/1000)
            pycom.rgbled(white)
            while (rec == 0) and ((chrono.read_us() - sync_start) < sync_slot):
                machine.idle()
                sack_rcv = chrono.read_us()
                recv_pkg = lora_sock.recv(30)
                if (len(recv_pkg) > 2):
                    recv_pkg_len = recv_pkg[1]
                    recv_pkg_id = recv_pkg[0]
                    if (int(recv_pkg_id) == (my_sf-5)):
                        sack_rcv = chrono.read_us()
                        dev_id, leng, s_msg = struct.unpack(_LORA_RCV_PKG_FORMAT % recv_pkg_len, recv_pkg)
                        s_msg = str(s_msg)[2:]
                        s_msg = s_msg[:-1]
                        (index, proc_gw, acks) = s_msg.split(":")
                        (index, proc_gw) = (int(index), int(proc_gw)*1000)
                        print("SACK received!", s_msg)
                        print(lora.stats())
                        lora.power_mode(LoRa.SLEEP)
                        active_rx += (chrono.read_us() - sync_start)
                        clock_correct = 0
                        if (acks != ""):
                            acks = zfill(bin(int(acks, 16))[2:], index)
                            if (acks[my_slot] == "1"):
                                print("ACK!")
                                succeeded += 1
                                repeats = 0
                            else:
                                print("I will repeat the last packet")
                                retrans += 1
                                repeats += 1
                                i -= 1
                                if (repeats == 4):
                                    print("Packet dropped!")
                                    repeats = 0
                                    dropped += 1
                                    retrans -= 1
                                    i += 1
                        machine.idle()
                        rec = 1
                        ack_lasted = (chrono.read_us()-sync_start)
                        if (ack_lasted > sync_slot + guard): # this is a hardware bug
                            print("The clock went for a walk...", (ack_lasted-sync_slot)/1000, "ms of misalignment!")
                            time.sleep_us(round_length-100000) # sorry, we'll miss one round
                            sync()
                            clock_correct = -1
                        elif (ack_lasted < sync_slot/3): # normally this should't happen
                            print("warning! very short SACK length (ms):", (chrono.read_us()-sync_start)/1000)
                            time.sleep_us(sync_slot - int(chrono.read_us()-sync_start) + 0) # this must be tuned on
                        else: # adaptive SACK slot length
                            if (i == 1): # what if the first packet is dropped. I have to fix this
                                clocks = [ack_lasted]
                            else:
                                clocks.append(ack_lasted)
                                sync_slot = 0
                                for j in clocks:
                                    sync_slot += j
                                sync_slot = int(sync_slot/len(clocks))
                                if (len(clocks) == 10):
                                    clocks = [sync_slot]
                            print("new sync slot length (ms):", sync_slot/1000)
            if (rec == 0):
                lora.power_mode(LoRa.SLEEP)
                active_rx += (chrono.read_us() - sync_start)
                print("I will repeat the last packet")
                retrans += 1
                repeats += 1
                i -= 1
                if (repeats == 4):
                    print("Packet dropped!")
                    print("Synchronisation lost!")
                    repeats = 0
                    dropped += 1
                    retrans -= 1
                    i += 1
                    pycom.rgbled(red)
                    sync()
                    clock_correct = -1
            print("sync slot lasted (ms):", (chrono.read_us()-sync_start)/1000)
            tas = chrono.read_us()-sack_rcv+2000 # add 2ms for proc after that point
            print("time after SACK (ms):", tas/1000)
            if (tas < 13000):
                print("Warning! time after SACK was short!")
                time.sleep_us(int(13000-tas))
                print("corrected time after SACK (ms):", (chrono.read_us()-sack_rcv)/1000)
            print("transmitted/delivered/retransmitted/dropped:", i, succeeded, retrans, dropped)
            # f.write('transmitted/delivered/retransmitted: %d / %d / %d\n' % (i, succeeded, retrans))
        rl = chrono.read_us()-start
        print("round lasted (ms):", rl/1000)
        print("radio active time (rx/tx) (s):", active_rx/1e6, "/", active_tx/1e6)
        if (rl > round_length+sync_slot+13000+proc_and_switch) and (clock_correct == 0):
            print("Warning! frame lasted longer than expected!")
            clock_correct = rl - (round_length+sync_slot+13000+proc_and_switch)
            print("corrected round lasted (ms):", (chrono.read_us()-start)/1000)
        i += 1

    # send out stats
    print("I'm sending stats")
    stat_msg = str(i-1)+":"+str(succeeded)+":"+str(retrans)+":"+str(dropped)+":"+str(active_rx/1000)+":"+str(active_tx/1000)
    pkg = struct.pack(_LORA_PKG_FORMAT % len(stat_msg), MY_ID, len(stat_msg), stat_msg)
    for x in range(3): # send it out 3 times (watch out for collision in case of many nodes. I have to fix this)
        lora.init(mode=LoRa.LORA, tx_iq=True, region=LoRa.EU868, frequency=freqs[7], power_mode=LoRa.TX_ONLY, bandwidth=LoRa.BW_125KHZ, sf=12, tx_power=7)
        pycom.rgbled(blue)
        while (lora.ischannel_free(-90) == False):
            print("Channel is busy!")
            random_sleep(2)
        lora_sock.send(pkg)
        lora.power_mode(LoRa.SLEEP)
        random_sleep(2)
    pycom.rgbled(off)
Пример #19
0
def wait_while_idling(seconds):
    then = time.time() + seconds
    while then > time.time():
        machine.idle()
Пример #20
0
def wifi_connect():
    wlan.connect(ssid, auth=(WLAN.WPA2, password), timeout=5000)
    while not wlan.isconnected():
        machine.idle()
    cfg = wlan.ifconfig()
    print('WLAN connected to ip {} gateway {}'.format(cfg[0], cfg[2]))
Пример #21
0
 def wait_until_not_busy(self):
     """Waits until display is ready (until BUSY_N is high)"""
     while self.is_busy:
         idle()
Пример #22
0
 def wait_not_busy(self):
     while stm.mem32[self._sr] & self._sr_busy:
         machine.idle()
Пример #23
0
def flash_wait_not_busy():
    while stm.mem32[stm.FLASH + stm.FLASH_SR] & 1 << 16:
        machine.idle()
Пример #24
0
    def mainloop(self, stopOnError=False):
        now = 0
        while True:
            if time.ticks_ms() <= now:
                continue

            if self.ready:
                # fix current millis, before start of task
                now = time.ticks_ms()
                task = self.ready[0]  # peek queue
                if task.time2run <= now:
                    if task.period > 0:
                        task.time2run += task.period
                    else:
                        task.time2run = now
                    #log.info ("Memory free: %d" , gc.mem_free() )

                    self.ready.pop(0)  # remove item for queue
                    #                    rq = "queue: "
                    #                    for t in self.ready:
                    #                        rq = "%s %s %d" % (rq,t.name,t.tid)
                    #                    log.info (rq)

                    log.trace("Running task %s , %d , %d", task.name, task.tid,
                              task.time2run)
                    result = None
                    try:
                        result = task.run()
                    except StopIteration:
                        self.exit(task)
                        continue  # do not reschedule current task
                    except Exception as e:
                        tup = e.args
                        log.warn("Task %s: Exception: %s %s ", task.name,
                                 e.__class__, tup)
                        if stopOnError:
                            raise e

                    if result:
                        if isinstance(result, Streamer):
                            mask = select.POLLIN
                            if isinstance(result, StreamWait):
                                # task will be rescheduled by the poller
                                continue  # do not reschedule current task

                            elif isinstance(result, StreamReader):
                                pass
                            elif isinstance(result, StreamWriter):
                                mask = select.POLLOUT

                            elif isinstance(result, StreamReaderWriter):
                                mask |= select.POLLOUT
                            # task will be rescheduled by the poller
                            fd = result.fd
                            log.debug("Registered stream")
                            self.poll.register(fd, mask)
                            self.io_waiting_task[task] = fd

                        if isinstance(result, Tasker):
                            # All taskers will be rescheduled!
                            if isinstance(result, GetTaskRef):
                                task.params = task

                            elif isinstance(result, Wait):
                                task.time2run -= task.period
                                task.time2run += result.timeout

                            elif isinstance(result, AddTask):
                                task = result.task
                                self.taskmap[task.tid] = task
                                self.schedule(task)

                            elif isinstance(result, WaitTask):
                                result = self.waitforexit(task, result.tid)
                                task.params = result
                                # If waiting for a non-existent task,
                                # reschedule current task now
                                if result:
                                    continue

                            elif isinstance(result, CreateTask):
                                log.debug("CreateTask called by: %s ",
                                          task.name)
                                tid = self.task(result.target, result.name,
                                                result.prio, result.period,
                                                result.time2run)
                                task.params = tid

                            elif isinstance(result, KillTask):
                                log.debug("KillTask called by:%s ", task.name)
                                kill = self.taskmap.pop(result.tid, None)
                                if kill:
                                    kill.target.close()
                                    task.params = True
                                else:
                                    task.params = False

                            elif isinstance(result, GetTaskDict):
                                task.params = self.taskmap

                            elif isinstance(result, KillOs):
                                for tid in self.taskmap:
                                    kill = self.taskmap.pop(tid, None)
                                    if kill:
                                        log.debug("Killing task %s", kill.name)
                                        kill.target.close()
                                log.info("Goodbye cruel world, I am dying")
                                return

                        if isinstance(result, Signaler):
                            to = result.timeout
                            if isinstance(result, SendSignal):
                                self.sendsignal(result.signal, result.value)
                                # reschedule current task

                            elif isinstance(result, SendWaitSignal):
                                self.sendsignal(result.signal, result.value)
                                self.wait4signal(task, result.signal)

                            elif isinstance(result, Wait4Signal):
                                self.wait4signal(task, result.signal)

                            elif isinstance(result, Wait4Signals):
                                self.wait4signals(task, result.signals)

                            if to > 0:
                                ## reschedule task for timeout
                                task.time2run = now + to
                            else:
                                continue  # do not reschedule current task

                    self.schedule(task)
                else:
                    self.idlecount += 1
                    machine.idle()
            else:
                self.idlecount += 1
                machine.idle()
Пример #25
0
 async def _idle_task(self):
     while True:
         await asyncio.sleep_ms(10)
         idle()  # Yield to underlying RTOS
Пример #26
0
def connect(net):
    # Connect to WiFi network
    wlan.connect(nets[net]['SSID'], auth=nets[net]['AUTH'], timeout=5000)
    while not wlan.isconnected():
        idle() # save power while waiting
    print('Connected to ' + nets[net]['SSID'] + '!')
Пример #27
0
            self.sta.connect(
                env.get('wireless').get('ssid'),
                env.get('wireless').get('password'))
            count = 0
            while not self.sta.status() == network.STAT_GOT_IP and count < 5:
                utime.sleep_ms(500)
                count += 1
            try:
                ntptime.settime()
            except:
                pass
        if env.get('scenes'):
            for item in env.get('scenes'):
                self.scenes.add_sensors(item)
        self.timer = Timer(0)
        self.timer.init(mode=Timer.PERIODIC,
                        period=60000,
                        callback=self.read_sensors)

    def read_sensors(self, t=None):
        for scene in self.scenes.sensors:
            for _id, data in scene.values():
                publish(_id, data)


if __name__ == '__main__':
    with open('env.json', 'r') as f:
        device = Device(ujson.loads(f.read()))
    while True:
        idle()
Пример #28
0
def sleep_from_until (start, delay):
  ## while time.ticks_diff(start, time.ticks_ms()) < delay:
  while time.ticks_diff(time.ticks_ms(),start) < delay:
    machine.idle()
  return start + delay
Пример #29
0
def switchchannel(c):
    """Push channel select button until desired state is reached"""
    while pushchannel() != c:
        machine.idle()
    return c
Пример #30
0
 def wait_not_busy(self):
     while machine.mem32[stm.FLASH + stm.FLASH_SR] & 1 << 16:
         machine.idle()
Пример #31
0
def start_transmissions(_pkts):
    global lora
    global index
    global lora_sock
    global active_tx
    global active_rx
    global my_slot
    global proc_gw
    global AppSKey
    global succeeded
    global retrans
    global dropped
    global join_start
    global guard
    global sack_rcv
    global msg
    global sack_bytes
    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))
    proc_and_switch = 12000 # time for preparing the packet and switch radio mode (us)
    if (int(MY_ID) == 22 or int(MY_ID) == 34): # fipy nodes switch faster
        proc_and_switch = 10000
    if (my_slot == -1):
        join_start = time.ticks_us()
        join_request(my_sf)
    else:
        sync()
    repeats = 0
    clock_correct = 0
    sync_slot = int(airtime_calc(my_sf,1,sack_bytes+2,my_bw_plain)*1000+3*guard/2)
    clocks = [sync_slot]
    print("-----")
    print("MY SLOT:", my_slot)
    print("Net size:", index)
    print("Time on air (ms):", airt/1000)
    print("Guard time (ms):", guard/1000)
    print("Duty cycle slots:", duty_cycle_limit_slots)
    print("Default SACK slot length (ms):", sync_slot/1000)
    print("Gw processing time (ms):", int(proc_gw/1000))
    print("Time after SACK rec (ms):", (time.ticks_us()-sack_rcv)/1000)

    i = 1
    delays = []
    delay = 0
    (succeeded, retrans, dropped, active_rx, active_tx) = (0, 0, 0, 0.0, 0.0)
    print("S T A R T")
    while(i <= _pkts): # stop after pkts # of packets
        print(i, "----------------------------------------------------")
        start = time.ticks_us()
        pycom.rgbled(green)
        print("starting a new round at (ms):", start/1000)
        # calculate the time until the sack packet (round_length)
        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))
        if (len(delays) > 0):
            delay = sum(delays) / len(delays)
        round_length += delay + proc_gw # clock delays + gw proc time (us)
        t = (my_slot*(airt + 2*guard) + guard - proc_and_switch) # sleep time before transmission
        print("sleep time (ms):", t/1000)
        pycom.rgbled(off)
        # time.sleep_us(int(t))
        machine.sleep(int(t/1000), 0) # light sleep mode
        _thread.start_new_thread(generate_msg, ())
        pycom.rgbled(red)
        on_time = time.ticks_us()
        lora.init(mode=LoRa.LORA, tx_iq=True, region=LoRa.EU868, frequency=freqs[my_sf-5], power_mode=LoRa.TX_ONLY, bandwidth=my_bw, sf=my_sf, tx_power=14)
        pkg = struct.pack(_LORA_PKG_FORMAT % len(msg), MY_ID, len(msg), msg)
        print("Sending packet of", len(pkg), "bytes at (ms):", (time.ticks_us()-start)/1000)
        lora_sock.send(pkg)
        pycom.rgbled(off)
        lora.power_mode(LoRa.SLEEP)
        active_tx += (time.ticks_us() - on_time)
        t = round_length - (time.ticks_us() - start)
        if t < 0:
            t = 0
            print("cannot align clock!")
        print("sleep time after data (s):", t/1e6, "/ clock correction (ms):", clock_correct/1000)
        # time.sleep_us(int(t))
        machine.sleep(int(t/1000), 0) # light sleep mode
        rec = 0
        sack_rcv = 0
        clock_correct = 0
        acks = ""
        lora_sock.setblocking(True)
        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)
        sync_start = time.ticks_us()
        print("started sync slot at (ms):", time.ticks_ms())
        pycom.rgbled(white)
        lora_sock.settimeout(sync_slot/1e6)
        try:
            while (rec == 0):
                machine.idle()
                sack_rcv = time.ticks_us()
                recv_pkg = lora_sock.recv(255)
                if (len(recv_pkg) > 2):
                    recv_pkg_len = recv_pkg[1]
                    recv_pkg_id = recv_pkg[0]
                    if (int(recv_pkg_id) == (my_sf-5)):
                        sack_rcv = time.ticks_us()
                        lora.power_mode(LoRa.SLEEP)
                        active_rx += (time.ticks_us() - sync_start)
                        wt = sack_rcv-sync_start-airtime_calc(my_sf,1,recv_pkg_len,my_bw_plain)*1000
                        print("Waiting time before receiving SACK (ms):", wt/1000)
                        if (wt != guard) and (i > 1):
                            delays.append(wt-guard)
                        if (len(delays) > 3):
                            delays.pop(0)
                        clock_correct = wt - guard
                        try:
                            dev_id, leng, s_msg = struct.unpack(_LORA_RCV_PKG_FORMAT % recv_pkg_len, recv_pkg)
                            s_msg = str(s_msg)[2:][:-1]
                            (index, proc_gw, acks) = s_msg.split(":")
                            (index, proc_gw) = (int(index), int(proc_gw)*1000)
                            print("SACK received!", s_msg)
                            print(lora.stats())
                            if (acks != ""):
                                acks = zfill(bin(int(acks, 16))[2:], index)
                                if (acks[my_slot] == "1"):
                                    print("ACK!")
                                    succeeded += 1
                                    repeats = 0
                                else:
                                    print("I will repeat the last packet")
                                    retrans += 1
                                    repeats += 1
                                    i -= 1
                                    if (repeats == 4):
                                        print("Packet dropped!")
                                        repeats = 0
                                        dropped += 1
                                        retrans -= 1
                                        i += 1
                            machine.idle()
                            rec = 1
                            ack_lasted = time.ticks_us()-sync_start
                            if (i == 1): # what if the first packet is dropped. I have to fix this
                                clocks = [ack_lasted]
                            else:
                                clocks.append(ack_lasted)
                                sync_slot = int(sum(clocks)/len(clocks))
                                if (len(clocks) == 10):
                                    clocks = pop(0)
                            print("new sync slot length (ms):", sync_slot/1000)
                        except:
                            print("wrong SACK format!")
                            pass
        except:
            if (rec == 0):
                lora.power_mode(LoRa.SLEEP)
                active_rx += time.ticks_us() - sync_start
                print("I will repeat the last packet")
                retrans += 1
                repeats += 1
                i -= 1
                if (repeats == 4):
                    print("Packet dropped!")
                    print("Synchronisation lost!")
                    repeats = 0
                    dropped += 1
                    retrans -= 1
                    i += 1
                    pycom.rgbled(red)
                    time.sleep_us(int(round_length-sync_slot-proc_gw))
                    sync()
                    clock_correct = 0
        print("sync slot lasted (ms):", (time.ticks_us()-sync_start)/1000)
        print("time after SACK (ms):", (time.ticks_us()-sack_rcv)/1000)
        print("round lasted (ms):", (time.ticks_us()-start)/1000)
        print("transmitted/delivered/retransmitted/dropped:", i, succeeded, retrans, dropped)
        print("radio active time (rx/tx) (s):", active_rx/1e6, "/", active_tx/1e6)
        i += 1

    # send out stats
    print("I'm sending stats")
    stat_msg = str(i-1)+":"+str(succeeded)+":"+str(retrans)+":"+str(dropped)+":"+str(active_rx/1e6)+":"+str(active_tx/1e6)
    pkg = struct.pack(_LORA_PKG_FORMAT % len(stat_msg), MY_ID, len(stat_msg), stat_msg)
    for x in range(3): # send it out 3 times
        lora.init(mode=LoRa.LORA, tx_iq=True, region=LoRa.EU868, frequency=freqs[7], power_mode=LoRa.TX_ONLY, bandwidth=LoRa.BW_125KHZ, sf=12, tx_power=7)
        pycom.rgbled(blue)
        # while (lora.ischannel_free(-90) == False):
        #     print("Channel is busy!")
        #     random_sleep(5)
        lora_sock.send(pkg)
        lora.power_mode(LoRa.SLEEP)
        random_sleep(10)
    pycom.rgbled(off)
Пример #32
0
 def wait_not_busy(self):
     while machine.mem32[stm.FLASH + stm.FLASH_SR] & _Flash._FLASH_SR_BSY_MASK:
         machine.idle()
Пример #33
0
import machine
from network import WLAN
import time
import socket
import utime

wlan = WLAN(mode=WLAN.STA)

nets = wlan.scan()
for net in nets:
    if net.ssid == 'FabLab':
        print('Network found!')
        wlan.connect(net.ssid, auth=(net.sec, 'MakerFaire'), timeout=5000)
        while not wlan.isconnected():
            machine.idle() # save power while waiting
        print('WLAN connection succeeded!')
        break

rtc = machine.RTC()
rtc.init((2015, 1, 1, 1, 0, 0, 0, 0))
print("Before network time adjust", rtc.now())
print('Setting RTC using Sodaq time server')

s=socket.socket()
addr = socket.getaddrinfo('time.sodaq.net', 80)[0][-1]
s.connect(addr)
s.send(b'GET / HTTP/1.1\r\nHost: time.sodaq.net\r\n\r\n')
ris=s.recv(1024).decode()
s.close()
rows = ris.split('\r\n')            # transform string in list of strings
seconds = rows[7]
Пример #34
0
def check_for_updates(ssid, password, app_url):
    import network
    import machine
    import os
    from time import sleep

    # activate wifi module in station mode
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)

    # status indicator
    led = machine.Pin(2, machine.Pin.OUT)
    led.off()  # turn led on

    try:
        # iterate through available networks
        for s in wlan.scan():
            if s[0].decode('utf-8') == ssid:
                print('Network found!')
                wlan.connect(ssid, password)
                while not wlan.isconnected():
                    machine.idle()

                print('WLAN connection succeeded!')
                # 2 times led blink to indicate, network connected
                for i in range(2):
                    led.on()
                    sleep(0.1)
                    led.off()
                    sleep(0.1)
                led.on()  # finally turn off the led

                try:
                    import urequests
                except:
                    import upip
                    upip.install("micropython-urequests")
                    import urequests

                # check for updates
                res = urequests.get(app_url).text

                current_version = '0.0'
                with open("app.py", "r") as f:
                    current_version = f.read().split("\n")[0].lstrip("#v")

                fetched_version = res.split("\n")[0].lstrip("#v")
                print("Fetched: v{}, Current: v{}".format(
                    fetched_version, current_version))

                if fetched_version == current_version:
                    print("Not updating current app")
                else:
                    print(
                        "Updating current app to v{}".format(fetched_version))

                    # 5 times long-short led blink to indicate, app update running
                    for i in range(5):
                        led.off()
                        sleep(0.5)
                        led.on()
                        sleep(0.1)
                    led.on()  # finally turn off the led

                    with open("app.py", "w") as f:
                        f.write(res)

                    # 2 times short led blink to indicate, app update finished
                    for i in range(2):
                        led.off()
                        sleep(0.1)
                        led.on()
                        sleep(0.1)
                    led.on()  # finally turn off the led

    except Exception as e:
        print(e)

        # if error is about scan failed, don't use led indicator
        if str(e) != "scan failed":
            # 7 times long-short led blink to indicate, error occured
            for i in range(7):
                s = 0.5 if i % 2 == 0 else 0.1
                led.off()
                sleep(s)
                led.on()
                sleep(0.5)
            led.on()  # finally turn off the led

    wlan.active(False)
    led.on()  # finally turn off the led
Пример #35
0
def settimeout(duration):
   pass

def on_message(topic, msg):
    print("topic is: " + str(topic))
    print("msg is: " + str(msg))

wlan = WLAN(mode=WLAN.STA)
nets = wlan.scan()
for net in nets:
    if net.ssid == wifi_ssid:
        print("Network " + wifi_ssid + " found!")
        wlan.connect(net.ssid, auth=(net.sec, wifi_passwd), timeout=5000)
        while not wlan.isconnected():
            #machine.idle() # save power while waiting
            idle() # save power while waiting
        print("WLAN connection succeeded!")
        print (wlan.ifconfig())
        break

client = MQTTClient(MYDEVID, broker_addr, 1883)
if not client.connect():
    print ("Connected to broker: " + broker_addr)

client.set_callback(on_message)
client.subscribe("sensors/")

print("Checking messages ...")

while 1:
    client.check_msg()
Пример #36
0
def init():
    sta_if.connect(ssid, password)
    while not sta_if.isconnected():
        machine.idle()  # save power while waiting
Пример #37
0
def sleep_from_until(start, delay):
    while time.ticks_diff(start, time.ticks_ms()) < delay:
        machine.idle()
    return start + delay
Пример #38
0
def takeANap():
    """Hang a few milliseconds"""
    #machine.sleep(0.01)
    #machine.lightsleep(10)
    machine.idle()
    time.sleep_ms(10)
Пример #39
0
#Read the button, if pressed then not in deepsleep mode and connected to your wifi (to avoid many problem to update your code)
bouton = Pin('G4', mode=Pin.IN, pull=Pin.PULL_UP)
if bouton() == 0 or True:  #TODO
    pycom.rgbled(0xff9900)  #orange
    from network import WLAN
    wlan = WLAN(mode=WLAN.STA)
    nets = wlan.scan()
    for net in nets:
        if net.ssid == 'TP-LINK_2.4GHz':
            print('SSID present.')
            wlan.connect(net.ssid,
                         auth=(net.sec, 'werbrauchtschoninternet'),
                         timeout=5000)
            while not wlan.isconnected():
                machine.idle()
            print('Connetion WLAN/WiFi OK!')

            print("Sync time.")
            rtc.ntp_sync("pool.ntp.org")
            while not rtc.synced():
                print("Wait to be in sync")
                time.sleep(10)
            print("RTC is in sync. ", rtc.now())
            # machine.main('main2.py')
            # machine.main('main.py')
            break
else:
    pycom.rgbled(0x7f0000)
    # machine.main('main.py')
machine.main('main.py')
Пример #40
0
 def WaitforReady(self):
     while self.pin_hrdy.value() == 0:
         machine.idle()
Пример #41
0
from machine import UART
import machine
import os
from network import WLAN

uart = UART(0, baudrate=115200)
os.dupterm(uart)

wifi_ssid = 'YOURWIFISSID'
wifi_pass = '******'

if machine.reset_cause() != machine.SOFT_RESET:
        
    wlan = WLAN(mode=WLAN.STA)
    
    wlan.connect(wifi_ssid, auth=(WLAN.WPA2, wifi_pass), timeout=5000)

    while not wlan.isconnected(): 
         machine.idle()


machine.main('main.py')
Пример #42
0
def wifi_connect():
    wlan.connect(ssid, auth=(WLAN.WPA2, password), timeout=5000)
    while not wlan.isconnected():
        machine.idle()
    cfg = wlan.ifconfig()
    print('WLAN connected to ip {} gateway {}'.format(cfg[0], cfg[2]))