示例#1
0
def main(server="192.168.0.10"):
    ap_if = network.WLAN(network.AP_IF)
    ap_if.active(False)

    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    sta_if.connect('EEERover','exhibition')

    c = MQTTClient(machine.unique_id(), server)
    c.connect()
    c.publish(b"esys/Thom&Doug/test", bytes("hello", 'utf-8'))
    c.disconnect()
示例#2
0
 def __init__(self):
     self.topic = "esys/dadada/"
     if client_id == "":
         self.client_id = machine.unique_id()
     else:
         self.client_id = client_id
     self.broker = broker
     self.client = MQTTClient(self.client_id, self.broker)
     self.timestamp = ""
     self.client.set_callback(self.update_timestamp())
     self.client.connect()
     self.client.subscribe("esys/time")
示例#3
0
def main(server="192.168.0.10"):
    # Setup the network
    ap_if = network.WLAN(network.AP_IF)
    ap_if.active(False)

    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    sta_if.connect('EEERover','exhibition')

    # init the sensors
    gas = gas_sensor_setup(5, 4, 100000)
    th = th_sensor_setup(5, 4)
    pre = pre_sensor_setup(5, 4, 100000)

    # Wait for i2c setup
    time.sleep_ms(500)

    c = MQTTClient(machine.unique_id(), server)
    c.connect()

    while True:
        # Gather readings
        no2_val, co_val = gas_sensor_read(gas)
        t_val, h_val = th_sensor_read(th)
        pre_val = pre_sensor_read(pre)

        # Create JSON message to be sent
        # Dummy Long and Lat for Imperial
        send_msg = {
            'id': "1",
            'long': 0.1749,
            'lat': 51.4988,
            'no2': no2_val,
            'co': co_val,
            'temp': t_val,
            'hum': h_val,
            'pre': pre_val
        }

        # Print out readings for debugging
        print("Temp ", t_val)
        print("no2 ", no2_val)
        print("Pressure ", pre_val)
        print("hum ", h_val)
        print("co", co_val)

        # MQTT publish the readings
        c.publish(b"esys/Thom&Doug/test", bytes(json.dumps(send_msg), 'utf-8'))

        time.sleep_ms(5000)

    c.disconnect()
示例#4
0
def setupMqtt():
   global client;
   #client = MQTTClient(CONFIG['client_id'], CONFIG['broker'])
   client = MQTTClient(CONFIG['client_id'].decode("utf-8"), "io.adafruit.com",user="", password="", port=1883) //for adafruit broker update name and pass
   client.set_callback(mqttRecv)
   client.connect()
   #tmp2 =b'dangervoid/feeds/{}/{}'.format(CONFIG['client_id'].decode("utf-8"),CONFIG['topic'].decode("utf-8"))
   tmp2 =b'dangervoid/feeds/{}'.format(CONFIG['topic'].decode("utf-8"))
   
   print("Listening on topic: {}".format(tmp2))
   client.subscribe(tmp2)
   client.subscribe(topic=tmp2) 
   print("Mqtt connected to {}".format(CONFIG['broker']))
    def connect_and_subscribe():
        client = MQTTClient(CONF['mqttClientName'], CONF['mqttBroker'],
                            CONF['mqttPort'], CONF['mqttUser'],
                            CONF['mqttPass'])
        # Subscribed messages will be delivered to this callback
        client.set_callback(sub_cb)
        client.connect()
        client.subscribe(
            CONF['mqttSubTopic'].encode())  # where we see if motion is active
        print('Connected to %s, subscribed to %s topic' %
              (CONF['mqttBroker'], CONF['mqttSubTopic']))

        return client
示例#6
0
def connect_and_subscribe():
    global client
    client = MQTTClient(machine_id, broker)
    client.set_callback(callback)
    try:
        client.connect()
        print("Connected to {}".format(broker))
        for topic in (b'config', b'cmd', b'relay1'):
            t = topic_name(topic)
            client.subscribe(t)
            print("Subscribed to {}".format(t))
    except OSError as e:
        print(b"mqtt error: {}".format(e))
