示例#1
0
def start_mqtt_listener(event_queue, mqtt_server_host, mqtt_port):

    def on_mqtt_connect(client, _userdata, _flags, _rc):
        client.subscribe(SL5G_IP_TOPIC)

    def on_mqtt_publish(_client, _userdata, msg):
        panel_id = re.match(SL5G_PANEL_REGEX, msg.topic).group(1)
        event_queue.post_found_ip(panel_id, msg.payload.decode("utf-8"))


    client = mqtt.Client()
    client.on_connect = on_mqtt_connect
    client.on_message = on_mqtt_publish

    try:
        client.connect(mqtt_server_host, mqtt_port, 60)
    except OSError as e:
        print("Could not connect to MQTT server: {}".format(e))
        event_queue.post_shutdown()

    def shutdown():
        client.loop_stop()

    event_queue.post_register_shutdown_hook(shutdown)

    client.loop_start()

    return client
示例#2
0
def main_program():
    """This program subscribes to the mqtt server and publishes specfic
    data items to thingspeak channels
    """
    time_cntr = time.time()

    # set up logging
    FORMAT = '%(asctime)-15s %(message)s'
    logging.basicConfig(filename='thingspeak.log',
        level=config["general"].getint("loglevel"),
            format=FORMAT)
    logging.info('Thingspeak starting')

    # Connect to the mqtt server
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect(config['mqtt'].get('ip_address','127.0.0.1'),
      config['mqtt'].getint('port', 1883),
      config['mqtt'].getint('timeout',60))

    # Blocking call that processes network traffic, dispatches callbacks and
    # handles reconnecting.
    # Other loop*() functions are available that give a threaded interface and a
    # manual interface.
    client.loop_start()
    
    while True:
      time.sleep(1)
      if time_cntr + 60 < (time.time()):
        time_cntr = time.time()
        config.read(config_fname)
示例#3
0
def init_mqtt(url="localhost", port=1883, keep_alive=60):
    """Init MQTT connection"""
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    try:
        print(url, port, keep_alive)
        client.connect(url, port, keep_alive)
        client.loop_start()
        return client
    except Exception as e:
        log.exception(e)
        return None
示例#4
0
    # reconnect then subscriptions will be renewed.
    client.subscribe("/door/front/mode")
    client.subscribe("/door/front/add")
    client.subscribe("/door/front/status")


db = Database()

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
## Clears any retained messages on the mode channel, eliminates triggering a door open on boot and removes any retained message from clients
client.publish("/door/front/mode", "Clear", retain=True)

client.connect("192.168.68.112", 1883, 60)
client.loop_start()

GPIO.setmode(GPIO.BOARD)  # Use physical pin numbering
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP)

Alert("Door Lock Started")
while (end_Thread == 0):
    input_state = GPIO.input(7)

    if (input_state == False):

        mode = db.fetch("mode")

        if (mode == 0):

            try:
示例#5
0
def main_program():
    """This program subscribes to the mqtt server and publishes specfic
    data items to thingspeak channels
    """
    time_cntr = time.time()

    # set up logging
    FORMAT = '%(asctime)-15s %(message)s'
    logging.basicConfig(filename='thingspeak.log',
        level=config["general"].getint("loglevel"),
            format=FORMAT)
    logging.info('Thingspeak starting')

    # Connect to the mqtt server
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect(config['mqtt'].get('ip_address','127.0.0.1'),
      config['mqtt'].getint('port', 1883),
      config['mqtt'].getint('timeout',60))

    # Blocking call that processes network traffic, dispatches callbacks and
    # handles reconnecting.
    # Other loop*() functions are available that give a threaded interface and a
    # manual interface.
    client.loop_start()
    
    while True:
      time.sleep(1)
      if time_cntr + 60 < (time.time()):
        time_cntr = time.time()
        config.read(config_fname)
        
      nCnt=0
      for uD in updateList:
  
        # if it's taken longer than 5 seconds, send the update anyway  
        timeDiff = datetime.datetime.now() - uD.init_dt
        if timeDiff.seconds > 5:
          logging.info("Timeout - sending update anyway")
          uD.complete = 1
  
        if uD.complete == 1:
          headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain",
            "THINGSPEAKAPIKEY": uD.api_key}
 
          params = "field1={}".format(uD.field1)
          if uD.field2 != '':
            params = params + "&field2={}".format(uD.field2)
          if uD.field3 != '':
            params = params + "&field3={}".format(uD.field3)
          if uD.field4 != '':
            params = params + "&field4={}".format(uD.field4)
          if uD.field5 != '':
            params = params + "&field5={}".format(uD.field5)
          if uD.field6 != '':
            params = params + "&field6={}".format(uD.field6)
          if uD.field7 != '':
            params = params + "&field7={}".format(uD.field7)
          if uD.field8 != '':
            params = params + "&field8={}".format(uD.field8)
          print(params)
          try:
            conn = http.client.HTTPConnection(config['thingspeak'].get('url'))
            conn.request("POST", "/update", params, headers)
            response = conn.getresponse()
            logging.info("HTTP send success")
            conn.close()
            updateList.pop(nCnt)
          except:
 
            logging.warning("HTTP send error {}:{}".format(headers, params))
        else:
          nCnt += 1
