Exemplo n.º 1
0
def initMQTT():
    topic = config.MQTT_TOPIC
    bTopic = bytes(topic, 'UTF-8')
    c = MQTTClient(config.MQTT_CLIENT_ID,
                   config.MQTT_SERVER,
                   user=secrets.MQTT_USER,
                   password=secrets.MQTT_PASS)
    # Print diagnostic messages when retries/reconnects happens
    c.DEBUG = False
    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=True):
        c.subscribe(bTopic)
    return c
Exemplo n.º 2
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()
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 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.º 5
0
def init_mqtt():
    log("MQTT Connecting")
    cli = MQTTClient(config.mqtt_name, config.mqtt_server)
    cli.DEBUG = True
    cli.set_callback(sub_cb)
    cli.connect()
    cli.subscribe(config.mqtt_subscribe)
    log("MQTT Connected")
    return cli
Exemplo n.º 6
0
def Conexion_MQTT():
    #client_id = b"Covid_1" + ubinascii.hexlify(machine.unique_id())
    client_id = CONFIG["client_id"]
    mqtt_server = CONFIG["broker"]
    port_mqtt = 1883
    user_mqtt = None #Si su servidor no necesita usuario escribe None sin comillas
    pswd_mqtt = None #Si su servidor no necesita contraseña escribe None sin comillas
    client = MQTTClient(client_id, mqtt_server,port_mqtt,user_mqtt,pswd_mqtt)
    client.DEBUG = True
    client.set_callback(form_sub)
    client.connect(True)
    client.subscribe(CONFIG["subscribe"])
    print('Conectado a %s' % mqtt_server)
    return client
Exemplo n.º 7
0
def connect():
    from umqtt.robust import MQTTClient
    c = MQTTClient(ID, mqttHost, ssl=mqttSSL, user=mqttUser, password=mqttPass)
    c.DEBUG = True
    if not c.connect():
        print('connected, will publish to {}/{}/#'.format(mqttTopicRoot, ID))
        c.set_last_will('{}/{}/status'.format(mqttTopicRoot, ID),
                        'offline',
                        retain=True)
        c.publish('{}/{}/status'.format(mqttTopicRoot, ID),
                  'connected',
                  retain=True)
        return c
    return None
Exemplo n.º 8
0
def mqtt_reconnect():
    # Create an instance of MQTTClient
    global client
    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.DEBUG = True
    client.set_callback(onMessage)
    client.connect(clean_session=True)
    client.subscribe(CONFIG['TOPIC'])
    print("ESP8266 is Connected to %s and subscribed to %s topic" %
          (CONFIG['MQTT_BROKER'], CONFIG['TOPIC']))
Exemplo n.º 9
0
def main():
    i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4), freq=10000)
    led = machine.Pin(2, machine.Pin.OUT)
    do_connect()
    client = MQTTClient(cfg.getSYS("mqtt.id"), cfg.getSYS("mqtt.broker"))
    client.DEBUG = True
    client.set_callback(sub_cb)
    if not client.connect(clean_session=True):
        client.subscribe(t.ACTION_STATUS + "/#")
        client.publish(t.CONNECT, cfg.getSYS("serial"))
    while 1:
        print("loop START")
        gc.collect()
        toggle(led)
        update_sensors(client, i2c)
        utime.sleep(1)
        client.check_msg()
        toggle(led)
    client.disconnect()
Exemplo n.º 10
0
 def __init__(self, connection_string):
     self._connection_string = connection_string
     self._lastUpdated = 0
     self._updateSas = True
     
     parsed_connection = self._parse_connection()
     self._shared_access_key = parsed_connection.get("SharedAccessKey")
     self._shared_access_key_name =  parsed_connection.get("SharedAccessKeyName")
     self._gateway_hostname = parsed_connection.get("GatewayHostName")
     self._hostname = parsed_connection.get("HostName")
     self._device_id = parsed_connection.get("DeviceId")
     self._module_id = parsed_connection.get("ModuleId")
     self._username = self._hostname + '/' + self._device_id
     self._c2d_cb = None
     
     self._sas = self._generate_sas_token()
     
     c = MQTTClient(client_id=self._device_id, server=self._hostname, port=8883, user=self._username, password=self._sas, keepalive=120, ssl=True)
     c.DEBUG = True
     c.set_callback(self._callback_handler)
     
     self._mqtt_client = c
