class BotController(object): def __init__(self, config): self.broker = config.get('mqtt_host') self.name = config.get('name') self.keysDB = Mongodb(**config.get('mongodb')) self.bots = {} self.config = config.get('webAPI') self.api = webAPI(self.config) def run(self): self.api.registerController() for bot, config in self.config.get('bots').items(): self.bots[bot] = Bot(bot, config, self.keysDB) r = self.api.subscribeBot(**self.bots[bot].credentials) log.debug("subscription response code = '{}".format(r)) self.mqtt = MQTT(self.broker, name=self.name, botController=self) def newCommand(self, command): log.debug('command = {}'.format(command)) botWebName = command.get('recipient') bot = self.keysDB.getBotName(botWebName) log.debug("webName= {}, bot= {}".format(botWebName, bot)) if bot: r = self.mqtt.publish(bot + '/command', str(command)) log.debug("response: '{}'".format(r)) else: log.error("BotWebName '{}' not found".format(botWebName)) def sendMessage(self, message, sender, recipientId): bot = self.keysDB.getBotName(sender) log.debug("sending message: {} {} {} {}".format( bot, sender, recipientId, message)) self.api.sendMessage(messageText=message, recipientId=recipientId, **self.bots[bot].credentials) def sendEvent(self, sender, message): for admin, adminId in self.bots[sender].admins.items(): log.debug("sending message: {} {} {} {}".format( sender, message, admin, adminId)) self.api.sendMessage(messageText=message, recipientId=adminId, **self.bots[sender].credentials) def updateDB(self, webName, credentials): for bot in self.bots: if self.bots[bot].webName == webName: self.keysDB.storeConfig(bot, webName, credentials) return ('Successfully updated config') return ( 'device not config for botCOntroller, See system administrator')
with open("humidity.txt", "a") as file: print("Writing into humidity.txt") file.write(msg.payload) file.write("\n") file.close() elif msg.topic == "pressure": with open("pressure.txt", "a") as file: print("Writing into pressure.txt") file.write(msg.payload) file.write("\n") file.close() else: print("Not a valid topic") # Publish a message - Client is connected mqttc.publish(user, "Getting started ...") mqttc.on_receive(on_message) localtime = time.asctime(time.localtime(time.time())) for topic in topic_list: mqttc.subscribe(topic) # Continue the network loop, exit when an error occurs with open(topic + ".txt", "a") as file: header = "-------------- Data for " + topic + ": " + localtime + " --------------" file.write(header) file.write("\n") mqttc.loop() # rc = 0 # while rc == 0:
#!/usr/bin/python from sense_hat import SenseHat from mqtt import MQTT import time import sys sense = SenseHat() mqtt = MQTT("lgvohswk", "VcimBX_iUvkb") sense.clear() try: while True: temp = sense.get_temperature() temp = round (temp, 1) print("Temperature C", temp) mqtt.publish("temperature", temp) #sense.show_message(str(temp)) humidity = sense.get_humidity() humidity = round (humidity,1) print("Humidity", humidity) mqtt.publish("humidity", humidity) pressure = sense.get_pressure() pressure = round (pressure,1) print("Pressure", pressure) mqtt.publish("pressure", pressure) time.sleep(1) except KeyboardInterrupt: pass
class Alarm(object): def __init__(self, name, device, passcode, mqtt_host, speed=115200, **kwargs): log.debug(kwargs) self.name = name self.passcode = passcode self.port = serial.serial_for_url(device, baudrate=speed, timeout=0) self.broker = mqtt_host self.dcs1500state = 'unknown' self.status = 'unknown' self.lastStatus = 'unknown' self.mqtt = MQTT(broker=self.broker, name=self.name, menu=self.command) def start(self): self.thread = Thread(name="alarm_monitor", target=self.__monitor) self.event = threading.Event() self.thread.start() self.__monitor() def stop(self): self.mqtt.loop_stop() self.mqtt.disconnect() self.event.set() def __readSerial(self): buffer_string = '' while not self.event.is_set(): self.event.wait(timeout=1.0) buffer_string = buffer_string + self.port.read( self.port.inWaiting()).decode(('utf-8')) if '\n' in buffer_string: timestamp = datetime.today().isoformat() lines = buffer_string.split('\n') last_received = lines[-2] # Last full line. buffer_string = lines[-1] # First part of next line. self.dcs1500state = last_received self.alarmTime = timestamp break def __get_status(self): """ Monitors serial port until there is a full update from the arduino.Monitors """ self.__readSerial() if self.dcs1500state[21:26] == 'Armed': self.status = 'ARMED' if self.dcs1500state[39] == 'A': self.status = 'TRIPPED' elif self.dcs1500state[1:3] == 'RA': self.status = 'ARMING' else: self.status = 'DISARMED' pass def __monitor(self): log.debug("started Monitor") while not self.event.is_set(): self.event.wait(timeout=1.0) self.__get_status() if self.status != self.lastStatus: self.sendEventNotification("alarm is {}, previously {}".format( self.status, self.lastStatus.lower())) log.info( "alarm status change to: {} previous status: {}".format( self.status, self.lastStatus)) self.lastStatus = self.status def __on(self): self.port.write(self.passcode.encode()) def __off(self): self.port.write(self.passcode.encode()) def get_status(self): return self.status def sendEventNotification(self, msg): message = { "recipientId": "admins", "sender": self.name, "message": msg } try: log.debug("publish {}/event msg: {}".format( self.name, str(message))) self.mqtt.publish(self.name + "/event", str(message)) except requests.exceptions.ConnectionError as e: log.warning("Connection Error: {}".format(e)) pass def command(self, cmd, respond): command = cmd.lower() if self.status == 'unknown': self.get_status() respond('connot process command at this time') elif command == 'off': if self.status != 'DISARMED': self.__off() respond('alarm turning off') else: respond('alarm already off') elif command == 'on': if self.status == 'DISARMED': self.__on() respond('alarm turning on') else: respond('alarm aLready on') elif command == 'hi': respond(self.get_status()) else: respond('invalid command')
while True: data = s.recv(1024) data = decrypt(data) # if no valid data was received if data == None: continue # print(data.hex(' ')) # check first two bytes of mac, they must be 0x17 and 0x00 mac = data[0:6] if mac[0] != 0x17 and mac[1] != 0x00: continue # battery state (percent) if data[10] > 0: mqtt.publish('sensor/0x%s/battery/state' % (mac.hex()), data[10]) # water usage, millilitres if data[11] == 2: # convert to litres litres = int.from_bytes(data[12:20], 'little') / 1000 mqtt.publish('sensor/0x%s/water/state' % (mac.hex()), litres) # mqtt.publish('water/%s/usage' % (mac.hex()), litres) # if data[9] != 0: # mqtt.publish('e7b4202e-0ced-11ec-ab05-fb55d0334872/led1/switch', 'ON') # else: # mqtt.publish('e7b4202e-0ced-11ec-ab05-fb55d0334872/led1/switch', 'OFF')
t_control.cooler.fanOff() else: t_control.cooler.fanOn() elif "target_temp" in topic: t_control.pid.target = float(msg) else: print("Unknown topic received") # setup subscriptions broker.setCallback(subCB) broker.subscribe("FAN") broker.subscribe("PID_P") broker.subscribe("PID_I") sleep(0.1) broker.subscribe("PID_I_SetValue") broker.subscribe("target_temp") count = 50 # main loop print("reached main loop") while True: print(od.measure(200)) # all repeating actions broker.publish("exp1.temperature",t_control.thermometer.read()) #testing disp.write("temperature: " + str(int(t_control.thermometer.read())),0,0) disp.write("Algae: " + "derp/mL",1,0) disp.plot((t_control.thermometer.read()-15)*6) broker.publish("exp1.P_value",t_control.pid.P_value) #testing broker.publish("exp1.I_value",t_control.pid.I_value) #testing sleep(10)
def on_input_change(self, signal): if (signal == self.strobe or (signal == self.input and self.auto.value >= 0.5)): MQTT.publish(self.name, self.input.value, True, True)
def first_eval(self): MQTT.publish(self.name, self.input.value, True, True)