Exemplo n.º 1
0
class MQTTReader:
    __slots__ = ('host', 'port', 'topic', 'client')

    def __init__(self, name, host, port, topic):
        self.topic = topic
        self.host = host
        self.port = port
        self.client = MQTTClient(name, host, port)
        self.client.set_callback(sub_cb)

        self._connect()

        self.client.subscribe(topic=self.topic)

    def _connect(self):
        print("Connecting to %s:%s" % (self.host, self.port))
        self.client.connect()
        print("Connection successful")

    def on_completed(self):
        print("mqtt_completed, disconnecting")
        self.client.disconnect()

    def on_error(self, e):
        print("mqtt on_error: %s, disconnecting" % e)
        self.client.disconnect()

    def disconnect(self):
        self.client.disconnect()

    def wait_msg(self):
        self.client.wait_msg()
Exemplo n.º 2
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.º 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()
def connect_mqtt():
    try:
        with open(KEY_FILE, "r") as f:
            key = f.read()

        print("MQTT received KEY")

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

        print("MQTT received CERTIFICATE")

        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()
        mqtt_client.set_callback(sub_cb)
        print("MQTT is connected")
        mqtt_client.subscribe(SHADOW_GET_TOPIC)
        print("Subscribed to %s topic" % (SHADOW_GET_TOPIC))
        while True:
            mqtt_client.publish(SHADOW_UPDATE_TOPIC, str(read_sensor_value()))
            mqtt_client.wait_msg()

    except Exception as e:
        print('Cannot connect to MQTT ' + str(e))
        raise
Exemplo n.º 5
0
 def start_mqtt(self, server="ops-senpai.5z.fyi"):
     c = MQTTClient("dog",
                    "ops-senpai.5z.fyi",
                    port=30001,
                    user="******",
                    password="******")
     c.set_callback(self._sub_cb)
     c.connect()
     c.subscribe(b"printme")
     try:
         while True:
             # Blocking wait for message
             c.wait_msg()
     finally:
         c.disconnect()
Exemplo n.º 6
0
def listen():
    global client
    global state
    #Create an instance of MQTTClient
    client = MQTTClient(CONFIG['CLIENT_ID'],
                        CONFIG['MQTT_BROKER'],
                        user=CONFIG['USER'],
                        password=CONFIG['PASSWORD'],
                        port=CONFIG['PORT'])
    # Attach call back handler to be called on receiving messages
    client.set_callback(onMessage)
    client.connect()
    client.subscribe(CONFIG['TOPIC'])
    client.subscribe('Acknowledgement')

    print("ESP8266 is Connected to %s and subscribed to %s topic" %
          (CONFIG['MQTT_BROKER'], CONFIG['TOPIC']))
    while (1):
        client.wait_msg()
Exemplo n.º 7
0
def main(server="broker.hivemq.com", topic=b"testtopic/1"):
    global msgRxd
    global msgTime

    msgCnt = 0
    connectOut = machine.Pin(13, machine.Pin.OUT)
    updateLedState(connectOut, msgCnt)
    
    print("Connecting to MQTT server: ", server)
    c = MQTTClient("umqtt_client", server)
    c.set_callback(sub_cb)
    c.connect()
    print("Subscribing to: ", topic)
    c.subscribe(topic)

    lastMsgTime = msgTime
    
    while True:
        # Set to True/False depending on whether you want to test
        # blocking I/O or not. NOTE: Setting to True makes it
        # difficult to Control-C when using WebREPL.
        if False:
            # Blocking wait for message
            print("Waiting for new message from topic: ", topic)
            c.wait_msg()
        else:
            # Non-blocking wait for message
            print("Checking for new message from topic: ", topic)
            c.check_msg()

        mtime = msgTime
        msg = msgRxd
        if mtime != lastMsgTime and msgRxd != None:
            print((topic, msg))
            lastMsgTime = mtime
            msgCnt = msgCnt + 1
            updateLedState(connectOut, msgCnt)
        else:
            # Then need to sleep to avoid 100% CPU usage (in a real
            # app other useful actions would be performed instead)
            time.sleep_ms(1000)

    c.disconnect()
Exemplo n.º 8
0
def main(server=mqtt_server):

    mqtt_client = MQTTClient(mqtt_clientID, mqtt_server)
    # mqtt berichten gaan naar deze callback functie
    mqtt_client.set_callback(sub_cb)
    # connecteer  op mqtt server
    mqtt_client.connect()
    # subscribe op de topics
    mqtt_client.subscribe(mqtt_topic)
    # status mqtt connectie
    print("Verbonden met mqtt %s, geabonneerd op %s topic" %
          (mqtt_server, mqtt_topic))

    try:
        while True:
            # wacht op mqtt messages
            mqtt_client.wait_msg()
    finally:
        # verbreek mqtt connectie
        mqtt_client.disconnect()
Exemplo n.º 9
0
def main():
	global client

	clearLeds()

	# Get settings from config.json
	while(getSettings() == False):
		time.sleep(10)
	
	# Connects to Wifi
	setup()

	# Open up the connection to MQTT
	print("Setting Up Connection To MQTT server")
	client = MQTTClient(clientName, mqttServerAddress)
	client.set_callback(messageReceived)

	# print("Waiting for Network")
	# conn = network.WLAN(network.STA_IF)
	# while(conn.ifconfig()[0] == '0.0.0.0'):
	# 	time.sleep(100)

	# print("Network Ready")

	# Try to connect to MQTT server
	print("Attempting to connect to MQTT server")
	try:
		client.connect()
	except:
		print("Failed. Network info:")
		print(network.WLAN(network.STA_IF).ifconfig())
	client.subscribe(channelName)
	print("Connected and Subscribed to %s channel" % channelName)


	# Listen to MQTT
	while(True):
		print("")
		print("Listening to channel")
		client.wait_msg();
