def _update_last_activity(self, direction): self._last_activity_lock.acquire() if direction == LA_OUT or direction == LA_BOTH: self._last_activity_out = timers.now() elif direction == LA_IN or direction == LA_BOTH: self._last_activity_in = timers.now() self._last_activity_lock.release()
def _do_loop(self): should_reconnect = False while True: try: self._read_packet() self._message_retry_check() if timers.now() > self._last_activity_out + self.keepalive*1000: print_d("send ping tim_out") self._send_pingreq() except TimeoutError: if timers.now() > self._last_activity_in + self.keepalive*1500: print_d("la + ka", self._last_activity_in + self.keepalive) # reconnect should_reconnect = True else: print_d("send ping tim_in") self._send_pingreq() except IOError: # reconnect should_reconnect = True if should_reconnect: should_reconnect = False if self._state == mqtt_cs_reconnecting: self._reconnection_event.wait() else: self._state = mqtt_cs_disconnected self.reconnect()
def _update_last_activity(self, direction): self._last_activity_lock.acquire() if direction == LA_OUT or direction == LA_BOTH: self._last_activity_out = timers.now() if direction == LA_IN or direction == LA_BOTH: self._last_activity_in = timers.now() self._last_activity_lock.release()
def _handle_publish(self): header = self._in_packet.command message = MQTTMessage() message.dup = (header & 0x08)>>3 message.qos = (header & 0x06)>>1 message.retain = (header & 0x01) message.topic, c_pos = self._unpack_str16(0) if len(message.topic) == 0: raise MQTTProtocolError if message.qos > 0: message.mid, c_pos = _unpack16(self._in_packet.packet, c_pos) message.payload = str(self._in_packet.packet[c_pos:]) message.timestamp = timers.now() if message.qos == 0: self._in_packet.data['message'] = message self._in_packet.data['return_code'] = MQTT_ERR_SUCCESS elif message.qos == 1: self._send_puback(message.mid) self._in_packet.data['message'] = message self._in_packet.data['return_code'] = MQTT_ERR_SUCCESS elif message.qos == 2: self._send_pubrec(message.mid) print_d("pubrec sent",message.mid) message.state = mqtt_ms_wait_for_pubrel self._in_message_lock.acquire() self._in_messages.append(message) self._in_message_lock.release() self._in_packet.data['return_code'] = MQTT_ERR_SUCCESS else: raise MQTTProtocolError
def _handle_publish(self): header = self._in_packet.command message = MQTTMessage() message.dup = (header & 0x08) >> 3 message.qos = (header & 0x06) >> 1 message.retain = (header & 0x01) message.topic, c_pos = self._unpack_str16(0) if len(message.topic) == 0: raise MQTTProtocolError if message.qos > 0: message.mid, c_pos = _unpack16(self._in_packet.packet, c_pos) message.payload = str(self._in_packet.packet[c_pos:]) message.timestamp = timers.now() if message.qos == 0: self._in_packet.data['message'] = message self._in_packet.data['return_code'] = MQTT_ERR_SUCCESS elif message.qos == 1: self._send_puback(message.mid) self._in_packet.data['message'] = message self._in_packet.data['return_code'] = MQTT_ERR_SUCCESS elif message.qos == 2: self._send_pubrec(message.mid) print_d("pubrec sent", message.mid) message.state = mqtt_ms_wait_for_pubrel self._in_message_lock.acquire() self._in_messages.append(message) self._in_message_lock.release() self._in_packet.data['return_code'] = MQTT_ERR_SUCCESS else: raise MQTTProtocolError
def is_warmed_up(): _lock.acquire() if timers.now() - _since > 60000 and not _lowpower: ret = True else: ret = False _lock.release() return ret
def scan_report_cb(data): global scanned_list scanned_time = int(timers.now() / 1000) rssi = -int(data[2]) data_save = { "identifier": data[4], "timestamp": scanned_time, "rssi": rssi } scanned_list.append(data_save)
def _breconnect_cb(self, _): tnow = timers.now() tdiff = tnow - self.last_reconnection_try if tdiff > 10000: psw = self.create_jwt() # get timestamp from a reliable source else: psw = self.create_jwt(timestamp_diff = (tdiff // 1000)) self.last_reconnection_try = tnow mqtt.Client.set_username_pw(self, 'unused', password=psw)
def pressed(): print('publish random sample...') thing.mqtt.publish( "dev/sample", json.dumps({ 'Device ID': thing_conf['thingname'], 'Time': timers.now(), 'Humidity': random(0, 50), 'Temperature': random(0, 100) }))
def _writeloop_htbm(self): _last_htb = timers.now() while True: while self.reconnecting: sleep(1000) try: try: timeout = 1000 * self.heartbeat - (timers.now() - _last_htb) if timeout <= 0: raise QueueEmpty msg = self.wq.get(timeout=timeout) except QueueEmpty: self._send({"cmd": "HTBM"}) _last_htb = timers.now() else: self._send(msg) except Exception as e: self.log("Exception in writeloop+htbm", e) self._reconnect()
def _perform_reading(self): """Perform a single-shot reading from the sensor and fill internal data structure for calculations""" if timers.now() - self._last_reading < self._min_refresh_time: return # turn on temp oversample & pressure oversample self._write(_BME680_REG_CTRL_MEAS, [(self._temp_oversample << 5) | (self._pressure_oversample << 2)]) # turn on humidity oversample self._write(_BME680_REG_CTRL_HUM, [self._humidity_oversample]) # set filter self._write(_BME680_REG_CONFIG, [self._filter << 2]) # set heater self._write(_BME680_BME680_RES_WAIT_0, [self._calc_heater_duration(150)]) self._write(_BME680_BME680_RES_HEAT_0, [self._calc_heater_resistance(300)]) # gas measurements enabled self._write(_BME680_REG_CTRL_GAS, [_BME680_RUNGAS]) ctrl = self._read_byte(_BME680_REG_CTRL_MEAS) ctrl = (ctrl & 0xFC) | 0x01 # enable single shot! self._write(_BME680_REG_CTRL_MEAS, [ctrl]) new_data = False while not new_data: data = self._read(_BME680_REG_MEAS_STATUS, 15) new_data = data[0] & 0x80 != 0 sleep(5) self._last_reading = timers.now() self._adc_pres = _read24(data[2:5]) / 16 self._adc_temp = _read24(data[5:8]) / 16 self._adc_hum = struct.unpack('>H', bytes(data[8:10]))[0] self._adc_gas = int(struct.unpack('>H', bytes(data[13:15]))[0] / 64) self._gas_range = data[14] & 0x0F var1 = (self._adc_temp / 8) - (self._temp_calibration[0] * 2) var2 = (var1 * self._temp_calibration[1]) / 2048 var3 = ((var1 / 2) * (var1 / 2)) / 4096 var3 = (var3 * self._temp_calibration[2] * 16) / 16384 self._t_fine = int(var2 + var3)
def publish(self, topic, payload=None, qos=0, retain=False): """ .. method:: publish(topic, payload=None, qos=0, retain=False) Publishes a message on a topic. This causes a message to be sent to the broker and subsequently from the broker to any clients subscribing to matching topics. * *topic* is the topic that the message should be published on. * *payload* is the actual message to send. If not given, or set to None a zero length message will be used. * *qos* is the quality of service level to use. * *retain*: if set to true, the message will be set as the "last known good"/retained message for the topic. It returns the mid generated for the message to give the possibility to set a callback precisely for that message. """ local_mid = self._mid_generate() if qos == 0: self._send_publish(local_mid, topic, payload, qos, retain, False) return local_mid else: message = MQTTMessage() message.timestamp = timers.now() message.mid = local_mid message.topic = topic if payload is None or len(payload) == 0: message.payload = None else: message.payload = payload message.qos = qos message.retain = retain message.dup = False self._out_message_lock.acquire() self._out_messages.append(message) if qos == 1: message.state = mqtt_ms_wait_for_puback elif qos == 2: message.state = mqtt_ms_wait_for_pubrec self._out_message_lock.release() self._send_publish(message.mid, message.topic, message.payload, message.qos, message.retain, message.dup) return local_mid
def _do_loop(self): should_reconnect = False while True: try: self._read_packet() self._message_retry_check() if timers.now( ) > self._last_activity_out + self.keepalive * 1000: print_d("send ping tim_out") self._send_pingreq() except TimeoutError: if timers.now( ) > self._last_activity_in + self.keepalive * 1500: print_d("la + ka", self._last_activity_in + self.keepalive) # reconnect should_reconnect = True else: print_d("send ping tim_in") self._send_pingreq() except IOError: # reconnect should_reconnect = True except MQTTError: should_reconnect = True if self._is_closed: print_d("exiting...") break elif should_reconnect: should_reconnect = False if self._state == mqtt_cs_reconnecting: self._reconnection_event.wait() else: self._state = mqtt_cs_disconnected self.reconnect()
def _run(arg): # refresh while True: _lock.acquire() try: if not _lowpower: _update() else: _since = timers.now() except Exception as e: print("Air Exc:", e) finally: _lock.release() sleep(_AIR_UPDATE)
def _handle_pubrec(self): if self._in_packet.remaining_length != 2: raise MQTTProtocolError mid, z = _unpack16(self._in_packet.packet,0) print_d("Rec PUBREC mid:",mid) self._out_message_lock.acquire() for m in self._out_messages: if m.mid == mid: m.state = mqtt_ms_wait_for_pubcomp m.timestamp = timers.now() self._out_message_lock.release() return self._send_pubrel(mid, False) self._out_message_lock.release() self._in_packet.data['return_code'] = MQTT_ERR_SUCCESS
def _handle_pubrec(self): if self._in_packet.remaining_length != 2: raise MQTTProtocolError mid, z = _unpack16(self._in_packet.packet, 0) print_d("Rec PUBREC mid:", mid) self._out_message_lock.acquire() for m in self._out_messages: if m.mid == mid: m.state = mqtt_ms_wait_for_pubcomp m.timestamp = timers.now() self._out_message_lock.release() return self._send_pubrel(mid, False) self._out_message_lock.release() self._in_packet.data['return_code'] = MQTT_ERR_SUCCESS
def _message_retry_check_actual(self, messages, lock): lock.acquire() now = timers.now() for m in messages: if m.timestamp + self._message_retry < now: if m.state == mqtt_ms_wait_for_puback or m.state == mqtt_ms_wait_for_pubrec: m.timestamp = now m.dup = True self._send_publish(m.mid, m.topic, m.payload, m.qos, m.retain, m.dup) elif m.state == mqtt_ms_wait_for_pubrel: m.timestamp = now m.dup = True self._send_pubrec(m.mid) elif m.state == mqtt_ms_wait_for_pubcomp: m.timestamp = now m.dup = True self._send_pubrel(m.mid, True) lock.release()
def check_terminal(s): global start_check, count_check while s.available() > 0: c = s.read()[0] if c == __ORD('+'): t = timers.now() count_check += 1 if count_check == 1: start_check = t if t - start_check < 1000: if count_check == 3: count_check = 0 return True else: start_check = t count_check = 1 else: count_check = 0 return False
def start(): thread(_run, "AirQuality Task") _since = timers.now()
def connect(self, port=8883): self.last_reconnection_try = timers.now() mqtt.Client.set_username_pw(self, 'unused', password=self.create_jwt()) mqtt.Client.connect(self, self.endpoint, 60, port=port, ssl_ctx=self.ssl_ctx, breconnect_cb=self._breconnect_cb, aconnect_cb=self._aconnect_cb)
for retry in range(15): try: device.connect() break except Exception as e: print("connecting...", e) else: print("Failed - reset!") mcu.reset() print("connected.") last_time = 0 last_time_debug = 0 while True: sleep(1000) now_time = timers.now() if now_time - last_time < 5000: continue last_time = now_time sigma = accel.get_sigma() if sigma < 0.1: low_power = True else: low_power = False if polaris.isBatteryBackup(): airsensor.set_lowpower(low_power) ts = modem.rtc() print("modem RTC =", ts)
def _connect(self, host, keepalive, port=PORT, ssl_ctx=None, breconnect_cb=None, aconnect_cb=None, sock_keepalive=None): self._before_reconnect = breconnect_cb self._after_connect = aconnect_cb self._host = host self._port = port ip = __default_net["sock"][0].gethostbyname(host) self._ssl_ctx = ssl_ctx if ssl_ctx is None: self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: self._sock = ssl.sslsocket(ctx=ssl_ctx) try: self._sock.settimeout(keepalive*1000) except Exception as e: print(e) # no timeout pass if sock_keepalive and len(sock_keepalive) == 3: try: self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) except Exception as e: print(e) # no keepalive pass try: self._sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, sock_keepalive[0]) except Exception as e: print(e) # no keepalive pass try: self._sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, sock_keepalive[1]) except Exception as e: print(e) # no keepalive pass try: self._sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, sock_keepalive[2]) except Exception as e: print(e) # no keepalive pass try: self._sock.connect((ip,port)) except Exception as e: self._sock.close() raise e # protocol_name(str) + protocol_level + flags + keepalive + client_id(str) remaining_length = 2+4 + 1+1+2 + 2+len(self._client_id) connect_flags = 0 if self.clean_session: connect_flags = connect_flags | 0x02 if self._will_topic: if self._will_payload is not None: remaining_length = remaining_length + 2+len(self._will_topic) + 2+len(self._will_payload) else: remaining_length = remaining_length + 2+len(self._will_topic) + 2 connect_flags = connect_flags | 0x04 | ((self._will_qos & 0x03) << 3) | ((self._will_retain & 0x01) << 5) if self._username: remaining_length = remaining_length + 2+len(self._username) connect_flags = connect_flags | 0x80 if self._password: connect_flags = connect_flags | 0x40 remaining_length = remaining_length + 2+len(self._password) packet = bytearray() #fixed header packet.append(CONNECT) self._pack_remaining_length(packet, remaining_length) # variable header self._pack_str16(packet,PROTOCOL_NAMEv311) # protocol name packet.append(MQTTv311) # protocol level packet.append(connect_flags) _append16(packet, keepalive) self._pack_str16(packet, self._client_id) if self._will_topic: self._pack_str16(packet, self._will_topic) # CHECK!! if self._will_payload: self._pack_str16(packet, self._will_payload) if self._username: self._pack_str16(packet, self._username) if self._password: self._pack_str16(packet, self._password) self.keepalive = keepalive self._sock.sendall(packet) self._handle_connack() self._update_last_activity(LA_BOTH) if self._after_connect is not None: self._after_connect(self) rc = 0 # code below for reconnection # at the moment rc is always set to None by self._send_publish: useless self._out_message_lock.acquire() for m in self._out_messages: m.timestamp = timers.now() if m.qos == 0: rc = self._send_publish(m.mid, m.topic, m.payload, m.qos, m.retain, m.dup) if rc != 0: self._out_message_lock.release() return rc elif m.qos == 1: if m.state == mqtt_ms_publish: m.state = mqtt_ms_wait_for_puback rc = self._send_publish(m.mid, m.topic, m.payload, m.qos, m.retain, m.dup) if rc != 0: self._out_message_lock.release() return rc elif m.qos == 2: if m.state == mqtt_ms_publish: m.state = mqtt_ms_wait_for_pubrec rc = self._send_publish(m.mid, m.topic, m.payload, m.qos, m.retain, m.dup) if rc != 0: self._out_message_lock.release() return rc elif m.state == mqtt_ms_resend_pubrel: m.state = mqtt_ms_wait_for_pubcomp rc = self._send_pubrel(m.mid, m.dup) if rc != 0: self._out_message_lock.release() return rc self._out_message_lock.release() return MQTT_ERR_SUCCESS
################################################################################ # Timers Basics # # Created by VIPER Team 2015 CC # Authors: G. Baldi, D. Mazzei ################################################################################ import timers import streams #create a serial port with default parameters streams.serial() #create a new timer t=timers.timer() #start the timer t.start() minutes=0 while True: if t.get()>= 60000: #check if 60 seconds are passed t.reset() #timer can be reset minutes +=1 seconds=t.get()//1000 print("time is:", minutes,":",seconds) #just print the current value since timer starts or last reset print("System time is:", timers.now(), "(millis)") #timers.now() gives the system time in milliseconds since program starts print() sleep(500) #run every 500 millisec
# Authors: G. Baldi, D. Mazzei ################################################################################ import timers import streams # create a serial port with default parameters streams.serial() # create a new timer t = timers.timer() # start the timer t.start() minutes = 0 while True: if t.get() >= 60000: #check if 60 seconds are passed t.reset() #timer can be reset minutes += 1 seconds = t.get() // 1000 print( "time is:", minutes, ":", seconds) #just print the current value since timer start or last reset print( "System time is:", timers.now(), "(millis)" ) #timers.now() gives the system time in milliseconds since program start print() sleep(500) #run every 500 millisec
def _connect(self, host, keepalive, port=PORT, ssl_ctx=None, breconnect_cb=None, aconnect_cb=None, sock_keepalive=None): self._before_reconnect = breconnect_cb self._after_connect = aconnect_cb self._host = host self._port = port ip = __default_net["sock"][0].gethostbyname(host) self._ssl_ctx = ssl_ctx if ssl_ctx is None: self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: self._sock = ssl.sslsocket(ctx=ssl_ctx) try: self._sock.settimeout(keepalive * 1000) except Exception as e: print(e) # no timeout pass if sock_keepalive and len(sock_keepalive) == 3: try: self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) except Exception as e: print("Ignoring socket options", e) # no keepalive pass try: self._sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, sock_keepalive[0]) except Exception as e: print("Ignoring socket options", e) # no keepalive pass try: self._sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, sock_keepalive[1]) except Exception as e: print("Ignoring socket options", e) # no keepalive pass try: self._sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, sock_keepalive[2]) except Exception as e: print("Ignoring socket options", e) # no keepalive pass try: self._sock.connect((ip, port)) except Exception as e: self._sock.close() raise e # protocol_name(str) + protocol_level + flags + keepalive + client_id(str) remaining_length = 2 + 4 + 1 + 1 + 2 + 2 + len(self._client_id) connect_flags = 0 if self.clean_session: connect_flags = connect_flags | 0x02 if self._will_topic: if self._will_payload is not None: remaining_length = remaining_length + 2 + len( self._will_topic) + 2 + len(self._will_payload) else: remaining_length = remaining_length + 2 + len( self._will_topic) + 2 connect_flags = connect_flags | 0x04 | ( (self._will_qos & 0x03) << 3) | ( (self._will_retain & 0x01) << 5) if self._username: remaining_length = remaining_length + 2 + len(self._username) connect_flags = connect_flags | 0x80 if self._password: connect_flags = connect_flags | 0x40 remaining_length = remaining_length + 2 + len(self._password) packet = bytearray() #fixed header packet.append(CONNECT) self._pack_remaining_length(packet, remaining_length) # variable header self._pack_str16(packet, PROTOCOL_NAMEv311) # protocol name packet.append(MQTTv311) # protocol level packet.append(connect_flags) _append16(packet, keepalive) self._pack_str16(packet, self._client_id) if self._will_topic: self._pack_str16(packet, self._will_topic) # CHECK!! if self._will_payload: self._pack_str16(packet, self._will_payload) if self._username: self._pack_str16(packet, self._username) if self._password: self._pack_str16(packet, self._password) self.keepalive = keepalive self._sock.sendall(packet) self._handle_connack() self._update_last_activity(LA_BOTH) if self._after_connect is not None: self._after_connect(self) rc = 0 # code below for reconnection # at the moment rc is always set to None by self._send_publish: useless self._out_message_lock.acquire() for m in self._out_messages: m.timestamp = timers.now() if m.qos == 0: rc = self._send_publish(m.mid, m.topic, m.payload, m.qos, m.retain, m.dup) if rc != 0: self._out_message_lock.release() return rc elif m.qos == 1: if m.state == mqtt_ms_publish: m.state = mqtt_ms_wait_for_puback rc = self._send_publish(m.mid, m.topic, m.payload, m.qos, m.retain, m.dup) if rc != 0: self._out_message_lock.release() return rc elif m.qos == 2: if m.state == mqtt_ms_publish: m.state = mqtt_ms_wait_for_pubrec rc = self._send_publish(m.mid, m.topic, m.payload, m.qos, m.retain, m.dup) if rc != 0: self._out_message_lock.release() return rc elif m.state == mqtt_ms_resend_pubrel: m.state = mqtt_ms_wait_for_pubcomp rc = self._send_pubrel(m.mid, m.dup) if rc != 0: self._out_message_lock.release() return rc self._out_message_lock.release() return MQTT_ERR_SUCCESS
print("Failed connect...", e) else: raise TimeoutError print("Device is connected") polaris.ledGreenOn() # start the device device.run() sfw.kick() print("Device is up and running") # if not registered, register device to Fortebit Cloud if not cloud.isRegistered(device, email): sfw.kick() retry = timers.now() print("Device is not registered, register device...") while timers.now() - retry < 60000: if cloud.register(device, email): sfw.kick() if cloud.isRegistered(device, email): break if not device.is_connected(): raise ConnectionError sleep(5000) print("Retry device registration...") else: raise TimeoutError sfw.kick() print("Device is registered")
def _log(self, *args): print(timers.now(), *args)