示例#7
0
def get_mqtt_client(project_id, cloud_region, registry_id, device_id, jwt):
    """Create our MQTT client. The client_id is a unique string that identifies
    this device. For Google Cloud IoT Core, it must be in the format below."""
    client_id = 'projects/{}/locations/{}/registries/{}/devices/{}'.format(
        project_id, cloud_region, registry_id, device_id)
    print('Sending message with password {}'.format(jwt))
    client = MQTTClient(client_id.encode('utf-8'),
                        server='mqtt.googleapis.com',
                        port=8883,
                        user=b'ignored',
                        password=jwt.encode('utf-8'),
                        ssl=True)
    return client
示例#8
0
def connect_to_mqtt():
    print("Connecting to MQTT broker")
    client = MQTTClient(CONFIG['client_id'],
                        CONFIG['broker'],
                        user=CONFIG['username'],
                        password=CONFIG['password'])
    try:
        client.connect()
        print("Connected to {}".format(CONFIG['broker']))
        return client
    except:
        print("Failed to connect to MQTT, retrying...")
        return None
示例#9
0
def connect_and_subscribe(client_id, server, topic_sub, topic_pub, user,
                          password):
    client = MQTTClient(client_id=client_id,
                        server=server,
                        user=user,
                        password=password)
    client.set_callback(sub_cb)
    client.connect(clean_session=False)
    client.subscribe(topic_sub, qos=1)
    # client.publish(topic_pub, b'I am alive')
    print('Connected to %s MQTT broker, subscribed to %s topic' %
          (server, topic_sub))
    return client
示例#10
0
 def connect(self, address):
     self.disconnect()
     self.address = address
     self.broker  = MQTTClient(self.name, self.address)
     if self.broker.connect() != 0:
         # failed
         self.broker = None
         return False
     # succeeded
     self.broker.set_callback(self._handle_broker_subscription)
     self.broker.subscribe(self.topic_set)
     self.broker.subscribe(self.topic_toggle)
     return True
示例#11
0
文件: main.py 项目: jangeador/esp8266
def connect_and_subscribe():
    global client
    client = MQTTClient(CONFIG['client_id'], CONFIG['broker'],
                        user=CONFIG['mqtt_user'],
                        password=CONFIG['mqtt_password'])
    client.set_last_will(topic_name(b'lwt'), 'our lwt')
    client.set_callback(callback)
    client.connect()
    print("Connected to {}".format(CONFIG['broker']))
    for topic in (b'config', b'control'):
        t = topic_name(topic)
        client.subscribe(t)
        print("Subscribed to {}".format(t))
示例#12
0
def main(server=SERVER):
    c = MQTTClient(client_id, mqtt_server, mqtt_port, mqtt_user, mqtt_password)
    # 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" % (mqtt_server, topic))

    try:
        while True:
            c.wait_msg()
    finally:
        c.disconnect()
示例#13
0
def connect_and_subscribe():
    client_id = ubinascii.hexlify(machine.unique_id())
    mqtt_server = credentials.mqtt_server
    topic_sub = credentials.topic
    client = MQTTClient(client_id, mqtt_server)
    client.user = credentials.user
    client.pswd = credentials.pswd
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(topic_sub)
    print('Connected to %s MQTT broker, subscribed to %s topic' %
          (mqtt_server, topic_sub))
    return client
示例#14
0
def main(server=SERVER):
    client = MQTTClient(CLIENT_ID, server)
    client.set_callback(led_callback)
    client.connect()
    client.subscribe(TOPIC)
    print("Connected to %s, subscribed to %s topic" % (server, TOPIC))

    try:
        while 1:
            #micropython.mem_info()
            client.wait_msg()
    finally:
        client.disconnect()
