def main(quit=True):
    global t
    c = MQTTClient(CLIENT_ID, SERVER)
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(TOPIC, qos = QOS)
    print("Connected to %s, subscribed to %s topic" % (SERVER, TOPIC))
    n = 0
    pubs = 0
    try:
        while 1:
            n += 1
            if not n % 100:
                t = ticks_ms()
                c.publish(TOPIC, str(pubs).encode('UTF8'), retain = False, qos = QOS)
                c.wait_msg()
                pubs += 1
                if not pubs % 100:
                    print('echo received in max {} ms min {} ms'.
                          format(maxt, mint))
                    if quit:
                        return
            sleep(0.05)
            c.check_msg()
    finally:
        c.disconnect()
Esempio n. 2
0
def publish_msg(topic, msg):
    if topic and msg:
        try:
            c = MQTTClient("umqtt_client", "0.0.0.0")
            c.connect()
            c.publish(topic, msg)
            c.disconnect()
        except Exception as e:
            print(e)
            time.sleep(3)
            machine.idle()
Esempio n. 3
0
def main(server=SERVER):
    #端口号为:6002
    c = MQTTClient(CLIENT_ID, server, 6002, username, password)
    c.set_callback(sub_cb)
    c.connect()
    print("Connected to %s" % server)
    try:
        while 1:
            c.wait_msg()
    finally:
        c.disconnect()
Esempio n. 4
0
def main(server, port, USER, PWD):
    c = MQTTClient("umqtt_client", server, port, USER, PWD)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe("foo_topic")
    while True:
        if True:
            c.wait_msg()
        else:
            c.check_msg()
            time.sleep(1)
    c.disconnect()
Esempio n. 5
0
def msg_Pub():
    global c
    server = SERVER
    c = MQTTClient(CLIENT_ID, server, 1883, username, passwd)
    c.connect()
    while True:
        SoilHum = soilhum_read()
        paylod_ = {'SoilHum': SoilHum}
        msg_ = json.dumps(paylod_)
        c.publish(TOPIC, msg_, retain=True)
        oledisplay(SoilHum)
        time.sleep(2)
Esempio n. 6
0
def connect_mqtt():
    server = "server IP"
    global client_id
    client_id = "client"  #insert your client ID
    username = '******'  #insert your MQTT username
    password = '******'  #insert your MQTT password
    global topic
    topic = ('sensor/temperature')
    global c
    c = MQTTClient(client_id, server, 0, username, password)
    c.connect()
    time.sleep(3)
Esempio n. 7
0
def connect_and_subscribe():
    global client_id, mqtt_server, topic_sub
    client = MQTTClient(client_id, mqtt_server)
    client.set_last_will(topic='hack42/tele/loungeledjes/status',
                         msg='offline',
                         retain=True)
    client.connect()
    client.publish('hack42/tele/loungeledjes/ifconfig',
                   str(sta_if.ifconfig()),
                   retain=True)
    client.publish('hack42/tele/loungeledjes/status', 'online', retain=True)
    return client
Esempio n. 8
0
def main(server=SERVER):
    #端口号为:6002
    c = MQTTClient(CLIENT_ID, server, 6002, username, password)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(TOPIC)
    print("Connected to %s, subscribed to %s topic" % (server, TOPIC))
    try:
        while 1:
            c.wait_msg()
    finally:
        c.disconnect()
Esempio n. 9
0
def main(server=SERVER):
    #6002
    do_connect()
    c = MQTTClient(CLIENT_ID, server,6002,username,password)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(TOPIC)
    print("Connected to %s, subscribed to %s topic" % (server, TOPIC))
    try:
        while 1:
            c.wait_msg()
    finally:
        c.disconnect()
Esempio n. 10
0
def mqttconfig(v):
    global mqttobject
    if wlan.isconnected():
        mqttconn.deinit()
        mqttobject = MQTTClient(secrets["devicename"],
                                secrets["mqttserver"],
                                port=1883,
                                user=secrets["mqttusername"],
                                password=secrets["mqttpass"])
        mqttobject.set_callback(mqttcallback)
        mqttobject.connect()
        mqttobject.subscribe(secrets["topicsub"])
        mqttpublisher()
        mqttconn.init(period=150, mode=Timer.PERIODIC, callback=newmsg)
