示例#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
文件: mqtt_test.py 项目: mzdesa/me100
        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!
    time.sleep(1)
示例#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
from mqttclient import MQTTClient
import binascii, machine, time, gc

mqtt = MQTTClient("iot.eclipse.org")


def mqtt_callback(topic, msg):
    print("callback:", topic, msg)
    global run
    if topic == b'stop':
        run = False
    else:
        print("received unknown topic={:s}, msg='{:s}'".format(topic, msg))


mqtt.set_callback(mqtt_callback)
mqtt.subscribe("stop")

run = True
count = 0

while run:
    mqtt.check_msg()
    mqtt.publish("x", str(count))
    count += 1
    if count > 100: run = False
    time.sleep(1)

print("mqtt demo: stop MQTT client and return to REPL")
mqtt.disconnect()
示例#7
0
BROKER = "dev.home"
BROKER = "iot.eclipse.org"
print("Connecting to broker", BROKER, "...")
mqtt = MQTTClient(BROKER)
print("Connected!")


def mqtt_callback(topic, msg):
    global led, run
    if topic == b'repl':
        run = False
        print("got run false")


mqtt.set_callback(mqtt_callback)
mqtt.subscribe("repl")

# Joystick
button = Pin(A21, mode=Pin.IN, pull=Pin.PULL_UP)
xout = ADC(Pin(ADC0))
yout = ADC(Pin(ADC3))
xout.atten(ADC.ATTN_6DB)
yout.atten(ADC.ATTN_6DB)

# offset
xoff = 1920
yoff = 2005
scale = 1900

# filter
alpha = 0.5
示例#8
0
            motors.brake(0)
            motors.brake(1)
        else:
            print("release brake")
    elif topic == b'x':
        x = float(msg)
        set_speed()
    elif topic == b'y':
        y = float(msg)
        set_speed()
    elif topic == b'repl2':
        run = False


mqtt.set_callback(mqtt_callback)
mqtt.subscribe("repl")
mqtt.subscribe("x")
mqtt.subscribe("y")
mqtt.subscribe("stop")

# motor controller

freq = 100
stop = False
motors = None


def speed_to_freq(speed):
    f = 2500 * fabs(speed) - 450
    return min(max(20, f), 500)
示例#9
0
PWD = None

print("Connecting to broker", BROKER, "...")
#sleep(2)
#CREATING the mqtt object and CONNECTING to the broker
mqtt = MQTTClient(BROKER, user=USER, password=PWD, ssl=False)

print("Connected!")


def mqtt_callback(topic, msg):
    print("RECEIVE topic = {}, msg = {}".format(topic, msg))


mqtt.set_callback(mqtt_callback)
mqtt.subscribe("charles/esp32/hi")

#PUBLISH - SUBSCRIBE LOOP
for i in range(5):
    #PUBLISHING a message
    topic = "charles/esp32/hi"
    message = "Hello " + str(random.randint(1, 101))
    print("PUBLISH topic = {} message = {}".format(topic, message))
    mqtt.publish(topic, message)

    #CHECKING for a new message
    for _ in range(5):
        mqtt.check_msg()
        sleep(0.5)  #pause for 0.5 second

#Close sockets
示例#10
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
示例#11
0

def mqtt_callback(topic, msg):
    global currentSpeed

    message = msg.decode(
        "utf-8"
    )  #msg comes in as byte-format, decode turns it directly into a string

    currentSpeed = int(round(float(message)))
    if currentSpeed > MAX_SPEED:  #Capping it
        currentSpeed = MAX_SPEED


mqtt.set_callback(mqtt_callback)
mqtt.subscribe("charles/pc/boserBeater")  #SUBSCRIBE TO COMPUTER TOPIC

################################
# SETUP                        #
################################

#Connect DRV V_in from Vusb. This is running on 5V
from machine import PWM, Pin, Timer
from board import A20, A21, A6, A14, A15
from time import sleep, ticks_ms
from max6675 import MAX6675

################################
# THERMOCOUPLE                 #
################################
so = Pin(A14, mode=Pin.IN)