Exemplo n.º 10
0
def main(server="localhost"):
    conn_wifi()
    client = MQTTClient("client_2",
                        "18.188.220.135",
                        user="******",
                        password="******",
                        port=1883)
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(b"hello/lights")
    while True:
        if True:
            # Blocking wait for message
            client.wait_msg()
        else:
            # Non-blocking wait for message
            client.check_msg()
            # Then need to sleep to avoid 100% CPU usage (in a real
            # app other useful actions would be performed instead)
            time.sleep(1)

    client.disconnect()
Exemplo n.º 11
0
    # gecodeerde text publiceren
    mqtt_cl.publish(TOPIC2, code)


# wifi object aanmaken
myWifi = simpleWifi.Wifi()
# connecteren met wifi
if not (myWifi.open()):
    myWifi.get_status()
    sys.exit()
# tonen status wifi
myWifi.get_status()

try:
    # mqtt client aanmaken
    mqtt_cl = MQTTClient('esp_frank_16', BROKER)
    # callback functie instellen
    mqtt_cl.set_callback(messages)
    # connecteren op mqtt broker
    mqtt_cl.connect()
    # subscriben op topic
    mqtt_cl.subscribe(TOPIC1)
    # wachten op broker berichten
    while True:
        mqtt_cl.wait_msg()
except Exception as e:
    print('Problemen met MQTT - %s' % e)
finally:
    mqtt_cl.disconnect()
    myWifi.close()
Exemplo n.º 12
0
thingspeakMqttApiKey = b"MQTT_API_KEY"  # EDIT - enter Thingspeak MQTT API Key
client = MQTTClient(client_id=myMqttClient,
                    server=thingspeakUrl,
                    user=thingspeakUserId,
                    password=thingspeakMqttApiKey,
                    ssl=False)
#
# callback to handle data when MQTT channel updates
#
client.set_callback(cb)
client.connect()

#
# subscribe a Thingspeak channel field using MQTT
#
thingspeakChannelId = b"CHANNEL_ID"  # EDIT - enter Thingspeak Channel ID
thingspeakChannelReadApiKey = b"READ_API_KEY"  # EDIT - enter Thingspeak Read API Key
subscribeTopic = bytes(
    "channels/{:s}/subscribe/fields/field1/{:s}".format(
        thingspeakChannelId, thingspeakChannelReadApiKey), 'utf-8')
client.subscribe(subscribeTopic)

#
# wait until new data has been Published to the Thingspeak channel
#
while True:
    client.wait_msg()
    time.sleep(1)

client.disconnect()
Exemplo n.º 13
0
class CatFeeder(object):
    def __init__(self):
        """"""
        self._client = None
        self._button = Pin(5, mode=Pin.IN, pull=Pin.PULL_UP)
        self._done_payload = 'Done feeding!'

        self._servo_buzz = Feeder(
            pin_servo=0,
            trigger=14,
            echo=2,
        )

        self._servo_tuxedo = Feeder(
            pin_servo=4,
            trigger=12,
            echo=13,
        )

        print('Instancing button and servos.')
        self._button.irq(handler=self.button_pressed, trigger=Pin.IRQ_RISING)
        print('Setting IRQ.')

    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()

    def button_pressed(self, pin):
        if pin.value():
            time.sleep_ms(300)
            print('#' * 80)
            self._client.publish(MANUAL_FEEDING, "")

    def on_message(self, topic, message):
        """"""
        print(topic, message)

        msg = message.strip().decode('utf-8')

        self._client.publish(LAST_FED_TOPIC, "Feeding...")
        self.feed()

    def feed(self):
        """"""
        time.sleep(0.2)
        self._servo_buzz.feed()
        print('fed buzz')
        time.sleep(1)
        print('pause 1 sec')
        self._servo_tuxedo.feed()
        print('fed tuxedo')

        self.done_feeding()

    def done_feeding(self):
        """"""
        time.sleep(0.2)
        self._client.publish(DONE_TOPIC, self._done_payload)
        time.sleep(0.2)
        self._client.publish(QTY_BUZZ_TOPIC,
                             self._servo_buzz.remaining_quantity)
        time.sleep(0.2)
        self._client.publish(QTY_TUXEDO_TOPIC,
                             self._servo_tuxedo.remaining_quantity)

        print("Done feeding!\n\n")
        print('/' * 80)
        print('Waiting for message...')
        while True:
            self._client.wait_msg()

    def run(self):
        self.mqtt_connect()

    def open_close_test(self, open_=48, pause=1):
        """"""
        self._servo_buzz.open_position = open_
        self._servo_tuxedo.open_position = open_
        self._servo_buzz.pause_open = pause
        self._servo_tuxedo.pause_open = pause

        self._servo_buzz.feed()
        print('fed buzz')
        time.sleep(1)
        print('pause 1 sec')
        self._servo_tuxedo.feed()

        while True:
            self._client.wait_msg()
