コード例 #1
0
ファイル: main.py プロジェクト: liuyuelin1/mqtt-esp32
def callback(p):
    global ytime
    global gtimemax
    global gtimemin
    if p.value():
        ytime = utime.ticks_cpu()
    else:
        setdiff(utime.ticks_diff(utime.ticks_cpu(), ytime))
        print(getdiff())
コード例 #2
0
 def _log(self, message, *args):
     """
     Outputs a log message to stdout.
     """
     if len(args)==0:
         print('[{}] '.format(utime.ticks_cpu()) + str(message))
     else:
         print('[{}] {}'.format(
             utime.ticks_cpu(),
             str(message).format(*args)
             ))
コード例 #3
0
    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)
                #print(data.decode('latin-1'))
                _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.errno != 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')
コード例 #4
0
    def __init__(self, screen_width, screen_height, size, display, color):
        """Initialize box.

        Args:
            screen_width (int): Width of screen.
            screen_height (int): Width of height.
            size (int): Square side length.
            display (ILI9341): display object.
            color (int): RGB565 color value.
        """
        self.size = size
        self.w = screen_width
        self.h = screen_height
        self.display = display
        self.color = color
        # Generate non-zero random speeds between -5.0 and 5.0
        seed(ticks_cpu())
        r = random() * 10.0
        self.x_speed = 5.0 - r if r < 5.0 else r - 10.0
        r = random() * 10.0
        self.y_speed = 5.0 - r if r < 5.0 else r - 10.0

        self.x = self.w / 2.0
        self.y = self.h / 2.0
        self.prev_x = self.x
        self.prev_y = self.y
コード例 #5
0
def get_random_bits(k):
    result = 0
    for _ in range(k):
        time.sleep(0)
        result <<= 1
        result = result | last_bit(utime.ticks_cpu())
    return result
コード例 #6
0
 def handler(x):
     t_cpu = utime.ticks_cpu()
     self._log("_send_down_link alarm fired at {} late {}us",t_cpu,t_cpu-t_req)
     self._send_down_link(
         payload,
         tmst, tx_pk["txpk"]["datr"],
         int(tx_pk["txpk"]["freq"] * 1000 + 0.0005) * 1000
     )
コード例 #7
0
ファイル: espTemp.py プロジェクト: marcelb98/espTemp
    def __init__(self):
        self.ow = onewire.OneWire(Pin(12))  # create a OneWire bus on GPIO12
        self.ow.scan()  # return a list of devices on the bus
        self.ow.reset()  # reset the bus
        self.ds = ds18x20.DS18X20(self.ow)

        self.rtc = machine.RTC()
        self.rtc.irq(trigger=self.rtc.ALARM0, wake=machine.DEEPSLEEP)

        self.led = Pin(2, Pin.OUT)
        self.led.on()  # led is inverted

        # seeding prng
        t1 = utime.ticks_cpu()
        self.get_temp()
        t2 = utime.ticks_cpu()
        urandom.seed(t2 - t1)
コード例 #8
0
    def _send_down_link(self, data, tmst, datarate, frequency):
        """
        Transmits a downlink message over LoRa.
        """
        self.lora.init(
            mode=LoRa.LORA,
            region=self.region,
            frequency=frequency,
            bandwidth=self._dr_to_bw(datarate),     # LoRa.BW_125KHZ
            sf=self._dr_to_sf(datarate),
            preamble=8,
            coding_rate=LoRa.CODING_4_5,
            power_mode=LoRa.ALWAYS_ON,
            #tx_iq=True
        )

        if WINDOW_COMPENSATION=='cycle':
            self.window_compensation = -((self.downlink_count % 25) * 1000)
        else:
            self.window_compensation = WINDOW_COMPENSATION

        t_adj = utime.ticks_add(tmst, self.window_compensation)
        self.lora_sock.settimeout(1)
        t_cpu = utime.ticks_cpu()
        self._log("BEFORE spin wait at {} late {}",t_cpu,t_cpu-tmst)
        while utime.ticks_diff(t_adj, utime.ticks_cpu()) > 0:
            pass
        t_cpu = utime.ticks_cpu()
        self._log("BEFORE lora_sock.send at {} late {} window_compensation {}",t_cpu,t_cpu-tmst,self.window_compensation)
        self.lora_sock.send(data)
        self._log("AFTER lora_sock.send late {}",utime.ticks_cpu()-tmst)
        self.lora_sock.setblocking(False)
        self._log(
            'Sent downlink packet scheduled on {}, at {:,d} Hz using {}: {}',
            tmst,
            frequency,
            datarate,
            data
        )
        self.downlink_count += 1
