Пример #1
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()
Пример #2
0
class MQTTWriter:
  __slots__ = ('client')
  def __init__(self, id='1', server='io.adafruit.com', user='******',  password = '******', port=1883):
    self.client = MQTTClient(
    client_id=id, 
    server=server, 
    user=user, 
    password='******', 
    port=port
    )
    self._connect()

  def _connect(self):
    print("Connecting....."))
    self.client.connect()
    print("Connection successful")

  def on_next(self, topic, data):
    # data = bytes(json.dumps(x), 'utf-8')
    # self.client.publish(bytes(self.topic, 'utf-8'), data)
    self.client.publish(topic=topic, msg=data)

  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()
Пример #3
0
class MQTT_MESSAGE:
    def __init__(self, server):
        self.station = network.WLAN(network.STA_IF)
        # self.station.ifconfig(
        #     ('192.168.3.201', '255.255.255.0', '192.168.3.1', '192.168.3.1'))
        self.server = server
        self.station.active(True)
        self.station.connect()
        while self.station.isconnected() == False:
            pass
        print('wifi connected')
        client_id = ubinascii.hexlify(machine.unique_id()) + '-bbb'
        print(client_id, self.server)

        self.client = MQTTClient(client_id, self.server)
        self.client.connect()
        print('mqtt connected')

    def restart_and_reconnect():
        print('Failed to connect to MQTT broker. Reconnecting...')
        utime.sleep(10)
        machine.reset()

    def send(self, topic, payload):

        try:

            self.client.publish(topic, json.dumps(payload))
            # client.disconnect()
            print('message sent')
        except OSError as e:
            client.disconnect()
            restart_and_reconnect()
        except:
            client.disconnect()
Пример #4
0
def main():
    config = utils.Config()

    # On board LED
    led = machine.Pin(2, machine.Pin.OUT, machine.Pin.PULL_UP)

    sensor = dht.DHT22(machine.Pin(config.get("dht_gpio", 4)))

    client_id = "esp8266_" + ubinascii.hexlify(machine.unique_id()).format()
    client = MQTTClient(client_id, config.get("mqtt_broker"),
                        config.get("mqtt_port"), config.get("mqtt_user"),
                        config.get("mqtt_passwd"))
    try:
        client.connect()
    except OSError as e:
        # Just report and continue, since publish will try to reconnect
        print("Error when connecting to the MQTT broker")
    else:
        print("Connected to {}".format(config.get("mqtt_broker")))

    # Iterate and publish
    while True:
        sensor.measure()
        led.low()
        client.publish("{}/temperature".format(config.get("mqtt_topic")),
                                      str(sensor.temperature()))
        client.publish("{}/humidity".format(config.get("mqtt_topic")),
                                      str(sensor.humidity()))
        led.high()
        time.sleep(5)
Пример #5
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()
Пример #6
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()
Пример #7
0
class AsyncMqttMessages(object):
    def __init__(self):
        config = Config()
        self.heatmessage = {'Heating': ''}
        self.tempMessage = {'TempIN': '', 'TempOUT': ''}
        self.mqttID = config.mqttID
        self.mqttBroker = config.mqttBroker
        self.user = config.mqttUser
        self.password = config.mqttPassword
        self.client = MQTTClient(self.mqttID, self.mqttBroker, 1883, self.user,
                                 self.password)
        self.client.connect()
        self.client.set_callback(sub_cb)
        self.client.subscribe(topic="home/attackHeater/stat")

    def publishHeat(self, message):
        self.heatmessage['Heating'] = message
        m = ujson.dumps(self.heatmessage)
        self.client.publish(topic="home/attacHeater/heating", msg=m)

    def publishTemp(self, temp_in, temp_out):
        self.tempMessage['TempIN'] = temp_in
        self.tempMessage['TempOUT'] = temp_out
        m = ujson.dumps(self.tempMessage)
        self.client.publish(topic="home/attacHeater/heating", msg=m)
