Exemplo n.º 1
0
def mqtt_msg(config):
    host = config['host']
    port = config['port']
    mqtt_id = config['mqtt_id']
    topic = config['topic']
    delay = config['delay']

    client = MQTTClient(mqtt_id, host, port=port)
    client.connect()

    d = dht.DHT22(machine.Pin(4))
    try:
        '''required or a timeout error occurs !?'''
        d.measure()
    except:
        print('d.measure() failed')

    while True:
        try:
            d.measure()
            t = time.localtime()

            timestamp = '{}{:02d}{:02d}{:02d}{:02d}{:02d}'.format(
                t[0], t[1], t[2], t[3], t[4], t[5])
            temperature = d.temperature()
            humidity = d.humidity()

            m = '{{"tsp":"{}", "tmp":{:02.2f}, "hmd":{:02.2f}}}'.format(
                timestamp, temperature, humidity)

            client.publish(topic=topic, msg=m)
        except:
            print('d.measure() failed')

        time.sleep(delay)
Exemplo n.º 2
0
def mqtt_server():
    global client
    global client_int
    if client == None:
        client = MQTTClient(client_id='1ebe9d4c-9e49-4bf4-8abb-f322009c377c',
                            server='m16.cloudmqtt.com',
                            port=17330,
                            user='******',
                            password='******')
        #client = MQTTClient(client_id='1ebe9d4c-9e49-4bf4-8abb-f322009c377c', server='m16.cloudmqtt.com', port=17661, user='******', password='******')
        client.set_callback(sub_cb)
        client.connect()

        print("Connected to MQTT Client")

        # the first argument is the topic, the second is the message
        client.subscribe("Sensor_Data")

        client_int = Timer(3)
        client_int.init(period=1000,
                        mode=Timer.PERIODIC,
                        callback=client_interrupt)
        #client.publish("SessionID", b"four"*8, True, 0)
        client.publish("SessionID", AES.sessionID, True, 0)
        client_interrupt(None)
Exemplo n.º 3
0
def run():
    sleep(4)
    show_default()

    c = MQTTClient('ledkrant', 
        mqtt_server["ip"], 
        user=mqtt_server["user"], 
        password=mqtt_server["password"])

    c.DEBUG = True
    c.set_callback(sub_callback)
    c.connect()
    c.subscribe(b"ledkrant/write")
    c.subscribe(b"ledkrant/time")
    c.subscribe(b"ledkrant/brightness")
    c.subscribe(b"ledkrant/reset")
    c.subscribe(b"ledkrant/color")
    c.subscribe(b"ledkrant/textcolor")
    c.subscribe(b"ledkrant/party")
    c.subscribe(b"ledkrant/setxy")

    while 1:
        c.wait_msg()

    c.disconnect()
Exemplo n.º 4
0
def main(config):
    global temperature_sensor, motion_sensor, humidity_sensor

    client_id = "esp8266_room_sensor_" + ubinascii.hexlify(
        machine.unique_id()).decode('utf-8')
    print(client_id)
    mqtt = MQTTClient(client_id,
                      config['mqtt']['broker'],
                      port=config['mqtt']['port'],
                      user=config['mqtt']['user'],
                      password=config['mqtt']['password'])
    mqtt.connect()
    print("Connected to {}".format(config['mqtt']['broker']))

    motion_sensor = hassnode.BinarySensor(mqtt, config['motion']['name'],
                                          "motion",
                                          config['motion']['entity_id'])
    temperature_sensor = hassnode.Sensor(mqtt, config['temperature']['name'],
                                         "°C",
                                         config['temperature']['entity_id'])
    humidity_sensor = hassnode.Sensor(mqtt, config['humidity']['name'], "%",
                                      config['humidity']['entity_id'])

    pir = Pin(PIR_PIN, Pin.IN)
    pir.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=motion_callback)

    loop = asyncio.get_event_loop()
    loop.create_task(dht_task())
    loop.run_forever()
Exemplo n.º 5
0
 def mqtt(self):
     print("connecting to mqtt ROBUST at {}".format(self.serverIP))
     self.c = MQTTClient("umqtt_client", self.serverIP)
     self.c.set_callback(self.processMEssage)
     self.c.connect()
     self.c.subscribe("master/#")
     print("connected to mqtt broker")