Exemplo n.º 14
0
    myWifi.get_status()
    sys.exit()
myWifi.get_status()

try:
    # mqtt client aanmaken
    mqttCl = MQTTClient(ID, BROKER)
    # callback functie instellen voor ontvangen berichten
    mqttCl.set_callback(mqttMsg)
    # connectie maken met mqtt broker
    mqttCl.connect()
    # subscriben op TOPIC
    mqttCl.subscribe(TOPIC1)
    # wachten op mqtt berichten
    while True:
        mqttCl.wait_msg()
        utime.sleep(10)

except Exception as e:
    print("mqtt of netwerk probleem - %s" % e)

finally:
    # led uit
    pLed1.value(0)
    # als wifi aan
    if myWifi.get_status() == 1:
        # als mqtt client aan
        if mqttCl != None:
            # mqtt client afzetten
            mqttCl.disconnect()
        # wifi afzetten
Exemplo n.º 15
0
class Web:
    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 = {}

    def getConnected(self):
        return self.Connected

    def connectToWifi(self):
        # WiFi connection information
        WIFI_SSID = self.wifiName
        WIFI_PASSWORD = self.wifiPassword

        # 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(WIFI_SSID, WIFI_PASSWORD)

        # wait until the device is connected to the WiFi network
        MAX_ATTEMPTS = 20
        attempt_count = 0
        while not wifi.isconnected() and attempt_count < MAX_ATTEMPTS:
            attempt_count += 1
            time.sleep(1)

        if attempt_count == MAX_ATTEMPTS:
            print('could not connect to the WiFi network')
            self.Connected = "F"
            wifi.active(False)
            return Offline.Offline("Offline_Data.txt")

        self.Connected = "T"
        return self

    def connectToMQTT(self):
        try:
            self.client.connect()
            return 0
        except Exception:
            return -1

    def cb(self, topic, msg):
        tp = str(topic, 'utf-8')
        tp = (tp.split('/'))[-1]
        ms = float(str(msg, 'utf-8'))
        self.values[tp] = ms

    def _subscribe(self, feedname):
        mqtt_feedname = bytes(
            '{:s}/feeds/{:s}'.format(self.ADAFRUIT_USERNAME, feedname),
            'utf-8')
        self.client.set_callback(self.cb)
        self.client.subscribe(mqtt_feedname)

        mqtt_feedname_get = bytes(
            '{:s}/feeds/{:s}/get'.format(self.ADAFRUIT_USERNAME, feedname),
            'utf-8')
        self.client.publish(mqtt_feedname_get, '\0')

        self.client.wait_msg()

    def publish(self, feedname, stringToPublish):
        mqtt_feedname = bytes(
            '{:s}/feeds/{:s}'.format(self.ADAFRUIT_USERNAME, feedname),
            'utf-8')

        self.client.publish(mqtt_feedname,
                            bytes(stringToPublish, 'utf-8'),
                            qos=0)

    def subscribe_to_keys(self, listOfKeys):
        for s in listOfKeys:
            bs = str(s, 'utf-8')
            self.values[s] = -9999
            self._subscribe(bs)

    def get_latest_value(self, key):
        return self.values[key]

    def update_values(self):
        self.client.check_msg()
Exemplo n.º 16
0
class MQTTReaderAWS:
    __slots__ = ('host', 'port', 'topic', 'client')

    def __init__(self, client_id, host, port, topic, key_file, cert_file):
        self.client_id = client_id
        self.host = host
        self.port = port
        self.topic = topic
        self.key_file = key_file
        self.cert_file = cert_file
        self.mqtt_client = None

        self.connect_mqtt()

        self.mqtt_client.set_callback(sub_cb)
        self.mqtt_client.subscribe(topic=self.topic)

    def connect_mqtt(self):

        try:
            with open(self.key_file, "r") as f:
                key = f.read()
            print("Got Key")

            with open(self.cert_file, "r") as f:
                cert = f.read()
            print("Got Cert")

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

        except Exception as e:
            print('Cannot connect MQTT: ' + str(e))
            raise

    def disconnect(self):
        self.mqtt_client.disconnect()

    # Checks whether a pending message from server is available.
    # If not, returns immediately with None. Otherwise, does
    # the same processing as wait_msg.
    def wait_msg(self):
        self.mqtt_client.wait_msg()

    # Wait for a single incoming MQTT message and process it.
    # Subscribed messages are delivered to a callback previously
    # set by .set_callback() method. Other (internal) MQTT
    # messages processed internally.
    def check_msg(self):
        try:
            self.mqtt_client.check_msg()
        except:
            pass

    # Behaves like wait_msg, but worse
    def subscribe(self):
        self.mqtt_client.subscribe(self.topic, 0)

    def last_msg(self):
        return (str(MESSAGE, 'utf-8'))
Exemplo n.º 17
0
        print(e)
        
#conexion a red wifi
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect("ssid", "pass")
time.sleep(5)

#credenciales para conexion a ubidots
ubidotsToken = "token"
clientID = "espcontrol"
topic=b"/v1.6/devices/espprueba/r/lv" #el topic define a que device en especifico es que se va a subir datos
                                 #b"/v1.6/devices/{NOMBRE_DISPOSITIVO}" en el que NOMBRE_DISPOSITIVO es quien
                                 #define entre los devices creados al cual se quiere subir el dato