示例#15
0
def mqtt_pub(client_id, maqtt_server, username, password, port, Topic_pub,
             Topic_sub):
    client = MQTTClient(client_id,
                        server=mqtt_server,
                        user=username,
                        password=password,
                        port=port)
    client.connect()
    client.set_callback(receive_handler)
    client.subscribe(Topic_sub)
    print('Connected to %s MQTT broker, subscribed to %s topic' %
          (mqtt_server, Topic_sub))
    return client
示例#16
0
def connect_and_subscribe():
    global client_id, mqtt_server, userid, password, port
    client = MQTTClient(client_id,
                        server=mqtt_server,
                        user=userid,
                        password=password,
                        port=port)
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(b"SessionID")
    client.subscribe(b"Acknowledge")
    #print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
    return client
示例#17
0
def main(server=SERVER):
    c = MQTTClient(CLIENT_ID, server)
    c.connect()
    threshold = 256
    print("Connected to %s, waiting for ring" % server)
    while True:
        while True:
            if piezo.value() > threshold:
                break
            time.sleep_ms(20)
        print("Ring")
        c.publish(TOPIC, b"ON")
        time.sleep_ms(200)
示例#18
0
def publishSenser():
message['datastreams'][0]['datapoints'][0]['value']=sound.read()
message['datastreams'][1]['datapoints'][0]['value']=light.read()
c.publish('$dp',pubdata(message))                   #publish报文上传数据点
print('publish message:',message)


mywifi.connectWiFi("ssid","password")

c = MQTTClient(CLIENT_ID, SERVER,6002,username,password)
c.connect()
print("Connected to %s" % SERVER)
tim1.init(period=1000, mode=Timer.PERIODIC, callback=lambda _:publishSenser())     #每隔一秒上传数据点
示例#19
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:
            c.wait_msg()
    finally:
        c.disconnect()
示例#20
0
def subs(server="m15.cloudmqtt.com"):
    global client_id, mqtt_server, topic_sub

    c = MQTTClient(client_id=CLIENT_ID,
                   server='m15.cloudmqtt.com',
                   user='******',
                   password='******',
                   port='16060')
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"Sensor_Data")
    c.wait_msg()
    c.disconnect()
示例#21
0
文件: main.py 项目: ivakorin/vabox
def mqtt(topic, data):
    config = get_config('config')
    client = MQTTClient(client_id=config['client_id'],
                        server=config['broker'],
                        port=config['mqtt_port'],
                        user=config['mqtt_user'],
                        password=config['mqtt_pass'])
    client.connect()
    try:
        client.publish('vabox/' + config['client_id'] + '/' + topic, str(data))
        client.disconnect()
    except OSError:
        pass
示例#22
0
def publish(client_id=CLIENT_ID, hostname=SERVER, topic="", keepalive=60):
    global msg_payload
    global payload_Topic
    global tempUpdate
    global temp_Inbound
    global precipUpdate
    global precip_Inbound
    global alertUpdate
    global alert_Inbound
    global dailyUpdate
    global temp_Topic
    global daily_Topic
    global precip_Topic
    global topic_ToSend
    global msg_ToSend
    global missed_Obs
    global topic_File
    global msg_File
    # Connect to the MQTT server.

    #xbee_debug("Publishing", "")
    client = MQTTClient(client_id, hostname)
    #xbee_debug("#X","- Connecting to '%s'... " % hostname)
    brokerConnected = True
    print(brokerConnected)
    brokerConnected = client.connect()
    print(brokerConnected)
    if (brokerConnected == True
            and (topic == daily_Topic or topic == precip_Topic)):
        publishBackup(topic)
    elif brokerConnected == False:
        #xbee_debug("#X","Client Connected")
        client.publish(topic, msg_payload)
        time.sleep(1)
        if topic == temp_Topic and tempUpdate == True:
            tempUpdate = False
            temp_Inbound = False
        if topic == daily_Topic and dailyUpdate == True:
            dailyUpdate = False
            temp_Inbound = False
        if topic == precip_Topic and precipUpdate == True:
            precipUpdate = False
            precip_Inbound = False
        if topic == alert_Topic and alertUpdate == True:
            alertUpdate = False
            alert_Inbound = False
        client.disconnect()
        payload_Topic = ""
        msg_payload = ""
    else:
        pass
