def __init__(self): #Starts and connect MQTT client to AWS MQTT Broker self.mqtt = Mqtt() self.mqtt.connect() #Stats loading data self.loadData()
def __init__(self): self.__topic = "topic/audio_transmission" root_ca = "./certs/RootCA.pem" key = "./certs/xxxxxxxx-private.pem.key" cert = "./certs/xxxxxxxx-certificate.pem.crt" endpoint = "xxxxxxxxxxx-ats.iot.ap-northeast-1.amazonaws.com" self.__mqtt = Mqtt(root_ca, key, cert, endpoint)
async def __setup_mqtt(self): hw.log.debug("Setting up mqtt ...") if hw.MQTT and hw.WIFI: from mqtt import Mqtt mqtt = Mqtt(dev.opc) dev.OPERATORS.append(mqtt) dev.CONSUMERS.append(mqtt) dev.opc.set_mqtt(mqtt) mqtt.setup()
def setup_mqtt(): try: m = Mqtt(MQTT_CLIENT_NAME, MQTT_BROKER) m.connect() except OSError as ose: logger.print_error("MQTT Setup Failed!") raise return m
def __init__(self, configFilename): self.startTime = datetime.now() self.logger = self.getLogger() self.logger.info("Reading configuration file '%s'..." % configFilename) self.init(configFilename) self.terminated = False self.mqtt = Mqtt(self) self.createThreads() self._intervalDict = {} self.sensors = {}
def run_route_planner(): """Runs the whole program.""" # Initialize global settings and screen. settings = Settings() pygame.init() screen = pygame.display.set_mode( (settings.screen_width, settings.screen_height)) pygame.display.set_caption("Route Planner 1.1") # Make a next button. next_button = Button(settings, screen, "Next") # Hard coded map. world = World(settings.map_width, settings.map_height) """world.matrix = [["601000", "100100", "100010", "100001", "100000", "100000"], ["100000", "100000", "100100", "100000", "100000", "100000"], ["100000", "100000", "100000", "100000", "100000", "100000"], ["100000", "100000", "100000", "100000", "100000", "100000"], ["100000", "100000", "100000", "100000", "100000", "100000"], ["100000", "100000", "100000", "100000", "100000", "100000"]]""" world.matrix = [["601000", "500100", "310010", "610001", "600000", "610000"], ["530000", "400000", "310000", "510000", "530000", "100000"], ["100000", "100000", "100000", "530000", "620000", "100000"], ["100000", "100000", "100000", "100000", "100000", "100000"], ["100000", "100000", "100000", "100000", "100000", "100000"], ["100000", "100000", "100000", "100000", "100000", "100000"]] # Create nodes for the world matrix. nodes = Nodes(world.matrix) # Make a new robot instance. robot = Robot() # Init and subscribe to mqtt broker. mqtt = Mqtt(settings.broker, settings.get_client_id(), settings.username, settings.password, settings.topic) buttons = [] # Print out nodes to check if algoritm is correct. """ for node in nodes.nodes_dict: print(node + " : ", nodes.nodes_dict[node]) """ while True: # main loop rf.update_map(world.matrix, nodes, mqtt.msgs, robot) rf.check_events(settings, robot, buttons, next_button, mqtt) rf.update_robot_route(world.matrix, nodes.nodes_dict, robot) buttons = rf.update_screen(screen, settings, world.matrix, nodes, next_button, robot) """for node in nodes.nodes_dict: print(node + " : ", nodes.nodes_dict[node])""" # if no more tasks are left, the mission is complete. if len(robot.goals) == 0: print("Mission Complete!") mqtt.client.loop_stop() mqtt.client.disconnect() break
def transform(self, data): if self.counter == 0: print('main_state: mqtt/up') config = data['config'] broker_address = config.state['broker_address'] device_name = config.state['device_name'] main_topic = config.state['main_topic'] mqtt = Mqtt(device_name, main_topic) if mqtt.connect(broker_address): data['mqtt_server'] = mqtt return 'main/loop_once' else: self.counter += 1 if self.counter >= MAX_TRIES: config.delete() machine.reset()
class Job(): def __init__(self, commandList): self.__commandList = commandList config = json.load(open('./config.json', 'r')) logFile = "./log/{}".format(config["appName"]) logger = Logger(config["appName"], config["logLevel"], filename=logFile) port = 8883 self.__topic = config["topic"] self.__mqtt = Mqtt(logger, config["endPoint"], port, config["rootCA"], config["certificate"], config["privateKey"], config["clientId"]) self.__mqtt.subscribe(self.__topic + "/Request", self.__callback) self.__result = None self.__loop() def __callback(self, client, userdata, message): print(self) p = json.loads(message.payload) if ("command" in p): command = p["command"] param = None if ("param" in p): param = p["param"] for key in self.__commandList.keys(): if (command == key): self.__result = self.__commandList[key](param) return def __loop(self): while True: time.sleep(0.5) if (self.__result is None): continue payload = {"message": self.__result} self.__result = None self.__mqtt.publish(self.__topic + "/Response", json.dumps(payload))
class Todo: def __init__(self): self.mqtt = Mqtt() self.mqtt.set_on_message(self._on_message) def _on_message(self, mqtt, topic, msg): if msg == b'on': import wakeup wakeup.send() elif msg == b'off': pass else: pass gc.collect() def run(self): self.mqtt.start()
def main(): parametros = validacao_parametros() global dynamodb global mqtt mqtt = Mqtt(parametros['broker'], parametros['user'], parametros['password'], parametros['topic'], on_connect) dynamodb = Dynamo(parametros['dynamodb']) subscriber()
def setup(): host = 'iot' port = 1883 topics = [ "TEMP/TEMPSENSOR", "HUM/TEMPSENSOR", "HUM/#", "TEMP/#", "NIGHTLAMP2/state", "KINDLE/#", "phones/#", "printer/#", "LUX/state", "DESK/state" ] # CONFIG return Mqtt(host, port, topics, [to_influx], _json=False)
def __init__(self, commandList): self.__commandList = commandList config = json.load(open('./config.json', 'r')) logFile = "./log/{}".format(config["appName"]) logger = Logger(config["appName"], config["logLevel"], filename=logFile) port = 8883 self.__topic = config["topic"] self.__mqtt = Mqtt(logger, config["endPoint"], port, config["rootCA"], config["certificate"], config["privateKey"], config["clientId"]) self.__mqtt.subscribe(self.__topic + "/Request", self.__callback) self.__result = None self.__loop()
def __init__(self): self.wifi = Wifi( ssid=CONFIG["WIFI_SSID"], password=CONFIG["WIFI_PASSWORD"], gmt=CONFIG["GMT"], ) self.mqtt = Mqtt( ip=CONFIG["MQTT_IP"], user=CONFIG["MQTT_USER"], password=CONFIG["MQTT_PASS"], keepalive=CONFIG["MQTT_KEEPALIVE"], ) self.mqtt.set_last_will( topic=CONFIG["LW_TOPIC"], msg=ujson.dumps(CONFIG["LW_MSG_OFFLINE"]), retain=CONFIG["LW_RETAIN"], qos=CONFIG["LW_QOS"], ) self.dht22 = DHT22(Pin(CONFIG["DHT22_PIN"])) self.is_sending_synchronizate = False
class Producer(): def __init__(self): self.__topic = "$aws/rules/audio_transmission_rule/topic/audio_transmission" root_ca = "./certs/RootCA.pem" cert = "./certs/xxxxxxxxxx-certificate.pem.crt" key = "./certs/xxxxxxxxxx-private.pem.key" endpoint = "xxxxxxxxxxx-ats.iot.ap-northeast-1.amazonaws.com" self.__mqtt = Mqtt(root_ca, key, cert, endpoint) def send(self, data): now = datetime.now() # 時刻とデータの結合 ts = now.timestamp() ts = struct.pack('<d', ts) transfer_data = ts + data try: self.__mqtt.publish(self.__topic, transfer_data) print("publish {}byte".format(len(transfer_data))) except Exception as e: print("Exception: {}", e.args)
def main(): parametros = validacao_parametros() global mqtt global logs mqtt = Mqtt(parametros['broker'], parametros['user'], parametros['password'], parametros['topic']) logs = Logs(parametros['group'], parametros['stream']) scheduler = sched.scheduler(time.time, time.sleep) schedule_it(scheduler, int(parametros['messages']), int(parametros['seconds']), publisher) mqtt.connect() mqtt.client.loop_start() scheduler.run() mqtt.client.loop_stop() mqtt.client.disconnect()
def main(): # Fetch the arguments from command line args = build_argparser().parse_args() # Connect to the MQTT server and return MQTT client mqtt = Mqtt() mqtt.connect() # Perform inference on the input stream infer_on_stream(args, mqtt) mqtt.disconnect()
class Producer(): def __init__(self): self.__topic = "topic/audio_transmission" root_ca = "./certs/RootCA.pem" key = "./certs/xxxxxxxx-private.pem.key" cert = "./certs/xxxxxxxx-certificate.pem.crt" endpoint = "xxxxxxxxxxx-ats.iot.ap-northeast-1.amazonaws.com" self.__mqtt = Mqtt(root_ca, key, cert, endpoint) def send(self, data): now = datetime.now().strftime('%Y-%m-%dT%H:%M:%S') b64_data = base64.b64encode(data) raw_data = b64_data.decode() # デバッグ用にデータ削減 #raw_data = raw_data[0:40] payload = json.dumps({ "timestamp": now, "raw_data": raw_data }) self.__mqtt.publish(self.__topic, payload) print("publish {}byte".format(len(payload)))
# Ajout ou suppression du relay si POST confirm = form.getvalue("confirm") topic = form.getvalue("topic") idRelay = form.getvalue("idRelay") nameRelay = form.getvalue("nameRelay") brightness = form.getvalue("brightness") html = """<!DOCTYPE html> <head> <title>Config MQTT pour Home-Assistant</title> </head> <body> """ if confirm: Mqtt.publish(confirm, None, True) elif topic: html += '<br /><form action="/init.py" method="post">' html += "Confirmez-vous la suppression du topic: " + topic + " ?" html += '<input type="hidden" name="confirm" value="' + topic + '" />' html += '<input type="submit" name="suppr" value="Supprimer" />' html += "</form><br /><br /><hr>" elif idRelay and nameRelay: if re.match(r"^r[0-9]{2}$", idRelay) and not brightness or re.match(r"^d[0-9]c[0-9]$", idRelay) and brightness: topic = Constantes.mqttTopic + "/light/" + idRelay + "/config" payload = "{ \"~\": \"" + Constantes.mqttTopic + "/light/" + idRelay + "\"" # TODO payload += ", \"name\": \"" + nameRelay + "\"" payload += ", \"unique_id\": \"" + idRelay + "_light\"" payload += ", \"command_topic\": \"~/set\"" payload += ", \"state_topic\": \"~/state\"" payload += ", \"schema\": \"json\""
dis = Display(10, 10) bor = Board(10, 10) bor.fill(False) def abc(data): global bor bor.data = [(ord(d) > 128) for d in data] dr = Driver("192.168.1.214", 6454) #dr = Driver("xd-table.local", 6454) dr.callbacks.append(abc) #dr.callbacks.append(call) dr.start_listening() dr.calibrate() m = Manager(bor) mqtt = Mqtt("127.0.0.1", 1883, m, dr) #ui = UdpInterface(on_press, 4444) set_start = datetime.now() get_start = datetime.now() try: while not exit_flag: time.sleep(1.0 / set_hz) dt = (datetime.now() - set_start).total_seconds() set_start = datetime.now() if (datetime.now() - get_start).total_seconds() > (1.0 / get_hz): get_start = datetime.now() # dr.get_touchscreen() effect = m.get()
from mqtt import Mqtt from commands.temp import Temp from commands.cams import Cams from commands.cry import Cry from commands.set import Set from api import ApiServer from mail import MailServer from tg import Telegram from util import import_env, log if __name__ == "__main__": import_env() mqtt = Mqtt() telegram = Telegram() telegram.start() temp_command = Temp(telegram=telegram, mqtt=mqtt) cams_command = Cams(telegram=telegram) cry_command = Cry(telegram=telegram, mqtt=mqtt) set_command = Set(telegram=telegram, mqtt=mqtt) api_server = ApiServer(telegram=telegram) api_server.start() mail_server = MailServer() mail_server.start() try:
else: return tryDecode def mqtt2telegram(topic, payload): logging.debug('mqtt2telegram: ' + topic) topic = topic.replace('_', ' ') parser = getParser(topic) payload = parser(topic, payload) logging.debug('Sending to Telegram ...') msg = """<b>mqtt2telegram:</b> <i>{}</i> {} """.format(topic, payload) logging.info(msg) bot.sendMsgToOwner(msg) BROKERHOST = os.getenv('MQTTHOST') BROKERPORT = int(os.getenv('MQTTPORT')) USERNAME = os.getenv('MQTTUSERNAME') PASSWORD = os.getenv('MQTTPASSWORD') mqtt = Mqtt(BROKERHOST, BROKERPORT, USERNAME, PASSWORD) mqtt.setCallback(mqtt2telegram) mqtt2telegram('Status', 'Bot (re-)initialized!') mqtt.loop_forever() mqtt2telegram('Status', 'Bot shutdown ...')
panel_thread.start() fanout_thread = Fanout(cmd_queue, fanout_queues_list) fanout_thread.start() ctl_thread = ControlThread(logic_board_out, raw_bypass_queue, cmd_to_control_queue) ctl_thread.start() if 'link' in cfg and cfg['link']['url']: linker_thread = Linker(cfg['link']['url'], cmd_to_linker_queue) linker_thread.start() if 'mqtt' in cfg and cfg['mqtt']['url']: mqtt_thread = Mqtt(cfg['mqtt']['url'], cfg['mqtt']['port'], cfg['mqtt']['use_ssl'], cfg['mqtt']['validate_cert'], cfg['mqtt']['user'], cfg['mqtt']['passwd'], cmd_to_mqtt_queue, cmd_queue) mqtt_thread.start() panel_status_thread = PanelStatus(panel_in, cmd_queue, raw_bypass_queue) panel_status_thread.start() cron_thread = CronCommands(cmd_queue) cron_thread.start() sleep_thread = SleepThread(cmd_queue) sleep_thread.start() # webservice / flask app = Flask("SeviControl") app.logger.setLevel(logging.DEBUG)
def __init__(self): self.sensores = Sensores() self.sender = Sender() # self.database = DataBase() self.mqtt = Mqtt() self.Config = ConfigParser.ConfigParser()
import os import sys from mqtt import Mqtt BROKERHOST = os.getenv('MQTTHOST') BROKERPORT = int(os.getenv('MQTTPORT')) USERNAME = os.getenv('MQTTUSERNAME') PASSWORD = os.getenv('MQTTPASSWORD') mqtt = Mqtt(BROKERHOST, BROKERPORT, USERNAME, PASSWORD) mqtt.waitForConnection() mqtt.publish('failcloud/test/testPublish', 'hi hello')
import io, time, picamera import picamera.array import numpy as np # import cv2 from mqtt import Mqtt if __name__ == '__main__': from sys import argv def msg(msg): if msg == 'record': detected = True mqtt = Mqtt(*([msg, 'CCTV'] + argv[1:])) detected = False class DetectMotion(picamera.array.PiMotionAnalysis): def analyse(self, a): global detected a = np.sqrt( np.square(a['x'].astype(np.float)) + np.square(a['y'].astype(np.float)) ).clip(0, 255).astype(np.uint8) # If there're more than 15 vectors with a magnitude greater # than 80, then say we've detected motion if (a > 80).sum() > 15: detected = True stream = None outfile = None last_pos = 0
import uasyncio as asyncio from sensor import SensorProcess from consumer import DefaultConsumer import dev logging._level = logging.DEBUG opc = Controller() sp = SensorProcess() def_consumer = DefaultConsumer() ops = [] wifi = Wifi('ybb-home') ops.append(wifi) ops.append(SysOp(opc)) ops.append(def_consumer) mqtt = Mqtt(opc) ops.append(mqtt) opc.setup(ops) opc.set_mqtt(mqtt) consumers = [] consumers.append(def_consumer) consumers.append(mqtt) print(opc.commands.keys()) async def test(): await wifi.async_connect() print(mqtt.get_info()) mqtt.setup()
class Irrigate: def __init__(self, configFilename): self.startTime = datetime.now() self.logger = self.getLogger() self.logger.info("Reading configuration file '%s'..." % configFilename) self.init(configFilename) self.terminated = False self.mqtt = Mqtt(self) self.createThreads() self._intervalDict = {} self.sensors = {} def start(self, test=True): if self.cfg.mqttEnabled: self.logger.info("Starting MQTT...") self.mqtt.start() self.logger.debug("Starting worker threads...") for worker in self.workers: self.logger.info("Starting worker thread '%s'." % worker.getName()) worker.setDaemon(test) worker.start() self.logger.debug("Starting sensors...") for sch in self.cfg.schedules.values(): if sch.sensor != None: sensorHandler = sch.sensor.handler try: if not sensorHandler.started: self.logger.info("Starting sensor '%s'." % format(sensorHandler)) sensorHandler.start() self.sensors[sch.sensor.type] = sensorHandler except Exception as ex: self.logger.error("Error starting sensor '%s': '%s'." % (sch.sensor.type, format(ex))) self.logger.info("Starting timer thread '%s'." % self.timer.getName()) self.timer.start() def init(self, cfgFilename): self.cfg = config.Config(self.logger, cfgFilename) self.valves = self.cfg.valves self.q = queue.Queue() def createThreads(self): self.workers = [] for i in range(self.cfg.valvesConcurrency): worker = Thread(target=self.valveThread, args=()) worker.setDaemon(False) worker.setName("ValveTh%s" % i) self.workers.append(worker) self.timer = Thread(target=self.timerThread, args=()) self.timer.setDaemon(True) self.timer.setName("TimerTh") def evalSched(self, sched, timezone, now): todayStr = calendar.day_abbr[datetime.today().weekday()] if not todayStr in sched.days: return False lat, lon = self.cfg.getLatLon() if sched.seasons != None and not self.getSeason(lat) in sched.seasons: return False hours, minutes = sched.start.split(":") startTime = datetime.now() if sched.type == 'absolute': startTime = startTime.replace(hour=int(hours), minute=int(minutes), second=0, microsecond=0, tzinfo=pytz.timezone(timezone)) else: sun = Sun(lat, lon) if sched.type == 'sunrise': startTime = sun.get_local_sunrise_time().replace( second=0, microsecond=0, tzinfo=pytz.timezone(timezone)) elif sched.type == 'sunset': startTime = sun.get_local_sunset_time().replace( second=0, microsecond=0, tzinfo=pytz.timezone(timezone)) if hours[0] == '+': hours = hours[1:] startTime = startTime + timedelta(hours=int(hours), minutes=int(minutes)) if hours[0] == '-': hours = hours[1:] startTime = startTime - timedelta(hours=int(hours), minutes=int(minutes)) if startTime == now: return True return False def getSeason(self, lat): month = datetime.today().month season = None if lat >= 0: if 3 <= month <= 5: season = "Spring" elif 6 <= month <= 8: season = "Summer" elif 9 <= month <= 11: season = "Fall" elif month == 12 or month <= 2: season = "Winter" else: if 3 <= month <= 5: season = "Fall" elif 6 <= month <= 8: season = "Winter" elif 9 <= month <= 11: season = "Spring" elif month == 12 or month <= 2: season = "Summer" return season def valveThread(self): while not self.terminated: try: irrigateJob = self.q.get(timeout=5) if irrigateJob.valve.handled: self.logger.warning( "Valve '%s' already handled. Returning to queue in 1 minute." % (irrigateJob.valve.name)) time.sleep(61) self.q.put(irrigateJob) else: valve = irrigateJob.valve valve.handled = True self.logger.info( "Irrigation cycle start for valve '%s' for %s minutes." % (valve.name, irrigateJob.duration)) duration = timedelta(minutes=irrigateJob.duration) valve.secondsLast = 0 valve.secondsRemain = duration.seconds initialOpen = valve.secondsDaily sensorDisabled = False openSince = None startTime = datetime.now() while startTime + duration > datetime.now(): # The following two if statements needs to be together and first to prevent # the valve from opening if the sensor is disable. if irrigateJob.sensor != None and irrigateJob.sensor.handler.started: try: holdSensorDisabled = irrigateJob.sensor.handler.shouldDisable( ) if holdSensorDisabled != sensorDisabled: sensorDisabled = holdSensorDisabled self.logger.info( "Suspend set to '%s' for valve '%s' from sensor" % (sensorDisabled, valve.name)) except Exception as ex: self.logger.error( "Error probing sensor (shouldDisable) '%s': %s." % (irrigateJob.sensor.type, format(ex))) if not valve.open and not valve.suspended and not sensorDisabled: valve.open = True openSince = datetime.now() valve.handler.open() self.logger.info("Irrigation valve '%s' opened." % (valve.name)) if valve.open and (valve.suspended or sensorDisabled): valve.open = False valve.secondsLast = (datetime.now() - openSince).seconds openSince = None valve.secondsDaily = initialOpen + valve.secondsLast initialOpen = valve.secondsDaily valve.secondsLast = 0 valve.handler.close() self.logger.info("Irrigation valve '%s' closed." % (valve.name)) if valve.open: valve.secondsLast = (datetime.now() - openSince).seconds valve.secondsDaily = initialOpen + valve.secondsLast if valve.enabled == False: self.logger.info( "Valve '%s' disabled. Terminating irrigation cycle." % (valve.name)) break if self.terminated: self.logger.warning( "Program exiting. Terminating irrigation cycle for valve '%s'..." % (valve.name)) break valve.secondsRemain = ((startTime + duration) - datetime.now()).seconds self.logger.debug("Irrigation valve '%s' Last Open = %ss. Remaining = %ss. Daily Total = %ss." \ % (valve.name, valve.secondsLast, valve.secondsRemain, valve.secondsDaily)) time.sleep(1) self.logger.info("Irrigation cycle ended for valve '%s'." % (valve.name)) if valve.open and not valve.suspended: valve.secondsLast = (datetime.now() - openSince).seconds valve.secondsDaily = initialOpen + valve.secondsLast if valve.open: valve.open = False valve.handler.close() self.logger.info( "Irrigation valve '%s' closed. Overall open time %s seconds." % (valve.name, valve.secondsDaily)) valve.handled = False self.q.task_done() except queue.Empty: pass self.logger.warning("Valve handler thread '%s' exited." % threading.currentThread().getName()) def queueJob(self, job): self.q.put(job) if job.sched != None: self.logger.info( "Valve '%s' job queued per sched '%s'. Duration %s minutes." % (job.valve.name, job.sched.name, job.duration)) else: self.logger.info( "Valve '%s' adhoc job queued. Duration %s minutes." % (job.valve.name, job.duration)) def everyXMinutes(self, key, interval, bootstrap): if not key in self._intervalDict.keys(): self._intervalDict[key] = datetime.now() return bootstrap if datetime.now() >= self._intervalDict[key] + timedelta( minutes=interval): self._intervalDict[key] = datetime.now() return True return False def timerThread(self): try: while True: now = datetime.now().replace(tzinfo=pytz.timezone( self.cfg.timezone), second=0, microsecond=0) if now.hour == 0 and now.minute == 0: for aValve in self.valves.values(): aValve.secondsDaily = 0 if self.everyXMinutes("idleInterval", self.cfg.telemIdleInterval, False) and self.cfg.telemetry: delta = (datetime.now() - self.startTime) uptime = ((delta.days * 86400) + delta.seconds) // 60 self.mqtt.publish("/svc/uptime", uptime) for valve in self.valves.values(): self.telemetryValve(valve) for sensor in self.sensors.keys(): self.telemetrySensor(sensor, self.sensors[sensor]) if self.everyXMinutes("activeinterval", self.cfg.telemActiveInterval, False) and self.cfg.telemetry: for valve in self.valves.values(): if valve.handled: self.telemetryValve(valve) if self.everyXMinutes("scheduler", 1, True): # Must not evaluate more or less than once every minute otherwise running jobs will get queued again for aValve in self.valves.values(): if aValve.enabled: if aValve.schedules != None: for valveSched in aValve.schedules.values(): if self.evalSched(valveSched, self.cfg.timezone, now): jobDuration = valveSched.duration if valveSched.sensor != None and valveSched.sensor.handler != None and valveSched.sensor.handler.started: try: factor = valveSched.sensor.handler.getFactor( ) if factor != 1: jobDuration = jobDuration * factor self.logger.info( "Job duration changed from '%s' to '%s' based on input from sensor." % (valveSched.duration, jobDuration)) except Exception as ex: self.logger.error( "Error probing sensor (getFactor) '%s': %s." % (valveSched.sensor.type, format(ex))) job = model.Job( valve=aValve, duration=jobDuration, sched=valveSched, sensor=valveSched.sensor) self.queueJob(job) time.sleep(1) except Exception as ex: self.logger.error( "Timer thread exited with error '%s'. Terminating Irrigate!" % format(ex)) self.terminated = True def telemetryValve(self, valve): statusStr = "enabled" if not valve.enabled: statusStr = "disabled" elif valve.suspended: statusStr = "suspended" elif valve.open: statusStr = "open" self.mqtt.publish(valve.name + "/status", statusStr) self.mqtt.publish(valve.name + "/dailytotal", valve.secondsDaily) self.mqtt.publish(valve.name + "/remaining", valve.secondsRemain) if valve.open: self.mqtt.publish(valve.name + "/secondsLast", valve.secondsLast) def telemetrySensor(self, name, sensor): prefix = "sensor/" + name + "/" statusStr = "Enabled" try: if sensor.shouldDisable(): statusStr = "Disabled" elif sensor.getFactor() != 1: statusStr = "Factored" self.mqtt.publish(prefix + "factor", sensor.getFactor()) telem = sensor.getTelemetry() if telem != None: for t in telem.keys(): self.mqtt.publish(prefix + t, telem[t]) except Exception as ex: statusStr = "Error" self.mqtt.publish(prefix + "status", statusStr) def getLogger(self): formatter = logging.Formatter( fmt='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') handler = logging.FileHandler('log.txt', mode='w') handler.setFormatter(formatter) screen_handler = logging.StreamHandler(stream=sys.stdout) # screen_handler.setFormatter(formatter) logger = logging.getLogger("MyLogger") logger.setLevel(logging.DEBUG) logger.addHandler(handler) logger.addHandler(screen_handler) return logger
class Handler: def __init__(self): self.sensores = Sensores() self.sender = Sender() # self.database = DataBase() self.mqtt = Mqtt() self.Config = ConfigParser.ConfigParser() def manejar_10(self, datos): # try: time = datos["data"].split("/")[2] cfgfile = open("gateway.ini", "w") self.Config.add_section("Router-Params") self.Config.set("Router-Params", "mac", datos["data"].split("/")[0]) self.Config.set("Router-Params", "source", datos["data"].split("/")[1]) self.Config.set("Router-Params", "refresco", datos["data"].split("/")[3]) self.Config.write(cfgfile) cfgfile.close() def manejar_20(self, datos): numero_sensores = 0 pointer = 0 lista_sensores = [] numero_sensores = int(datos["data"][pointer].encode("hex")) pointer += 1 j = 0 while j < numero_sensores: (pointer, sensores_valores) = self.sensores.descomponer(datos["data"], pointer) sensores_valores["sensor"] = self.sensores.get_sensor(sensores_valores["sensor"]) lista_sensores.append(sensores_valores) j = j + 1 resultado = self.database.comprobar_mota("00" + datos["source_addr"].encode("hex")) if resultado == None: resultado = self.database.get_highest() if resultado[0] == None: source = 1 else: source = resultado[0] + 1 self.database.insertar_mota(datos, source, numero_sensores, datetime.datetime.now()) self.database.insertar_sensores(source, lista_sensores) else: source = resultado[0] self.database.update_mota(datetime.datetime.now(), source, 0) source = str(source) if len(source) == 1: source = "000" + source elif len(source) == 2: source = "00" + source elif len(source) == 3: source = "0" + source self.sender.send_10(source, datos["source_addr"]) ## print lista_sensores ## def manejar_30(self, datos): numero_sensores = 0 pointer = 0 lista_medidas = [] numero_sensores = int(datos["data"][pointer].encode("hex"), 16) num_seq = int(datos["frag_num"].encode("hex"), 16) pointer += 1 guardar = False resultado = self.database.comprobar_mota("00" + datos["source_addr"].encode("hex")) # mensaje consecutivo if (num_seq == resultado[1] + 1) or ((num_seq == 1) and (resultado[1] == 255)): guardar = True self.sender.send_ack(datos["source_addr"], datos["frag_num"], 1) # mensaje no consecutivo elif num_seq > resultado[1] + 1: print ("Se han perdido mensajes... Habra que recuperarlos.") guardar = True self.sender.send_ack(datos["source_addr"], datos["frag_num"], 2) self.database.insertar_retrasos(datos["source_id"].encode("hex"), resultado[1], num_seq) # mensaje repetido else: self.sender.send_ack(datos["source_addr"], datos["frag_num"], 3) if guardar: j = 0 while j < 3: hora = datos["data"][pointer : pointer + 4] pointer += 4 hora = int(hora.encode("hex"), 16) i = 0 while i < (numero_sensores / 3) - 1: (pointer, sensores_valores) = self.sensores.descomponer(datos["data"], pointer) sensores_valores.update({"hora": hora}) lista_medidas.append(sensores_valores) i += 1 j += 1 ## Transformar medidas ## for medida in lista_medidas: # print medida medida = self.sensores.transformar(medida) # print medida ## DATABASE ## self.database.insertar_medida(datos, lista_medidas) self.database.update_mota(datetime.datetime.now(), datos["source_id"].encode("hex"), num_seq) ## MQTT ## self.Config.read("conf.ini") if self.Config.get("MQTT", "activado") == "True": self.mqtt.send(lista_medidas, datos["source_id"].encode("hex")) def manejar_40(self, datos): numero_sensores = 0 pointer = 0 lista_medidas = [] numero_sensores = int(datos["data"][pointer].encode("hex"), 16) pointer += 1 j = 0 while j < numero_sensores / 2: (pointer, sensores_valores) = self.sensores.descomponer(datos["data"], pointer) sensores_valores["hora"] = int(sensores_valores["hora"].encode("hex"), 16) sensores_valores["id"] = sensores_valores["id"] + "-" + sensores_valores["id2"].encode("hex") lista_medidas.append(sensores_valores) j += 1 ## print lista_medidas ## self.database.insertar_medida(datos, lista_medidas) def comprobar(self, datos): if datos["application_id"] == "\x10": self.manejar_10(datos) elif datos["application_id"] == "\x20": self.manejar_20(datos) elif datos["application_id"] == "\x30": # mensajes sincronos self.manejar_30(datos) elif datos["application_id"] == "\x40": self.manejar_40(datos) else: print "mensaje no reconocido"
'location': style[0] }) def publish_status(status_manager): print("publish status", status_manager.status) mqtt.simple_send("doors/status", status_manager.status, retain=True) mqtt.simple_send("status/doorserver/public", status_manager.public, retain=True) mqtt.simple_send("status/doorserver/locked", not status_manager.open, retain=True) mqtt.simple_send("status/doorserver/occupied", status_manager.occupied, retain=True) hmac_calculator = hmac.new(config.hmac_key, digestmod='sha512') validator = Validator(hmac_calculator) status = StatusManager(on_change=publish_status) interpreter = Interpreter(status_manager=status, open_door=open_door, close_door=close_door, alarm_door=alarm_door) mqtt = Mqtt(addr=config.mqtt_broker, validator=validator, interpreter=interpreter, status_manager=status) mqtt.start()
#CATC------ importamos las sigueintes librerias import threading import logging import time import os import sys #CATC importamos de otros programas from mqtt import Mqtt from audio import Sonido from comandos import Comandos from datetime import datetime from globals import * #CATC imvocamos ala clase Mqtt y le enviamos parametros cli = Mqtt("proyectos", "proyectos980", "167.71.243.238", 1883, USER_ID_1, USER_ID_2, USER_ID_3) #CATC igualamos una funciones a utilizar com = Comandos() aud = Sonido() #CATC configuramos la fucion Alive para estar avisando en elsevidor #CATC que nos encontremaos activos def alive(delay=com.delay_a()): while True: alive = com.command_alive() + bytes(str(cli.carnet()), 'utf-8') cli.client.publish(str(cli.topicalive()), alive) time.sleep(delay)
import ubinascii import time import machine import json from connect import Connect from led_pwm import LedPwm from lcd import Lcd from temperature_dht11 import TemperatureSensor as Dht from mqtt import Mqtt dht = Dht(4) led = LedPwm(2) lcd = Lcd(spi=1, cs=2, dc=15, rst=0, bl=12) config = json.loads(open('config.json').read()) client_id = ubinascii.hexlify(machine.unique_id()) try: mqtt = Mqtt(client_id, config['broker_ip']) except: mqtt = False while True: # Connect to wifi Connect.check_and_reconnect() try: data = { 'temperature': dht.read_temp_and_hum()[0], 'humidity': dht.read_temp_and_hum()[1] } print(str(time.localtime()) + ' ' + str(data)) if not mqtt: try: mqtt = Mqtt(client_id, config['broker_ip'])
import threading import logging import time import os import sys from mqtt import Mqtt from audio import Sonido from comandos import Comandos from datetime import datetime cli = Mqtt("proyectos", "proyectos980", "167.71.243.238", 1883) com = Comandos() aud = Sonido() def alive(delay=com.delay_a()): while True: alive = com.command_alive() + bytes(str(cli.carnet()), 'utf-8') cli.client.publish(str(cli.topicalive()), alive) time.sleep(delay) t1 = threading.Thread(name='alive', target=alive, daemon=True) listaHilos = [] #Luego de configurar cada hilo, se inicializan t1.start() for i in listaHilos: i.start() #Loop principal: leer los datos de los sensores y enviarlos al broker en los topics adecuados cada cierto tiempo
if __name__ != '__main__': gunicorn_logger = logging.getLogger('gunicorn.error') app.logger.info('loglevel is ' + str(app.logger.level)) app.logger.info('set loglevel to ' + str(gunicorn_logger.level)) # app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) app.logger.info('set loglevel to ' + str(logging.DEBUG)) app.logger.setLevel(logging.DEBUG) app.logger.info('loglevel is ' + str(app.logger.level)) else: app.logger.info('loglevel is ' + app.logger.info.level) todoist_api = todoist.TodoistAPI(TODOIST_TOKEN) mqtt = Mqtt(BROKERHOST, BROKERPORT, USERNAME, PASSWORD, topics=[], log=app.logger) mqtt.loop_start() def verify_headers(headers): return headers.get('USER-AGENT') == 'Todoist-Webhooks' def verify_hmac(req): request_hmac = req.headers.get('X-Todoist-Hmac-Sha256') key = bytes(TODOIST_CLIENT_SECRET, 'latin-1') calculated_hmac = hmac.new(key, msg=req.get_data(), digestmod=hashlib.sha256).digest() calculated_hmac = base64.b64encode(calculated_hmac) calculated_hmac = calculated_hmac.decode('ascii') app.logger.info('Comparing ' + calculated_hmac + ' with ' + request_hmac)