#inicializacion de cliente para mqtt y conexion
client = MQTTClient(clientID, "industrial.api.ubidots.com", 1883, user = ubidotsToken, password = ubidotsToken) #creacion de objeto
client.connect() #conexion a ubidots

client.set_callback(cb) #seteo de funcion de callback                  
client.subscribe(topic) #conectarse a topics definidos
client.subscribe(b"/v1.6/devices/espprueba/g/lv")
client.subscribe(b"/v1.6/devices/espprueba/b/lv")

while True:
    try:
        client.wait_msg() #recepcion del dato     
    except Exception as e:
        print(e)
        client.disconnect()
        sys.exit()
Exemplo n.º 18
0
class IoTCClient():
    def __init__(self,
                 id_scope,
                 device_id,
                 credentials_type: IoTCConnectType,
                 credentials,
                 logger=None,
                 storage=None):
        self._device_id = device_id
        self._id_scope = id_scope
        self._credentials_type = credentials_type
        self._content_type = 'application%2Fjson'
        self._content_encoding = 'utf-8'
        self._connected = False
        self._credentials = credentials
        self._storage = storage
        self._events = {}
        self._model_id = None
        if logger is not None:
            self._logger = logger
        else:
            self._logger = ConsoleLogger(IoTCLogLevel.API_ONLY)
        self._twin_request_id = time()

    def set_content_type(self, content_type):
        self._content_type = encode_uri_component(content_type)

    def set_content_encoding(self, content_encoding):
        self._content_encoding = content_encoding

    def set_log_level(self, log_level: IoTCLogLevel):
        self._logger.set_log_level(log_level)

    def _on_message(self, topic, message):
        topic = topic.decode('utf-8')
        self._logger.debug(topic)
        if topic == HubTopics.TWIN_RES.format(200, self._twin_request_id):
            self._logger.info('Received twin: {}'.format(message))

        if topic.startswith(HubTopics.PROPERTIES):
            # desired properties
            self._logger.info(
                'Received desired property message: {}'.format(message))
            message = json.loads(message.decode('utf-8'))
            self.on_properties_update(message)

        elif topic.startswith(HubTopics.COMMANDS):
            # commands
            match = self._commands_regex.match(topic)
            if match is not None:
                if all(m is not None for m in [match.group(1),
                                               match.group(2)]):
                    command_name = match.group(1)
                    command_req = match.group(2)
                    command = Command(command_name, message)
                    try:
                        command_name_with_components = command_name.split("*")

                        if len(command_name_with_components) > 1:
                            # In a component
                            self._logger.debug("Command in a component")
                            command = Command(
                                command_name_with_components[1],
                                message,
                                component_name=command_name_with_components[0],
                            )

                        def reply_fn():
                            self._logger.debug(
                                'Acknowledging command {}'.format(
                                    command.name))
                            self._mqtt_client.publish(
                                '$iothub/methods/res/{}/?$rid={}'.format(
                                    200, command_req).encode('utf-8'), '')
                            if command.component_name is not None:
                                self.send_property({
                                    "{}".format(command.component_name): {
                                        "{}".format(command.name): {
                                            "value": command.value,
                                            "requestId": command_req
                                        }
                                    }
                                })
                            else:
                                self.send_property({
                                    "{}".format(command.name): {
                                        "value": command.value,
                                        "requestId": command_req
                                    }
                                })

                        command.reply = reply_fn
                        self._on_commands(command)
                        sleep(0.1)
                    except:
                        pass

        elif topic.startswith(
                HubTopics.ENQUEUED_COMMANDS.format(self._device_id)):
            params = topic.split(
                "devices/{}/messages/devicebound/".format(self._device_id),
                1)[1].split('&')
            for param in params:
                p = param.split('=')
                if p[0] == "method-name":
                    command_name = decode_uri_component(p[1])
                    command = Command(command_name, message)
                    try:
                        command_name_with_components = command_name.split("*")

                        if len(command_name_with_components) > 1:
                            # In a component
                            self._logger.debug("Command in a component")
                            command = Command(
                                command_name_with_components[1],
                                message,
                                component_name=command_name_with_components[0],
                            )
                    except:
                        pass

                    self._logger.debug(
                        'Received enqueued command {} with message: {}'.format(
                            command.name, command.value))
                    self._on_enqueued_commands(command)

    def connect(self, force_dps=False):
        creds = None

        if force_dps:
            self._logger.info("Refreshing credentials...")

        if self._storage is not None and force_dps is False:
            creds = self._storage.retrieve()

        if creds is None:
            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,
                                       creds.password,
                                       ssl=True,
                                       keepalive=60)
        self._commands_regex = ure.compile(
            '\$iothub\/methods\/POST\/(.+)\/\?\$rid=(.+)')
        try:
            self._mqtt_client.connect(False)
            self._connected = True
            self._logger.info('Device connected!')
            if self._storage:
                self._storage.persist(creds)
            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'), '{{}}')
        except:
            self._logger.info("ERROR: Failed to connect to Hub")
            if force_dps is True:
                exit(1)
            self.connect(True)

    def is_connected(self):
        if self._connected == True:
            return True
        return False

    def set_model_id(self, model):
        self._model_id = model

    def send_property(self, payload):
        self._logger.debug('Sending properties {}'.format(json.dumps(payload)))
        self._mqtt_client.publish(
            HubTopics.PROP_REPORT.format(time()).encode('utf-8'),
            json.dumps(payload))

    def send_telemetry(self, payload, properties=None):
        topic = 'devices/{}/messages/events/?$.ct={}&$.ce={}'.format(
            self._device_id, self._content_type, self._content_encoding)
        if properties is not None:
            for prop in properties:
                topic += '&{}={}'.format(prop, properties[prop])

        self._mqtt_client.publish(topic.encode('utf-8'),
                                  json.dumps(payload).encode('utf-8'))

    def on(self, event, callback):
        self._events[event] = callback

    def listen(self):
        if not self.is_connected():
            return
        self._mqtt_client.ping()
        self._mqtt_client.wait_msg()
        sleep(0.5)

    def _handle_property_ack(
        self,
        callback,
        property_name,
        property_value,
        property_version,
        component_name=None,
    ):
        if callback is not None:
            ret = callback(property_name, property_value, component_name)
        else:
            ret = True
        if ret:
            if component_name is not None:
                self._logger.debug("Acknowledging {}".format(property_name))
                self.send_property({
                    "{}".format(component_name): {
                        "{}".format(property_name): {
                            "ac": 200,
                            "ad": "Property received",
                            "av": property_version,
                            "value": property_value,
                        }
                    }
                })
            else:
                self._logger.debug("Acknowledging {}".format(property_name))
                self.send_property({
                    "{}".format(property_name): {
                        "ac": 200,
                        "ad": "Property received",
                        "av": property_version,
                        "value": property_value,
                    }
                })
        else:
            self._logger.debug(
                'Property "{}" unsuccessfully processed'.format(property_name))

    def on_properties_update(self, patch):
        try:
            prop_cb = self._events[IoTCEvents.PROPERTIES]
        except:
            return
        # Set component at false by default
        is_component = False

        for prop in patch:
            is_component = False
            if prop == "$version":
                continue

            # check if component
            try:
                is_component = patch[prop]["__t"]
            except KeyError:
                pass
            if is_component:
                for component_prop in patch[prop]:
                    if component_prop == "__t":
                        continue
                    self._logger.debug(
                        'In component "{}" for property "{}"'.format(
                            prop, component_prop))
                    self._handle_property_ack(
                        prop_cb,
                        component_prop,
                        patch[prop][component_prop]["value"],
                        patch["$version"],
                        prop,
                    )
            else:
                self._handle_property_ack(prop_cb, prop, patch[prop]["value"],
                                          patch["$version"])

    def _cmd_resp(self, command: Command, value):
        self._logger.debug('Responding to command "{}" request'.format(
            command.name))
        self.send_property({
            '{}'.format(command.name): {
                'value': value,
                'requestId': command.request_id
            }
        })

    def _on_commands(self, command: Command):
        try:
            cmd_cb = self._events[IoTCEvents.COMMANDS]
        except KeyError:
            return

        self._logger.debug('Received command {}'.format(command.name))
        cmd_cb(command)

    def _on_enqueued_commands(self, command: Command):
        try:
            cmd_cb = self._events[IoTCEvents.ENQUEUED_COMMANDS]
        except KeyError:
            return

        self._logger.debug('Received enqueued command {}'.format(command.name))

        cmd_cb(command)