示例#23
0
def sense():
    import machine, onewire, ds18x20
    import network
    import boot
    import ubinascii
    from umqtt.simple import MQTTClient
    import time
    pin = 21
    # connect to the network and set network varialbe (just in case)
    # boot.connect()
    # sta_if = network.WLAN(network.STA_IF)

    #pull from the temperature.py script

    print("setting up sensor")
    from temperature import TemperatureSensor
    t = TemperatureSensor(pin, 'DS18B20-1')
    num_sens = len(t.ds.scan())

    print('Found ' + str(num_sens) + ' Sensors. reading....')
    for k in range(0, num_sens):
        print('Temp of sensor ' + str(k) + ': ')
        temp = t.read_temp(
            addr_num=k)  # use t.read_temp(False) to return Celsius
        print(temp)

    # connect to devans laptop IP
    print("connecting.... ")

    c = MQTTClient("ESP32_dev", "192.168.121.117", port=1883, keepalive=60)
    c.connect()

    print("Done it should be connected")
    c.publish('sensor-setup', str(num_sens))

    try:
        while True:
            for k in range(0, num_sens):
                print("Data To Published, Temperature is " +
                      str(t.read_temp(addr_num=k)) + ' F' + ' From Sensor ' +
                      str(k))
                c.publish(
                    'sensor-data',
                    str(t.name) + '-' + str(k) + ' Temp: ' +
                    str(t.read_temp(addr_num=k)) + ' F')
                print("Done!")
                time.sleep(1)
    except KeyboardInterrupt:
        print('interrupted!')

    c.disconnect()
示例#24
0
 def __init__(self,
              topics,
              client_id,
              mqtt_server_ip,
              callback=basic_callback,
              debug=False):
     self.server_ip = mqtt_server_ip
     self.id = client_id
     self.__mqtt_client = MQTTClient(self.id, self.server_ip)
     self.__callback = callback
     self.topics = list(topics)
     self.connected = False
     self.debug = debug
     self.__connect()
示例#25
0
    def __init__(self):
        self.SSID = SSID
        self.KEY = KEY

        self.dev_name = b'badge-' + hexlify(machine.unique_id())

        self.sta = network.WLAN(network.STA_IF)

        self.client = MQTTClient(self.dev_name,
                                 'mqtt.balda.ch',
                                 user='******',
                                 password='******')
        self.client.set_callback(self.mqtt_cb)
        self.CALLBACKS = {}
def get_client():
    #Create our MQTT client.
    client = MQTTClient(client_id=DEVICE_ID,
                        server=MQTT_BRIDGE_HOSTNAME,
                        port=MQTT_BRIDGE_PORT)
    client.set_callback(on_message)

    try:
        client.connect()
    except Exception as err:
        print(err)
        raise(err)

    return client
def main(server=SERVER):
    c = MQTTClient(CLIENT_ID, server, PORT_NO, USERNAME, PASSWORD, 60)
    # 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()
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()
示例#29
0
def main(server="192.168.0.10"):
    ap_if = network.WLAN(network.AP_IF)
    ap_if.active(False)

    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    sta_if.connect('EEERover', 'exhibition')

    send_msg = {'data_to_send': "heloo", 'also_send_this': 56}

    c = MQTTClient(machine.unique_id(), server)
    c.connect()
    c.publish(b"esys/Thom&Doug/test", bytes(json.dumps(send_msg), 'utf-8'))
    c.disconnect()
示例#30
0
def temperature():
    while (True):
        try:
            d = dht.DHT22(machine.Pin(4))
            d.measure()

            c = MQTTClient('client', '192.168.4.4')

            c.connect()
            c.publish('temperature',
                      str(d.temperature()) + ' ' + str(d.humidity()))
            time.sleep(1800)
        except:
            time.sleep(10)