Esempio n. 11
0
def main(server=SERVER):
    c = MQTTClient(CLIENT_ID, server)
    c.connect()
    print("Connected to %s, waiting for button presses" % server)
    while True:
        while True:
            if button.value() == 0:
                break
            time.sleep_ms(20)
        print("Button pressed")
        c.publish(TOPIC, b"toggle")
        time.sleep_ms(200)

    c.disconnect()
Esempio n. 12
0
def main(server="0.0.0.0"):
    try:
        c = MQTTClient("yitian-it", server)
        c.set_callback(sub_cb)
        time.sleep(4)
        c.connect()
        c.subscribe(b"toilet")
        while True:
            c.check_msg()
            time.sleep(1.5)
    except Excepthion as e:
        print(e)
        c.disconnect()
        machine.reset()
Esempio n. 13
0
def mqtt_connect():
    global client

    client = MQTTClient(
        config['settings']['mqtt_clientid'].encode(),
        config['settings']['mqtt_server'],
        1883,
        config['settings']['mqtt_user'].encode(),
        config['settings']['mqtt_pass'].encode())
    
    client.set_callback(mqtt_callback)
    client.connect()
    client.subscribe('sleep2mqtt/control'.encode())
    client.subscribe('hass/status'.encode())
Esempio n. 14
0
def main(server=SERVER):
    c = MQTTClient(CLIENT_ID, server)
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(TOPIC)
    print("Connected to %s, subscribed to %s topic" % (server, TOPIC))

    try:
        while 1:
            #micropython.mem_info()
            c.wait_msg()
    finally:
        c.disconnect()
Esempio n. 15
0
def main():
    global wl_net
    # Initialize wireless network
    if not wl_net:
        wl_net = init_wifi()

    # Initialize DHT
    sensor = dht.DHT22(machine.Pin(4))

    # Main loop to read temp and send it
    # Read the temperature
    sensor.measure()
    temp = sensor.temperature() * 9.0 / 5.0 + 32.0
    humid = sensor.humidity()
    print('v1.2: Temp / Humid = {:2} / {:2}'.format(temp, humid))

    # Send it through MQTT
    mqtt_c = MQTTClient(MQ_CLIENT,
                        MQ_BROKER_IP,
                        user=MQ_USER,
                        password=MQ_PASSWORD)
    mqtt_c.connect()

    json_array = {
        "temp": "{}".format(temp),
        "hum": "{}".format(humid),
    }

    import ujson

    #    {"source":"TV (0)","pvr_status":"NONE","powerstate":"Normal","tv_mode":"Cable (1)","volume":"7","channel_number":"45","channel_name":"Nat Geo HD","program_name":"Personaje ale nazismului","resolution":"1920x1080","error":false}

    mqtt_c.publish(MQ_TOPIC.encode('utf-8'),
                   ujson.dumps(json_array),
                   retain=True)

    mqtt_c.disconnect()

    # configure RTC.ALARM0 to be able to wake the device
    rtc = machine.RTC()
    rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)

    # set RTC.ALARM0 to fire after 10 seconds (waking the device)
    rtc.alarm(rtc.ALARM0, 10000)  # For debugging, 10 seconds
    # rtc.alarm(rtc.ALARM0, 1000 * DELAY_MLOOP)  # Default: 60 seconds
    # Make sure that the Node MCU has pin D0 (L15) wired to RST (R3)

    # put the device to sleep
    machine.deepsleep()
Esempio n. 16
0
 def mqttMain(self):
     try:
         c =MQTTClient("umqtt_client", server=self._host,port=1883)
         self.c = c
         self.ledTrue(5,0.2)
         # c =MQTTClient("umqtt_client", server="192.168.50.53",port=1883)
         c.set_callback(self.sub_cb)
         c.connect()
         # c.subscribe("001")
         print('mqtt connect ok')
         self.ledTrue(5,0.1)
         return c
     except OSError as e:
         self.ledTrue(3,0.1)
         self.mqttMain()
Esempio n. 17
0
class MqttHelper:
    
    def __init__(self, serverAddress, clientId):
        self.mqttClient = MQTTClient(clientId, serverAddress)
        self.mqttClient.connect()
            
    def Publish(self, topic, message):
        self.mqttClient.publish(topic, message)

    def Subscribe(self, topic, callback):
        self.mqttClient.set_callback(callback)
        self.mqttClient.subscribe(topic)
        
    def CheckForMessage(self):
        self.mqttClient.check_msg()