Exemplo n.º 19
0
class IoTCClient():
    def __init__(self,
                 id_scope,
                 device_id,
                 credentials_type: IoTCConnectType,
                 credentials,
                 logger=None):
        self._device_id = device_id
        self._id_scope = id_scope
        self._credentials_type = credentials_type
        self._content_type = 'application%2Fjson'
        self._content_encoding = 'utf-8'
        self._connected = False
        self._credentials = credentials
        self._events = {}
        self._model_id = None
        if logger is not None:
            self._logger = logger
        else:
            self._logger = ConsoleLogger(IoTCLogLevel.API_ONLY)
        self._twin_request_id = time()

    def set_content_type(self, content_type):
        self._content_type = encode_uri_component(content_type)

    def set_content_encoding(self, content_encoding):
        self._content_encoding = content_encoding

    def set_log_level(self, log_level: IoTCLogLevel):
        self._logger.set_log_level(log_level)

    def _on_message(self, topic, message):
        topic = topic.decode('utf-8')
        if topic == HubTopics.TWIN_RES.format(200, self._twin_request_id):
            self._logger.info('Received twin: {}'.format(message))

        if topic.startswith(HubTopics.PROPERTIES):
            # desired properties
            self._logger.info(
                'Received desired property message: {}'.format(message))
            message = json.loads(message.decode('utf-8'))
            self.on_properties_update(message)

        elif topic.startswith(HubTopics.COMMANDS):
            # commands
            self._logger.info('Received command {} with message: {}'.format(
                topic, message))
            match = self._commands_regex.match(topic)
            if match is not None:
                if all(m is not None for m in [match.group(1),
                                               match.group(2)]):
                    command_name = match.group(1)
                    command_req = match.group(2)
                    command = Command(command_name, command_req)
                    if message is not None:
                        command.payload = message
                    self._on_commands(command)

        elif topic.startswith(
                HubTopics.ENQUEUED_COMMANDS.format(self._device_id)):
            params = topic.split(
                "devices/{}/messages/devicebound/".format(self._device_id),
                1)[1].split('&')
            for param in params:
                p = param.split('=')
                if p[0] == "method-name":
                    command_name = p[1].split("Commands%3A")[1]

            self._logger.info(
                'Received enqueued command {} with message: {}'.format(
                    command_name, message))
            command = Command(command_name, None)
            if message is not None:
                command.payload = message
            self._on_enqueued_commands(command)

    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'),
            '{{}}')

    def is_connected(self):
        if self._connected == True:
            return True
        return False

    def set_model_id(self, model):
        self._model_id = model

    def send_property(self, payload):
        self._logger.debug('Sending properties {}'.format(json.dumps(payload)))
        self._mqtt_client.publish(
            HubTopics.PROP_REPORT.format(time()).encode('utf-8'),
            json.dumps(payload))

    def send_telemetry(self, payload, properties=None):
        topic = 'devices/{}/messages/events/?$.ct={}&$.ce={}'.format(
            self._device_id, self._content_type, self._content_encoding)
        if properties is not None:
            for prop in properties:
                topic += '{}={}&'.format(
                    encode_uri_component(prop),
                    encode_uri_component(properties[prop]))

            topic = topic[:-1]
        self._mqtt_client.publish(topic.encode('utf-8'),
                                  json.dumps(payload).encode('utf-8'))

    def on(self, event, callback):
        self._events[event] = callback

    def listen(self):
        if not self.is_connected():
            return
        self._mqtt_client.ping()
        self._mqtt_client.wait_msg()
        sleep(1)

    def on_properties_update(self, patch):
        try:
            prop_cb = self._events[IoTCEvents.PROPERTIES]
        except:
            return

        for prop in patch:
            if prop == '$version':
                continue
            ret = prop_cb(prop, patch[prop]['value'])
            if ret:
                self._logger.debug('Acknowledging {}'.format(prop))
                self.send_property({
                    '{}'.format(prop): {
                        "value": patch[prop]["value"],
                        'status': 'completed',
                        'desiredVersion': patch['$version'],
                        'message': 'Property received'
                    }
                })
            else:
                self._logger.debug(
                    'Property "{}" unsuccessfully processed'.format(prop))

    def _cmd_resp(self, command: Command, value):
        self._logger.debug('Responding to command "{}" request'.format(
            command.name))
        self.send_property({
            '{}'.format(command.name): {
                'value': value,
                'requestId': command.request_id
            }
        })

    def _cmd_ack(self, command: Command):
        self._logger.debug('Acknowledging command {}'.format(command.name))
        self._mqtt_client.publish(
            '$iothub/methods/res/{}/?$rid={}'.format(
                200, command.request_id).encode('utf-8'), '')

    def _on_commands(self, command: Command):
        try:
            cmd_cb = self._events[IoTCEvents.COMMANDS]
        except KeyError:
            return

        self._logger.debug('Received command {}'.format(command.name))
        self._cmd_ack(command)

        cmd_cb(command, self._cmd_resp)

    def _on_enqueued_commands(self, command: Command):
        try:
            cmd_cb = self._events[IoTCEvents.ENQUEUED_COMMANDS]
        except KeyError:
            return

        self._logger.debug('Received enqueued command {}'.format(command.name))
        self._cmd_ack(command)

        cmd_cb(command)