Exemplo n.º 11
0
import time
from umqtt.robust import MQTTClient


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


c = MQTTClient("umqtt_client", "localhost")
# Print diagnostic messages when retries/reconnects happens
c.DEBUG = True
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
Exemplo n.º 12
0
from umqtt.robust import MQTTClient

import config

mqtt_client = MQTTClient(
    server=config.MQTT_SERVER,
    client_id=config.MQTT_CLIENT_ID,
    user=config.MQTT_USER,
    password=config.MQTT_PASSWORD,
)
mqtt_client.DEBUG = True
Exemplo n.º 13
0
		else:
			return False


def sub_cb(topic, msg):
    t = topic.decode('ASCII')
    m = msg.decode('ASCII')
    if t == IN:
        print("IN: %s" % m)
        if(m.startswith('T')):
        	if(len(m) > 2):
        		print(m[1] + m[2])
        	else:
        		print(m[1])
        if(m == 'ligar led'):
        	pinA.value(1)
        if(m == 'desligar led'):
        	pinA.value(0)

while True:
	if wifi.isconnected():
		umqtt_client = MQTTClient("P3", MQTT_SERVER)
		umqtt_client.DEBUG = True
		umqtt_client.set_callback(sub_cb)
		umqtt_client.connect(clean_session=False)
		umqtt_client.subscribe(IN)
		print("Connected to MQTT broker: %s" % MQTT_SERVER)
		break

while True:
	umqtt_client.check_msg()
Exemplo n.º 14
0
def init_controller(cli_name, mqtt_links):
    """
    Prepares controller for work starting
    initializes mqtt_links
    """
    global ml
    global cname
    global mqtt_cli
    global tool_verbs

    ml = mqtt_links
    cname = cli_name

    groups = dict()

    for t, ma in ml.items():
        if ma[0] not in tool_verbs:
            print("FATAL: Invalid tool type:", ma[0], "for link", t)
            return None

        else:  # run initialization routine for the tool type
            if tool_verbs[ma[0]][2](ma) != True:
                print("FATAL: Could not initialize tool type [", ma[0],
                      "] for link [", t, "!!!")
                return None

            # check mosfet groups
            if ma[0] == b"MOSFET":
                if ma[1][3] != mlc.NO_GROUP:
                    if ma[1][3] not in groups:
                        groups[ma[1][3]] = [
                            mlc.NO_SEQ, []
                        ]  # first item is a sequence flag for a group
                    groups[ma[1][3]][1].append(
                        ma[1][0])  # group consists of pin numbers of mosfets
                    ma[2].insert(
                        3, groups[ma[1][3]]
                    )  # group info holds in 4th item of the run-time objects list
                    if ma[1][3] == mlc.SEQ:
                        groups[ma[1][3]][0] = mlc.SEQ
                        # sequental group has an extra item in a group list which indicates next mosfet to power on
                        if len(groups[ma[1][3]]) == 2:
                            # add next mosfet index into group info
                            # it should be the first item in a group list
                            groups[ma[1][3]].append(groups[ma[1][3]][1][0])
                else:
                    # if mosfet isn't in any group, add an empy group to its run-time
                    ma[2].insert(3, [mlc.NO_SEQ, []])

    import mqtt_cfg

    c = MQTTClient(cname, mqtt_cfg.mqtt_srv_name)
    print("Trying to connect to", mqtt_cfg.mqtt_srv_name)
    c.DEBUG = True
    c.connect(clean_session=False)
    print("Connected")
    c.set_callback(cb)

    # subscribe for mqtt links
    for mak in ml.keys():
        c.subscribe(mak)
        print("Subscribed for", mak)

    # subscribe for system mqtt requests
    c.subscribe(cname)
    print("Subscribed for", cname)

    mqtt_cli = c

    publish_status(b"READY")

    return c