Exemplo n.º 6
0
 def mqtt_start(self, mqtt_broker, mqtt_client_id, mqtt_port=1883):
     self.mqtt_topic_in = str(self.wlan.get_hostname() + MQTT_TPIN).encode()
     self.mqtt_topic_out = str(self.wlan.get_hostname() +
                               MQTT_TPOU).encode()
     try:
         self.mqtt = MQTTClient(mqtt_client_id, mqtt_broker, mqtt_port)
         self.mqtt.set_callback(self.mqtt_subscribe_callback)
         self.mqtt.connect(clean_session=False)
         print('[+] Sonoff.mqtt_start: Connected to ({0}'.format(
             str(mqtt_broker)))
     except KeyboardInterrupt:
         raise
     except Exception as e:
         eprint('[-] Sonoff.mqtt_setup: {0}'.format(e))
         eprint('    Failed to connect to MQTT, resetting..')
         self.reset()
     try:
         self.mqtt.subscribe(self.mqtt_topic_in)
         print('[+] Sonoff.mqtt_start: Subscribed to {0}'.format(
             self.mqtt_topic_in.decode('utf-8')))
     except KeyboardInterrupt:
         raise
     except Exception as e:
         eprint('[-] Sonoff.mqtt_setup: {0}'.format(e))
         eprint('    Failed to subscribe to {1}, resetting..'.format(
             self.mqtt_topic_in.decode('utf-8')))
         self.reset()
         self.led.blink(3)
Exemplo n.º 7
0
def send_mqtt(payload_out):
    global ip
    slimDNS = None

    try:
        slimDNS = SlimDNSServer(wlan.ifconfig()[0])
        host_address_bytes = slimDNS.resolve_mdns_address(MQTT_SERVER_MDNS_ADDRESS)
        print(host_address_bytes)
        if ip != None:
            print(ip)
        ip = bytes_to_dotted_ip(host_address_bytes)
    except Exception as e:
        print("Could not connect find mDNS address " + str(e))

    if ip != None:
        print('Connecting to MQTT server:', ip)
        mqtt = None
        try:
            mqtt = MQTTClient(client_id=unique_id, server=ip, port=1883)        
            mqtt.connect()
        except Exception as e:
            print('Could not connect to MQTT server')
            return

        try: 
            mqtt.publish("vendingmachine/sensors", payload_out)
            mqtt.disconnect()
        except Exception:
            print("Failed To Publish")
Exemplo n.º 8
0
def initialise(settings=configuration.mqtt.settings):
    global client, keepalive, topic_path

    client_id = get_unique_id()
    keepalive = settings["keepalive"]
    topic_path = settings["topic_path"]
    if topic_path == "$me": topic_path = "aiko_esp/" + get_unique_id() + "/0"

    client = MQTTClient(client_id,
                        settings["host"],
                        settings["port"],
                        keepalive=keepalive)

    client.set_callback(on_message)
    client.set_last_will(topic_path + "/state", "nil")
    client.connect()  # TODO: Catch exception

    event.add_timer_handler(mqtt_ping_handler, keepalive * 1000)

    if settings["mqtt_insecure_exec"]:
        add_message_handler(on_exec_message, "$me/exec")

    for topic in settings["topic_subscribe"]:
        if topic.startswith("$all/"): topic = "+/+/+" + topic[4:]
        if topic.startswith("$me/"): topic = topic_path + topic[3:]
        client.subscribe(topic)

    print("  ###### MQTT: Connected to %s: %s" %
          (settings["host"], topic_path))
    def connect(self):
        prov = ProvisioningClient(self._id_scope, self._device_id,
                                  self._credentials_type, self._credentials,
                                  self._logger, self._model_id)
        creds = prov.register()
        self._mqtt_client = MQTTClient(self._device_id,
                                       creds.host,
                                       8883,
                                       creds.user.encode('utf-8'),
                                       creds.password.encode('utf-8'),
                                       ssl=True,
                                       keepalive=60)
        self._commands_regex = ure.compile(
            '\$iothub\/methods\/POST\/(.+)\/\?\$rid=(.+)')
        self._mqtt_client.connect(False)
        self._connected = True
        self._logger.info('Device connected!')
        self._mqtt_client.set_callback(self._on_message)
        self._mqtt_client.subscribe(HubTopics.TWIN)
        self._mqtt_client.subscribe('{}/#'.format(HubTopics.PROPERTIES))
        self._mqtt_client.subscribe('{}/#'.format(HubTopics.COMMANDS))
        self._mqtt_client.subscribe('{}/#'.format(
            HubTopics.ENQUEUED_COMMANDS.format(self._device_id)))

        self._logger.debug(self._twin_request_id)
        self._mqtt_client.publish(
            HubTopics.TWIN_REQ.format(self._twin_request_id).encode('utf-8'),
            '{{}}')