Exemplo n.º 20
0
                strip.write()
                time.sleep(parsed['s'])
    strip.fill([0, 0, 0, 0])
    strip.write()


def handle_mqtt_message(topic, message):
    if topic == MQTT_PREFIX + b'json':
        process_json(message)


if __name__ == '__main__':
    strip = apa102.APA102(machine.Pin(APA102_PIN_CI),
                              machine.Pin(APA102_PIN_DI),
                              APA102_PIXELS)
    strip.fill([0, 0, 0, 0])
    strip.write()
    del strip
    wlan = network.WLAN(network.STA_IF)
    while not wlan.isconnected():
        pass  # Wait until connected to wifi
    mqtt = MQTTClient("gyro", MQTT_BROKER)
    mqtt.set_callback(handle_mqtt_message)
    mqtt.connect()
    mqtt.subscribe(MQTT_PREFIX + b'json')
    while True:
        try:
            mqtt.wait_msg()
        except:
            pass  # Ignore errors in request handling
Exemplo n.º 21
0
class Mqtt:
    def __init__(self,
                 mqttapi,
                 ADAFRUIT_IO_URL=b'io.adafruit.com',
                 ADAFRUIT_USERNAME=b'Dreambot',
                 ADAFRUIT_IO_KEY=b'aio_AdWB65gxoBGd08a7ja2Ws0DJr1WJ',
                 mqtt_client_id=bytes(
                     'client_' + str(int.from_bytes(os.urandom(3), 'little')),
                     'utf-8'),
                 WIFI_SSID='Bendix',
                 WIFI_PASSWORD='******',
                 MAX_ATTEMPTS=20,
                 attempt_count=0):

        self.ADAFRUIT_USERNAME = ADAFRUIT_USERNAME

        self.mqttapi = mqttapi

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

        # turn off the WiFi Access Point
        self.ap_if = network.WLAN(network.AP_IF)
        self.ap_if.active(False)

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

        # wait until the device is connected to the WiFi network
        while not self.wifi.isconnected() and attempt_count < MAX_ATTEMPTS:
            attempt_count += 1
            time.sleep(1)
            print(attempt_count)

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

        try:
            self.client.connect()
        except Exception as e:
            print('could not connect to MQTT server {}{}'.format(
                type(e).__name__, e))
            sys.exit()

        self.client.set_callback(self.cb)

        self.feednames = [
            b'Peltier Element',
            b'Fan',
            b'P',
            b'I',
            b'D',
        ]

        for feedname in self.feednames:
            txt = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, feedname),
                        'utf-8')
            self.client.subscribe(txt)

    def __call__(self):
        try:
            self.client.wait_msg()
        except KeyboardInterrupt:
            print('Ctrl-C pressed...exiting')
            self.client.disconnect()
            sys.exit()

    def cb(self, topic, msg):
        try:
            self.mqttapi[topic](str(msg, 'utf-8'))
        except Exception as e:
            print(e)
            print("missing key in " + str(topic, 'utf-8'))
        finally:
            print(topic)
            print(msg)

    def publish(self, topic, value):
        try:
            mqtt_feedname = bytes(
                '{:s}/feeds/{:s}'.format(self.ADAFRUIT_USERNAME, topic),
                'utf-8')
            self.client.publish(mqtt_feedname,
                                bytes(str(value), 'utf-8'),
                                qos=0)
        except KeyboardInterrupt:
            print('Ctrl-C pressed...exiting')
            self.client.disconnect()
            sys.exit()
        finally:
            return value
