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()
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)
def mp_connect(): global mp print("connecting to mqtt broker ...") BROKER = "iot.eclipse.org" mqtt = MQTTClient(server=BROKER) print("mqtt", mqtt) mqtt.connect() mp = PlotClient(mqtt) print("mp", mp)
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 adafruit_connection(self): """Make the AdaFruit connection.""" print("Connecting to Adafruit...") self.mqtt = MQTTClient(self.adafruit_io_url, port='1883', user=self.adafruit_username, password=self.adafruit_aio_key) time.sleep(0.5) print("AdaFruit connection made at:", self.adafruit_username)
from machine import Pin, ADC from board import LED, A21, ADC0, ADC3 from mqttclient import MQTTClient import gc, time, machine led = Pin(LED, mode=Pin.OUT) BROKER = "mac15.home" 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)
from network import WLAN, STA_IF from util import Vector3, dist MPU9250._chip_id = 115 BATCH_SIZE = 200 CALIBRATION_SIZE = 200 DATA_FREQUENCY = 60000 # Data collection frequency in ms SEND_TIME = 5 # time in s to wait for a MQTT message to go out BROKER = "mqtt.thingspeak.com" TS_CHANNEL_ID = "472546" TS_WRITE_KEY = "TQ6PXDYGOSXZV2XA" OFFSETS = {} SCALARS = set(["noise", "temp"]) print("Connecting to broker", BROKER, "...") mqtt = MQTTClient(BROKER, user=None, password=None, ssl=True) print("MQQTClient Connected!") i2c = I2C(id=0, scl=Pin(SCL), sda=Pin(SDA), freq=100000) imu = MPU9250(i2c) def imu_collect(): return { "accel": Vector3.from_imu_vector(imu.accel.xyz), "gyro": Vector3.from_imu_vector(imu.gyro.xyz), "mag": Vector3.from_imu_vector(imu.mag.xyz), "temp": imu.temperature }
import socket import machine 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))
from drv8833 import DRV8833 from mqttclient import MQTTClient import time, gc from math import fabs # robot controlled by joystick # remote led control led = Pin(LED, mode=Pin.OUT) # mqtt BROKER = "iot.eclipse.org" BROKER = "mac15.home" BROKER = "habiandev.local" BROKER = "dev.home" mqtt = MQTTClient(BROKER) print("connected to broker at", BROKER) run = True x = y = 0 brake = False def set_speed(): global motors, x, y, brake if brake: motors.brake(0) motors.brake(1) return sp0 = x + y sp1 = x - y
session = "rimuru" BROKER = "iot.eclipse.org" # check wifi connection wlan = network.WLAN(network.STA_IF) wlan.active(True) ip = wlan.ifconfig()[0] if ip == '0.0.0.0': print("no wifi connection") # code to handle the problem ... else: print("connected to WiFi at IP", ip) # connect to MQTT broker print("Connecting to MQTT broker", BROKER, "...", end="") mqtt = MQTTClient(BROKER) print("Connected!") #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
if c.isdigit(): num = num + c direc = num[-1] #the last number will be the direction num = num[0:-1] #the rest of the number will be the number of steps print("direction" + direc) print("number of steps" + num) #drive the motor #a1.drive(num, dir) 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))
np.set(0,R,0,0) time.sleep(0.1) np.set(0,0,0,0) time.sleep(0.1) sys.exit() else: print("connected to WiFi at IP", ip) # Connect to MQTT broker BROKER = "internetoflaundry.xyz" topic = "data" print("Connecting to MQTT broker", BROKER, "...", end="") try: mqtt = MQTTClient(BROKER) except: print("Could not connect to MQTT") for _ in range(10): np.set(0,Y,0,0) time.sleep(0.1) np.set(0,0,0,0) time.sleep(0.1) print("Connected!") # Start running while True: min = 10000 max = 0 measurements = 3000
if wlan.isconnected(): 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
if pid > 0: # Save child PID to file and exit parent process runfile = open("/var/run/mqtt-ciao.pid", "w") runfile.write("%d" % pid) runfile.close() sys.exit(0) except OSError, e: logger.critical("Fork failed") sys.exit(1) mqtt_queue = Queue() ciao_queue = Queue() try: mqttclient = MQTTClient(shd["conf"]["params"], ciao_queue) except Exception, e: logger.critical("Exception while creating MQTTClient: %s" % e) sys.exit(1) signal.signal(signal.SIGINT, signal.SIG_IGN) #ignore SIGINT(ctrl+c) signal.signal(signal.SIGHUP, signal_handler) signal.signal(signal.SIGTERM, signal_handler) if mqttclient.connect(): logger.info("Connected to %s" % shd['conf']['params']['host']) shd["requests"] = {} ciaoclient = MQTTCiao(shd, mqtt_queue, ciao_queue) ciaoclient.start()
# Encoders ... rpm_a = RPM(A6) rpm_b = RPM(A7) rpm = rpm_a if MOTOR == "A" else rpm_b # Motor power supply (Rigol DP832A) print("Connect to DP832A power supply") pwr = get_resource(RPC_RECEIVER, "pwr") print("pwr", pwr) pwr.config(1, v=0, i=0.4, ovp=8, ocp=1, enabled=True) pwr.config(2, enabled=False) pwr.config(3, enabled=False) # setup remote plotter print("connect to mqtt broker") mqtt = MQTTClient("iot.eclipse.org") plotter = MQTTPlotter(mqtt) RPM_VOLTAGE = "rpm_voltage" plotter.new_series(RPM_VOLTAGE, "Voltage [V]", "RPM", "Current [mA]") # run test print("run test ...") for v in linrange(0.5, 6.5, 12): gc.collect() print("Test voltage = {:8.2f} V".format(v)) # set motor voltage pwr.config(1, v=v) # wait a little to make sure motor runs at constant speed sleep(1) # reset rpm counter rpm.reset()
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)
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)
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()
from plotclient import PlotClient from mqttclient import MQTTClient from math import sin, cos, exp, pi mqtt = MQTTClient("iot.eclipse.org") mp = PlotClient(mqtt, session="hopla") #give series unique name SERIES = "sinusoid" #data column names mp.new_series(SERIES, 'time', 'cos', 'sin', 'sin*cos') #generate data def f1(t): return cos(2 * pi * t) * exp(-t) def f2(t): return sin(2 * pi * t) * exp(-t) def f3(t): return sin(2 * pi * t) * cos(2 * pi * t) * exp(-t) for t in range(200): t *= 0.025 #submit each datapoint to the plot server mp.data(SERIES, t, f1(t), f2(t), f3(t))
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))
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()
TS_CHANNEL_ID = '440884' TS_WRITE_KEY = '7839Z0UZ5F1YQ5TB' topic = "channels/" + TS_CHANNEL_ID + "/publish/" + TS_WRITE_KEY ############################# WIFI ####################################################### wlan = network.WLAN(network.STA_IF) wlan.active(True) ip = wlan.ifconfig()[0] if ip == '0.0.0.0 ': print("no wifi connection") sys.exit() else: print("connected to WiFi at IP", ip) print("Connecting to MQTT broker", BROKER, "...", end="") mqtt = MQTTClient(BROKER, user="", password="", ssl=True) print("connected!") # turn on LED led = Pin(LED, mode=Pin.OUT) led(1) print("awake") ############################# INA219 ####################################################### # initialize ina219 from ina219 import INA219 from board import SDA, SCL # from ina219_app import INA import time import json
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()
# e.g. your name & make corresponding change in mqtt_plot_host.py session = "wigglesc" BROKER = "iot.eclipse.org" machine.reset() # check wifi connection wlan = network.WLAN(network.STA_IF) wlan.active(True) ip = wlan.ifconfig()[0] if ip == '0.0.0.0': print("no wifi connection") sys.exit() else: print("connected to WiFi at IP", ip) # connect to MQTT broker print("Connecting to MQTT broker", BROKER, "...", end="") mqtt = MQTTClient(BROKER) #system index out of range error print("Connected!") ############################# Plot Client####################################################### mp = PlotClient(mqtt, session) SERIES = "data" ############################# DATA ####################################################### # initialize ina219 from ina219 import INA219 from machine import I2C, Pin from board import SDA, SCL # from ina219_app import INA import time import json
session = 'madesa/ESP32/helloworld' BROKER = 'broker.mqttdashboard.com' # check wifi connection wlan = network.WLAN(network.STA_IF) wlan.active(True) ip = wlan.ifconfig()[0] if ip == '0.0.0.0': print("no wifi connection") sys.exit() else: print("connected to WiFi at IP", ip) # connect to MQTT broker print("Connecting to MQTT broker", BROKER, "...", end="") mqtt = MQTTClient(BROKER, port=1883) print("Connected!") # send data # In this sample, we send "fake" data. Replace this code to send useful data, # e.g. measurement results. i2c = I2C(id=0, scl=Pin(SCL), sda=Pin(SDA), freq=100000) print("scanning I2C bus ...") print("I2C:", i2c.scan()) SHUNT_RESISTOR_OHMS = 0.1 ina = INA219(SHUNT_RESISTOR_OHMS, i2c) ina.configure()
r = (v/i)*1000 else: r = 0 return [v, i, p, r] from mqttclient import MQTTClient from time import sleep from plotclient import PlotClient from machine import deepsleep #set up broker TS_CHANNEL_ID = '436309' TS_WRITE_KEY = 'HRHIBUDP4FBOK88A' BROKER = 'mqtt.thingspeak.com' USER = '' PWD = '' mqtt = MQTTClient(BROKER) topic = "channels/" + TS_CHANNEL_ID + "/publish/" + TS_WRITE_KEY values = VoltageRead() v = values[0] i = values[1] sleep(0.3) message = "field1={}&field2={}".format(v, i) print("Publishing message {}, {}".format(v, i)) mqtt.publish(topic, message) mqtt.disconnect() from board import A10 from machine import Pin, PWM import machine
return [v, i, p, r] # Set up MQTT and plotclient for use on ESP32 from mqttclient import MQTTClient from time import sleep from plotclient import PlotClient #set up broker BROKER = 'iot.eclipse.org' USER = '' PWD = '' # connect (from lecture slides) print("Connecting to broker", BROKER, "...") mqtt = MQTTClient( BROKER, user=USER, password=PWD, ssl=True, ) mp = PlotClient(mqtt, session="BOSERBOIS_Plotter_2") #name series SERIES = 'power' #publish series mp.new_series(SERIES, 'R', 'P') lastmessage = [1, 1, 1, 1] while True: message = VoltageRead() if abs( message[2] - lastmessage[2] ) > 0.1 * message[2]: # Just checking that the change is greater than 10% mp.data(SERIES, message[3], message[2])
#### TO DO: Modify mqtt broker, get this publisher set up as a callback to a timer #start telnet server for remote login from network import telnet print("start telnet server") telnet.start(user='******', password='******') #Set up pulissher node from mqttclient import MQTTClient from time import sleep from machine import deepsleep #set up broker BROKER = 'iot.eclipse.org' USER = '' PWD = '' mqtt = MQTTClient(BROKER) topic = sleep(0.3) ### TO DO: Set up the callback to record and actuate the servos at the same time, #also possibly figure out phased arrays ### TO DO: Include this in the other callback from machine import Timer from board import A10, A12, A8, A6 from machine import Pin, PWM import machine import time DUTY = 0 pin1 = Pin(A10, mode=Pin.OUT)
adafruitAioKey = 'aio_CHOe50GxVH1hRAGMCF4XbXjHK6KE' # Define callback function def sub_cb(topic, msg): # print("Message type:", type(msg)) # int_msg = int(msg) # print("Int Message type:", type(int_msg)) # print(int_msg) print(msg) # 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 = "kaileo/feeds/pckt-refill" testMessage = "Hello Adafruit World" # testMessage = "1" mqtt.publish(feedName, testMessage) print("Published {} to {}.".format(testMessage, feedName))
import random #IOT ECLIPSE BROKER #BROKER = "iot.eclipse.org" #USER = None #PWD = None #HiveMQ Broker BROKER = "broker.hivemq.com" #iot.eclipse.org USER = None 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"
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()
def test_publishOne(self): #connect #publishone #disconnect #connect #publishone #... #publishone #disconnect topic = "test_topic" message = "test_message" mqtt_client = MQTTClient() mqtt_client.connect() mqtt_client.publish_one(topic, message) mqtt_client.publish_one(topic, message) #raw_input("Wait for restart push server and return.") mqtt_client.publish_one(topic, message) mqtt_client.publish_one(topic, message) mqtt_client.publish_one(topic, message) mqtt_client.start_send() mqtt_client.disconnect()