コード例 #9
0
def test(canvas):
    """Bouncing box."""

    try:
        clear()
        colors = [
            lv_colors.RED, lv_colors.GREEN, lv_colors.BLUE, lv_colors.YELLOW,
            lv_colors.CYAN, lv_colors.MAGENTA
        ]

        # Generate non-zero random speeds between -5.0 and 5.0
        seed(ticks_cpu())
        x_speed = []
        y_speed = []

        for i in range(6):
            r = random() * 10.0
            if r < 5:
                x_speed.append(r)
            else:
                x_speed.append(r - 10)

            r = random() * 10.0
            if r < 5:
                y_speed.append(r)
            else:
                y_speed.append(r - 10)

        # print("speed_x: ",x_speed)
        sizes = [12, 11, 10, 9, 8, 7]
        boxes = [
            Box(CANVAS_WIDTH, CANVAS_HEIGHT, sizes[i], canvas, x_speed[i],
                y_speed[i], colors[i]) for i in range(6)
        ]

        while True:
            timer = ticks_us()
            for b in boxes:
                b.update_pos()
                b.draw()
            # Attempt to set framerate to 30 FPS
            timer_dif = 33333 - ticks_diff(ticks_us(), timer)
            if timer_dif > 0:
                sleep_us(timer_dif)

    except KeyboardInterrupt:
        sys.exit()
コード例 #10
0
def main():
    ''' Main entry point '''
    driver = LEDBTN()
    game = Simon(driver)

    print('Welcome Lights')
    game.welcome()

    while True:
        # Wait for keypress to start game
        driver.get_pressed()

        print('Game Start')
        game.fail_game()
        urandom.seed(time.ticks_cpu())
        game.game_loop()
        print("Game finished, starting new game")
コード例 #11
0
    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)
コード例 #12
0
    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,
            region=self.region,
            power_mode=LoRa.ALWAYS_ON,
            #tx_iq=True,
            device_class=LoRa.CLASS_C
            )

        self.lora_sock.send(data)
        self._log(
            'Sent downlink packet scheduled on {}, at {:.3f} Mhz using {}: {}',
            utime.ticks_cpu(),
            self._freq_to_float(frequency),
            datarate,
            data
        )
コード例 #13
0
        SENS = SENS - SENSi
        OFF = OFF - OFFi
        Pres = (raw_d1 * SENS / 2097152 - OFF) / 3276800  # barometric pressure
        #

        Temp = Temp / 100
        fTemp = (Temp * 9 / 5) + 32
        print('Temp = ', '%.1fC' % Temp)
        print('Temp = ', '%.1fF' % fTemp)
        print('Pressure = ', '%.1f ' % Pres)
    except:
        print('ms5837 read failed')

    # build ms5837 sensor data payload
    try:
        time_snapshot = str(utime.ticks_cpu())
        #print_TH = "T9602:" + time_snapshot + ":Humidity:" + str(t96h) + "%:Temp:" + str(fTemp) + "F:#" #T9602 humidity and temp
        print_PT = "MS5837:" + time_snapshot + ":Press:" + str(
            Pres) + "mB:Temp:" + str(fTemp) + "F:#"  # MS5837 sensor payload
        print(print_PT)
    except:
        print("sensor payload build failed")

    #transmit Temp Humidity data over Zigbee to coordinator
    try:
        xbee.transmit(TARGET_64BIT_ADDR, print_PT)
        #xbee.transmit(ROUTER_64BIT_x1B2D, print_TH)
        print("send data to coordinator")
    except:
        print("xbee coordinator transmit failed")
コード例 #14
0
 def run():
     seed(ticks_cpu())
     lcd.setRotation(3)
     Snake.timer.init(period=Snake.speed,
                      mode=Timer.PERIODIC,
                      callback=Snake.move)