Пример #8
0
def connect_and_subscribe(sub_callback=None):
    """Connectes to MQTT-Host and subscribes to topics. MQTT-IP, -Port and Topics must be defined in
    credentials.json.

    Args:
        sub_callback (func(topic, msg), optional): Callback-Function when message is recieved.

    Returns:
        MQTT-Client
    """
    with open("credentials.json", "r") as f:
        credentials = ujson.load(f)

    try:
        from umqtt.robust import MQTTClient
    except ImportError as e:
        import upip
        upip.install('micropython-umqtt.simple')
        upip.install('micropython-umqtt.robust')
        from umqtt.robust import MQTTClient

    # Set Options for MQTT-Broker
    client = MQTTClient(ubinascii.hexlify(machine.unique_id()),
                        credentials["mqtt"]["host"],
                        credentials["mqtt"]["port"])
    # Set callback to handle Messages
    if sub_callback is not None:
        client.set_callback(sub_callback)
    # Connect
    client.connect(clean_session=False)
    for topic in credentials["mqtt"]["topics"]:
        client.subscribe(topic)
    time.sleep(3)
    client.check_msg()
    return client
Пример #9
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)
Пример #10
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)
Пример #11
0
class Wireless:
    def __init__(self,
                 name='UPC0666645',
                 password='******',
                 host='192.168.0.87',
                 id='1'):
        """
        Initiation of Wireless class which is responsible for all wireless connections, including WiFi and MQTT.
        Arguments are WiFi name, password, MQTT broker IP and device ID. All are set by default, as its the first
        device made.
        """
        self.name = name
        self.password = password
        self.host_ip = host
        self.device_id = id

        self.wlan = network.WLAN(network.STA_IF)
        self.client = MQTTClient(id, host)

        self.topic = 'esp8266/' + id

    def wifi_connect(self):
        """
        Check connection status with any WiFi network. IF ESP8266 is not connected to any WiFi try to connect
        with declared one. If attempt fails, wait 100ms and try again. Return if device connects succesfully
        or it failes 50 times.
        """
        try:
            attempt = 0
            wlan = self.wlan
            if wlan.isconnected() == False:
                wlan.active(True)
                wlan.connect(self.name, self.password)
                while wlan.isconnected() == False and attempt <= 50:
                    attempt += 1
                    utime.sleep_ms(100)
                    pass
            return
        except:
            return

    def wifi_status(self):
        """ Get status of WiFi connection. """
        return self.wlan.isconnected()

    def mqtt_connect(self):
        """ Connect with declared MQTT client. """
        try:
            self.client.connect()
            self.mqtt_is_connected = True
        except:
            self.mqtt_is_connected = False

    def mqtt_status(self):
        """ Get the MQQT connection status. """
        return self.mqtt_is_connected

    def publish(self, data):
        """ Publish 'data' on set topic. """
        self.client.publish(self.topic, data)
Пример #12
0
class Connect:
    def __init__(self):
        self.sta = network.WLAN(network.STA_IF)
        self.ConnectWiFi()
        self.c = MQTTClient("umqtt_client", "192.168.110.51")
        self.ConnectMQTT()

    def ConnectMQTT(self):
        print("connecting to mqtt ROBUST")
        self.c.set_callback(self.deb)
        self.c.connect()
        self.c.subscribe("test/msg")

    def Emit(self):
        emi = MQTTClient('emiter', "192.168.110.51")
        emi.connect()
        emi.publish("test/msg", "from nodeMCU !")
        emi.disconnect()

    def deb(self, topic, msg):
        print((topic, msg))

    def ConnectWiFi(self):
        self.sta.active(True)
        self.sta.connect('g.tec', '#g.tec#17!')

        print("connecting to WiFi at gtec")

        while self.sta.isconnected() == False:
            pass

        print("Connection successful")
        print(self.sta.ifconfig())