Exemplo n.º 10
0
def device_connect():
    global MQTT_CLIENT

    try:  #all this below runs once ,equivalent to Arduino's "setup" function)
        with open(KEY_FILE, "r") as f:
            key = f.read()

        print("set private Key")

        with open(CERT_FILE, "r") as f:
            cert = f.read()

        print("set client Cert")

        MQTT_CLIENT = MQTTClient(client_id=MQTT_CLIENT_ID,
                                 server=MQTT_HOST,
                                 port=MQTT_PORT,
                                 keepalive=5000,
                                 ssl=True,
                                 ssl_params={
                                     "cert": cert,
                                     "key": key,
                                     "server_side": False
                                 })
        MQTT_CLIENT.connect()
        print('MQTT Connected')
        MQTT_CLIENT.set_callback(sub_cb)
        MQTT_CLIENT.subscribe(SUB_TOPIC)
        print('Subscribed to %s as the incoming topic' % (SUB_TOPIC))
        return MQTT_CLIENT
    except Exception as e:
        print('Cannot connect MQTT: ' + str(e))
        raise
Exemplo n.º 11
0
    def connect(self):
        # turn off the WiFi Access Point
        ap_if = network.WLAN(network.AP_IF)
        ap_if.active(False)

        # connect the device to the WiFi network
        wifi = network.WLAN(network.STA_IF)
        wifi.active(True)
        wifi.connect(self.WIFI_SSID, self.WIFI_PSWD)

        attempt_count = 0
        while not wifi.isconnected() and attempt_count < 20:
            attempt_count += 1
            time.sleep(1)

        if attempt_count == 20:
            print('could not connect to the WiFi network')
            sys.exit()

        self.client = MQTTClient(client_id=self.mqtt_client_id,
                                 server=self.ADAFRUIT_IO_URL,
                                 user=self.ADAFRUIT_USERNAME,
                                 password=self.ADAFRUIT_IO_KEY,
                                 ssl=False)

        try:
            self.client.connect()
        except Exception as e:
            print('could not connect to MQTT server {}{}'.format(
                type(e).__name__, e))
            sys.exit()
Exemplo n.º 12
0
def mqtt_client(server):
    # setup the BUTton and LED
    global led
    import machine, ubinascii, utime
    machine_id = b'ESP8266-%s' % ubinascii.hexlify( machine.unique_id() )
    led = machine.Pin(2)
    led.init(machine.Pin.OUT)
    button = machine.Pin(0)
    button.init(machine.Pin.IN, machine.Pin.PULL_UP)
    # setup Mosquitto
    from umqtt.robust import MQTTClient
    mqttc = MQTTClient(machine_id, server)
    mqttc.connect()
    mqttc.set_last_will(b'test/bradley_edu', b'%s signoff 1' % ( machine_id ) )
    mqttc.set_callback(callback_function)
    mqttc.subscribe(b'test/#')

    # run Mosquitto
    butstate = button.value()
    while True:
        if button.value()!=butstate:
            butstate = button.value()
            mqttc.publish(b'test/bradley_edu', b'%s B0 %s' % ( machine_id , str(butstate) ) )
        mqttc.check_msg()  # this will check for messages and call the callback function if needed
        utime.sleep_ms(20) # time to allow the callback function to do its job to avoid calling multiple instances
    # we actually never quit but this is how shutdown should look like
    mqttc.disconnect()
