def __init__(self, apin, callback, int_mode=True): """Constructor. Args: apin: an ADC pin object. callback: callback functino when a frame is colelct. callback(data) where data is a list of byte. int_mode: True for interrupt mode. """ self.apin_ = apin self.callback_ = callback self.stream_ = [0] * self.FRAME_SIZE self.num_samples_ = 0 # Number of data in stream_[] self.recording_ = False self.samples_in_sec_ = 0 # For statistic us = int(1000000 / self.HZ) if int_mode: self.timer_ = Timer.Alarm(self.hz, us=us, periodic=True) self.second_ = Timer.Alarm(self.second, s=1, periodic=True)
def __init__(self, ble_comm): self.HEADSIZE = 20 self.INTERVAL = .1 self.q = b'' self.ble_comm = ble_comm self.chr = ble_comm.chr_rx self.call_cnt = 0 # mutex for self.q usage self.q_lock = _thread.allocate_lock() self._timer = Timer.Alarm(self.interval_cb, self.INTERVAL, periodic=True)
def _udp_thread(self): """ UDP thread, reads data from the server and handles it. """ while not self.udp_stop: try: data, src = self.sock.recvfrom(1024) _token = data[1:3] _type = data[3] if _type == PUSH_ACK: self._log("Push ack") print("Push ack") elif _type == PULL_ACK: self._log("Pull ack") print("Pull ack") elif _type == PULL_RESP: self.dwnb += 1 ack_error = TX_ERR_NONE tx_pk = ujson.loads(data[4:]) 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) 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')
def init_static(): is_pytrack = True try: py = Pytrack() Gps.l76 = L76GNSS(py, timeout=30) #l76.coordinates() Gps._timer = Timer.Alarm(Gps.gps_periodic, 30, periodic=True) print("Pytrack detected") except: is_pytrack = False print("Pytrack NOT detected") #TODO: how to check if GPS is conencted return is_pytrack
def periodic_event(self, arg): if self.data_type == "gps": # get position from gps to be sent over LoRA _thread.start_new_thread(GpsSIM28.get_position, (self.logger, self.lora)) elif self.data_type == "sensors": # flash averages of PM data to sd card to be sent over LoRa get_sensor_averages(logger=self.logger, lora=self.lora) if self.lora is not False: # Schedule LoRa messages if LoRa is enabled # if device was last transmitting a day or more ago, reset message_count for the day today = time.gmtime() date = str(today[0]) + str(today[1]) + str(today[2]) if self.lora.transmission_date != date: self.lora.message_count = 0 self.lora.transmission_date = date config.save_configuration({ "message_count": self.lora.message_count, "transmission_date": date }) # send 2, 3 or at most 4 messages per interval based on length of interval lora_slot = int( float(config.get_config("interval")) * 60) // 30 # lora_rate changes for each 30 seconds if lora_slot < 2: raise Exception("Interval has to be at least a minute") else: lora_rate = lora_slot if lora_slot > 4: lora_rate = 4 waiting = self.lora.lora_buffer.size( lora_rate) # check how many messages are waiting (up to 4) remaining = self.lora.message_limit - self.lora.message_count # check how many more we can send today if remaining <= 0: self.logger.info("LoRa message limit reached for the day") if remaining - waiting >= 0: count = waiting # if we have more than we want to send, send them all else: count = remaining # if we have less than we want to send, send up to the limit for val in range( count ): # Schedule up to 4 randomly timed messages within interval self.random_alarm = Timer.Alarm(self.random_event, s=self.get_random_time(), periodic=False) else: raise Exception("Non existent data type")
def __init__ (self, x_pos, y_pos, theta, Delta_T, Encodeur_Mot_Droit, Encodeur_Mot_Gauche) : self.x_pos = x_pos self.y_pos = y_pos self.theta = theta self.Delta_T = Delta_T self.Encodeur_Mot_Droit = Encodeur_Mot_Droit self.Encodeur_Mot_Gauche = Encodeur_Mot_Gauche self.Encodeur_Mot_Droit.ticks_voieA_odometrie = 0 self.Encodeur_Mot_Droit.ticks_voieB_odometrie = 0 self.Encodeur_Mot_Gauche.ticks_voieA_odometrie = 0 self.Encodeur_Mot_Gauche.ticks_voieB_odometrie = 0 self.alarm = Timer.Alarm(self.IT_Delta_x_y_theta, ms = self.Delta_T, periodic = True)
def pir_handler(pir): global fadeout_timer stop_pir() pir_value = pir() utime.sleep_ms(200) if pir_value == pir() and pir_value is 0: print('motion detected') motion_started() fadeout_timer = Timer.Alarm(fadeout_timer_handler, 10, periodic=True) else: print('false positive - motion not detected') start_pir()
def __init__(self, microphone): """Constructor. Args: microphone: an microphone.Microphone object """ self.microphone_ = microphone self.pressed_ = False self.state_ = self.RELEASED self.cnt_ = None # For debounce pycom.heartbeat(False) # RGB LED self.pin_ = Pin(self.PIN_STR, mode=Pin.IN, pull=Pin.PULL_DOWN) self.timer_ = Timer.Alarm(self.timer, us=self.DEBOUNCE_US, periodic=True)
def LoRa_Setup(self): lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) dev_addr = struct.unpack( ">l", binascii.unhexlify('90 53 07 24'.replace(' ', '')))[0] nwk_swkey = binascii.unhexlify(NvsExtract(NWKSKEY).retval()) app_swkey = binascii.unhexlify(NvsExtract(APPSKEY).retval()) lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey)) print("Done") # create a LoRa socket self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) self.s.bind(5) # make the socket non-blocking self.s.setblocking(True) self.Sensor_Setup() # instead of polling, we put soft interrupts if self.tFrequency != 0: send_t = Timer.Alarm(self.lora_send_temp, float(self.tFrequency) * 60.0, periodic=True) time.sleep(10) if self.altFrequency != 0: send_alt = Timer.Alarm(self.lora_send_alt, float(self.altFrequency) * 60.0, periodic=True) time.sleep(10) if self.acclFrequency != 0: send_accl = Timer.Alarm(self.lora_send_accl, float(self.acclFrequency) * 60.0, periodic=True) time.sleep(10) if self.lightFrequency != 0: send_light = Timer.Alarm(self.lora_send_light, float(self.lightFrequency) * 60.0, periodic=True) print("Timers Done")
def _udp_thread(self): while True: try: data, src = self.sock.recvfrom(1024) _token = data[1:3] _type = data[3] if _type == PUSH_ACK: print("Push ack") elif _type == PULL_ACK: print("Pull ack") elif _type == PULL_RESP: self.dwnb += 1 ack_error = TX_ERR_NONE tx_pk = json.loads(data[4:]) print("tx_pk : {}".format(tx_pk)) print("tx_pk[txpk][data] : {}".format( tx_pk["txpk"]["data"])) tmst = tx_pk["txpk"]["tmst"] t_us = tmst - time.ticks_us() - 5000 if t_us < 0: t_us += 0xFFFFFFFF if t_us < 20000000: #toSend = binascii.a2b_base64(tx_pk["txpk"]["data"]) toSend = generateDataFuzzRandomLength() hexToString = ":".join("{:02x}".format(c) for c in toSend) print("toSend : {}".format(hexToString)) self.uplink_alarm = Timer.Alarm( handler=lambda x: self._send_down_link( toSend, tx_pk["txpk"]["tmst"] - 10, tx_pk[ "txpk"]["datr"], int(tx_pk["txpk"]["freq"] * 1000000)), us=t_us) else: ack_error = TX_ERR_TOO_LATE print("Downlink timestamp error!, t_us:", t_us) self._ack_pull_rsp(_token, ack_error) print("Pull rsp") except socket.timeout: pass except OSError as e: if e.errno == errno.EAGAIN: pass else: print("UDP recv OSError Exception") except Exception: print("UDP recv Exception") # Wait before trying to receive again time.sleep(0.025)
def start(self): # Change WiFi to STA mode and connect self.wlan = WLAN(mode=WLAN.STA) self._connect_to_wifi() # Get a time Sync self.rtc = machine.RTC() self.rtc.ntp_sync(self.ntp, update_period=self.ntp_period) # Get the server IP and create an UDP socket self.server_ip = socket.getaddrinfo(self.server, self.port)[0][-1] self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.setblocking(False) # Push the first time immediatelly self._push_data(self._make_stat_packet()) # Create the alarms self.stat_alarm = Timer.Alarm(handler=lambda t: self._push_data( self._make_stat_packet()), s=60, periodic=True) self.pull_alarm = Timer.Alarm(handler=lambda u: self._pull_data(), s=25, periodic=True) # Start the UDP receive thread _thread.start_new_thread(self._udp_thread, ()) # Initialize LoRa in LORA mode self.lora = LoRa(mode=LoRa.LORA, frequency=self.frequency, bandwidth=LoRa.BW_125KHZ, sf=self.sf, preamble=8, coding_rate=LoRa.CODING_4_5, tx_iq=True) # Create a raw LoRa socket self.lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.lora_sock.setblocking(False) self.lora_tx_done = False self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=self._lora_cb)
def __init__(self, interval, app_eui, app_key, dp_callback): self.interval = interval # num secs to sleep self.callback = dp_callback self.app_eui = ubinascii.unhexlify( app_eui) # determines app to connect to self.app_key = ubinascii.unhexlify(app_key) # grants access self.lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) # used to join a network self.s = socket.socket( socket.AF_LORA, socket.SOCK_RAW) # used to send data to joined network self.connect() # joins application specified through app_eui self.__alarm = Timer.Alarm(self._uploader, interval, periodic=True)
def write_lora(): global alarme, poll_again, message_sent_to_lora while True: if enable_send_to_lora: rliste, wliste, elist = select.select([], [s], [], 0.05) if len(wliste) != 0 and len(to_send) != 0: with mutex: poll_again = False alarme.cancel() s.send(bytes(to_send[0])) message_sent_to_lora = True print("sent = {}".format(to_send[0])) del to_send[0] alarme = Timer.Alarm(handler=polling, s=POLLING_INTERVAL, periodic=True)
def __init__(self, sensor_logger, status_logger): self.sensor_logger = sensor_logger self.status_logger = status_logger # Initialise i2c - bus no., type, baudrate, i2c pins self.i2c = I2C(0, I2C.MASTER, baudrate=9600, pins=('P9', 'P10')) self.address = 0x45 # get one sensor reading upon init to catch any errors and calibrate the sensor self.read() # start a periodic timer interrupt to poll readings at a frequency self.processing_alarm = Timer.Alarm( self.process_readings, s=int(config.get_config("TEMP_period")), periodic=True)
def __init__(self, file_, dt=1.0): self.dt = dt self.n = 0 self.buf_index = 0 self.buf_0_len = 1 self.buf_0 = [[0, 0, 0] for i in range(self.buf_0_len)] self.rtc = RTC() self.i2c = I2C(baudrate=400000) self._setup() self._connnect_socket() self.begin = time.ticks_ms() self.__alarm = Timer.Alarm(self._handler, dt, periodic=True)
def emit(self, level, msg): """Generate the message and write it to the UART. :param level: The level at which to log :param msg: The core message """ pycom.heartbeat(False) if level == 00: colour = 0x0000 #NOTSET elif level == 10: colour = 0x0000 #DEBUG elif level == 20: colour = 0x007f00 #INFO elif level == 30: colour = 0x7f7f00 #WARNING elif level == 40: colour = 0x7f0000 #ERROR elif level == 50: colour = 0x7f0000 #CRITICAL pycom.rgbled(0x007f00) # green Timer.Alarm(handler=lambda u: pycom.heartbeat(True), s=2)
def __init__(self, meshaging, lock): self.lock = lock #_thread.allocate_lock() self.meshaging = meshaging self.mesh = MeshInternal(self.meshaging) self.sleep_function = None self.single_leader_ts = 0 self.statistics = Statistics(self.meshaging) self._timer = Timer.Alarm(self.periodic_cb, self.INTERVAL, periodic=True) # just run this ASAP self.periodic_cb(None) pass
def sub_cb(topic, msg): if topic.decode('utf-8') == 'garden/water' and msg.decode( 'utf-8') == 'toggle': led.toggle() if topic.decode('utf-8') == 'garden/water' and msg.decode( 'utf-8') == 'start': led.value(1) led_timer = Timer.Alarm(lambda t: led.value(0), 5, periodic=False) # led_timer = Timer(1) # led_timer.init(mode=Timer.ONE_SHOT) # timer_a = led_timer.channel(Timer.A, freq=1000, period=5000) # timer_a.irq(handler=lambda t: led.value(0), trigger=Timer.TIMEOUT) if topic.decode('utf-8') == 'garden/water' and msg.decode( 'utf-8') == 'stop': led.value(0) print(str(topic), str(msg))
def _udp_thread(self): while True: try: data, src = self.sock.recvfrom(1024) _token = data[1:3] _type = data[3] print('Data from UDP socket: ' + str(data[4:])) print('Data src: ' + str(src)) print('Data token: ' + str(_token)) print('Data type: ' + str(_type)) if _type == PUSH_ACK: print("Push ack") elif _type == PULL_ACK: print("Pull ack") elif _type == PULL_RESP: self.dwnb += 1 ack_error = TX_ERR_NONE tx_pk = json.loads(data[4:]) tmst = tx_pk["txpk"]["tmst"] t_us = tmst - time.ticks_us() - 5000 if t_us < 0: t_us += 0xFFFFFFFF if t_us < 20000000: self.uplink_alarm = Timer.Alarm( handler=lambda x: self._send_down_link( binascii.a2b_base64(tx_pk["txpk"]["data"]), tx_pk["txpk"]["tmst"] - 10, tx_pk["txpk"][ "datr"], int(tx_pk["txpk"]["freq"] * 1000000)), us=t_us) else: ack_error = TX_ERR_TOO_LATE print("Downlink timestamp error!, t_us:", t_us) self._ack_pull_rsp(_token, ack_error) print("Pull rsp") except socket.timeout: pass except OSError as e: if e.errno == errno.EAGAIN: pass else: print("UDP recv OSError Exception") except Exception: print("UDP recv Exception") # Wait before trying to receive again time.sleep(0.025)
def __init__(self, config, message_cb): self.lock = _thread.allocate_lock() self.meshaging = Meshaging(self.lock) self.config = config self.mesh = MeshInternal(self.meshaging, config, message_cb) self.sleep_function = None self.single_leader_ts = 0 self.end_device_m = False # self.statistics = Statistics(self.meshaging) self._timer = Timer.Alarm(self.periodic_cb, self.INTERVAL, periodic=True) # just run this ASAP self.periodic_cb(None) pass
def gps_init(logger): logger.info("Turning GPS on - Terminal output is disabled until GPS finishes") uos.dupterm(None) # deinit terminal output on serial bus 0 # turn GPS module on via transistor GPS_transistor.value(1) # set up serial input for gps signals serial = UART(0, baudrate=9600, pins=('P22', 'P21')) # Tx, Rx chrono = Timer.Chrono() chrono.start() indicator_led = Timer.Alarm(blink_led, s=1.6, arg=(0x000055, 0.4, False), periodic=True) return serial, chrono, indicator_led
def readsens(self): self.raw = self.acc.acceleration( ) # Devuelve tuple con aceleracion en tres ejes (G) print("Aceleracion-> X:%fG Y:%fG Z:%fG" % (self.raw[0], self.raw[1], self.raw[2])) #Cálculos #if (self.raw[0] > 2.1) or (self.raw[1] > 2.1) or (self.raw[2] > 2.1): # print("Enviando datos") # XR=int(self.raw[0]*10000).to_bytes(2,'little') # YR=int(self.raw[1]*10000).to_bytes(2,'little') # ZR=int(self.raw[2]*10000).to_bytes(2,'little') # XL=int(self.last[0]*10000).to_bytes(2,'little') # YL=int(self.last[1]*10000).to_bytes(2,'little') # ZL=int(self.last[2]*10000).to_bytes(2,'little') # data = XR+YR+ZR+XL+YL+ZL # _thread.start_new_thread(self.send,data) # Se crea un hilo para el envío de valores self._compare_update() alarmaPub = Timer.Alarm(self.readsens(), 10, periodic=False)
def __init__(self, mqtt): """ Constructor Args: mqtt: MQTT object to handle mqtt network initialization if WiFi connection succeeds """ self.mqtt = mqtt self.wlan = WLAN(mode=WLAN.STA) self.nets = self.wlan.scan() self.connected = False #Set up 1 second connection test timer Timer.Alarm(self.connection_test, 1, periodic=True) #Connect Wifi _thread.start_new_thread(self.connect, ())
def create_thread(self, name, handler, **kwargs): if name in self.threads: raise Exception("Thread {} already exists".format(name)) def thread_handler(arg=None): try: if arg is None: handler() else: handler(arg) except Exception as e: log_message("{} Thread Failed: {}".format(name, e)) time.sleep(5) reset() thread = Timer.Alarm(handler=thread_handler, **kwargs) self.threads[name] = thread
def __init__(self, Kp, Ki, Kd, Delta_T, Encodeur_Mot, Moteur_Pont_H): self.Kp = Kp self.Ki = Ki self.Kd = Kd self.Delta_T = Delta_T self.Encodeur_Mot = Encodeur_Mot self.Moteur_Pont_H = Moteur_Pont_H self.ticks_voieA = 0 # Retour encodeur voie A self.ticks_voieB = 0 # Retour encodeur voie B self.somme_erreur = 0.0 self.erreur_precedente = 0.0 self.delta_erreur = 0.0 self.consigne = 0.0 # Consigne initiale de vitesse de rotation du moteur self.alarm = Timer.Alarm(self.IT_Moteur_correcteur_pid, ms=self.Delta_T, periodic=True)
def __init__(self, dac, int_mode=True, debug=False): """Constructor. Args: dac: a DAC object. int_mode: True for interrupt mode. debug: True for debug mode. """ self.dac_ = dac self.debug_ = debug self.buf_size_ = self.HZ * 2 self.buf_ = [0.0] * self.buf_size_ self.head_ = 0 # Next to pop self.tail_ = 0 # Next to push self.us_ = int(1000000 / self.HZ) if int_mode: self.timer_ = Timer.Alarm(self.hz, us=self.us_, periodic=True)
def MQTT_Setup(self): # Connect to a mqtt server self.id = NvsExtract(ID).retval() self.client = MQTTClient(str(self.id), str(NvsExtract(M_SERVER).retval()), port=int(NvsExtract(M_PORT).retval())) self.client.connect() print("MQTT Connected") self.Sensor_Setup() if self.active == 1: # alarm basically used for callbacks to prevent polling print("alarm") if (self.tFrequency): pub_t1 = Timer.Alarm(self.temp_publish, float(self.tFrequency), arg=1, periodic=True) time.sleep(0.1) if (self.tFrequency): pub_t2 = Timer.Alarm(self.temp_publish, float(self.tFrequency), arg=2, periodic=True) time.sleep(0.1) if (self.altFrequency): pub_alt = Timer.Alarm(self.alt_publish, float(self.altFrequency), arg=self.alt_sensor.altitude(), periodic=True) time.sleep(0.1) if (self.acclFrequency): pub_accl1 = Timer.Alarm(self.accl_publish, float(self.acclFrequency), arg=1, periodic=True) time.sleep(0.1) if (self.acclFrequency): pub_accl2 = Timer.Alarm(self.accl_publish, float(self.acclFrequency), arg=2, periodic=True) time.sleep(0.1) if (self.lightFrequency): pub_light = Timer.Alarm(self.light_publish, float(self.lightFrequency), arg=self.light_sensor.light(), periodic=True) time.sleep(0.1)
def __init__(self, debug=False): """Constructor.""" self.debug_ = debug self.lora_ = LoRa(mode=LoRa.LORA, region=LoRa.US915, power_mode=LoRa.ALWAYS_ON, tx_power=20, # 5~20 preamble=8, # default: 8 sf=7, # 7~12. Higher ==> Longer coding_rate=LoRa.CODING_4_8, # 4_8 is most stable. bandwidth=LoRa.BW_125KHZ) # create a raw LoRa socket self.sock_ = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.sent_in_second_ = 0 # number of packet sent in this second self.second_ = Timer.Alarm(self.second, s=1, periodic=True) # To count how long will we take to send out a packet. self.chrono_ = Timer.Chrono()
def button_handler(self, pin): if self.debounce_timer.read_ms() >= 10: # 10 ms software switch debounce self.debounce_timer.reset() value = pin.value() if value == 1: # Button pressed if self.config_enabled: self.config_press = Timer.Alarm(self.start_config, s=2.5, periodic=False) self.reboot_timer.reset() elif value == 0: # Button released # Cancel alarm to enter config, since button was not held for 2.5 seconds continuously if self.config_press is not False: self.config_press.cancel() # If button was pressed and released within 1.5 seconds, then reboot the device if self.reboot_timer.read() < 1.5: try: # if sd card failed to mount handle exception thrown in logger self.logger.info("Button press - rebooting...") except Exception as e: pass reset()
def __init__(self): Thing.__init__(self, 'urn:dev:ops:my-pysense', 'My PySense', [ 'Temperature', 'Humidity', 'Pressure', 'Luminance', 'Accelerometer' ], 'A Sensor Shield') self.seconds = 0 self.temperature = Value(0.0) self.humidity = Value(0.0) self.light = lt.light()[0] self.accelaration_0 = li.acceleration()[0] self.accelaration_1 = li.acceleration()[1] self.accelaration_2 = li.acceleration()[2] self.roll = li.roll() self.pitch = li.pitch() self.__alarm = Timer.Alarm(self._seconds_handler, s=10, periodic=True) #self._alarm = Timer.Alarm(updateMemPycom, 1, arg=None, periodic=True) self.add_property( Property( self, 'temperature', self.temperature, #, self.updateTemperature), metadata={ '@type': 'Temperature', 'title': 'Temperature', 'type': 'number', 'description': 'The temperature sensor value', })) self.add_property( Property(self, 'humidity', self.humidity, metadata={ '@type': 'Humidity', 'title': 'Humidity', 'type': 'number', 'description': 'The humidity sensor value', }))