示例#1
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()
示例#2
0
文件: app.py 项目: ludoza/tah_admin
def listens_for(mapper, connection, target, event_type):

    topic = f'{mapper.local_table}'
    payload = f'{event_type[0]} {target.id}'
    app.logger.debug(f'publish {topic}, {payload}')
    MQTTClient.publish(topic, payload=payload)  #, qos=1, retain=False)
    MQTTClient.publish_payloads()
示例#3
0
#for speed in speeds:
"""
for i in range(50):
    cps_A, cps_B = hot_wheels(speed)
    # add additional values as required by application
    topic = "{}/data".format(session)
    data = "{},{}".format(cps_A, cps_B)
    print("send topic='{}' data='{}'".format(topic, data))
    mqtt.publish(topic, data)
"""
t = 0


def callback():
    global controller, desired_cps, P, t
    # proportional control and print actual_cps (for plotting)
    cps = controller.p_control(desired_cps, P)
    t += Ts
    topic = "{}/data".format(session)
    data = "{},{}".format(t, cps)
    print("send topic='{}' data='{}'".format(topic, data))
    mqtt.publish(topic, data)


# do the plotting (on host)
print("tell host to do the plotting ...")
mqtt.publish("{}/plot".format(session), "create the plot")
# free up resources
# alternatively reset the microphyton board before executing this program again
mqtt.disconnect()
示例#4
0
        break
    #print("Waiting for Wifi connection...")
    sleep(1)

#print('Wifi connected at', wlan.ifconfig()[0])

#MQTT
tSpeak = 'mqtt.thingspeak.com'  #broker

channelID = '480665'  #SIP Channel
writeKey = '7PZPPOGEBEHAPKH3'
topic = "channels/" + channelID + "/publish/" + writeKey

#print("Connecting to broker ", tSpeak, "...")
mqtt = MQTTClient(tSpeak)
#print("Connected!")

message = "field1={}&field2={}&field3={}&field4={}&field5={}".format(\
          plant1, plant2, watered1, watered2, reservoir)

#print("Publish TOPIC = {}, MSG = {}".format(topic, message))
mqtt.publish(topic, message)  #publish the message

#print("All done")

mqtt.disconnect()  #close the socket

################################################################################
#Reset
deepsleep(2 * 60 * 60 * 1000)  #to take measurements every 2 hours
示例#5
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()
示例#6
0
run = True
next_blink = 0  # time when next to blink the led

while run:
    gc.collect()
    # check for messages
    mqtt.check_msg()
    xfilt = (1 - alpha) * xfilt + alpha * (xout.readraw() - xoff)
    yfilt = (1 - alpha) * yfilt + alpha * (yout.readraw() - yoff)
    xx = xfilt / scale
    yy = yfilt / scale
    print("x={:8.3f}  y={:8.3f}".format(xx, yy))
    # print("x={:40s}|   y={:40s}|".format(int(20*(xx+1))*'*', int(20*(yy+1))*'*'))
    if abs(old_x - xx) > 0.005:
        print("publish x", xx)
        mqtt.publish("x", str(xx))
        old_x = xx
    if abs(old_y - yy) > 0.005:
        print("publish y", yy)
        mqtt.publish("y", str(yy))
        old_y = yy
    if old_button is not button():
        mqtt.publish("stop", str(not button()))
        old_button = button()
    # slowly blink the led
    if time.ticks_diff(time.ticks_ms(), next_blink) > 0:
        next_blink = time.ticks_add(time.ticks_ms(), 1000)
        led(not led())
    time.sleep_ms(200)

print("Joystick: stop MQTT client and return to REPL")
示例#7
0
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
mqtt.disconnect()
示例#8
0
from mqttclient import MQTTClient
from time import sleep
import math

server = "io.adafruit.com"
# update with your values from AdafruitIO ...
aio_user = "******"
aio_key = "73609b18b6204c14aa793035fce4161d"

mqtt = MQTTClient(server=server, user=aio_user, password=aio_key, ssl=True)

for t in range(100):
    s = math.sin(t/10)
    mqtt.publish("{}/feeds/sms-feed".format(aio_user), str(s))
    time.sleep(3)
示例#9
0
import random

MAX_SPEED = 100

#IOT BROKER
BROKER = "broker.hivemq.com"  #Alternatively, iot.eclipse.org
USER = None
PWD = None

print("Connecting to broker", BROKER, "...")

#CREATING the mqtt object and CONNECTING to the broker
mqtt = MQTTClient(BROKER, user=USER, password=PWD,
                  ssl=False)  #False for hivemq
topic = "charles/esp32/boserBeater"
mqtt.publish(topic,
             "BoserBeater is online :^)")  #ESP32 IS PUBLISHING, CP RECEIVING
print("BoserBeater is online :^)")
currentSpeed = 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
示例#10
0
from mqttclient import MQTTClient 
from time import sleep

BROKER = 'iot.eclipse.org'
USER = None
PWD = None

mqtt = MQTTClient(BROKER, user = USER, password=PWD, ssl = TRUE)

i = 1
while True:
	i += 1
	topic = '/patrick/esp32/hi'
	mqtt.publish(topic, 'Hello {}'.format(i))