Пример #13
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
Пример #14
0
class TemperatureClient:
    """
    Represents an MQTT client which publishes temperature data on an interval
    """
    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()

    def publishTemperature(self):
        """
        Reads the current temperature and publishes a JSON payload on the
        configured topic, e.g., `{"unit": "F", "degrees": 72.5}`
        """
        t = self.sensor.read_temp(self.fahrenheit)
        payload = dict(degrees=t)
        if self.fahrenheit:
            payload['unit'] = 'F'
        else:
            payload['unit'] = 'C'
        self.client.publish(self.topic, json.dumps(payload))

    def start(self, interval=60):
        """
        Begins to publish temperature data on an interval (in seconds).
        This function will not exit! Consider using deep sleep instead.
        :param interval: How often to publish temperature data (60s default)
        :type interval: int
        """
        while True:
            self.publishTemperature()
Пример #15
0
class MQTTWriter:
    __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._connect()

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

    def on_next(self, x):
        data = bytes(json.dumps(x), 'utf-8')
        self.client.publish(bytes(self.topic, 'utf-8'), data)

    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()
Пример #16
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
Пример #17
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()
Пример #18
0
def main():
    led = Pin(2, Pin.OUT, value=1)

    def sub_cb(topic, msg):
        led.off()  # actually on
        utime.sleep_ms(500)
        led.on()  # actually off

    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    sta_if.connect(WLAN_ESSID, WLAN_PASSWORD)
    while not sta_if.isconnected():
        utime.sleep_ms(1)
    print("WLAN Connected")

    c = MQTTClient(MQTT_ID,
                   MQTT_SERVER,
                   user=MQTT_USERNAME,
                   password=MQTT_PASSWORD)
    c.DEBUG = True
    c.set_callback(sub_cb)
    c.connect(clean_session=False)
    c.subscribe(MQTT_TOPIC)
    print("MQTT Connected")

    gc.collect()

    while True:
        c.check_msg()
        utime.sleep_ms(10)

    c.disconnect()
Пример #19
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 = get_topic_path(namespace)

    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))
Пример #20
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()
Пример #21
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")
Пример #22
0
class MQTTlocal:
    __slots__ = ('host', 'port', 'topic', 'client')

    def __init__(self, name, host, port, pub_topic, sub_topic):
        self.sub_topic = sub_topic
        self.pub_topic = pub_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.sub_topic)

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

    def on_next(self, x):
        data = bytes(json.dumps(x), 'utf-8')
        self.client.publish(bytes(self.pub_topic, 'utf-8'), data)

    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 check_msg(self):
        print("Check messages")
        self.client.check_msg()
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
def mqttB(config):  #HeartBeat client
    state = DISCONNECTED
    global clientB
    if config['username'] != "NA" and config['password'] != "NA":
        clientB = MQTTClient(MAC,
                             config['host'],
                             user=config['username'],
                             password=config['password'],
                             port=int(config['port']),
                             keepalive=60,
                             ssl=False)
    else:
        clientB = MQTTClient(MAC,
                             config['host'],
                             port=int(config['port']),
                             keepalive=60,
                             ssl=False)
    while state != CONNECTED:
        try:
            state = CONNECTING
            clientB.connect()
            state = CONNECTED
        except:
            print('Could not establish MQTT-B connection')
            time.sleep(1)
    if state == CONNECTED:
        print('MQTT-B Connected')
Пример #25
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')
Пример #27
0
class EVENTS:
    def mqtt_sub_cb(topic, msg):
        print((topic, msg))

    def __init__(self, client, broker, id):
        self.uid = '{:02x}{:02x}{:02x}{:02x}'.format(id[0], id[1], id[2],
                                                     id[3])
        self.client = MQTTClient(client, broker)
        self.client.set_callback(self.mqtt_sub_cb)
        print('attempt to %s MQTT broker' % (broker))
        try:
            self.client.connect()
            print('Connected to %s MQTT broker' % (broker))
        except:
            print("error connecting to MQTT broker")
            pass

    def logit(self, ts, temp, pressure, humidity, device="", delimiter=","):
        print("ts=", ts)
        payload = {
            "uid":
            str(self.uid),
            "device:":
            str(device),
            "ts":
            str(ts),
            "ts2":
            '{:04d}/{:02d}/{:02d} {:02d}:{:02d}:{:02d}.{:06d}'.format(
                ts[0], ts[1], ts[2], ts[4], ts[5], ts[6], ts[7]),
            "temp":
            str(temp),
            #                   "pressure":str(pressure),
            "pressure":
            '{:3.2f}'.format(pressure),
            "humidity":
            str(humidity)
        }
        d = ujson.dumps(payload)
        try:
            self.client.publish("sensors/", d)
            self.client.publish("sensorsd/id", str(self.uid), qos=1)
            self.client.publish("sensorsd/id/ts", str(ts), qos=1)
            self.client.publish("sensorsd/id/ts/temp", str(temp), qos=1)
            self.client.publish("sensorsd/id/ts/pressure",
                                str(pressure),
                                qos=1)
            self.client.publish("sensorsd/id/ts/humidity",
                                str(humidity),
                                qos=1)