Exemplo n.º 22
0
class UnmanagedDevice:
    """
    An "unmanaged device" for the Watson IoT platform.

    Can be used with "Quickstart";
    see https://quickstart.internetofthings.ibmcloud.com
    """
    decoders = {}
    encoders = {}
    commands = {}

    def __init__(self,
                 org=QUICKSTART_ORG,
                 device_type=None,
                 device_id=None,
                 username='******',
                 token='',
                 port=8883,
                 clean_session=True,
                 domain=DOMAIN,
                 ssl_params=None,
                 log_level='info'):
        """
        Builds proper params for connecting to IoT platform MQTT broker.
        Registers JSON encoder & decoder.
        Creates MQTT client object, but does not connect.

        `quickstart` implies an *insecure* connection!

        `device_type` and `token` not necessary if `org` is `quickstart`.

        :param log_level: Logging level
        :type log_level: str
        :param org: IoT platform organization
        :type org: str
        :param device_type: IoT platform device type
        :type device_type: str
        :param device_id: IoT platform client identifier
        :type device_id: str
        :param username: IoT platform username
        :type username: str
        :param token: IoT platform API token
        :type token: str
        :param port: MQTT broker port
        :type port: int
        :param clean_session: Whether to use a clean session when connecting
        :type clean_session: bool
        :param domain: IoT platform domain name
        :type domain: str
        :param ssl_params: Additional SSL parameters for a secure connection
        :type ssl_params: dict
        """
        if not device_id:
            raise Exception('"device_id" parameter required')
        self.org = org

        if not self.is_quickstart:
            if not device_type:
                raise Exception('"device_type" parameter required')
            if not token:
                raise Exception('"token" parameter required')

        self.username = username
        self.token = token
        self.device_type = device_type
        self.address = '%s.messaging.%s' % (org, domain)
        self.client_id = 'd:%s:%s:%s' % (self.org, self.device_type, device_id)
        self.port = port
        self.keep_alive = 60
        self.logger = logging.getLogger(
            '%s.%s' % (self.__module__, self.__class__.__name__))
        self.logger.level = LOG_LEVELS[log_level]

        self.clean_session = clean_session
        self.ssl_params = ssl_params or {}

        self.client = MQTTClient(self.client_id,
                                 self.address,
                                 user=self.username,
                                 password=self.token,
                                 keepalive=60,
                                 ssl=self.is_secure,
                                 ssl_params=self.ssl_params)
        if self.logger.level == logging.DEBUG:
            self.client.DEBUG = True
        self.set_decoder('json', bytes_to_json)
        self.set_encoder('json', json.dumps)
        self.set_decoder('text', bytes_to_utf8)
        # noinspection PyTypeChecker
        self.set_encoder('text', str)

    @property
    def is_connected(self):
        """
        Crudely checks connectivity by pinging
        :return: Whether or not socket is alive
        :rtype: bool
        """
        try:
            self.client.ping()
            return True
        except OSError:
            return False

    def set_encoder(self, name, func):
        """
        "Registers" an encoder
        :param name: Name of encoder
        :type name: str
        :param func: Encoding function
        :type func: function
        """
        self.encoders[name] = func

    def unset_encoder(self, name):
        """
        "Un-registers" a encoder
        :param name: Name of existing encoder
        :type name: str
        """
        try:
            del self.encoders[name]
        except KeyError:
            pass

    def set_decoder(self, name, func):
        """
        "Registers" a decoder
        :param name: Name of decoder
        :type name: str
        :param func: Decoding function
        :type func: function
        """
        self.decoders[name] = func

    def unset_decoder(self, name):
        """
        "Un-registers" a decoder
        :param name: Name of existing decoder
        :type name: str
        """
        try:
            del self.decoders[name]
        except KeyError:
            pass

    def set_command(self, command_id, handler):
        """
        "Registers" a command handler (if org is not "quickstart")
        :param command_id: Command ID
        :type command_id: str
        :param handler: Command handler
        :type handler: function
        """
        if self.is_quickstart:
            raise Exception('"quickstart" org does not support commands')
        self.commands[command_id] = handler

    def unset_command(self, command_id):
        """
        "Unregisters" a command
        :param command_id: Command ID
        :type command_id: str
        """
        try:
            del self.commands[command_id]
        except KeyError:
            pass

    @property
    def is_secure(self):
        """
        Secure connection? `False` if `org` is `quickstart`
        :return: Whether or not SSL is enabled.
        :rtype: bool
        """
        return self.port == 8883 and not self.is_quickstart

    @property
    def is_quickstart(self):
        """
        Is "quickstart" org?
        :return: Whether or not `org` is `quickstart`
        :rtype: bool
        """
        return self.org == QUICKSTART_ORG

    def connect(self):
        """
        Connects to the MQTT broker.  If not a "quickstart" org,
        then subscribes to commands.
        """
        self.client.connect(self.clean_session)
        self.logger.debug('client "%s" connected to %s:%s' %
                          (self.client_id, self.address, self.port))

        if not self.is_quickstart:

            def message_callback(topic, message):
                """
                Callback executed when a msg for a subscribed topic is received
                :param topic: Raw MQTT topic
                :type topic: bytes
                :param message: Raw MQTT message
                :type message: bytes
                """
                topic = bytes_to_utf8(topic)
                matches = TOPIC_REGEX.match(topic)
                command_id = matches.group(1)
                message_format = matches.group(2)
                if message_format in self.decoders:
                    message = self.decoders[message_format](message)
                else:
                    self.logger.debug(
                        'no suitable decoder for message format "%s"' %
                        message_format)
                self.logger.debug('topic: %s\nmessage: %s' % (topic, message))
                if command_id in self.commands:
                    self.logger.info('received command "%s"' % command_id)
                    self.commands[command_id](message)
                else:
                    self.logger.warning('command "%s" received, \
but no handler registered' % command_id)

            self.client.set_callback(message_callback)
            self.client.subscribe(DEVICE_COMMAND_TOPIC)
            self.logger.debug('subscribed to device command topic: %s',
                              DEVICE_COMMAND_TOPIC)

    def publishEvent(self, event_id, payload, message_format='json', qos=0):
        """
        Publishes an event
        :param event_id: Event ID
        :type event_id: str
        :param payload: Event payload
        :type payload: Any
        :param message_format: Message format
        :type message_format: str
        :param qos: Quality of Service
        :type qos: int
        """
        if not self.is_connected:
            raise Exception('client is not connected')
        if qos == 2:
            raise Exception('QoS level 2 not implemented')
        event_id = event_id.strip()
        if message_format in self.encoders:
            payload = self.encoders[message_format](payload)
        self.client.publish('iot-2/evt/%s/fmt/%s' % (event_id, message_format),
                            payload, qos)

    def disconnect(self):
        """
        Disconnects (if connected)
        """
        try:
            self.client.disconnect()
            self.logger.warning('Closed connection to the IBM Watson \
IoT Platform')
        except OSError:
            self.logger.warning('Attempted to disconnect from a \
            disconnected socket')

    def loop(self):
        """
        Non-blocking check-for-messages.  You need to do something else
        after this, such as `time.sleep(1)`, or other meaningful work,
        if you are going to do this in a busy-loop.

        This appears unsupported in some environments (incl. unix)
        """
        self.client.check_msg()

    def sync_loop(self):
        """
        Blocking check-for-messages.  Run this in a busy-loop.
        """
        self.client.wait_msg()