コード例 #15
0
    def _udp_thread(self):
        """
        UDP thread, reads data from the server and handles it.
        """
        loops = 0
        while not self.udp_stop:
            if loops % 20 == 19:
                b4 = utime.ticks_cpu()
                gc.collect()
                self._log("gc.collect for {} us",utime.ticks_diff(utime.ticks_cpu(),b4))
            b4 = utime.ticks_cpu()
            utime.sleep_ms(UDP_THREAD_CYCLE_MS)
            t_diff = utime.ticks_diff(utime.ticks_cpu(),b4)
            if t_diff > (UDP_THREAD_CYCLE_MS*1000*1.5):
                self._log("overslept! for {} us",t_diff)
            try:
                b4 = utime.ticks_cpu()
                data, src = self.sock.recvfrom(1024)
                self._log("sock.recvfrom for {} us",utime.ticks_diff(utime.ticks_cpu(),b4))
                _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._log("Pull resp")
                    self.dwnb += 1
                    ack_error = TX_ERR_NONE
                    tx_pk = ujson.loads(data[4:])
                    if DEBUG:
                       self._log("tx data "+ujson.dumps(tx_pk))
                    payload = ubinascii.a2b_base64(tx_pk["txpk"]["data"])
                    # depending on the board, pull the downlink message 1 or 6 ms upfronnt
                    
                    # tmst = utime.ticks_add(tx_pk["txpk"]["tmst"], self.window_compensation)
                    # t_us = utime.ticks_diff(utime.ticks_cpu(), utime.ticks_add(tmst, -15000))
                    tmst = tx_pk["txpk"]["tmst"]
                    t_req = utime.ticks_add(tmst, -RX_DELAY_TIMER_EARLY)
                    t_cpu = utime.ticks_cpu()
                    self._log("t_cpu {}",t_cpu)
                    t_us = utime.ticks_diff(t_req, t_cpu)
                    self._log("t_us {}",t_us)
                    if 1000 < t_us < 10000000:
                        self._log("Delaying for {} at {}, so should fire at t_req {}, compensated early_by {}",t_us,t_cpu,t_req,RX_DELAY_TIMER_EARLY)
                        def handler(x):
                            t_cpu = utime.ticks_cpu()
                            self._log("_send_down_link alarm fired at {} late {}us",t_cpu,t_cpu-t_req)
                            self._send_down_link(
                                payload,
                                tmst, tx_pk["txpk"]["datr"],
                                int(tx_pk["txpk"]["freq"] * 1000 + 0.0005) * 1000
                            )
                        self.uplink_alarm = Timer.Alarm(handler=handler, us=t_us)
                    else:
                        ack_error = TX_ERR_TOO_LATE
                        self._log('Downlink timestamp error!, t_us: {}', t_us)
                    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)

        # we are to close the socket
        self.sock.close()
        self.udp_stop = False
        self._log('UDP thread stopped')
コード例 #16
0
def callback(p):
    global START, END, ticks_cpu
    if START == 0:
        START = ticks_cpu()
    else:
        END = ticks_cpu()
コード例 #17
0
import utime
try:
    utime.sleep_ms
except AttributeError:
    print("SKIP")
    raise SystemExit

utime.sleep_ms(1)
utime.sleep_us(1)

t0 = utime.ticks_ms()
t1 = utime.ticks_ms()
print(0 <= utime.ticks_diff(t1, t0) <= 1)

t0 = utime.ticks_us()
t1 = utime.ticks_us()
print(0 <= utime.ticks_diff(t1, t0) <= 500)

# ticks_cpu may not be implemented, at least make sure it doesn't decrease
t0 = utime.ticks_cpu()
t1 = utime.ticks_cpu()
print(utime.ticks_diff(t1, t0) >= 0)
コード例 #18
0
    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()
            if DEBUG:
                self._log("stats "+ujson.dumps(stats))
                self._log('rx_timestamp diff: {}', utime.ticks_diff(stats.rx_timestamp,utime.ticks_cpu()))
            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._log('Received and uploading packet: {}', packet)
            self._push_data(packet)
            self._log('after _push_data')
            self.rxfw += 1
            
        if events & LoRa.TX_PACKET_EVENT:
            self.txnb += 1
            lora.init(
                mode=LoRa.LORA,
                region=self.region,
                frequency=self.frequency,
                bandwidth=self.bw,
                sf=self.sf,
                preamble=8,
                coding_rate=LoRa.CODING_4_5,
                power_mode=LoRa.ALWAYS_ON,
                #tx_iq=True
                )