Exemplo n.º 13
0
    def __init__(self,
                 client_id,
                 server,
                 pin,
                 fahrenheit=True,
                 topic=None,
                 **kwargs):
        """
        Instantiates a TemperatureSensor and MQTTClient; connects to the
        MQTT broker.
        Arguments `server` and `client_id` are required.
        :param client_id: Unique MQTT client ID
        :type client_id: str
        :param server: MQTT broker domain name / IP
        :type server: str
        :param pin: 1-Wire bus pin
        :type pin: int
        :param fahrenheit: Whether or not to publish temperature in Fahrenheit
        :type fahrenheit: bool
        :param topic: Topic to publish temperature on
        :type topic: str
        :param kwargs: Arguments for MQTTClient constructor
        """
        self.sensor = TemperatureSensor(pin)
        self.client = MQTTClient(client_id, server, **kwargs)
        if not topic:
            self.topic = 'devices/%s/temperature/degrees' % \
                         self.client.client_id
        else:
            self.topic = topic
        self.fahrenheit = bool(fahrenheit)

        self.client.connect()
Exemplo n.º 14
0
    def __init__(self, wifiName, wifiPassword, ADAFRUIT_IO_URL,
                 ADAFRUIT_USERNAME, ADAFRUIT_IO_KEY):
        self.wifiName = wifiName
        self.wifiPassword = wifiPassword
        self.ADAFRUIT_IO_URL = ADAFRUIT_IO_URL
        self.ADAFRUIT_USERNAME = ADAFRUIT_USERNAME
        self.ADAFRUIT_IO_KEY = ADAFRUIT_IO_KEY
        self.Connected = "F"
        # create a random MQTT clientID
        random_num = int.from_bytes(os.urandom(3), 'little')
        self.mqtt_client_id = bytes('client_' + str(random_num), 'utf-8')

        # connect to Adafruit IO MQTT broker using unsecure TCP (port 1883)
        #
        # To use a secure connection (encrypted) with TLS:
        #   set MQTTClient initializer parameter to "ssl=True"
        #   Caveat: a secure connection uses about 9k bytes of the heap
        #         (about 1/4 of the micropython heap on the ESP8266 platform)
        self.client = MQTTClient(client_id=self.mqtt_client_id,
                                 server=ADAFRUIT_IO_URL,
                                 user=ADAFRUIT_USERNAME,
                                 password=ADAFRUIT_IO_KEY,
                                 ssl=False)

        self.values = {}
Exemplo n.º 15
0
def connect_mqtt():
    global mqtt_client

    try:
        with open(KEY_FILE, "r") as f:
            key = f.read()

        print("Got Key")

        with open(CERT_FILE, "r") as f:
            cert = f.read()

        print("Got Cert")

        mqtt_client = MQTTClient(client_id=MQTT_CLIENT_ID,
                                 server=MQTT_HOST,
                                 port=MQTT_PORT,
                                 keepalive=5000,
                                 ssl=True,
                                 ssl_params={
                                     "cert": cert,
                                     "key": key,
                                     "server_side": False
                                 })
        mqtt_client.connect()
        print('MQTT Connected')

    except Exception as e:
        print('Cannot connect MQTT: ' + str(e))
        raise
Exemplo n.º 16
0
def main():
    machine.freq(160000000)

    c = MQTTClient("HSBNE-small-sign", "10.0.1.253", user="", password="")
    c.set_callback(sub_cb)
    c.set_last_will("devices/small-sign/state", "offline", retain=True)
    c.connect()
    c.subscribe("devices/small-sign/#")
    c.publish("devices/small-sign/state", "online", retain=True)
    c.publish("devices/main-sign/ip",
              network.WLAN(network.STA_IF).ifconfig()[0],
              retain=True)

    sign = SignMatrix()
    try:
        while True:
            while c.check_msg():
                pass
            if enable != 0:
                sign.set_delay(delay)
                sign.scroller(text)
            else:
                c.wait_msg()
    except KeyboardInterrupt:
        c.publish("devices/small-sign/state", "offline", retain=True, qos=1)
        c.disconnect()
Exemplo n.º 17
0
    def mqtt_connect(self):
        """"""
        print("Connecting to MQTT server...")

        self._client = MQTTClient(
            CLIENT_ID,
            MQTT_SERVER,
            user=MQTT_USERNAME,
            password=MQTT_PASSWORD,
        )

        self._client.set_callback(self.on_message)

        print("Connecting MQTT")

        self._client.set_last_will(STATUS_TOPIC, "Offline", retain=True)

        self._client.connect()

        self._client.subscribe(TOPIC)

        print("Connected to %s, subscribed to %s topic" % (MQTT_SERVER, TOPIC))

        self._client.publish(STATUS_TOPIC, "Connected", retain=True)

        while True:
            self._client.wait_msg()