Exemplo n.º 23
0
c.set_callback(sub_cb)
# Connect to server, requesting not to clean session for this
# client. If there was no existing session (False return value
# from connect() method), we perform the initial setup of client
# session - subscribe to needed topics. Afterwards, these
# subscriptions will be stored server-side, and will be persistent,
# (as we use clean_session=False).
#
# There can be a problem when a session for a given client exists,
# but doesn't have subscriptions a particular application expects.
# In this case, a session needs to be cleaned first. See
# example_reset_session.py for an obvious way how to do that.
#
# In an actual application, it's up to its developer how to
# manage these issues. One extreme is to have external "provisioning"
# phase, where initial session setup, and any further management of
# a session, is done by external tools. This allows to save resources
# on a small embedded device. Another extreme is to have an application
# to perform auto-setup (e.g., clean session, then re-create session
# on each restart). This example shows mid-line between these 2
# approaches, where initial setup of session is done by application,
# but if anything goes wrong, there's an external tool to clean session.
if not c.connect(clean_session=False):
    print("New session being set up")
    c.subscribe(b"foo_topic")

while 1:
    c.wait_msg()

c.disconnect()
Exemplo n.º 24
0
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(WIFI_SSID, WIFI_PW)
sta_if.ifconfig()

client = MQTTClient(client_id=MQTT_CLIENT_ID,
                    server=MQTT_HOST,
                    port=8883,
                    keepalive=4000,
                    ssl=True,
                    ssl_params={
                        "key": key,
                        "cert": cert,
                        "server_side": False
                    })


def subfunc(topic, msg):
    print(msg)


client.set_callback(subfunc)
client.connect()
print("Connect")
client.subscribe(topic=SUB_MQTT_TOPIC)

LED = Pin(14, Pin.OUT)

while True:
    print(type(client.wait_msg()))