def __init__(self, wf, cp):
     self.callBackFunction = None
     # load the configuration
     try:
         self.queue = []
         self.host = cp["host"]
         self.port = cp["port"]
         self.topic = cp["topic"]
         self.serializer = cp["serializer"]
         info("> MQTTListener   | " + self.serializer + " | URI: " + self.host + ":" + self.port + " | Topic: " +
              self.topic, Fore.CYAN)
     except KeyError as e:
         error("mqttListener definition was incomplete: " + str(e))
         exit(1)
     # create serializer
     if self.serializer == "JSON":
         self.serialize_function = lambda m: json.loads(m.decode('utf-8'))
     else:
         error("serializer not implemented")
         exit(1)
     try:
         # create mqtt client and connect
         self.mqtt = mqtt.Client()
         self.mqtt.connect(self.host, port=self.port)
         # register callback
         self.mqtt.on_message = self.on_message
         # subscribe and start listing on second thread
         self.mqtt.subscribe(self.topic, 0)
         self.mqtt.loop_start()
     except RuntimeError as e:
         error("connection to mqtt failed: " + str(e))
         exit(1)
예제 #2
0
def startMqtt():
    client = mqtt.Client(MQTT_ID)
    client.on_connect = on_connect
    client.on_message = on_message
    client.username_pw_set(MQTT_LGN, MQTT_PWD)
    client.connect(MQTT_ADDRESS, MQTT_PORT, MQTT_TIMEOUT)
    client.loop_forever()
예제 #3
0
    def __init__(self,
                 server,
                 port=1883,
                 username=None,
                 password=None,
                 cacert=None,
                 clientid=None,
                 callback=None,
                 statuscallback=None):

        # normally we want to be our messages / subscriptions
        # peristent however if there is no client_id specified
        # we turn this feature off as it creates clutter on broker
        clean_session = False

        self.server = server
        self.port = port
        self.pubid = 0

        # if not uid specified generate one
        if not clientid:
            clientid = self.__getclientid__()
            #str(base64.b32encode(uuid.uuid4().bytes)[:26], 'utf-8')
            clean_session = True

        self.clientid = clientid
        # in case of reconnect clean_session false means that subscriptions are restoreds
        self.mqttc = mqtt.Client(client_id=clientid,
                                 clean_session=clean_session)
        # generic subscription callback
        self.mqttc.subcallback = callback
        # specific callbacks
        self.mqttc.subcallbacks = {}

        self.statuscallback = statuscallback

        self.mqttc.owner = self

        # hardcoded login
        # TODO: proper authentication

        if not username:
            raise ValueError('You need to provide username/password!')
        else:
            self.mqttc.username_pw_set(username, password)

        # Assign event callbacks
        self.mqttc.on_message = Hermes.__on_message
        self.mqttc.on_connect = Hermes.__on_connect
        self.mqttc.on_publish = Hermes.__on_publish
        self.mqttc.on_subscribe = Hermes.__on_subscribe
        self.mqttc.on_disconnect = Hermes.__on_disconnect
        self.mqttc.on_log = Hermes.__on_log

        if cacert:
            self.mqttc.tls_set(cacert)
            # TODO: get rid of this once the DNS server name settles
            self.mqttc.tls_insecure_set(True)
예제 #4
0
    def __init__(self, client, mqtt_conf, topic):
        #ID
        self._unitId = unitid

        #subscribing To topics
        for pTopic in topic:
            self._topic.append(pTopic)

        # init mqtt client
        self._mqttClient = mqtt.Client(self._unitId)

        # Callback Init
        self._mqttClient.on_message = self.onMessage
        self._mqttClient.on_disconnect = self.onDisconnect
        self._mqttClient.on_message = self.onMessage

        # Connexion
        self._mqttClient.Connect(mqtt_conf['host'], mqtt_conf['port'],
                                 mqtt_conf['keepalive'])
