Пример #1
0
def run():
    global state
    global connection

    while True:
        # Wait for connection
        while state != CONNECTED:
            try:
                state = CONNECTING
                connection = MQTTClient(DEVICE_ID, server=HOST, port=8883)
                connection.connect(ssl=True,
                                   certfile='/flash/cert/certificate.crt',
                                   keyfile='/flash/cert/privateKey.key',
                                   ca_certs='/flash/cert/root-CA.cer')
                state = CONNECTED
            except:
                print('Error connecting to the server')
                time.sleep(0.5)
                continue

        print('Connected!')

        # Subscribe for messages
        connection.set_callback(_recv_msg_callback)
        connection.subscribe(TOPIC_DOWNLOAD)

        while state == CONNECTED:
            connection.check_msg()
            msg = '{"Name":"Pycom", "Data":"Test"}'
            print('Sending: ' + msg)
            _send_msg(msg)
            time.sleep(2.0)
Пример #2
0
def mqtt_benchmark(N, is_server, broker, user, pwd):
    received = 0

    def mqtt_callback(topic, msg):
        nonlocal received
        received += 1

    print("Connecting to MQTT broker", broker, "...")
    mqtt = MQTTClient(broker, user=user, password=pwd)
    mqtt.set_callback(mqtt_callback)
    mqtt.subscribe("iot49/{}".format(is_server))
    topic = "iot49/{}".format(not is_server)
    print("Starting test ...")
    gc.collect()
    try:
        t_start = time.ticks_ms()
        for i in range(N):
            if is_server:
                mqtt.publish(topic, "msg {}".format(i))
                mqtt.wait_msg()
            else:
                mqtt.wait_msg()
                mqtt.publish(topic, "ok {}".format(i))
        t_stop = time.ticks_ms()
        dt = time.ticks_diff(t_stop, t_start)
        if N != received:
            print("***** sent {} messages, received {}".format(N, received))
        print(">>> MQTT throughput, broker {}: {:8.4f} msg/s (N={})".format(
            broker, 1000 * received / dt, N))
    finally:
        mqtt.disconnect()
Пример #3
0
from mqttclient import MQTTClient
import time


def mqtt_callback(topic, msg):
    print("MQTT received topic={}, msg='{}'".format(topic, msg))


SERVER = "iot.eclipse.org"

mqtt = MQTTClient(SERVER)
mqtt.set_callback(mqtt_callback)
mqtt.subscribe("y")

# publish
for i in range(20):
    mqtt.check_msg()
    msg = "value=" + str(i)
    topic = "x"
    print("publish topic={} msg={}".format(topic, msg))
    mqtt.publish(topic, msg)
    time.sleep(1)

mqtt.disconnect()
Пример #4
0
    else:
        print(0)


# Connect to Adafruit server
print("Connecting to Adafruit")
mqtt = MQTTClient(adafruitIoUrl,
                  port='1883',
                  user=adafruitUsername,
                  password=adafruitAioKey)
time.sleep(0.5)
print("Connected!")

# This will set the function sub_cb to be called when mqtt.check_msg() checks
# that there is a message pending
mqtt.set_callback(sub_cb)

# Send test message
feedName = "mzdesa/feeds/me100project"
testMessage = "Robot Connected!"
# testMessage = "1"
mqtt.publish(feedName, testMessage)
print("Published {} to {}.".format(testMessage, feedName))

mqtt.subscribe(feedName)

#The following will be the "LOOP" section (analogous to arduino)
for i in range(10):  #read messages from Adafruit IO for 10 seconds
    mqtt.check_msg(
    )  #uses a callback function to limit the time the program runs (see inf. running commented out above)
    #print(x) - x ISN'T actually storing it!
Пример #5
0
class Subscribe(base_calvinsys_object.BaseCalvinsysObject):
    """
    Subscribe to data on given MQTT broker
    """
    def init(self,
             topics,
             hostname,
             port=1883,
             qos=0,
             client_id='calvinconstrained',
             will=None,
             auth=None,
             tls=None,
             transport='tcp',
             payload_only=False,
             **kwargs):
        def sub_cb(topic, msg):
            self.data.append({"topic": topic.decode('utf-8'), "payload": msg})

        self.data = []
        self.payload_only = payload_only
        self.topics = topics
        self.user = None
        self.password = None
        self.ssl = False
        self.ssl_params = None

        if auth:
            user = auth.get("username")
            password = auth.get("password")

        if tls:
            print("Using TLS")
            self.ssl = True
            key_file = open(tls.get("keyfile"), "r")
            key = key_file.read()
            cert_file = open(tls.get("certfile"), "r")
            cert = cert_file.read()
            self.ssl_params = {"key": key, "cert": cert}

        self.c = MQTTClient(client_id,
                            hostname,
                            port=port,
                            user=self.user,
                            password=self.password,
                            ssl=self.ssl,
                            ssl_params=self.ssl_params)
        self.c.set_callback(sub_cb)
        self.c.connect()
        for topic in self.topics:
            self.c.subscribe(topic.encode("ascii"))

    def can_write(self):
        return True

    def write(self, data=None):
        pass

    def can_read(self):
        try:
            data = self.c.check_msg()
        except:
            return False
        return bool(self.data)

    def read(self):
        data = self.data.pop(0)
        if self.payload_only:
            return data.get("payload")
        else:
            return data

    def close(self):
        self.c.disconnect()
Пример #6
0
    m2.duty(0)

    m3.duty(14)
    m4.duty(0)
    sleep(2.9 * anglefactor2)
    m3.duty(0)
    m4.duty(0)

    m1.deinit()
    m2.deinit()
    m3.deinit()
    m4.deinit()


topic = "{}/motor".format(session)
mqtt.set_callback(runMotor)
mqtt.subscribe(topic)
print("wow")

# wait for MQTT messages
# this function never returns
print("waiting for data ...")

while True:
    mqtt.check_msg()

    time.sleep(1)

# Set up motor control PWM pins

# Initially forward at 50% speed