Esempio n. 18
0
def main(server=SERVER):
    #端口号为:6002
    c = MQTTClient(CLIENT_ID, server, 6002, username, password)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(TOPIC)
    print("Connected to %s, subscribed to %s topic" % (server, TOPIC))
    #publish报文上传数据点
    c.publish('$dp', pubdata(message))
    print('publish message:', message)

    try:
        while 1:
            c.wait_msg()
    finally:
        c.disconnect()
Esempio n. 19
0
class MQTT_CLI:
    def __init__(self, wl, name, server):
        self._cli = MQTTClient(name, server)
        if not wl.isconnected():
            wl.connect()
        self._cli.connect()
        self._cli.disconnect()

    def publish(self, topic, msgobj):
        try:
            self._cli.connect()
            msgstr = json.dumps(msgobj)
            self._cli.publish(topic.encode(), msgstr.encode())
            self._cli.disconnect()
        except:
            pass
Esempio n. 20
0
def main(start='start'):
    c = MQTTClient("umqtt_client", server, port, user, password)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(btopic)
    while True:
        if True:
            # Blocking wait for message
            c.wait_msg()
        else:
            # Non-blocking wait for message
            c.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)

    c.disconnect()
Esempio n. 21
0
def main(server=SERVER):
    # 端口号为:6002
    c = MQTTClient(CLIENT_ID, server, 6002, username, password)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(TOPIC)
    tim_pubDate.init(period=5000,
                     mode=Timer.PERIODIC,
                     callback=lambda t: pubData(c, t))
    pubData(c, 10)
    print("Connected to %s, subscribed to %s topic" % (server, TOPIC))
    try:
        while 1:
            c.wait_msg()
    finally:
        print('mqtt closed')
        c.disconnect()
Esempio n. 22
0
def mqtt_connect():
    print("clientid:", ClientId, "\n", "Broker:", strBroker, "\n",
          "User Name:", user_name, "\n", "Password:"******"\n")

    client = MQTTClient(client_id=ClientId,
                        server=strBroker,
                        port=Brokerport,
                        user=user_name,
                        password=user_password,
                        keepalive=60)
    client.set_callback(recvMessage)  #设置回调函数
    #please make sure keepalive value is not 0
    client.connect()
    client.subscribe("/sys/" + ProductKey +
                     "/test1/thing/service/property/set")  #订阅主题

    while True:
        time.sleep(3)
Esempio n. 23
0
def main(server=SERVER):
    wlan = network.WLAN(network.STA_IF)
    if not wlan.isconnected():
        wlan.active(True)
        wlan.connect('Micropython-wifi', '12345678')
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())
    c = MQTTClient(CLIENT_ID, server)
    c.connect()
    print("Connected to %s, waiting for timer" % server)
    fail = False
    count = 0
    value = '0'
    data = uart.read(100)
    c.publish(TOPIC, value, retain=True)
    time.sleep(1)
    c.disconnect()
Esempio n. 24
0
def main(server=SERVER):
	#端口号为:6002
	c = MQTTClient(CLIENT_ID, server,6002,username,password)
	c.set_callback(sub_cb)
	c.connect()
	c.subscribe(TOPIC)
	print("Connected to %s, subscribed to %s topic" % (server, TOPIC))
	while 1:
		# c.wait_msg()
		try:
			l,t,p,h,H=read()
			rsp = http_put_data(l,'light intensity')
			rsp = http_put_data(t,'temperature')
			rsp = http_put_data(p,'pressure')
			rsp = http_put_data(h,'humidity')
			rsp = http_put_data(H,'altitude')
			time.sleep(2)
		except TypeError:
			pass