Exemplo n.º 18
0
def connect_and_subscribe():
    global client_id, mqtt_server, topic_sub
    client = MQTTClient(client_id, mqtt_server)
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(topic_sub)
    print('Connected to: %s \nSubscribed to: %s' % (mqtt_server, topic_sub))
    return client
def connect_mqtt():
    global mqtt_client
    mqtt_client = MQTTClient(client_id=MQTT_CLIENT_ID,
                             server=MQTT_HOST,
                             port=MQTT_PORT,
                             ssl=False)
    mqtt_client.connect()
    print('MQTT Connected')
Exemplo n.º 20
0
def create_mqtt_client(client_id, hostname, username, password, port=8883, keepalive=120, ssl=True):
    if not keepalive:
        keepalive = 120
    if not ssl:
        ssl = True
    c = MQTTClient(client_id=client_id, server=hostname, port=8883, user=username, password=password, keepalive=120, ssl=True)
    c.DEBUG = True
    return c
Exemplo n.º 21
0
 def __init__(self, on_message_handler):
     self._on_message_handler = on_message_handler
     self._device_id = config["device_id"]
     self._client = MQTTClient(client_id=self._device_id,
                               server=config["broker"],
                               ssl=False)
     self._client.set_message_received_handler(self._on_message)
     self._client.set_connected_handler(self._on_connected)
Exemplo n.º 22
0
 def __init__(self, name, server):
     self.mqtt = MQTTClient(hexlify(machine.unique_id()), server)
     self.name = name
     self.actions = {}
     self.publishers = {}
     self.connect()
     self.mqtt.set_callback(self.handle_mqtt_msgs)
     self.publish_all_after_msg = True
Exemplo n.º 23
0
 def __init__(self):
     self.mqtt = MQTTClient(
         client_id=config.MQTT_CLIENT_ID,
         server=config.MQTT_HOST,
         port=config.MQTT_PORT,
         user=config.MQTT_USER,
         password=config.MQTT_PASSWORD,
     )
Exemplo n.º 24
0
def mqttB(config):#HeartBeat client
    state = DISCONNECTED
    global clientB
    if config['username'] != "" and config['password'] != "":
        clientB = MQTTClient( MAC, config['host'] ,user=config['username'], password=config['password'], port=int(config['port']), keepalive=30, ssl=False)
    else:
        clientB = MQTTClient( MAC, config['host'] ,port=int(config['port']), keepalive=30, ssl=False)
    while state != CONNECTED:
        try:
            state = CONNECTING
            clientB.connect()
            state = CONNECTED
        except:
            gwlogging.sendLog(gwlogging.INFO, "Could not establish MQTT-BLE connection", MOD)
            time.sleep(1)
    if state == CONNECTED:
        gwlogging.sendLog(gwlogging.INFO, "MQTT-BLE Connected", MOD)
Exemplo n.º 25
0
    def __init__(self, client_id, server, topic=None, **kwargs):
        self.client = MQTTClient(client_id, server, **kwargs)
        if not topic:
            self.topic = 'test/%s/hello' % self.client.client_id
        else:
            self.topic = topic

        self.client.connect()
Exemplo n.º 26
0
def init_client(config):
    global mqtt_client
    mqtt_client = MQTTClient(config[cfg.idx('mqtt_cid')],
                        config[cfg.idx('mqtt_server')],
                   user = config[cfg.idx('mqtt_user')],
               password = config[cfg.idx('mqtt_pw')],
               keepalive = int(config[cfg.idx('mqtt_kalive')]))
    return mqtt_client
Exemplo n.º 27
0
 def __init__(self, uri, format):
     self.uri = uri
     self.format = format
     self.scheme, self.netloc, self.path, self.query, self.fragment = urlsplit(
         self.uri)
     self.connection = MQTTClient("umqtt_client", self.netloc)
     self.connection.DEBUG = True
     self.connection.connect()