示例#11
0
文件: mqtt.py 项目: arduino-org/Ciao
	shd["requests"] = {}

	ciaoclient = MQTTCiao(shd, mqtt_queue, ciao_queue)
	ciaoclient.start()

	# endless loop until SIGHUP/SIGTERM
	while shd["loop"] :
		if not mqtt_queue.empty():
			entry = mqtt_queue.get()
			logger.debug("Entry %s" % entry)

			# if entry received from ciao is an "out" message
			if entry['type'] == "out":
				topic = str(entry['data'][0])
				message = str(entry['data'][1])
			else:
				continue

			mqttclient.publish(topic, message)

		# the sleep is really useful to prevent ciao to cap all CPU
		# this could be increased/decreased (keep an eye on CPU usage)
		# time.sleep is MANDATORY to make signal handlers work (they are synchronous in python)
		time.sleep(0.01)

	mqttclient.disconnect()
	logger.info("MQTT connector is closing")
	sys.exit(0)

else:
	logger.critical("Unable to connect to %s" % shd["conf"]["params"]["host"])
        voltage = acs712.read()
        if voltage > max:
            max = voltage
        if voltage < min:
            min = voltage


    milliAmps = round((max - min) * 1000 * 0.707 / 2 / 66) - 2000
    if milliAmps < 0:
        milliAmps = 0
    
    # Send data
    data = "{} {}".format(round(time.time()), milliAmps)
    print("send topic='{}' data='{}'".format(topic, data))
    try:
        mqtt.publish(topic, data)
    except:
        print("Failed to publish MQTT")
        for _ in range(10):
            np.set(0,P,0,0)
            time.sleep(0.1)
            np.set(0,0,0,0)
            time.sleep(0.1)

    # Wait
    for i in range (0,25):
        np.set(0, 2 * i, 0, 0)
        time.sleep(0.03)
    for i in range (26,100):
        np.set(0, 2 * i, 0, 0)
        time.sleep(0.0033)
示例#13
0
import time

if __name__ == '__main__':
    #WLAN
    wlan = WLAN(mode=WLAN.STA)
    wlan.connect("FD-51", auth=(WLAN.WPA2, "fromage2chevre"), timeout=5000)

    while not wlan.isconnected():
        machine.idle()
    print("Connected to Wifi")

    #MQTT
    mqttServerAddr = "192.168.43.253"
    client = MQTTClient("lopy", mqttServerAddr, port=1883)
    client.connect()
    print("Connected to MQTT at : {}".format(mqttServerAddr))

    #LoRa
    lora = LoRa(mode=LoRa.LORA, frequency=868100000)
    s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
    s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
    s.setblocking(True)
    print("Listening to LoRaMAC")

    while True:
        print("waiting for data to send")
        loraClientData = int(s.recv(256))
        client.publish(topic="test/lopy", msg=str(loraClientData))
        print("data sent : {}".format(loraClientData))
        time.sleep(0.1)
示例#14
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)
示例#15
0
from time import sleep
from machine import deepsleep
import math
from busio import I2C
from board import SDA, SCL
from adafruit_bme680 import Adafruit_BME680_I2C as BME680

i2c = I2C(scl=SCL, sda=SDA)
bme = BME680(i2c, address=0x76)

server = "io.adafruit.com"
# update with your values from AdafruitIO ...
aio_user = "******"
aio_key = "dd9efcf7eb024bad8d4bf6cd16962973"

mqtt = MQTTClient(server=server, user=aio_user, password=aio_key, ssl=True)

while True:
    t = bme.temperature
    g = bme.gas
    h = bme.humidity
    p = bme.pressure
    a = bme.altitude
    mqtt.publish("{}/feeds/temperature".format(aio_user), str(t))
    mqtt.publish("{}/feeds/gas".format(aio_user), str(g))
    mqtt.publish("{}/feeds/humidity".format(aio_user), str(h))
    mqtt.publish("{}/feeds/pressure".format(aio_user), str(p))
    mqtt.publish("{}/feeds/altitude".format(aio_user), str(a))
    sleep(10)
    deepsleep(30000)
示例#16
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()
示例#17
0
文件: mqtt.py 项目: siwaphol/Ciao
    shd["requests"] = {}

    ciaoclient = MQTTCiao(shd, mqtt_queue, ciao_queue)
    ciaoclient.start()

    # endless loop until SIGHUP/SIGTERM
    while shd["loop"]:
        if not mqtt_queue.empty():
            entry = mqtt_queue.get()
            logger.debug("Entry %s" % entry)

            # if entry received from ciao is an "out" message
            if entry['type'] == "out":
                topic = str(entry['data'][0])
                message = str(entry['data'][1])
            else:
                continue

            mqttclient.publish(topic, message)

        # the sleep is really useful to prevent ciao to cap all CPU
        # this could be increased/decreased (keep an eye on CPU usage)
        # time.sleep is MANDATORY to make signal handlers work (they are synchronous in python)
        time.sleep(0.01)

    mqttclient.disconnect()
    logger.info("MQTT connector is closing")
    sys.exit(0)

else:
    logger.critical("Unable to connect to %s" % shd["conf"]["params"]["host"])