Esempio n. 25
0
def main(server=SERVER):
    print(config.value)
    wlan = network.WLAN(network.STA_IF) 
    if not wlan.isconnected():
        wlan.active(True)
        wlan.connect(config.value[0][1], config.value[0][2])
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig()) 
    c = MQTTClient(CLIENT_ID, server)
    c.connect()
    print("Connected to %s, waiting for timer" % server)
    value = '0'
    data = uart.read(100)
    while wlan.isconnected():
        data = uart.read(100)
        if data != None:
            a = str(data[2:])
            b = a.split('\'')
            e = b[1].split('\\')
            d = e[0].split(',')
            if d[0]=='IR':
                print(d[0])
                print(d[1])
                if d[1] == '128':
                    c.publish(config.value[2][1],"ON",retain=True)
                    c.publish(config.value[1][1],"Remote",retain=True)
                    print(d[1])
                if d[1] == '129':
                    c.publish(config.value[2][1],"OFF",retain=True)
                    c.publish(config.value[1][1],"Remote",retain=True)
                    print(d[1])
                if d[1] == '130':
                    c.publish(config.value[2][2],"ON",retain=True)
                    c.publish(config.value[1][2],"Remote",retain=True)
                    print(d[1])
                if d[1] == '131':
                    c.publish(config.value[2][2],"OFF",retain=True)
                    c.publish(config.value[1][2],"Remote",retain=True)
                    print(d[1])
                print("Time to publish")      
    c.disconnect()
Esempio n. 26
0
def publishMessage(clientID, serverIP, username, password, topicName, message):
  try:
     c = MQTTClient(clientID, serverIP,1883,username,password)
     if ( 0 == c.connect() ):
       c.publish(topicName, message, False)
       c.disconnect()
       print("publish ok")
     else:
       print("connect failed")
  except Exception:
      print("publishMessage failed")
Esempio n. 27
0
class Cn2Mqtt():

    # Class functionality variables.

    # This variable holds the mqtt connection.
    mqtt = ""

    def connect(self):
        """ connect function. This function is used to connect ESP8266 to the MQTT network.
        """
        state = 0
        while state != 2:
            try:
                self.mqtt = MQTTClient(client_id="CN2",
                                       server=BROKER_IP,
                                       port=BROKER_PORT,
                                       user=BROKER_USERNAME,
                                       password=BROKER_PASSWORD,
                                       ssl=False)
                self.mqtt.connect()
                state = 2
            except:
                print('Error connecting to the broker')
                time.sleep(0.5)
                continue

        print("Connected to MQTT network")
        self.mqtt.set_callback(self.on_message)

    def on_message(self, topic, payload):
        print((topic, payload))

    def publish(self, topic, msg, retain, qos):
        self.mqtt.publish(topic, msg, retain, qos)
        print("Message published successfully.")

    def subscribe(self, topic, qos):
        self.mqtt.subscribe(topic, qos)
        print("Subscribed to topic: " + topic)
Esempio n. 28
0
def run():
    global state
    global connection

    while True:
        while state != CONNECTED:
            try:
                state = CONNECTING
                connection = MQTTClient(client_id=TOPIC, server=HOST, port=8883, keepalive=10000, ssl=True, ssl_params={"certfile":"/flash/cert/cert.pem", "keyfile":"/flash/cert/privkey.pem", "ca_certs":"/flash/cert/aws-iot-rootCA.ca"})
                connection.connect()
                state = CONNECTED
            except:
                print('Could not establish MQTT connection')
                time.sleep(0.5)
                continue

        print('MQTT LIVE!')

        while state == CONNECTED:
            msg = '{"device_id":"some_id", "data":"some_data"}'
            pub_msg(msg)
            time.sleep(2.0)
Esempio n. 29
0
class mqtt:
    def __init__(self,oled, client_id='', username='', password='',macs=[],BROADCAST_IP='192.168.1.255',BROADCAST_PORT=40000):
        self.failed_count = 0
        self.oled = oled
        self.cs = check_status(oled=oled)
        self.server = "183.230.40.39"
        self.client_id = client_id
        self.username = username
        self.password = password
        self.topic = (chipid() + '-sub').encode('ascii') if client_id == '' else (client_id + '-' + chipid() + '-sub').encode('ascii')
        self.mqttClient = MQTTClient(self.client_id, self.server,6002,self.username,self.password)
        self.wakeonline = WAKE_ON_LINE(macs,BROADCAST_IP,BROADCAST_PORT)

    def sub_callback(self, topic, msg):
        cmd = msg.decode()
        if cmd == 'wakeup':
            self.oled.write_lines(line2='send wol package...')
            self.wakeonline.send()
            self.oled.write_lines(line2='')

    def ping(self,t):
        self.mqttClient.ping()
        self.cs.display_status()

    def connect(self):
        self.mqttClient.set_callback(self.sub_callback)
        self.mqttClient.connect()
        tim = Timer(-1)
        tim.init(period=30000, mode=Timer.PERIODIC, callback=self.ping) #Timer.PERIODIC   Timer.ONE_SHOT
        self.mqttClient.subscribe(self.topic)
        # print("Connected to %s, subscribed to %s topic." % (self.server, self.topic))
        try:
            while 1:
                msg = self.mqttClient.check_msg()
                print (msg)
        finally:
            self.mqttClient.disconnect()
            print('mqtt closed')
            tim.deinit()