#             self.client.publish("sensorsd/ts",str(timestamp),qos=1)
#             self.client.publish("sensorsd/temp",str(temp),qos=1)
#             self.client.publish("sensorsd/pressure",str(pressure),qos=1)
#             self.client.publish("sensorsd/humidity",str(humidity),qos=1)
        except:
            print("error publishing passing")
            pass
Пример #28
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
Пример #29
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
Пример #30
0
class Mqtt:
    def __init__(self, client_id, broker):
        self.client_id = client_id
        self.client = MQTTClient(client_id, broker)
        self.client.connect()
        print("Connected to {}".format(broker))

    def publish(self, topic, message):
        self.client.publish('{}/{}'.format(topic, self.client_id), message)
Пример #31
0
class MoistureMonitor():
    def __init__(self, led=None):
        self.led = led
        self.t = machine.Timer(0)
        self.a = machine.ADC(0)

        gc.collect()
        loops = 0
        self.m = MQTTClient(config.mqtt.id, config.mqtt.host, **config.mqtt["auth"])
        while True:
            try:
                self.m.connect()
            except (IndexError, OSError) as err:
                print("Retrying connect because of a {}...".format(str(err)))
                if loops > 10:
                    print("Resetting the board")
                    machine.reset()
            except MemoryError:
                print("Got a memory error. Resetting the board in 2 seconds")
                time.sleep(2)
                machine.reset()
            except:
                raise
            else:
                break
            loops += 1
            time.sleep(1)

    def start(self):
        self.m.publish(b'nodes', 'hi there')
        self.t.init(period=5000, mode=machine.Timer.PERIODIC, callback=lambda t: self.update())

    def stop(self):
        self.t.deinit()

    def update(self):
        now = time.localtime()
        tstamp = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(*now[0:6])

        val = { "m": self.a.read() / 1024, "t": tstamp }
        print("Updating moisture, new value is {}".format(val))

        self.m.publish(b"moisture", json.dumps(val).encode('utf-8'), retain=True)

        if self.led is not None:
            self.led(0)
            time.sleep(0.1)
            self.led(1)
Пример #32
0
class DoorAlarm(object):

    def __init__(self):
        self.config = None
        self.p0 = machine.Pin(2, machine.Pin.OUT)

    def load_config(self):
        with open('cfg.json', 'r') as cfg:
            self.config = ujson.load(cfg)

    def connect_wifi(self):
        ap_if = network.WLAN(network.AP_IF)
        ap_if.active(False)

        sta_if = network.WLAN(network.STA_IF)
        sta_if.active(True)

        if sta_if.isconnected():
            sta_if.disconnect()

        sta_if.connect(self.config['ssid'], self.config['passwd'])

        for _ in range(20):
            time.sleep(1)

            if sta_if.isconnected():
                return

        print('Unable to connect to AP: {}'.format(ssid))
        sys.exit(1)

    def mqtt_callback(self, topic, msg):
        self.p0.value(not self.p0.value())

    def mqtt_subscribe(self):
        client_id = b'tom_' + ubinascii.hexlify(machine.unique_id())
        self.mqtt = MQTTClient(client_id, self.config['host'],
                               port=int(self.config['port']))

        self.mqtt.set_callback(self.mqtt_callback)
        self.mqtt.connect()
        self.mqtt.subscribe(self.config['topic'])
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()