示例#6
0
def main_program():
    """This program subscribes to the mqtt server and publishes specfic
    data items to thingspeak channels
    """
    time_cntr = time.time()

    # set up logging
    FORMAT = '%(asctime)-15s %(message)s'
    logging.basicConfig(filename='thingspeak1a.log',
        level=config["general"].getint("loglevel"),
            format=FORMAT)
    logging.info('Thingspeak starting')

    # Connect to the mqtt server
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect(config['mqtt'].get('ip_address','127.0.0.1'),
      config['mqtt'].getint('port', 1883),
      config['mqtt'].getint('timeout',60))

    # Blocking call that processes network traffic, dispatches callbacks and
    # handles reconnecting.
    # Other loop*() functions are available that give a threaded interface and a
    # manual interface.
    client.loop_start()
    
    while True:
      time.sleep(1)
      if time_cntr + 60 < (time.time()):
        time_cntr = time.time()
        config.read(config_fname)
        print("Re-read config file")
        
      nCnt=0
      for uD in updateList:
 
  
        # if it's taken longer than 5 seconds, send the update anyway  
        timeDiff = datetime.datetime.now() - uD.init_dt
        if timeDiff.seconds > 5:
          logging.info("Timeout - sending update anyway")
          uD.complete = 1
  
        if uD.complete == 1:
          headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain",
            "THINGSPEAKAPIKEY": uD.api_key}
 
          params = "field1={}".format(uD.field1)
          if uD.field2 != '':
            params = params + "&field2={}".format(uD.field2)
          if uD.field3 != '':
            params = params + "&field3={}".format(uD.field3)
          if uD.field4 != '':
            params = params + "&field4={}".format(uD.field4)
          if uD.field5 != '':
            params = params + "&field5={}".format(uD.field5)
          if uD.field6 != '':
            params = params + "&field6={}".format(uD.field6)
          if uD.field7 != '':
            params = params + "&field7={}".format(uD.field7)
          if uD.field8 != '':
            params = params + "&field8={}".format(uD.field8)
          print(params)
          try:
            conn = http.client.HTTPConnection(config['thingspeak'].get('url'))
            conn.request("POST", "/update", params, headers)
            response = conn.getresponse()
            logging.info("HTTP send success")
            conn.close()
            updateList.pop(nCnt)
          except:
 
            logging.warning("HTTP send error {}:{}".format(headers, params))
        else:
          nCnt += 1
#    tsi = datos[datos['sensor'] == sensores['ParedeInterior']]['valores']
#    te = datos[datos['sensor'] == sensores['AmbienteExterior']]['valores']
#    # Concatenamos todos os valores atopados, nun único np.array (array unidimensional)
#    # e desbotamos os valores que non están dentro do rango de medida do DS18b20
#    # incluíndo o código de erro -127.0
##    print(datos)
##    print(ti); print(tsi); print(te)
#    try:
#        ti = np.concatenate(ti, axis=0); ti[(ti<-55) | (ti>125)] = np.nan
#        tsi = np.concatenate(tsi, axis=0); tsi[(tsi<-55) | (tsi>125)] = np.nan
#        te = np.concatenate(te, axis=0); te[(te<-55) | (te>125)] = np.nan
#
#        # Calculamos a media de cada sensor para o tempo dado
#        ti = ti[~np.isnan(ti)].mean(); tsi = tsi[~np.isnan(tsi)].mean(); te = te[~np.isnan(te)].mean()
#
#        U = hsi * (ti - tsi) / (ti - te)
#        U = np.around(U, decimals=2)
#    except ValueError:
#        U = None
#    return(U)

if __name__ == "__main__":
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect("192.168.3.1", 1883, 60)
    #    client.connect("iot.eclipse.org", 1883, 60)

    client.loop_start()  #Mellor loop_start, proporciona un fio non bloqueante
#   client.loop_forever() #loop_forever proporciona un fío bloqueante