Esempio n. 30
0
def connect():
    global mqtt_client
    global MQTT_CERT
    global MQTT_KEY
    try:
        mqtt_client = MQTTClient(client_id=MQTT_CLIENT_ID,
                                 server=MQTT_HOST,
                                 port=MQTT_PORT,
                                 keepalive=0,
                                 ssl=True,
                                 ssl_params={
                                     "cert": MQTT_CERT,
                                     "key": MQTT_KEY,
                                     "server_side": False,
                                     "server_hostname": MQTT_HOST,
                                     "do_handshake": True
                                 },
                                 debug=True)
        mqtt_client.connect()
        print('MQTT Connected')

    except Exception as e:
        print('Cannot connect MQTT: ' + str(e))
        raise
Esempio n. 31
0
def read_send():

    data_pm=bytearray(32)
    pm.readinto(data_pm)

    instruction_voc(light_on_voc)
    data_voc = instruction_voc(read_instruct_voc)
    if data_voc[0] == 255 and data_voc[1] == 135 and data_pm[0]==66 and data_pm[1]==77:
        data_g = (data_voc[2] * 256 + data_voc[3]) / 1000
        data_t = (data_voc[8] << 8 | data_voc[9]) / 100
        data_h = (data_voc[10] << 8 | data_voc[11]) / 100
        data_pm2_5 = data_pm[6]<<8 | data_pm[7]
        data_pm10 = data_pm[8] << 8 | data_pm[9]
        dataframe = {"params": {"concentration": data_g, "temperature": data_t, "humidity": data_h,
                                "pm2_5":data_pm2_5,"pm10":data_pm10}}

        tvoc_mqtt = MQTTClient(client_id=mqttClientId, server=server, port=port, user=mqttUsername, password=mqttPassword,keepalive=60)
        tvoc_mqtt.set_callback(callback)
        tvoc_mqtt.connect()
        time.sleep(1)
        tvoc_mqtt.publish(topic_p,json.dumps(dataframe))
        time.sleep(1)
        tvoc_mqtt.subscribe(topic_s)
        time.sleep(1)
Esempio n. 32
0
from simple import MQTTClient
import utime
import network
sta = network.WLAN(network.STA_IF)
sta.active(1)
sta.connect("Kritsnam_3", "hydro123")
utime.sleep_ms(6000)
c = MQTTClient(client_id="sahil12",
               server="172.26.83.102",
               port=1883,
               user="******",
               password="******")
c.connect()
f = 1
s = 'fej'
for i in range(1, 10):
    c.publish(topic="v1/devices/me/telemetry",
              msg='''{"firmware_version":'f', "serial_number":'s'}''')
    utime.sleep_ms(1000)
c.disconnect()
Esempio n. 33
0
from simple import MQTTClient

# Connection information
mqtthost = 'mqtt.enco.io'
mqttport = 8883
mqttssl = True
# Channel specific parameters
uname = '<< YOUR INFO HERE >>'
pwval = '<< YOUR INFO HERE >>'
topicName = '<< YOUR INFO HERE >>'
deviceId = '<< YOUR INFO HERE >>'

# Create an instance for further use, connect and use directly
connection = MQTTClient(client_id=deviceId,
                        server=mqtthost,
                        port=mqttport,
                        user=uname,
                        password=pwval,
                        ssl=mqttssl)
print('Connect to broker', mqtthost, ':', str(mqttport))
connection.connect()
print('Publish to ', topicName)
connection.publish(topicName, b'MQTTS Greetings from the WiPy !!')
print('Close')
connection.disconnect()
print('All done')