コード例 #1
0
def do_connect():
    import network
    sta_if = network.WLAN(network.STA_IF)
    
    start = time.ticks_ms() # get millisecond counter
    
    
    if not sta_if.isconnected():
        print('Connecting to network...')
        sta_if.active(True)
        sta_if.connect(WIFI_SSID, WIFI_PASSWORD)
        while not sta_if.isconnected():
            print('Waiting for connection...')
            time.sleep_ms(500)
            pin.value(not pin.value()) # Toggle the LED while trying to connect
            
            # compute time difference since we started looking for the network
            # If it's greater than 10s, we'll time out and just start up as 
            # an access point.
            delta = time.ticks_diff(time.ticks_ms(), start) 
            if delta > 10000:
                print('\r\nTimeout on network connection. Please:')
                print(' * check the SSID and password \r\n * connect to the esp8266 Access Point\r\n')
                break
            
    print('Network Configuration:', sta_if.ifconfig())
    pin.high() # Turn off the LED connected
コード例 #2
0
ファイル: rider.py プロジェクト: danicampora/lopy_ews
    def ride(self, crank):
        global DISTANCE_TARGET
        if self.distance_travelled <= DISTANCE_TARGET:
            # Pull the crank values and calculate the wheel rotations 
            crank_counter_local = str(crank.counter // 2)
            wheel_counter_local_calc = (crank.counter // 2) * 2.8 
            wheel_counter_local = str(wheel_counter_local_calc)
                
            # Workout distance travelled from previous loop
            last_distance_travelled = self.distance_travelled
            calc_current_timestamp = time.ticks_ms() / 1000
            current_timestamp = str(time.ticks_ms() / 1000)

            # Workout the Distance Travelled and covert from meters per second to miles per hour
            self.distance_travelled = (wheel_counter_local_calc * DISTANCE_PER_REVOLUTION) * 2.2237
            distance_loop = self.distance_travelled - last_distance_travelled
            self.speed = (self.distance_travelled / (calc_current_timestamp - self.starttime)) 
            self.distance_remaining = DISTANCE_TARGET - self.distance_travelled
            print("Wheel Counter: " + str(wheel_counter_local_calc) + " | Average Speed (miles per hour): " + str(self.speed) + " | Distance Remaining (meters): " + str(self.distance_remaining)) 

            # Write out speed and distance left to LCD display 
            self.lcd.clear()
            self.lcd.message("AMPH:" + str(int(self.speed)) + "\nMtrs:" + str(int(self.distance_remaining)))

            # this is sent by the gateway
            #json_str = '{"RiderName":"'+rider_name+'","Company":"'+company+'","BadgeNumber":'+badge_number+',"EventID":"'+event_id+'","RideTimestamp":'+start_timestamp+',"BikeID":'+bike_id+',"RideStatus":"'
            #+rider_status+'","RideInfo":[{"CounterTimestamp":'+current_timestamp+',"CrankCounter":'+crank_counter_local+',"WheelCounter":'+wheel_counter_local+'}]}'
            #json_reading = json.loads(json_str)     
            # print(json_reading)
            # TODO: Publish json_reading to TOPIC, QOS
            
            return False
        else:
            return True
コード例 #3
0
def main():
    # Executed on boot
    global switchPin
    global switchstate
    global lightstate
    switchPin = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)
    cm.setAP(False)   # We don't want AP in work mode by default
    savedData = boot.readSession()
    lightstate = int(savedData[1])
    switchstate = int(savedData[2])
    triac.activate(lightstate)
    print("Bulb reinitialised")
    attemptConnect()

    # Main program
    while(MainLoop):
        global compareTime
        time.sleep_ms(checkFrequency)
        if time.ticks_diff(time.ticks_ms(), compareTime) > reconnAttemptInterval:
            attemptConnect()
            print("Done MQTT connect")
            compareTime = time.ticks_ms()
        if not emergencyMode:
            checkInputChange(0)
            if cm.mqttActive:
                mqtt.check_msg()
        else:
            checkInputChange(1)
コード例 #4
0
 def makegauge(self):
     '''
     Generator refreshing the raw measurments.
     '''
     delays = (5, 8, 14, 25)
     while True:
         self._bmp_i2c.writeto_mem(self._bmp_addr, 0xF4, bytearray([0x2E]))
         t_start = time.ticks_ms()
         while (time.ticks_ms() - t_start) <= 5: # 5mS delay
             yield None
         try:
             self.UT_raw = self._bmp_i2c.readfrom_mem(self._bmp_addr, 0xF6, 2)
         except:
             yield None
         self._bmp_i2c.writeto_mem(self._bmp_addr, 0xF4, bytearray([0x34+(self.oversample_setting << 6)]))
         t_pressure_ready = delays[self.oversample_setting]
         t_start = time.ticks_ms()
         while (time.ticks_ms() - t_start) <= t_pressure_ready:
             yield None
         try:
             self.MSB_raw = self._bmp_i2c.readfrom_mem(self._bmp_addr, 0xF6, 1)
             self.LSB_raw = self._bmp_i2c.readfrom_mem(self._bmp_addr, 0xF7, 1)
             self.XLSB_raw = self._bmp_i2c.readfrom_mem(self._bmp_addr, 0xF8, 1)
         except:
             yield None
         yield True
コード例 #5
0
    def blink_all_timed(self, color, blink_duration, brightness=1):
        """ Blink the entire stand at 2Hz for blink_duration, turns off afterwards
        
        Arguments:
            color : can be 'red', 'green', 'blue', 
                    or a tuple of (r,g,b) where r, g, and b are between 0 and 255
            blink_duration : duration to blink for in seconds
            brightness : between 0 and 1, 0 is off, 1 is full brightness
        """
        start_time = time.ticks_ms()
        
        run_time = time.ticks_diff(time.ticks_ms(), start_time) 
        
        while run_time/1000 < blink_duration:
            if run_time % 500 < 250: 
                self.turn_all_to_color(color, brightness)
            else:
                self.turn_all_off()
            
            time.sleep_ms(1)
            run_time = time.ticks_diff(time.ticks_ms(), start_time) 

        # Ensure that all are off 
        self.turn_all_off()
        
コード例 #6
0
ファイル: download.py プロジェクト: BetaRavener/uPyLoader
def _read_timeout(cnt, timeout_ms=2000):
    time_support = "ticks_ms" in dir(time)
    s_time = time.ticks_ms() if time_support else 0
    data = sys.stdin.read(cnt)
    if len(data) != cnt or (time_support and time.ticks_diff(time.ticks_ms(), s_time) > timeout_ms):
        return None
    return data
コード例 #7
0
def testProto16():
	start = time.ticks_ms()
	print("Bounce LED on PROTO16-I2C card")

	# Set all of the pins to outputs
	for bit in range(0,16):
		mcp23017.digitalWrite(bit,0)	# preset to zero so LED doesn't blink
		mcp23017.pinMode(bit,mcp23017.OUTPUT)
		if mcp23017.digitalRead(bit)!=0:
			print("testProto16 (1): readback failed - expected 0, got 1")
			sys.exit(1)
		if mcp23017.digitalRead(bit)!=0:
			print("testProto16 (2): readback failed - expected 0, got 1")
			sys.exit(1)
		
	# Blink all LEDs
	for loopCount in range(0,10):
		for bit in range(0,32):
			mcp23017.digitalWrite(bit,1)
			time.sleep(0.5)
			if mcp23017.digitalRead(bit)!=1:
				print("testProto16 (3): readback failed - expected 1, got 0")
				sys.exit(1)
			mcp23017.digitalWrite(bit,0)
	deltaTime = time.ticks_diff(start, time.ticks_ms())/1000
	print("Test completed, time =",abs(deltaTime))
コード例 #8
0
ファイル: stepper.py プロジェクト: Woz4tetra/Atlas
 def step(self, num_steps):
     if time.ticks_diff(self.time0, time.ticks_ms()) > self.delay:
         steps_left = abs(num_steps)
         
         if num_steps > 0: self.direction = True
         if num_steps < 0: self.direction = False
         
         # decrement the number of steps, moving one step each time:
         while steps_left > 0:
             now = time.ticks_us()
             
             # move only if the appropriate delay has passed:
             if time.ticks_diff(self.last_step_time, now) >= self.step_delay:
                 self.last_step_time = now
                 
                 if self.direction:
                     self.step_number += 1
                     if self.step_number == self.step_num:
                         self.step_number = 0
                 else:
                     if self.step_number == 0:
                        self.step_number = self.step_num
                     self.step_number -= 1
                 steps_left -= 1
                 
                 self.step_motor(self.step_number % 4)
         self.time0 = time.ticks_ms()
コード例 #9
0
ファイル: mboot.py プロジェクト: DanielO/micropython
    def deployfile(self, filename, addr):
        pages = self.getlayout()
        page_erased = [False] * len(pages)
        buf = bytearray(128) # maximum payload supported by I2C protocol
        start_addr = addr
        self.setwraddr(addr)
        fsize = os.stat(filename)[6]
        local_sha = hashlib.sha256()
        print('Deploying %s to location 0x%08x' % (filename, addr))
        with open(filename, 'rb') as f:
            t0 = time.ticks_ms()
            while True:
                n = f.readinto(buf)
                if n == 0:
                    break

                # check if we need to erase the page
                for i, p in enumerate(pages):
                    if p[0] <= addr < p[0] + p[1]:
                        # found page
                        if not page_erased[i]:
                            print('\r% 3u%% erase 0x%08x' % (100 * (addr - start_addr) // fsize, addr), end='')
                            self.pageerase(addr)
                            page_erased[i] = True
                        break
                else:
                    raise Exception('address 0x%08x not valid' % addr)

                # write the data
                self.write(buf)

                # update local SHA256, with validity bits set
                if addr == start_addr:
                    buf[0] |= 3
                if n == len(buf):
                    local_sha.update(buf)
                else:
                    local_sha.update(buf[:n])

                addr += n
                ntotal = addr - start_addr
                if ntotal % 2048 == 0 or ntotal == fsize:
                    print('\r% 3u%% % 7u bytes   ' % (100 * ntotal // fsize, ntotal), end='')
            t1 = time.ticks_ms()
        print()
        print('rate: %.2f KiB/sec' % (1024 * ntotal / (t1 - t0) / 1000))

        local_sha = local_sha.digest()
        print('Local SHA256: ', ''.join('%02x' % x for x in local_sha))

        self.setrdaddr(start_addr)
        remote_sha = self.calchash(ntotal)
        print('Remote SHA256:', ''.join('%02x' % x for x in remote_sha))

        if local_sha == remote_sha:
            print('Marking app firmware as valid')
            self.markvalid()

        self.reset()
コード例 #10
0
ファイル: app.py プロジェクト: gratefulfrog/ArduGuitar
 def loop(self):
     lastDisplayTime = time.ticks_ms()
     while True:
         now = time.ticks_ms()
         if now - lastDisplayTime > self.displayDelta:
             lastDisplayTime = now
             line = 'X: ' + str(round(self.js.readX())) + '  Y: ' + str(round(self.js.readY()))
             print(line)
コード例 #11
0
    def timeit():
        spi = SpiMaster(1, baudrate=int(pyb.freq()[3] / 16))
        start = ticks_ms()

        for i in range(2 ** 10):
            spi.write_data(b'abcdefgh' * 4)
            spi.read_data()

        print("Millisecond ticks elapsed: %i" % ticks_diff(ticks_ms(), start))
コード例 #12
0
def testDigio128():
	start = time.ticks_ms()
	print("Testing DIGIO-128 card")
	# Set all of the pins to pulled up inputs
	for bit in range(0,128):
		digio128.pinMode(bit,digio128.INPUT_PULLUP)
	# verify all pins were set to pulled up inputs
	for bit in range(0,128):
		if digio128.digitalRead(bit) != 1:
			print("testDigio128(1): Expected pullup on input pin")
			sys.exit(1)
	# Write bits one at a time to 0
	for writtenBit in range(0,128):
		digio128.pinMode(writtenBit,digio128.OUTPUT)
		digio128.digitalWrite(writtenBit,0)
		loopBackBit=writtenBit^0x1f
		# Check all of the pins to be sure only one pin was set to 0
		for checkingBit in range(0,128):
			readValue = digio128.digitalRead(checkingBit)
			# The bit being tested should be 0
			if writtenBit == checkingBit:	# The bit being tested
				if readValue != 0:
					print("testDigio128(2): Expected a 0, got a 1")
					print("testDigio128(2): writtenBit =",writtenBit)
					print("testDigio128(2): checkingBit =",checkingBit)				
					print("testDigio128(2): readValue =",readValue)				
					print("testDigio128(2): loopBackBit =",loopBackBit)
					sys.exit(1)
			# The looped back bit should be 0
			elif checkingBit==loopBackBit:	# The loopback cable here
				if readValue!=0:
					print("testDigio128(3): Expected a 0, got a 1")
					print("testDigio128(3): writtenBit",writtenBit)
					print("testDigio128(3): checkingBit =",checkingBit)				
					print("testDigio128(3): readValue =",readValue)				
					print("testDigio128(3): Expected a 1, got a 0")
					print("testDigio128(3): loopBackBit =",loopBackBit)
					sys.exit(1)
				digio128.digitalWrite(writtenBit,1)
				if digio128.digitalRead(loopBackBit)!= 1:
					print("testDigio128(4): Expected a 1, got a 0")					
				digio128.digitalWrite(writtenBit,0)
			# All the other pins should be 1
			elif readValue!=1:
				print("testDigio128(5): writtenBit =",writtenBit)				
				print("testDigio128(5): checkingBit =",checkingBit)				
				print("testDigio128(5): readValue =",readValue)				
				print("testDigio128(5): Expected a 1, got a 0")
				print("testDigio128(5): loopBackBit =",loopBackBit)
				sys.exit(1)
		digio128.pinMode(writtenBit,digio128.INPUT_PULLUP)
	deltaTime = time.ticks_diff(start, time.ticks_ms())/1000
	print("Test passed, time =",abs(deltaTime))
コード例 #13
0
ファイル: __init__.py プロジェクト: scudderfish/FDS18X20
def tst():
    dat = machine.Pin("GP30")
    ow = OneWire(dat)
    ds = FDS1820(ow)
    print("devices:", ds.roms)
    start = time.ticks_ms()
    for x in range(0, 3):
        print("temperatures:", ds.slow_read_temps())
    print(time.ticks_diff(start, time.ticks_ms()))
    start = time.ticks_ms()
    for x in range(0, 3):
        print("temperatures:", ds.read_temps())
    print(time.ticks_diff(start, time.ticks_ms()))
コード例 #14
0
def test_main():
    """Test function for verifying basic functionality."""
    print("Running test_main")
    i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000)
    lcd = I2cLcd(i2c, DEFAULT_I2C_ADDR, 2, 16)
    lcd.putstr("It Works!\nSecond Line")
    sleep_ms(3000)
    lcd.clear()
    count = 0
    while True:
        lcd.move_to(0, 0)
        lcd.putstr("%7d" % (ticks_ms() // 1000))
        sleep_ms(1000)
        count += 1
        if count % 10 == 3:
            print("Turning backlight off")
            lcd.backlight_off()
        if count % 10 == 4:
            print("Turning backlight on")
            lcd.backlight_on()
        if count % 10 == 5:
            print("Turning display off")
            lcd.display_off()
        if count % 10 == 6:
            print("Turning display on")
            lcd.display_on()
        if count % 10 == 7:
            print("Turning display & backlight off")
            lcd.backlight_off()
            lcd.display_off()
        if count % 10 == 8:
            print("Turning display & backlight on")
            lcd.backlight_on()
            lcd.display_on()
コード例 #15
0
 def poll_mic(self):
     if self.mic.excited():
         self.mic_excited_t = ticks_ms()
         self.mic_ever_excited = True
         return True
     else:
         return False
コード例 #16
0
 def poll_beam(self):
     if self.beam.interrupted():
         self.beam_interrupted_t = ticks_ms()
         self.beam_ever_interrupted = True
         return True
     else:
         return False
コード例 #17
0
ファイル: mboot.py プロジェクト: DanielO/micropython
 def wait_response(self):
     start = time.ticks_ms()
     while 1:
         try:
             self.i2c.readfrom_into(self.addr, self.buf1)
             n = self.buf1[0]
             break
         except OSError as er:
             time.sleep_us(500)
         if time.ticks_diff(time.ticks_ms(), start) > 5000:
             raise Exception('timeout')
     if n >= 129:
         raise Exception(n)
     if n == 0:
         return b''
     else:
         return self.i2c.readfrom(self.addr, n)
コード例 #18
0
ファイル: max6675.py プロジェクト: psy0rz/stuff
 def refresh(self):
     """
     Start a new measurement.
     """
     self._cs.off()
     time.sleep_us(10)
     self._cs.on()
     self._last_measurement_start = time.ticks_ms()
コード例 #19
0
 def show():
     lights.update()
     if not verbose:
         return
     print('{}: laser {}'.format(ticks_ms(), beam.interrupted()), end=' ')
     sleep(0.1)
     print('deck %s' % deck.status(), end=' ')
     if piano.playing():
         print('Piano being played', end='')
     print()
コード例 #20
0
ファイル: test_dl.py プロジェクト: pfalcon/micropython-projs
def dl(url, debug=False):
    import uhashlib
    import ubinascii

    proto, dummy, host, path = url.split("/", 3)
    ai = socket.getaddrinfo(host, 80)
    addr = ai[0][4]
    s = socket.socket()
    s.settimeout(10)
    try:
        s.connect(addr)
        s.write(b"GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (path, host))
        size = 0
        hash = uhashlib.sha1()
        t = time.ticks_ms()
        buf = s.read(2000)
        assert buf, buf
        if debug:
            print("initial response:", buf)
        header, buf = buf.split(b"\r\n\r\n", 1)
        #print(header)
        #print(buf)
        hash.update(buf)
        size += len(buf)
        while 1:
            buf = s.read(1024)
            if buf == b"": break
            hash.update(buf)
            size += len(buf)
            sys.stdout.write("%dK\r" % (size >> 10))
#            sta.active(False)
        delta = time.ticks_diff(time.ticks_ms(), t)
        #print()
        print("Size :", size)
        print("Speed: %s bytes/s" % (size / delta * 1000))
        print("Elapsed: %s" % (delta / 1000))
        sha = str(ubinascii.hexlify(hash.digest()), "ascii")
        print("SHA1 :", sha)
        return size, sha
    finally:
        s.close()
コード例 #21
0
ファイル: gateway.py プロジェクト: danicampora/lopy_ews
 def __init__(self, name, company, badge, bike, eventid, ridetimestamp):
     self.name = name
     self.company = company
     self.badge = badge
     self.bike = bike
     self.status = 'finished'
     self.eventid = eventid
     self.speed = 0
     self.distance = 0
     self.crank = 0
     self.starttime = time.ticks_ms() / 1000
     self.ridetimestamp = ridetimestamp
コード例 #22
0
 def playing(self):
     """
     Determine if the piano is being played:
     1. A beam interruption (transition from unterrupted to interrupted)
     indicates the start of playing.
     2. It's no longer being played if the inter-note time has passed with
     no subsequent beam interruption
     """
     return self.poll_beam() \
         or self.beam_ever_interrupted \
         and ticks_diff(self.beam_interrupted_t, ticks_ms()) < self.ms_internote 
     """
コード例 #23
0
ファイル: main.py プロジェクト: adventureloop/tiny-artnet
def pktgen(displaycb):
    broadcast_addr = "255.255.255.255"
    print("       sending to: {} {} every {} seconds"
        .format(broadcast_addr, artnet_port, DELAY))

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    pktdata = []

    start = time.ticks_ms()
    while True:
        #pktdata = os.urandom(512)
        if time.ticks_diff(start, time.ticks_ms()) > 500:
            sock.sendto(gen_artnet_pkt(pktdata, universe), (broadcast_addr, artnet_port))
            start = time.ticks_ms()

        if displaycb: 
            pktdata = displaycb(pktdata)
        #time.sleep(DELAY)
        if not transmitter:
            print("no more transmitting")
            return
コード例 #24
0
ファイル: stepper.py プロジェクト: Woz4tetra/Atlas
 def __init__(self, step_num, phase_a1_pin, phase_a2_pin, phase_b1_pin, phase_b2_pin):
     self.motor_pin_1 = pyb.Pin(phase_a1_pin, pyb.Pin.OUT_PP)
     self.motor_pin_2 = pyb.Pin(phase_a2_pin, pyb.Pin.OUT_PP)
     self.motor_pin_3 = pyb.Pin(phase_b1_pin, pyb.Pin.OUT_PP)
     self.motor_pin_4 = pyb.Pin(phase_b2_pin, pyb.Pin.OUT_PP)
     
     self.step_number = 0
     self.direction = False
     self.last_step_time = 0
     self.step_num = step_num
     self.step_delay = 0
     
     self.time0 = time.ticks_ms()
     self.delay = self.step_delay / 2000
コード例 #25
0
def blinkDigio32():
	start = time.ticks_ms()
	print("Bounce LED on DIGIO32-I2C card")

	# Set all of the pins to inputs
	for bit in range(0,32):
		digio32.pinMode(bit,digio32.INPUT)
		
	# Blink all LEDs
	digio32.pinMode(0,digio32.OUTPUT)
	while True:
		digio32.digitalWrite(0,1)
		time.sleep(0.25)
		digio32.digitalWrite(0,0)
		time.sleep(0.25)
コード例 #26
0
def blinkProto16():
	start = time.ticks_ms()
	print("Bounce LED on Proto16-I2C card")

	# Set all of the pins to inputs
	for bit in range(0,32):
		mcp23017.pinMode(bit,mcp23017.INPUT)
		
	# Blink first LED
	mcp23017.pinMode(0,mcp23017.OUTPUT)
	while True:
		mcp23017.digitalWrite(0,1)
		time.sleep(0.25)
		mcp23017.digitalWrite(0,0)
		time.sleep(0.25)
コード例 #27
0
ファイル: rider.py プロジェクト: danicampora/lopy_ews
 def countdown(self):
     global COUNTDOWN_LENGTH
     global DISTANCE_TARGET
     count_down = COUNTDOWN_LENGTH
     self.lcd.clear()
     while(count_down > 0):
         print("Ready in " + str(count_down))
         self.lcd.home()
         self.lcd.message("Ready in\n {:2d}".format(count_down))
         count_down -= 1
         time.sleep_ms(1000)
     print("GO! GO! GO!")
     self.distance_remaining = DISTANCE_TARGET
     self.lcd.clear()
     self.lcd.message("GO! GO! \nGO!")
     self.starttime = time.ticks_ms() / 1000
     self.last_distance = 0
     self.speed = 0
     self.distance_travelled = 0
コード例 #28
0
ファイル: max6675.py プロジェクト: psy0rz/stuff
    def read(self):
        """
        Reads last measurement and starts a new one. If new measurement is not ready yet, returns last value.
        Note: The last measurement can be quite old (e.g. since last call to `read`).
        To refresh measurement, call `refresh` and wait for `ready` to become True before reading.
        :return: Measured temperature
        """
        # Check if new reading is available
        if self.ready():
            # Bring CS pin low to start protocol for reading result of
            # the conversion process. Forcing the pin down outputs
            # first (dummy) sign bit 15.
            self._cs.off()
            time.sleep_us(10)

            # Read temperature bits 14-3 from MAX6675.
            value = 0
            for i in range(12):
                # SCK should resemble clock signal and new SO value
                # is presented at falling edge
                self._cycle_sck()
                value += self._so.value() << (11 - i)

            # Read the TC Input pin to check if the input is open
            self._cycle_sck()
            self._error = self._so.value()

            # Read the last two bits to complete protocol
            for i in range(2):
                self._cycle_sck()

            # Finish protocol and start new measurement
            self._cs.on()
            self._last_measurement_start = time.ticks_ms()

            self._last_read_temp = value * 0.25

        return self._last_read_temp
コード例 #29
0
  lcd.print("Please Press Button B", 10 , 60, 0xFFFFFF)
  lcd.print("         to save file", 10 , 80, 0xFFFFFF)
  lcd.print("Current File length", 10 , 100, 0xFFFFFF)
  wait(0)

# test if a file is already existing
def file_exists(fname):
  try:
    with open(fname):
      pass
    return True
  except OSError:
     return False

refresh_screen()
t0 = time.ticks_ms()

while True:
  if  (time.ticks_ms()-last_time) >= Time_Interval*1000:
    last_time = time.ticks_ms()
    new_time = (time.ticks_ms()-t0) // 1000
    # when it s time, you can collect a new data from a sensor
    # some kind of env.get_temperature, works here with numbers
    temp = randint(200,300) / 10  # random number for temperature in °C
    humi = randint(40,60)         # random number for humidity in %
    abscisse.append(new_time)     # writing new value in each list
    temperatures.append(temp)
    humidities.append(humi)
    label0.setText(str(len(abscisse)))
    wait(0.1)
コード例 #30
0
import math
import time
import machine

machine.freq(240000000)  # standard frequency is 160000000 for ESP32

last = 10000

start = time.ticks_ms()
print("Prime numbers to 10000")

print('2, 3, 5, 7', end='')
for number in range(11, last, 2):
    prime = 1
    for divider in range(2, int(math.sqrt(number)) + 1, 1):
        if number / divider == int(number / divider):
            prime = 0

    if prime == 1:
        print(',', number, end='')

end = time.ticks_ms()
print('\nThis took:', (end - start), 'ms.')
コード例 #31
0
 def next_stage(self):
     self.current_stage += 1
     self._cycle_start_time = time.ticks_ms()
     print("Starting stage: {0}".format(
         self._CYCLES[self.current_stage]["name"]))
     print("Current temp: {0}".format(self.tc.read()))
コード例 #32
0
___name___ = "Homescreen (Default)"
___license___ = "MIT"
___categories___ = ["Homescreens"]
___dependencies___ = ["homescreen", "shared/logo.png", "shared/sponsors.png"]
___launchable___ = False
___bootstrapped___ = True

import ugfx
from homescreen import *
import time
from tilda import Buttons

# We ❤️ our sponsors
init()
ugfx.display_image(0, 0, "shared/sponsors.png")
wait_until = time.ticks_ms() + 3000
while time.ticks_ms() < wait_until:
    time.sleep(0.1)
    if Buttons.is_pressed(Buttons.BTN_A) or Buttons.is_pressed(
            Buttons.BTN_B) or Buttons.is_pressed(Buttons.BTN_Menu):
        break

# Padding for name
intro_height = 30
intro_text = "Hi! I'm"
name_height = 60
status_height = 20
info_height = 30
logo_path = "shared/logo.png"
logo_height = 150
logo_width = 56
コード例 #33
0
#read label file
f=open("labels.txt","r")
labels=f.readlines()
f.close()

#setup CNN
task = kpu.load(0x200000)

#Kmodel V4 need set output shape manually
#set_outputs(int idx, int w, int h, int ch)
kpu.set_outputs(task,0,6,1,1)

timep = 0
while(True):
    fps = 1000/(time.ticks_ms() - timep)
    timep = time.ticks_ms()

    img = sensor.snapshot()

    img = img.resize(224,224)
    a = img.pix_to_ai()

    fmap = kpu.forward(task,img)
    plist = fmap[:]
    pmax = max(plist)
    max_index = plist.index(pmax)
    result = labels[max_index].strip()

    img.draw_string(0,5,"%.2f:%s" % (pmax,result),scale=2,color=(0,255,0))
    img.draw_string(0,200,"%.1fFPS" % fps,scale=2,color=(255,0,0))
コード例 #34
0
        buzzer_on = True
    
btn20.irq(btn20_isr, trigger=Pin.IRQ_FALLING)
btn21.irq(btn21_isr, trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING)

%serialconnect

from machine import Pin
import time

class Button(object):
    def __init__(self, gpio):
        self.btn = Pin(gpio, Pin.IN)
        # set up IRQ
        self.btn.irq(self.isr, trigger=Pin.IRQ_FALLING)
        # flag and data
        self.pressed = False
        self.time_pressed = time.ticks_ms()
        
    def isr(self, t):
        self.pressed = True
        self.time_pressed = time.ticks_ms()
        
btn = Button(20)
start = time.ticks_ms()
for k in range(10):
    if btn.pressed:
        print(btn.time_pressed - start)
        btn.pressed = False
    time.sleep(1)
コード例 #35
0
def lift_now():
    entry = time.ticks_ms()
    RLY_UP.value(0)
    while not RLY_UP.value():
        if time.ticks_ms() >= entry + 500:
            RLY_UP.value(1)
コード例 #36
0
 def ready(self):
     """
     Signals if measurement is finished.
     :return: True if measurement is ready for reading.
     """
     return time.ticks_ms() - self._last_measurement_start > MAX6675.MEASUREMENT_PERIOD_MS
コード例 #37
0
 def __init__(self, arg=None):
     self.last_time = time.ticks_ms()
     self.clicks = 0
コード例 #38
0
        shader = fg if parts & 32 else bg  # bottom right
        for py in range(v_line):
            shader(x + h_line + 1, y + v_line + 2 + py)

        shader = fg if parts & 64 else bg  # bottom
        for px in range(h_line):
            shader(x + px + 1, y + v_line + v_line + 2)

        x += digit_width + digit_spacing

    return x, y


while True:
    t = ticks_ms()
    hue = t / 3000.0
    ox = int(32 * math.sin(t / 4000.0) + 32)
    oy = int(16 * math.sin((t + 5000) / 3000.0) + 16)
    hub.clear()

    year, month, day, wd, hour, minute, second, _ = rtc.datetime()
    hms = "{:02} {:02} {:02}".format(hour, minute, second)
    ymd = "{:04} {:02} {:02}".format(year, month, day)

    # Hour / Minute / Second
    draw_number(1, 1, hms, fg=shader_fg, bg=shader_bg)

    # Year / Month / Day
    draw_number(8, 20, ymd, fg=shader_fg, bg=shader_bg, digit_width=5, digit_height=7, digit_spacing=1)
コード例 #39
0
def timer_function():
    global button_eve

    TIEMR_FSM_START_WAIT = 0
    TIMER_FSM_START = 1
    TIMER_FSM_STOP = 2
    TIMER_FSM_RESET = 3

    timer_count_100ms_max = 10 * 60 * 10

    meos.showLEDPainting(TIME_START)

    TIMER_FSM_STATUS = TIEMR_FSM_START_WAIT
    TIMER_FSM_STATUS_CHANGED_FLAG = False
    while True:
        evens = button_eve.get_button_event()
        if TIMER_FSM_STATUS == TIEMR_FSM_START_WAIT:
            if TIMER_FSM_STATUS_CHANGED_FLAG == True:
                meos.showLEDPainting(TIME_START)

            #if button_eve.is_button_b_released() == True:
            #if button_eve.get_button_event(BUTTON_B) == BUTTON_EVENT_RELEASED:
            if evens[BUTTON_B] == BUTTON_EVENT_RELEASED:
                timer_start_time = time.ticks_ms()  # unit: ms
                timer_current_time = timer_start_time
                timer_last_time = timer_current_time

                TIMER_FSM_STATUS = TIMER_FSM_START
                TIMER_FSM_STATUS_CHANGED_FLAG = True
            else:
                TIMER_FSM_STATUS_CHANGED_FLAG = False

        elif TIMER_FSM_STATUS == TIMER_FSM_START:
            timer_current_time = time.ticks_ms()
            if timer_current_time - timer_last_time >= 100:
                timer_count_100ms = (timer_current_time -
                                     timer_start_time) // 100
                if timer_count_100ms >= timer_count_100ms_max:
                    meos.showLEDPainting(TIME_MAX)
                else:
                    meos.showTimer(timer_count_100ms)

                timer_last_time = timer_current_time

            #if button_eve.is_button_b_released() == True:
            #if button_eve.get_button_event(BUTTON_B) == BUTTON_EVENT_RELEASED:
            if evens[BUTTON_B] == BUTTON_EVENT_RELEASED:
                TIMER_FSM_STATUS = TIMER_FSM_STOP
                TIMER_FSM_STATUS_CHANGED_FLAG = True
            else:
                TIMER_FSM_STATUS_CHANGED_FLAG = False

        elif TIMER_FSM_STATUS == TIMER_FSM_STOP:
            #if button_eve.is_button_a_released():
            #if button_eve.get_button_event(BUTTON_A) == BUTTON_EVENT_RELEASED:
            if evens[BUTTON_A] == BUTTON_EVENT_RELEASED:
                TIMER_FSM_STATUS = TIMER_FSM_RESET
                TIMER_FSM_STATUS_CHANGED_FLAG = True
            else:
                TIMER_FSM_STATUS_CHANGED_FLAG = False

        elif TIMER_FSM_STATUS == TIMER_FSM_RESET:
            if TIMER_FSM_STATUS_CHANGED_FLAG == True:
                meos.showTimer(0)

            #if button_eve.is_button_b_released() == True:
            #if button_eve.get_button_event(BUTTON_B) == BUTTON_EVENT_RELEASED:
            if evens[BUTTON_B] == BUTTON_EVENT_RELEASED:
                timer_start_time = time.ticks_ms()  # unit: ms
                timer_current_time = timer_start_time
                timer_last_time = timer_current_time

                TIMER_FSM_STATUS = TIMER_FSM_START
                TIMER_FSM_STATUS_CHANGED_FLAG = True
            else:
                TIMER_FSM_STATUS_CHANGED_FLAG = False

        #if button_eve.is_button_c_long_pressed() == True:
        #if button_eve.get_button_event(BUTTON_C) == BUTTON_EVENT_LONG_PRESSED:
        if evens[BUTTON_C] == BUTTON_EVENT_LONG_PRESSED:
            break
        time.sleep(0.1)
コード例 #40
0
ファイル: BlynkLibWiPy.py プロジェクト: lemariva/uPyBlynk
    def run(self):
        self._start_time = time.ticks_ms()
        self._task_millis = self._start_time
        self._hw_pins = {}
        self._rx_data = b""
        self._msg_id = 1
        self._pins_configured = False
        self._timeout = None
        self._tx_count = 0
        self._m_time = 0
        self.state = DISCONNECTED

        if self._wdt:
            self._wdt = machine.WDT(timeout=WDT_TO)

        while True:
            while self.state != AUTHENTICATED:
                self._run_task()
                if self._wdt:
                    self._wdt.feed()
                if self._do_connect:
                    try:
                        self.state = CONNECTING
                        if self._ssl:
                            import ssl

                            print("SSL: Connecting to %s:%d" %
                                  (self._server, self._port))
                            ss = socket.socket(socket.AF_INET,
                                               socket.SOCK_STREAM,
                                               socket.IPPROTO_SEC)
                            self.conn = ssl.wrap_socket(
                                ss,
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs="/flash/cert/ca.pem",
                            )
                        else:
                            print("TCP: Connecting to %s:%d" %
                                  (self._server, self._port))
                            self.conn = socket.socket()
                        self.conn.connect(
                            socket.getaddrinfo(self._server, self._port)[0][4])
                    except:
                        self._close("connection with the Blynk servers failed")
                        continue

                    self.state = AUTHENTICATING
                    hdr = struct.pack(HDR_FMT, MSG_LOGIN, self._new_msg_id(),
                                      len(self._token))
                    print("Blynk connection successful, authenticating...")
                    self._send(hdr + self._token, True)
                    data = self._recv(HDR_LEN, timeout=MAX_SOCK_TO)
                    if not data:
                        self._close("Blynk authentication timed out")
                        continue

                    msg_type, msg_id, status = struct.unpack(HDR_FMT, data)
                    if status != STA_SUCCESS or msg_id == 0:
                        self._close("Blynk authentication failed")
                        continue

                    self.state = AUTHENTICATED
                    self._send(
                        self._format_msg(
                            MSG_HW_INFO,
                            "h-beat",
                            HB_PERIOD,
                            "dev",
                            "WiPy",
                            "cpu",
                            "CC3200",
                        ))
                    print("Access granted, happy Blynking!")
                    if self._on_connect:
                        self._on_connect()
                else:
                    self._start_time = sleep_from_until(
                        self._start_time, TASK_PERIOD_RES)

            self._hb_time = 0
            self._last_hb_id = 0
            self._tx_count = 0
            while self._do_connect:
                #print('do_connect')
                data = self._recv(HDR_LEN, NON_BLK_SOCK)
                if data:
                    msg_type, msg_id, msg_len = struct.unpack(HDR_FMT, data)
                    if msg_id == 0:
                        self._close("invalid msg id %d" % msg_id)
                        break
                    if msg_type == MSG_RSP:
                        if msg_id == self._last_hb_id:
                            self._last_hb_id = 0
                    elif msg_type == MSG_PING:
                        self._send(
                            struct.pack(HDR_FMT, MSG_RSP, msg_id, STA_SUCCESS),
                            True)
                    elif msg_type == MSG_HW or msg_type == MSG_BRIDGE:
                        data = self._recv(msg_len, MIN_SOCK_TO)
                        if data:
                            self._handle_hw(data)
                    else:
                        self._close("unknown message type %d" % msg_type)
                        break
                else:
                    self._start_time = sleep_from_until(
                        self._start_time, IDLE_TIME_MS)
                if not self._server_alive():
                    self._close("Blynk server is offline")
                    break
                self._run_task()

            if not self._do_connect:
                self._close()
                print("Blynk disconnection requested by the user")
            gc.collect()
コード例 #41
0
                                                     seconde_s)
        annee_s, mois_s, date_s, heure_s, minute_s, seconde_s, jour_s = convert_epoch_time(
            data.get("sys").get("sunset"))
        if operation_offset == "+":
            heure_s += heure_offset
        if operation_offset == "-":
            heure_s -= heure_offset
        coucher_soleil = "{0:02}:{1:02}:{2:02}".format(heure_s, minute_s,
                                                       seconde_s)
        vent_vitesse = data.get("wind").get("speed")  # vitesse du vent en m/s
        vent_vitesse *= 3.6  # conversion du vent en Km/h
        vent_orientation = data.get("wind").get("deg")  # origine du vent


rtc = RTC()  # horloge temps reel interne
compteur = time.ticks_ms() - requete_web_delai  # initialise le compteur

wp.tft.rect(0, 0, 240, 135, wp.st7789.GREEN)
wp.tft.hline(0, 18, 240, wp.st7789.GREEN)
wp.tft.hline(0, 36, 240, wp.st7789.GREEN)
wp.tft.hline(0, 99, 240, wp.st7789.GREEN)
wp.tft.hline(0, 117, 240, wp.st7789.GREEN)
wp.CentreTxt(wp.vga1_16x32, "Loading", wp.st7789.RED, wp.st7789.BLACK)

while True:
    if time.ticks_ms(
    ) - compteur >= requete_web_delai:  # test si 60s sont passees
        traite_date_heure()
        traite_openweathermap()
        time_str = "{:02}:{:02}".format(rtc.datetime()[4], rtc.datetime()[5])
        date_str = (jour) + " " + str(date) + " " + (mois) + " " + str(annee)
コード例 #42
0
 def debounce_handler(self, pin):
     if ticks_ms() > self._next_call:
         self._next_call = ticks_ms() + self.min_ago
         self.call_callback(pin)
コード例 #43
0
def GetTicks():
    return time.ticks_ms()
コード例 #44
0
                    contacts[received_id][0] // 60000).to_bytes(
                        2, 'big'
                    )  # "4 bytes serial, then 2 bytes for first timestamp"
                close_contacts[contactID] = (
                    contacts[received_id][1] // 60000).to_bytes(
                        2, 'big') + (b"!" if received_infected else b""
                                     )  # (last timestamp, infected)
                if not infected and received_infected:
                    infected = 1
                    open(INFECTED_FILENAME, "w").close()
        d = radio.receive_full()  # get next message from queue

    #send message
    radio.send_bytes(
        ID + "!" if infected else ID)  # append ! to ID if we're infected
    sleep(DELAY_BETWEEN_BROADCASTS)

    #save data to file
    if close_contacts and last_data_save + TIME_BETWEEN_DATA_SAVES < time.ticks_ms(
    ):
        f = open(DATA_FILENAME, "wb")
        for contactID, contact in close_contacts.items():
            f.write(contactID + contact + "\n")
            # line format: IIIIFFLL!\n
            # IIII = ID of other device
            # FF = initial contact timestampe
            # LL = last contact timestamp
            # ! = optional infected indicator
            # \n end of record
        f.close()
コード例 #45
0
ファイル: test.py プロジェクト: pmvr/micropython-fido2
def timing_kP():
    d = int.from_bytes(urandom(37), 'big', False)
    start = time.ticks_ms()  # get millisecond counter
    Q = secp256r1.kP(d, secp256r1.P)
    delta = time.ticks_diff(time.ticks_ms(), start)  # compute time difference
    print(delta)
コード例 #46
0
ファイル: 2lab3.py プロジェクト: makhojah/4764IoT
    def __init__(self):
        #LED
        self.freq = 1
        self.duty = 512
        self.led = PWM(Pin(LED),freq=self.freq,duty=self.duty)
        
        # Piezo
        #self.piezo = PWM(Pin(PIEZO),freq=self.freq,duty=self.duty)

        # ALS
        self.als = ADC(0)
        self.als_timer = Timer(0)
        self.als_timer.init(period=5000, mode=Timer.PERIODIC,callback=self.als_cb)

        # Buttons
        self.switch = Pin(SWITCH, Pin.IN)
        self.switch_ts = time.ticks_ms()
        self.switch_pending = False

        self.oled_a = Pin(OLED_A, Pin.IN)
        self.oled_a_ts = time.ticks_ms()
        self.oled_a_pending = False

        self.oled_b = Pin(OLED_B, Pin.IN)
        self.oled_b_ts = time.ticks_ms()
        self.oled_b_pending = False
        
        self.oled_c = Pin(OLED_C, Pin.IN)
        self.oled_c_ts = time.ticks_ms()
        self.oled_c_pending = False
        
        self.button_timer = Timer(1)
        self.button_timer.init(period=10, mode=Timer.PERIODIC,callback=self.button_cb2)
        #self.switch.irq(handler=self.switch_cb,trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING,hard=True)
    
        # OLED
        self.i2c = I2C(scl=Pin(SCL), sda=Pin(SDA), freq=100000)
        self.oled = ssd1306.SSD1306_I2C(128, 32, self.i2c)
        self.oled_brightness = 0.5 
        self.oled_direction = 0
        self.ticks = 0

        # RTC
        self.mode = 0 # 0: Clock, 1: Set, 2: Alarm
        self.rtc = RTC()
        date = (2018, 9, 27, 1, 12, 48, 0, 0)
        self.rtc.datetime(date)
        self.current_time = self.rtc.datetime()
        self.current_digit = 0
        self.current_tiktok = 1
        self.clock_timer = Timer(2)
        self.clock_timer.init(period=1000, mode=Timer.PERIODIC, callback=self.clock_cb)

        # Interrupt table
        self.INT_als = False
        self.INT_switch = False
        self.INT_oled_a = False
        self.INT_oled_b = False
        self.INT_oled_c = False
        self.INT_rtc = False

        self.control_timer = Timer(3)
        self.control_timer.init(period=10, mode=Timer.PERIODIC, callback=self.control_cb)

        # Alarm
        self.alarm_timer = Timer(4)

        # Globals
        self.globals = Globals()

        # test LED
        self.test_led = Pin(TEST_LED, Pin.OUT)
        self.test_led.off()
        
        return
コード例 #47
0
import hub75
import time

WIDTH, HEIGHT = 32, 32

hub = hub75.Hub75(WIDTH, HEIGHT, panel_type=hub75.PANEL_GENERIC)

hub.start()
hub.clear()
hub.flip()

while True:
    h = time.ticks_ms() / 5000.0
    hub.set_all_hsv(h, 1.0, 1.0)
    for y in range(8):
        for x in range(WIDTH):
            c = int(x * 255 / WIDTH)
            hub.set_rgb(x, y, c, c, c)
    for x in range(WIDTH):
        hub.set_rgb(x, x, 255, 0, 0)
        hub.set_rgb(WIDTH - 1 - x, x, 255, 0, 0)
    hub.flip()
    time.sleep(1.0 / 60)
コード例 #48
0
ファイル: BlynkLibWiPy.py プロジェクト: lemariva/uPyBlynk
 def _run_task(self):
     if self._task:
         c_millis = time.ticks_ms()
         if c_millis - self._task_millis >= self._task_period:
             self._task_millis += self._task_period
             self._task()
コード例 #49
0
    uos.rename('/sd/dataset.csv', '/sd/dataset.txt')
    f = open('/sd/dataset.txt', 'r')
    labels = f.readlines()
    f.close()
    olddatasetnum = len(labels)
    idpg = olddatasetnum
    dirfoc = len(labels) % 100
    dirfo = int(len(labels) / 100)
    print(dirfo, dirfoc)
    uos.rename('/sd/dataset.txt', '/sd/dataset.csv')
except:
    print("not dataset.csv")
    lcd.draw_string(45, 110, "read old dataset error", lcd.WHITE, lcd.RED)
    time.sleep(5)

tim = time.ticks_ms()

tim_b = tim

bt = 0

eee1 = 0
tong3 = 0
toss1 = 0

img_co_l = 0
img_co_f = 0
img_co_r = 0

try:
    os.mkdir("/sd/" + str(dirfo))
コード例 #50
0
ファイル: BlynkLibWiPy.py プロジェクト: lemariva/uPyBlynk
def sleep_from_until(start, delay):
    while abs(time.ticks_diff(start, time.ticks_ms())) < delay:
        machine.idle()
    return start + delay
コード例 #51
0
from board import A9, LED
from machine import Pin
import time

# Set up the pin in pull-up mode, so that a simple pushbutton can be used.
# when pressed, the pin is shorted to ground. When released, the internal
# pull-up resistor makes the input effectively high.
p = Pin(A9, mode=Pin.IN, pull=Pin.PULL_UP)

# Use the board LED for output
led = Pin(LED, mode=Pin.OUT)

counter = 0
last_state = 0
last_time = time.ticks_ms()

while True:
    # Read value on input pin
    state = p()

    # Compute time delta_t since last time the output changed
    t = time.ticks_ms()
    delta_t = t - last_time

    # Execute if more than 20 ms have elapsed since last output change and the current
    # input differs from the current output (XOR, ^, function is used)
    if delta_t > 20 and state ^ last_state:
        last_time = t
        counter += 1
        last_state = state
コード例 #52
0
    # R = point_mul(r, G)
    xy = curve25519.x25519_ed(r.to_bytes(32, 'little'), u, v)
    R = (int.from_bytes(xy[0], 'little'), int.from_bytes(xy[1], 'little'))
    Rs = point_compress(R)
    h = sha512_modq(Rs + A + msg)
    s = (r + h * a) % q
    return Rs + int.to_bytes(s, 32, "little")


from ubinascii import hexlify, unhexlify
# Test Vectors for Ed25519 - https://tools.ietf.org/html/rfc8032#section-7.1
# Test 1
print('Test 1: Length of message: 0 bytes')
secret = unhexlify(
    b'9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60')
start = time.ticks_ms()  # get millisecond counter
signature = sign(secret, b'')
delta = time.ticks_diff(time.ticks_ms(), start)  # compute time difference
print('Computation time: %d ms' % delta)
if hexlify(
        signature
) != b'e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b':
    print('Test 1 failed.')
    print(hexlify(signature))
else:
    print('Test 1 passed.')
print()

# Test 2
print('Test 2: Length of message: 1 byte')
secret = unhexlify(
コード例 #53
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()
コード例 #54
0
ファイル: 20210313c.py プロジェクト: n19k6/squarewave
    jmp(x_dec, "delay_high")
    jmp(y_dec, "y_high")

    # Cycles: 1 + 7 + 32 * (30 + 1) = 1000
    # 1+9+10*(6+32*(30+1)+1)
    set(pins, 0)
    set(y, 9)[8]
    label("y_low")
    set(x, 31)[5]
    label("delay_low")
    nop()[29]
    jmp(x_dec, "delay_low")
    jmp(y_dec, "y_low")


# Create the StateMachine with the blink_1hz program, outputting on Pin(20).
# frequency must be between 2000 and 125_000_000
sm = rp2.StateMachine(0, blink_1hz, freq=20000, set_base=Pin(20))

# Set the IRQ handler to print the millisecond timestamp.
#sm.irq(lambda p: print("sm1:"+str(time.ticks_ms())))

# Start the StateMachine.
sm.active(1)

# Each PIO instance has a 32-slot instruction memory
sm2 = rp2.StateMachine(1, blink_0_1hz, freq=2000, set_base=Pin(19))

# Set the IRQ handler to print the millisecond timestamp.
sm2.irq(lambda p: print("sm2:" + str(time.ticks_ms())))
sm2.active(1)
コード例 #55
0
 async def connect(self,
                   addr,
                   client_id,
                   clean,
                   user=None,
                   pwd=None,
                   ssl=None,
                   keepalive=0,
                   lw=None):
     if lw is None:
         keepalive = 0
     log.info("Connecting to %s id=%s clean=%d", addr, client_id, clean)
     log.debug("user=%s passwd-len=%s ssl=%s", user, pwd and len(pwd), ssl)
     try:
         # in principle, open_connection returns a (reader,writer) stream tuple, but in MP it
         # really returns a bidirectional stream twice, so we cheat and use only one of the tuple
         # values for everything.
         self._sock = await open_connection(addr, ssl)
     except OSError as e:
         if e.args[0] != EINPROGRESS:
             log.info("OSError in open_connection: %s", e)
             raise
     await asyncio.sleep_ms(10)  # sure sure this is needed...
     # Construct connect packet
     premsg = bytearray(b"\x10\0\0\0\0")  # Connect message header
     msg = bytearray(b"\0\x04MQTT\x04\0\0\0")  # Protocol 3.1.1
     if isinstance(client_id, str):
         client_id = client_id.encode()
     sz = 10 + 2 + len(client_id)
     msg[7] = (clean & 1) << 1
     if user is not None:
         if isinstance(user, str):
             user = user.encode()
         if isinstance(pwd, str):
             pwd = pwd.encode()
         sz += 2 + len(user) + 2 + len(pwd)
         msg[7] |= 0xC0
     if keepalive:
         msg[8] |= (keepalive >> 8) & 0x00FF
         msg[9] |= keepalive & 0x00FF
     if lw is not None:
         sz += 2 + len(lw.topic) + 2 + len(lw.message)
         msg[7] |= 0x4 | (lw.qos & 0x1) << 3 | (lw.qos & 0x2) << 3
         msg[7] |= lw.retain << 5
     i = self._write_varint(premsg, 1, sz)
     # Write connect packet to socket
     try:
         if self._sock is None:
             await asyncio.sleep_ms(100)  # esp32 glitch
         await self._as_write(premsg[:i], drain=False)
         await self._as_write(msg, drain=False)
         await self._send_str(client_id, drain=False)
         if lw is not None:
             await self._send_str(lw.topic
                                  )  # let it drain in case message is long
             await self._send_str(lw.message)
         if user is not None:
             await self._send_str(user, drain=False)
             await self._send_str(pwd, drain=False)
         try:
             await self._as_write(b"")  # cause drain
         except OSError as e:
             log.info("OSError in write: %s", e)
             raise
         # Await CONNACK
         # read causes ECONNABORTED if broker is out
         try:
             resp = await self._as_read(4)
         except OSError as e:
             log.info("OSError in read: %s", e)
             raise
         if resp[0] != 0x20 or resp[1] != 0x02:
             raise OSError(-1, "Bad CONNACK")
         if resp[3] != 0:
             if resp[3] < 6:
                 raise OSError(-1,
                               "CONNECT refused: " + CONN_ERRS[resp[3] - 1])
             else:
                 raise OSError(-1, "CONNECT refused")
     except Exception:
         self._sock.close()
         await self._sock.wait_closed()
         raise
     self.last_ack = ticks_ms()
     # gc.collect()
     log.debug("Connected")  # Got CONNACK
コード例 #56
0
 def isr(self, t):
     self.pressed = True
     self.time_pressed = time.ticks_ms()
コード例 #57
0
ファイル: life.py プロジェクト: gpshead/life_circle
  def run(self, initial_state=(), *, alive=orig,
          sleep_ms=50, iterations=-1, stay_alive=(2,3), new_born=(2,5)):
    """Classic life tunable using stay_alive and newborn sets.

    Args:
      initial_state: is a sequence of the [0,254] LEDs alive at the start.
      sleep_ms: The number of milliseconds to display each frame.
      alive: A tuple of colors a pixel will go through as it gets older.
      iterations: if > 0, the number of iterations to go through.
      stay_alive: LIFE - Number of neighbors required for a pixel to live.
      new_born: LIFE - Number of neighbors for new life on a dead pixel.

    Returns:
      The final state after running through all iterations.
    """
    assert len(alive)
    if not initial_state:
      initial_state = self._default_start_state
    current_state = bytearray(NUM_DISC_LEDS)  # wasteful
    for led in initial_state:
      current_state[led] = 1
    start_state = current_state
    colormap = {0: apa102._brightness(apa102.led_off, self.brightness)}
    for idx, color in enumerate(alive, 1):
      assert len(color) == 4
      colormap[idx] = apa102._brightness(color, self.brightness)
    max_alive = len(alive)

    count_dieoffs = 0
    count_iters = 0
    ticks_ms_refresh = 0
    if self.stats_display:
      self.stats_display.clear()
      self.stats_display.set_cursor(0,0)
      self.stats_display.write(' Rounds alive: 0\n')
      self.stats_display.write('Cyclic states: 0\n')  # Unimplemented.
      self.stats_display.write('Total dieoffs: 0')

    while iterations != 0:
      # Display the current state.
      start_ms = time.ticks_ms()
      self._display_state(current_state, colormap)
      if self.stats_display and time.ticks_ms() - ticks_ms_refresh > 1000:
        ticks_ms_refresh = time.ticks_ms()
        self.stats_display.set_text_cursor(15,0)
        self.stats_display.write(str(count_iters))
        try:
            self.stats_display.display()
        except Exception:
            # Error updating, nothing we can do about it.
            self.stats_display = None
      count_iters += 1
      wait_until = start_ms + sleep_ms
      now = time.ticks_ms()
      while now < wait_until:
        if wait_until - now > 10:
          time.sleep_ms(10)
        else:
          time.sleep_ms(1)
        now = time.ticks_ms()

      # all dead, restart.
      if (max(current_state) == 0):
        count_dieoffs += 1
        if self.stats_display:
          self.stats_display.set_text_cursor(15,0)
          self.stats_display.write(str(count_iters))
          self.stats_display.set_text_cursor(15,2)
          self.stats_display.write(str(count_dieoffs))
          self.stats_display.display()
        time.sleep_ms(1000+sleep_ms*3)  # pause
        # Randomly seed new life.
        for led in os.urandom(23):
          if led < len(current_state):
            current_state[led] = not current_state[led]

      # Compute the next iteration.
      next_state = bytearray(current_state)  # copy
      for led, alive in enumerate(current_state):
        live_neighbors = 0
        for neighbor in self._neighbors[led]:
          if current_state[neighbor]:
            live_neighbors += 1
        live_neighbors %= 7  # HACK, for torus to be meaningful.
        if alive:
          if live_neighbors in stay_alive:
            next_state[led] = min(next_state[led]+1, max_alive)
          else:
            next_state[led] = 0  # death
        else:  # dead
          if live_neighbors in new_born:
            next_state[led] = 1  # birth

      current_state = next_state

      if iterations > 0:
        iterations -= 1

    return current_state
コード例 #58
0
 async def read_msg(self):
     # t0 = ticks_ms()
     res = await self._as_read(1)
     # We got something, dispatch based on message type
     op = res[0]
     # log.debug("read_msg op=%x", op)
     if op == 0xD0:  # PINGRESP
         await self._as_read(1)
         self.last_ack = ticks_ms()
         self._pingresp_cb()
     elif op == 0x40:  # PUBACK: remove pid from unacked_pids
         sz = await self._as_read(1)
         if sz != b"\x02":
             raise OSError(-1, PROTO_ERROR, "puback", sz)
         rcv_pid = await self._as_read(2)
         pid = rcv_pid[0] << 8 | rcv_pid[1]
         self.last_ack = ticks_ms()
         self._puback_cb(pid)
     elif op == 0x90:  # SUBACK: flag pending subscribe to end
         resp = await self._as_read(4)
         pid = resp[2] | (resp[1] << 8)
         # print("suback", resp[3])
         self.last_ack = ticks_ms()
         self._suback_cb(pid, resp[3])
     elif (op & 0xF0) == 0x30:  # PUB: dispatch to user handler
         sz = await self._read_varint()
         topic_len = await self._as_read(2)
         topic_len = (topic_len[0] << 8) | topic_len[1]
         topic = await self._as_read(topic_len)
         # log.debug("topic:%s", topic)
         sz -= topic_len + 2
         retained = op & 0x1
         dup = op & 0x8
         qos = (op >> 1) & 3
         pid = None
         if qos:  # not QoS=0 -> got pid
             pid = await self._as_read(2)
             pid = pid[0] << 8 | pid[1]
             sz -= 2
         # log.debug("pid:%s sz=%d", pid, sz)
         if sz < 0:
             raise OSError(-1, PROTO_ERROR, "pub sz", sz)
         else:
             msg = await self._as_read(sz)
         # Dispatch to user's callback handler
         log.debug("dispatch pub %s pid=%s qos=%d", topic, pid, qos)
         # t1 = ticks_ms()
         try:
             cb = self._subs_cb(topic, msg, bool(retained), qos, dup)
             if is_awaitable(cb):
                 await cb  # handle _subs_cb being coro
         except Exception as e:
             log.exc(e, "exception in handler")
         # t2 = ticks_ms()
         # Send PUBACK for QoS 1 messages
         if qos == 1:
             pkt = bytearray(b"\x40\x02\0\0")
             struct.pack_into("!H", pkt, 2, pid)
             async with self._lock:
                 await self._as_write(pkt)
         elif qos == 2:
             raise OSError(-1, "QoS=2 not supported")
         # log.debug("read_msg: read:{} handle:{} ack:{}".format(ticks_diff(t1, t0),
         #    ticks_diff(t2, t1), ticks_diff(ticks_ms(), t2)))
     else:
         raise OSError(-1, PROTO_ERROR, "bad op", op)
     return op >> 4
コード例 #59
0
ファイル: gateway.py プロジェクト: danicampora/lopy_ews
    def run(self):
        data = self.recv()
        if data:
            print(data)
            parsed_json = json.loads(data.decode('ascii'))
            print(parsed_json)
            if parsed_json['RideStatus'] == "started":
                self.new_rider(parsed_json['RiderName'], parsed_json['Company'], 
                               parsed_json['BadgeNumber'], parsed_json['BikeID'],parsed_json['EventID'],parsed_json['RideTimestamp'])
                # start the race
                print(str({'id':parsed_json['BikeID'], 'cm': 's'}))
                packet_tx = json.dumps({'id':parsed_json['BikeID'], 'cm': 's'})
                print ("packet_tx = " + packet_tx)
                self.lora.send(packet_tx, True)

        lora_d = self.lora.recv()
        if lora_d:
            parsed_json = json.loads(lora_d.decode('ascii'))
            print(parsed_json)
            # update the rider info (if the rider already exists)
            bike_id = parsed_json['id']
            if bike_id in self.riders:
                self.riders[bike_id].speed = parsed_json['sp']
                self.riders[bike_id].distance = parsed_json['ds']
                self.riders[bike_id].crank = parsed_json['cr']
                if parsed_json['st'] == 'i' or parsed_json['st'] == 'f':
                    self.riders[bike_id].status = 'finished'
                elif parsed_json['st'] == 'r':
                    self.riders[bike_id].status = 'counting'
                else:
                    self.riders[bike_id].status = 'started'
                # Assemble the TCP packet
                wheel_count=self.riders[bike_id].crank * 7
                json_d = {"RiderName":self.riders[bike_id].name, "Company":self.riders[bike_id].company, "BadgeNumber":self.riders[bike_id].badge, \
                          "EventID":self.riders[bike_id].eventid, "RideTimestamp":'{:f}'.format(self.riders[bike_id].ridetimestamp), "BikeID":bike_id, \
                          "RideStatus":self.riders[bike_id].status, "RideInfo":[{"CounterTimestamp": float(time.ticks_ms()), \
                          "CrankCounter":self.riders[bike_id].crank, "WheelCounter":wheel_count}]}
                json_str = json.dumps(json_d)
                print("Outgoing from Gateway: " + str(json_str))
                self.send(json_str+"\n")
        if not self.connected:
            self.connect_to_wlan()
            self.connect_to_server()
コード例 #60
0
        # Configure as fire sensor
        pycom.heartbeat(False)
        pycom.wifi_on_boot(False)

        if USE_DEEPSLEEP:
            # For deepsleep, config from scratch and setup deepsleep reset
            # If first boot, get settings from remote
            client = FireSensor()
            client.setup_from_remote()
            client.check_sensor()
        else:
            # For sleep, setup once and go in loop
            client = FireSensor()
            client.setup_from_remote()

            start = time.ticks_ms()

            while True:
                if time.ticks_diff(start, time.ticks_ms()) > SLEEP_DELAY:
                    client.request_config(
                    )  # After timeout, get updated settings from server
                    start = time.ticks_ms()
                client.check_sensor()
    else:
        # Recover from deepsleep
        reason = machine.wake_reason()[0]

        if reason == machine.PIN_WAKE:
            print("Wake on PIN_INTERRUPT")

            client = FireSensor()