def get_data(): url = "http://air4thai.pcd.go.th/webV2/station.php?station=68t" data = requests.get(url) data.encoding = "utf-8" # print(data.content) soup = BeautifulSoup(data.text, 'lxml') # print(soup.prettify()) x = soup.find_all("td") # <- ค่าที่ใช้ในการค้นหา data_payload = [] for i in range(49, 58): temp = str(x[i])[19:] temp = temp[:-5] data_payload.append(temp) data_payload[8] = data_payload[8][40:] data_payload[8] = data_payload[8][:-8] payload = ('{' + '\"{}\":\"{}\", '.format('date', data_payload[0]) + '\"{}\":\"{}\", '.format('pm25', data_payload[1]) + '\"{}\":\"{}\", '.format('pm10', data_payload[2]) + '\"{}\":\"{}\", '.format('O3', data_payload[3]) + '\"{}\":\"{}\", '.format('CO', data_payload[4]) + '\"{}\":\"{}\", '.format('NO2', data_payload[5]) + '\"{}\":\"{}\", '.format('SO2', data_payload[6]) + '\"{}\":\"{}\", '.format('AQI', data_payload[7]) + '\"{}\":\"{}\"'.format('quality', data_payload[8]) + '}') print(payload) mqtt.publish(payload)
def _turnOff(self, reason="none"): _log.debug(f'turning off ({reason})...') if (self.relayState != "Off"): self.relayCycles += 1 self.relayState = "Off" # THINK: avoid an mqtt message by listening to plug state? mqtt.publish("Off", self.topicPlugCommand)
def _turnOn(self): _log.debug("turning on...") if (self.relayState != "On"): self.relayCycles += 1 self.relayState = "On" # THINK: avoid an mqtt message by listening to plug state? mqtt.publish("On", self.topicPlugCommand)
def notification_handler(mac, handle, data): value = str(binascii.hexlify(data)) print("received notification from " + mac + " and handle: " + hex(handle) + " with data: " + value) #send this via MQTT mqtt.publish(TOPIC_DEVICE + "/" + mac + "/notify/" + hex(handle), value)
def close(self): if self.opponent != 0: mqtt.publish( json.dumps({ 'cmd': 'clo', 'from': self.id, 'to': self.opponent })) mqtt.disconnect()
def onWant(self, id): if not self.wants: print("Now I don't want to connect:", id) return if id == self.id: print("I's me. Ignoring") return self.opponent = id self.wants = False msg = {'cmd': 'est', 'from': self.id, 'to': id} mqtt.publish(json.dumps(msg))
def open_box(db: Session, Box_ID: str): db_box = db.query(models.Box).filter_by(Box_ID=Box_ID).first() if db_box: db_box.Box_State = True db_box.Box_isOccupied = True db.commit() db.flush() db.refresh(db_box) publish(db_box.Fridge_ID, Box_ID) print("open the box") return db_box
async def controlLoop(self, nursery): _log.info("starting control loop...") prevTemp = None ui.cls() print('Press Ctrl-C to stop...') while True: # keep track of how long all of this takes self.start = trio.current_time() #get new current temperature newTemp = sensor.tempF() if prevTemp == None: prevTemp = newTemp _log.info( f"curTemp= ({newTemp}) delta ({newTemp-prevTemp}) error ({self.setPoint - newTemp})" ) prevTemp = newTemp # call the pid to get new power level & set the output accordingly level = self.pid2level(self.pid(newTemp)) curP, curI, curD = self.pid.components _log.debug(f'pid components ({curP} {curI} {curD})') # set power if enabled if self.pid.auto_mode == False: level = 0 self.setPower(level, nursery) _log.debug(f'pid output level ({level})') # update the screen # FIXME: look into why updateScreen takes ~2 seconds!! # FIXME: convert it into a trio loop based on pwmPeriod # convert into a class, and just update its members here # have the trio loop to actually update the screen # need checkpoints along the way! or some such until understand why takes so long ui.updateScreen(self.setPoint, newTemp, level) # publish the payload payload = { "enabled": int(self.pid.auto_mode == True), "curTemp": newTemp, "setPoint": self.setPoint, "level": level * 10, # to give percent power, not tenths power "curP": curP, "curI": curI, "curD": curD } # log.debug(f"mqtt payload ({json.dumps(payload)})") mqtt.publish(json.dumps(payload), self.topicStatus) await self.sleepFor(self.pwmPeriod)
async def task_medium(self, queue): """Work done at a medium sample rate.""" while True: timestamp = await queue.get() queue.task_done() sensors = await asyncio.gather( self.production_totalwh(), self.production_history(), ) for sensor in sensors: mqtt.publish(sensor) self._influxdb_client.write_sma_sensors(sensor=sensor, timestamp=timestamp)
async def task_fast(self, queue): """Work done at a fast sample rate.""" while True: timestamp = await queue.get() queue.task_done() sensors = await asyncio.gather( self.production_snapshot(), self.status_snapshot(), ) for sensor in sensors: mqtt.publish(sensor) self._influxdb_client.write_sma_sensors(sensor=sensor, timestamp=timestamp)
def send_info(topic, seconds_to_sleep=1.0): old_state = None while True: # Sleep for a while time.sleep(seconds_to_sleep) current_state = interface.get_current_playing() if old_state != current_state: # Store current state old_state = current_state # Logging current state print(f'Current song: {current_state}') # Publish info publish(topic=topic, message=current_state)
def main(): # Read Timestamp and Data timestamp = utime.time() # Epoch UTC temperature = round(tmp102.read_temp('F'), 1) # Send Data to MQTT Broker mqtt.publish(broker, topic + '/temp/value', str(temperature)) # Log Timestamp and Data locally? log_local(timestamp, temperature) t = utime.localtime(timestamp) print('{:4d}-{:0>2d}-{:0>2d} {:0>2d}:{:0>2d}:{:0>2d} UTC {}'.format( t[0], t[1], t[2], t[3], t[4], t[5], temperature)) utime.sleep(1) # Give UART time to print text before going to sleep
async def task_slow(self, queue): """Work done at a slow sample rate.""" while True: timestamp = await queue.get() queue.task_done() sensors = await asyncio.gather( self.inverter_efficiency(), self.co2_avoided(), self.sun_irradiance(timestamp=timestamp), self.sun_position(), ) for sensor in sensors: mqtt.publish(sensor) self._influxdb_client.write_sma_sensors(sensor=sensor, timestamp=timestamp)
def process_measurement(packet): try: print('\nPacket:', packet) *data, checksum, tail = struct.unpack('<HHBBBs', packet) pm25 = data[0] / 10.0 pm10 = data[1] / 10.0 # device_id = str(data[2]) + str(data[3]) checksum_OK = checksum == (sum(data) % 256) tail_OK = tail == b'\xab' packet_status = 'OK' if (checksum_OK and tail_OK) else 'NOK' print('PM 2.5:', pm25, '\nPM 10:', pm10, '\nStatus:', packet_status) mqtt.publish({'pm25': pm25, 'pm10': pm10, 'status': packet_status}) except Exception as e: print('Problem decoding packet:', e) sys.print_exception(e)
def process(data): ev=aioblescan.HCI_Event() xx=ev.decode(data) sensor_mac = ev.retrieve("peer") xx=Fluke().decode(ev) if xx: #send results via MQTT mqtt.publish(TOPIC_PREFIX + "/" +sensor_mac[0].val+ "/data", json.dumps(xx)) pattern = '%s,sensor_mac=%s,sensor_type=%s,sensor_unit=%s,sensor_sw_version=%s,sensor_fw_version=%s sensor_value=%.'+str(xx['decimalPlaces'])+'f,sensor_rssi=%i,sensor_battery=%i,sensor_adv=%i %i' output = (pattern % (DEVICE_HOST,xx['mac'],xx['type'].replace(" ","\ "),xx['unit'].replace(" ","\ "),xx['sw_version'],xx['fw_version'],xx['value'],xx['rssi'],xx['battery'],xx['advertizing'],time.time()*1000000000)) mqtt.publish(TOPIC_PREFIX_INFLUX + "/" +xx['mac']+ "/data", output) output = (pattern % (DEVICE_HOST+"_kafka",xx['mac'],xx['type'].replace(" ","\ "),xx['unit'].replace(" ","\ "),xx['sw_version'],xx['fw_version'],xx['value'],xx['rssi'],xx['battery'],xx['advertizing'],time.time()*1000000000)) kafka_producer.publish(KAFKA_TOPIC,output)
def main(): #连接MQTT服务器 connect("45.32.7.217", 1883) #探测yeelight灯 yeelight = Yeelight() detection_thread = Thread(target=yeelight.bulbs_detection_loop) detection_thread.start() while True: str = input() if str: publish("chat", str) yeelight.RUNNING = False detection_thread.join()
async def midnight(self) -> None: """Task to wake up after midnight and update the solar data for the new day.""" while True: right_now = datetime.datetime.now() tomorrow = right_now + datetime.timedelta(days=1) midnight = datetime.datetime.combine(tomorrow, datetime.time(0, 1)) await asyncio.sleep((midnight - right_now).total_seconds()) await self.solar_data_update() retries = 0 while True: if await self.read_instantaneous(True): break if retries == 10: _LOGGER.error( f"No response from inverter(s) after {retries} retries, giving up for now" ) break _RETRY = 5 retries += 1 _LOGGER.debug( f"No response from inverter(s), will retry in {_RETRY} seconds" ) await asyncio.sleep(_RETRY) # fake daylight and update everything saved_daylight = self._daylight self._daylight = True await asyncio.gather(*(inverter.read_inverter_production() for inverter in self._inverters)) self._influxdb_client.write_history( await self.get_yesterday_production(), 'production/midnight') await self.update_total_production(daylight=self._daylight) sensors = await asyncio.gather( self.production_totalwh(), self.production_history(), ) for sensor in sensors: if sensor: mqtt.publish(sensor) self._influxdb_client.write_sma_sensors( sensor=sensor, timestamp=int(midnight.timestamp())) await asyncio.sleep(600) self._daylight = saved_daylight
def scan_devices(results={}, tries=0): # return if maximum number of connection tries is reached if tries >= BLE_CONNECTION_TRIES: error.error( "aborted BLE search because of multiple connection errors!") return results try: #start scanning for BLE devices ble_devices = adapter.scan() print("found devices" + str(ble_devices)) for device in ble_devices: #check if this devices was already completely scanned if not device['address'] in results: dev = adapter.connect(device['address']) chars = dev.discover_characteristics() #create dictionary for results of this particular device results[device['address']] = {} #store device name in results results[device['address']]['name'] = device['name'] results[device['address']]['uuids'] = [ str(uuid) for uuid in chars ] else: print("skip device " + device['address'] + " because it was already scanned completely!") #send results via MQTT mqtt.publish(TOPIC_DEVICE + "/scan", json.dumps(results)) print("finished BLE scan successfully!") except pygatt.exceptions.NotificationTimeout: reset_scan(results, tries, "BLE scan: received notification timeout!") except pygatt.exceptions.NotConnectedError: reset_scan(results, tries, "BLE scan: received not connected error!") except pygatt.exceptions.BLEError: reset_scan(results, tries, "BLE scan: received general BLE error!")
def processFritzboxMessages(mqtt, fritzbox, stopEvent): while not stopEvent.is_set(): try: msg = fritzbox.getQueue().get() if msg is None: fritzbox.getQueue().task_done() continue logging.debug("Fritzbox message: topic=%s value=%r" % (msg['topic'], msg['value'])) try: mqtt.publish(topic=msg['topic'], value=msg['value'], retain=msg['retain']) except Exception as e: logging.error('Could not push to MQTT:' + str(e)) fritzbox.getQueue().task_done() except Exception as e: logging.error('Error while sending from Fritz!Box to MQTT: ' + str(e)) logging.debug("Stopping MQTT message thread ...")
def wantGame(self, wants): self.wants = wants if wants: msg = {'cmd': 'want', 'id': self.id} mqtt.publish(json.dumps(msg))
import ble import mqtt from config import * try: ble.start() mqtt.start() finally: #notify MQTT subscribers that gateway is offline mqtt.publish(TOPIC_PREFIX, "offline") ble.stop()
def send(self, message): if self.opponent == 0: print("I don't have any opponent") return msg = {'cmd': 'msg', 'to': self.opponent, 'body': message} mqtt.publish(json.dumps(msg))
def callback(self, topic): mqtt.publish(topic, self.payload())
def mainloop(): """ Main loop, gets battery data, gets summary.py to do logging""" global prevbatvoltage summary = logsummary.summary for i in range(config['sampling']['samplesav']): # printvoltage = '' # for i in range(numcells+1): # printvoltage = printvoltage + str(round(batdata.batvolts[i],3)).ljust(5,'0') + ' ' # print (printvoltage) batdata.getraw() # if batdata.batvoltsav[numcells] >= 55.2 and prevbatvoltage < 55.2: # reset SOC counter? # print batdata.socadj/(float(summary['current']['dod'][3])*24.0) if batdata.batvoltsav[numcells] < config['battery']['vreset'] \ and prevbatvoltage >= config['battery']['vreset'] \ and summary['current']['dod'][3] != 0 \ and -batdata.currentav[-3] < config['battery']['ireset']: # reset SOC counter? if summary['current']['dod'][3] <= 0: socerr = 0 else: socerr = batdata.socadj / (float(summary['current']['dod'][3]) * 24.0) socerr = max(socerr, -0.01) socerr = min(socerr, 0.01) config['battery']['ahloss'] = config['battery']['ahloss'] - socerr / 2 editbatconfig('battery', 'ahloss', str(config['battery']['ahloss'])) batdata.soc = config['battery']['socreset'] batdata.socadj = batdata.soc summary['current']['dod'][3] = 0 else: batdata.soc = batdata.soc + batdata.batah batdata.socadj = batdata.socadj + batdata.batahadj prevbatvoltage = batdata.batvoltsav[numcells] batdata.ah = batdata.ah + batdata.batah batdata.inahtot = batdata.inahtot + batdata.inah batdata.pwrbattot = batdata.pwrbattot + batdata.pwrbat batdata.pwrintot = batdata.pwrintot + batdata.pwrin # check alarms alarms.scanalarms(batdata) # update summaries batdata.pwravailable, batdata.minmaxdemandpwr = solaravailable(batdata) logsummary.update(summary, batdata) currenttime = str(logsummary.currenttime) prevtime = str(logsummary.prevtime) if currenttime[10:12] != prevtime[10:12]: # new minute loadconfig() logsummary.updatesection(summary, 'hour', 'current') logsummary.updatesection(summary, 'alltime', 'current') logsummary.updatesection(summary, 'currentday', 'current') logsummary.updatesection(summary, 'monthtodate', 'current') logsummary.updatesection(summary, 'yeartodate', 'current') logsummary.writesummary() # mqtt.publish(client,"batpwrin",str(-summary['alltime']['power'][0])) # mqtt.publish(client,"batpwrout",str(summary['alltime']['power'][1])) # mqtt.publish(client,"solarpwr",str(-summary['alltime']['power'][2])) # print(exec("config["mqtt"]["payload"])) for item in config['mqtt']['payload']: config['mqtt']['payload'][item] = eval( config['mqtt']['payload'][item]) mqtt.publish(config['mqtt']['topic'], f"{config['mqtt']['payload']}".replace("'", '"')) # print(f'{config["mqtt"]["payload"]}') # mqtt.publish(client,"broome_st/energy",\ # f'{{"batpwrin":{-summary["alltime"]["power"][0]},\ #"batpwrpwrout":{summary["alltime"]["power"][1]},\ #"solarpwr":{-summary["alltime"]["power"][2]},\ #"batsoc":{round(100*(1-summary["current"]["dod"][0]/config["battery"]["capacity"]),1)}\ #}}') # mqtt.publish(client,"loadpwr",str(summary['current']['power'][3])) batdata.ah = 0.0 batdata.ahadj = 0.0 batdata.inahtot = 0.0 batdata.pwrbattot = 0.0 batdata.pwrintot = 0.0 for i in range(batdata.numiins): batdata.kWhin[i] = 0.0 batdata.kWhout[i] = 0.0 for i in range(numcells): batdata.baltime[i] = 0 if currenttime[8:10] != prevtime[8:10]: # new hour logsummary.starthour(summary) if currenttime[6:8] != prevtime[6:8]: # newday logsummary.startday(summary) if currenttime[4:6] != prevtime[4:6]: # new month logsummary.startmonth(summary) if currenttime[0:4] != prevtime[0:4]: # new year logsummary.startyear(summary)
def heating_off(): mqtt.publish("flat/heating/hallway/chState", "off") storage.set("ch_running", False) ws.push_state()
broker = db[b'mqtt_broker'].decode('utf-8') db.close() # Set basename for MQTT Topic topic = 'devices/' + unique_id # Initialize variables and assume power is on current_power_status = 1 last_power_status = 1 print('Monitoring Power...') while True: current_power_status = pin.value() if current_power_status != last_power_status: # Send power changes to MQTT server timestamp = utime.time() mqtt.publish(broker, topic + '/power/timestamp', str(timestamp)) # Epoch UTC mqtt.publish(broker, topic + '/power/value', str(current_power_status)) # Store power changes locally f = open('key_store.db', 'r+b') db = btree.open(f) db[str(timestamp)] = str(current_power_status) db.flush() db.close() last_power_status = current_power_status utime.sleep(0.5)
def heating_set_on(): mqtt.publish("flat/heating/hallway/sensorLed", "on") storage.set("ch_set_on", True) ws.push_state()
def read_value_handler(mac, source, value): print("read value: " + str(binascii.hexlify(value))) #send this via MQTT mqtt.publish(TOPIC_DEVICE + "/" + mac + "/read/" + source, binascii.hexlify(value))
def heating_set_off(): mqtt.publish("flat/heating/hallway/sensorLed", "off") storage.set("ch_set_on", False) heating_off() # This will also call ws.push_state()
def heating_on(): mqtt.publish("flat/heating/hallway/chState", "on") storage.set("ch_running", True) ws.push_state()