Exemplo n.º 28
0
def mqtt1():  #HeartBeat Client
    isSSL = CONFIG.get('ssl')
    isUSR = CONFIG.get('usr')
    state = DISCONNECTED
    global client2
    if isSSL == True and isUSR == True:
        client2 = MQTTClient(MAC + "H",
                             CONFIG.get('host'),
                             user=CONFIG.get('user'),
                             password=CONFIG.get('pass'),
                             port=CONFIG.get('port'),
                             keepalive=10,
                             ssl=CONFIG.get('ssl'),
                             ssl_params={
                                 'cert_reqs': ssl.CERT_REQUIRED,
                                 'ca_certs': ROOT_CA,
                                 'certfile': CLIENT_CERT,
                                 'keyfile': PRIVATE_KEY
                             })
    elif isSSL == False and isUSR == True:
        client2 = MQTTClient(MAC + "H",
                             CONFIG.get('host'),
                             user=CONFIG.get('user'),
                             password=CONFIG.get('pass'),
                             port=CONFIG.get('port'),
                             keepalive=10,
                             ssl=CONFIG.get('ssl'))
    else:
        client2 = MQTTClient(MAC + "H",
                             CONFIG.get('host'),
                             user="",
                             password="",
                             port=CONFIG.get('port'),
                             keepalive=10,
                             ssl=CONFIG.get('ssl'))
    while state != CONNECTED:
        try:
            state = CONNECTING
            client2.connect()
            state = CONNECTED
        except:
            print('Could not establish MQTT-H connection')
            utime.sleep(0.5)
    if state == CONNECTED:
        print('MQTT-H Connected')
Exemplo n.º 29
0
def mqttSendQueue(inMqttBroker,
                  ioMqttCounter,
                  inMqttSendLimit=CONFIG['mqttSendLimit']):

    uping.ping(inMqttBroker, 1)
    topic = CONFIG["mqttMeasureTopic"]
    msgCount = 0

    mqttClient = MQTTClient(
        GLOBAL_MESSAGE_QUEUE.uniqueID(),
        inMqttBroker,
        ssl=CONFIG["mqttSSL"],
        user=CONFIG["mqttUser"],
        password=CONFIG["mqttPassword"],
    )
    mqttLastWill = ("-1, -1, -1, -1, -1, -1, -1, -1, -1, " +
                    GLOBAL_MESSAGE_QUEUE.uniqueID() + ", " +
                    MESSAGE_TYPES["mqttErrorMessage"] + ", " +
                    "UngracefulDisconnect, " +
                    "Ungraceful disruption of MQTT commit, ")
    printDebug("queue mqttLastWill", mqttLastWill)
    mqttClient.set_last_will(topic, mqttLastWill)

    try:
        mqttClient.connect()
        print("## Connected with MQTT Broker", inMqttBroker)
        printDataDebug("ioMqttData", ioMqttData)

        while (GLOBAL_MESSAGE_QUEUE.lenQ()[0] > 0
               and msgCount < inMqttSendLimit):
            msg = GLOBAL_MESSAGE_QUEUE.getMsg()
            mqttClient.publish(topic, json.dumps(msg))
            msgCount += 1
            ioMqttCounter += 1

    except Exception as e:
        sys.print_exception(e)
        errorMessage = mqttErrorMessage(
            GLOBAL_MESSAGE_QUEUE.uniqueID(),
            "Exception",
            "MQTTClientConnectError",
            str(e),
        )
        GLOBAL_MESSAGE_QUEUE.addMsg(errorMessage, "high")

    try:
        mqttClient.disconnect()
    except Exception as e:
        sys.print_exception(e)
        errorMessage = mqttErrorMessage(
            GLOBAL_MESSAGE_QUEUE.uniqueID(),
            "Exception",
            "MQTTClientDisconnectError",
            str(e),
        )
        GLOBAL_MESSAGE_QUEUE.addMsg(errorMessage, "high")
    return ioMqttCounter
Exemplo n.º 30
0
def connect_mqtt():
    global mqtt_clientID, mqtt_server
    client = MQTTClient(mqtt_clientID,
                        mqtt_server,
                        user=mqtt_username,
                        password=mqtt_username)
    client.connect()
    print("\nConnected to {} MQTT broker".format(mqtt_server))
    return client