예제 #5
0
        cv2.namedWindow('Window', cv2.WINDOW_AUTOSIZE)
        cv2.setWindowProperty('Window', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
        cv2.imshow("Window", img_result)



        if cv2.waitKey(1)&0xFF == ord('q'):
            break


# ----------------------------------------------------------------------------------------------------------------------#

video = cv2.VideoCapture(0)
if __name__ == '__main__':
    cart = mqtt.Client("cart")
    cart.on_connect = on_connect_cart
    cart.on_message = on_message_cart

    # Connect to MQTT broker
    try:
        cart.connect("163.180.117.195", 1883, 60)
    except:
        print("ERROR: Could not connect to MQTT")

    print("MQTT client start")
    cart.loop_start()

    lock = threading.Lock()
    # Creating thread for hallway detection
    t1 = threading.Thread(target=videoLineMeasurement_func, args=[lock])
예제 #6
0
파일: mqtt.py 프로젝트: Lalufu/ruuvi-mqtt
def mqtt_main(ruuvi_queue: multiprocessing.Queue, config: Dict[str,
                                                               Any]) -> None:
    """
    Main function for the MQTT process

    Connect to the server, read from the queue, and publish
    messages
    """
    def mqtt_on_connect(client, userdata, flags, rc):
        """
        Callback for the on_connect event

        This is called from a different thread
        """
        nonlocal connected, connected_cv
        LOGGER.debug("mqtt on_connect called, flags=%s, rc=%d", flags, rc)

        with connected_cv:
            connected = rc == 0
            if connected:
                connected_cv.notify()

    def mqtt_on_disconnect(client, userdata, rc):
        """
        Callback for the on_disconnect event

        This is called from a different thread
        """
        nonlocal connected, connected_cv
        LOGGER.debug("mqtt on_disconnect called, rc=%d", rc)
        if rc != 0:
            # Unexpected disconnect
            LOGGER.error("Unexpected disconnect from MQTT")

        with connected_cv:
            connected = False

            # We do not have to wake up the waiter for this,
            # because they'll just go back to sleep anyway

    LOGGER.info("mqtt process starting, paho.mqtt version %s",
                paho.mqtt.__version__)

    # connected is tracking the connection state to MQTT.
    # connected_cv is a condition variable that is protecing
    # access to connected, because it is modified from a different
    # thread.
    connected = False
    connected_cv = threading.Condition()

    client = mqtt.Client(config["mqtt_client_id"])
    client.on_connect = mqtt_on_connect
    client.on_disconnect = mqtt_on_disconnect

    # This will spawn a thread that handles events and reconnects
    client.loop_start()

    # We're going to loop until the connection succeeds, once
    # it does the paho state machine will take care of reconnects
    while True:
        try:
            client.connect(config["mqtt_host"], port=config["mqtt_port"])
        except Exception as exc:
            LOGGER.info(
                "Could not connect to %s:%s, retrying (%s)",
                config["mqtt_host"],
                config["mqtt_port"],
                exc,
            )
            time.sleep(2)
            continue

        break

    while True:
        # This will sleep unless we're connected
        with connected_cv:
            connected_cv.wait_for(lambda: connected)

        data = ruuvi_queue.get(block=True)
        LOGGER.debug("Read from queue: %s", data)

        client.publish(
            config["mqtt_topic"] % {
                "mac": data["mac"],
                "name": data["ruuvi_mqtt_name"]
            },
            json.dumps(data),
        )
예제 #7
0
import paho.mqtt


def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    global mac
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe(mac + "/#")


# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("brmtz-dev-001", 1883, 60)
client.loop_start()
예제 #8
0
MQTT_TIMEOUT = 60

MQTT_TOPIC_SUBSCRIBE = 'nomeTopico1'
MQTT_TOPIC_SUBSCRIBE2 = 'nomeTopico2'
MQTT_TOPIC_PUBLISH_CLIENTE1 = "iot/cliente1"
MQTT_TOPIC_PUBLISH_CLIENTE2 = "iot/cliente2"
MQTT_TOPIC_PUBLISH_CLIETNE3 = "iot/cliente3"
MQTT_LGN = 'iot'
MQTT_PSW = ''
BOX_ID = 'sensor_iot'

kronIDsCliente1 = ["001906075", "001906076", "001906077", "001906078", "001906079", "001906080", "001906081", "001906082", "001906083", "001906084", "001906085", "001906176"]
kronIDsCliente2 = ["1913751", "138465", "1256897"]
kronIDsCliente3 = ["0000101", "10010011"]

client = mqtt.Client(BOX_ID) # criacao do cliente mqtt

def on_connect(client, userdata, flags, rc): # callback executado ao conectar
    print('Conectado. Resultado: %s' % str(rc))
    client.subscribe(MQTT_TOPIC_SUBSCRIBE) # a chamada de subscricao e feita dentro do metodo de conexao.
    client.subscribe(MQTT_TOPIC_SUBSCRIBE2)
    
def on_subscribe(client, userdata, mid, granted_qos): # callback que informa quando foi feito um subscribe
    print('Inscrito no topico: %d' % mid)
    
def on_message(client, userdata, msg): # callback que mostra as menssagem publicadas nos topicos que estiver inscrito
    print('topico: %s' % msg.topic)
    print('Mensagem: %s' % msg.payload.decode('utf-8'))
    
    
    try:
예제 #9
0
 def __init__(self,unwarper):
     self.unwarper = unwarper
     self.db = self.init_fb()
     client=mqtt.Client()
     client.connect("129.215.202.200")
     water_reader()