def main(): # All things global should be defined here global firebaseApp global firebaseDB global lightEventsRef global carEventsRef global mqttClient global LED_HIGH global LED_LOW cred = credentials.Certificate( "mdec-5edc2-firebase-adminsdk-vg9vm-9c5355fe8e.json") firebaseApp = firebase_admin.initialize_app(cred) firebaseDB = database databaseURL = "https://mdec-5edc2.firebaseio.com/" lightEventsRef = database.reference("light/lightEvents", firebaseApp, databaseURL) carEventsRef = database.reference("car/carEvents", firebaseApp, databaseURL) mqttClient = MQTTClient() LED_HIGH = "D1" LED_LOW = "D2"
from mqtt_client import MQTTClient import time client = MQTTClient() client.start_loop() while True: client.publish('time/sync/current', str(time.time())) time.sleep(1)
################################################## ## MQTT Test ## Ensures MQTT Broker can be connected to ################################################## ## Unlicensed ################################################## ## Author: benchPSU ## Copyright: Copyright 2019, Spiroflow ## Credits: [Mark Gee, Joel Yeow, Harvin Iriawan, Raymond Ooi] ## License: None ## Version: 1.0 ## Maintainer: Mark Gee ## Status: active ################################################## # Import relevant modulesimport sys import sys sys.path.append("./mqtt_client") import paho.mqtt.client as mqtt from mqtt_client import MQTTClient # Define connection variables HOST = "test.mosquitto.org" PORT = 8884 TOPIC = "IC.embedded/benchpsu" client = MQTTClient(HOST, PORT, TOPIC) print("MQTT test success!")
# http("http://192.168.1.133:8000/configuration/room/setpoint/update", "POST", JSON.stringify({"sensor":currentSensorSelection, "setpoint":currentSetpointValue, "time":time})) import requests, random, time, json from mqtt_client import Receiver, MQTTClient class OnReceive(Receiver): def on_message(self, client, userdata, message): msg = str(time.time()) + "," + str(message.payload.decode("utf-8")) print(msg) receiver = OnReceive() client = MQTTClient(receiver, 'latency_tester') client.subscribe('latency/response') try: client.start_loop() timer = time.time() update = 1 / 1000 sender = 0 while True: t1 = time.time() t0 = t1 - timer if t0 >= update: print(str(time.time()) + ",send," + str(sender)) requests.post( 'http://192.168.1.133:8000/configuration/room/setpoint/update', data=json.dumps({ "sensor": '30:AE:A4:DF:9A:6C',
def subscribe(): from mqtt_client import MQTTClient MQTTClient().start()
from mqtt_client import MQTTClient import ssl import json import paho.mqtt.client as mqtt with open("config/config.json", "r") as load_f: parameter = json.load(load_f) cli = MQTTClient(parameter["host"], parameter["port"]) cli.tls_set(parameter["ca_cert"], parameter["certfile"], parameter["keyfile"]) cli.on_log cli.connect(parameter["username"], parameter["password"]) cli.on_connect cli.subscribe(parameter["topic0"]) cli._on_message cli.loop()
class Silvia: def __init__(self): self.is_on = False self.temp_f = 0 self.temp_f_target = 212 self.control_p = 2 self.control_i = 0.1 self.control_d = 2 self.temp_history = [] self.shed_on_time = None self.sched_off_time = None self.last_on_time = time.time() self.last_off_time = None self.pid_freq = 1 self.read_freq = 10 self.post_freq = 10 self.stop_funcs = [] self.mqtt_client = MQTTClient() self.pid = PID(self.control_p, self.control_i, self.control_d, setpoint=self.temp_f_target) self.pid.output_limits = (0, 100) spi = SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) cs = DigitalInOut(board.D5) self.sensor = MAX31855(spi, cs) he_pin = 26 # GPIO26 GPIO.setmode(GPIO.BCM) GPIO.setup(he_pin, GPIO.OUT) self.he_pwm = GPIO.PWM(he_pin, self.pid_freq * 3) self.he_pwm.start(0) def start(self): # Start loops and catch stop functions stop_pid = run_at_freq(self.run_pid, self.pid_freq, self.run_pid) stop_read_temp = run_at_freq(self.read_temp, self.read_freq) stop_post_status = run_at_freq(self.post_status, self.post_freq) self.stop_funcs = [stop_pid, stop_read_temp, stop_post_status] while True: time.sleep(1) # Run until interrupt def run_pid(self, pid): control = self.pid(self.temp_f) print(f"Temp F {self.temp_f} \t Duty Cycle {control}") self.he_pwm.ChangeDutyCycle(control) def read_temp(self): self.temp_f = c_to_f(self.sensor.temperature) def post_status(self): self.mqtt_client.publish({"message": self.temp_f}) def close(self): self.mqtt_client.close() for name, f in self.stop_funcs: print('Stopping', name) f()
class HospiTalkie: """ State Machine for a named HospiTalkie TODO: Only include logic for functions defined by the statemachine. """ def start(self, stm_driver, login_gui): print("init HospiTalkie") self.name = "Ola" self.stm_driver = stm_driver self.login_gui = login_gui self.mqtt_client = MQTTClient(self.name, self.stm_driver) self.player = Player(self.stm_driver) self.recorder = Recorder(self.stm_driver) self.fileManager = FileManager(self.stm_driver) self.messageCounter = 0 self.isBuffer = True self.sender = None def setRecipient(self): print("setRecipient HospiTalkie") self.currentRecipient = self.mqtt_client.selected_recipient self.currentRecipientTopic = self.mqtt_client.phonebook[ self.currentRecipient.title()].lower() print(self.currentRecipient, self.currentRecipientTopic) def sendMessage(self, message): print("sendMessage HospiTalkie") print("Sending message to:", self.currentRecipientTopic) self.mqtt_client.publish(self.currentRecipientTopic, message) self.stm_driver.send( "messagePublished", "HospiTalkie") # TODO: Use callback instead then send?? def authenticate(self, usr, pwd): print("authenticate HospiTalkie") self.mqtt_client.start_client(usr, pwd) def loginSuccess(self): print("loginSuccess HospiTalkie") self.login_gui.switch_gui() def loginError(self): print("loginError HospiTalkie") self.login_gui.login_error() def loadPhoneBook(self): print("loadPhoneBook") def display(self, text): import threading print("displaying: " + text) if text == "Contacts": self.login_gui.app.queueFunction(self.login_gui.app.setTitle, get_string("choose_reciever")) prevContact = list(self.mqtt_client.phonebook.keys())[ (self.mqtt_client.phonebook_counter - 1) % len(self.mqtt_client.phonebook)] self.mqtt_client.selected_recipient = list( self.mqtt_client.phonebook.keys())[ self.mqtt_client.phonebook_counter % len(self.mqtt_client.phonebook)] nextContact = list(self.mqtt_client.phonebook.keys())[ (self.mqtt_client.phonebook_counter + 1) % len(self.mqtt_client.phonebook)] print("Displaying: " + self.mqtt_client.selected_recipient) contact = prevContact + "\n" + "--> " + self.mqtt_client.selected_recipient + "\n" + nextContact self.login_gui.app.queueFunction(self.login_gui.app.setMessage, "mess", "" + contact + "") elif text == "next_contact": self.mqtt_client.phonebook_counter += 1 elif text == "btn_record": self.login_gui.app.queueFunction(self.login_gui.app.setTitle, get_string("record_message")) self.login_gui.app.queueFunction(self.login_gui.app.setMessage, "mess", get_string("btn_record")) elif text == "main_screen": print("main screen") self.login_gui.app.queueFunction(self.login_gui.app.setTitle, get_string("idle")) self.login_gui.app.queueFunction(self.login_gui.app.setMessage, "mess", get_string("main_screen")) self.login_gui.app.setLabel( "title", "Welcome To HospiTalkie " + self.mqtt_client.name.title()) elif text == "new_messages": self.login_gui.app.queueFunction(self.login_gui.app.setTitle, get_string("new_message")) self.login_gui.app.queueFunction( self.login_gui.app.setMessage, "mess", get_string("new_messages_description")) elif text == "saved_messages": self.isBuffer = False self.messages = glob.glob("./Messages/*.wav") self.message = self.messages[self.messageCounter % len(self.messages)] self.currentRecipient = self.message[self.message. rfind("/"):][1:].split("-")[0] self.currentRecipientTopic = self.mqtt_client.phonebook[ self.currentRecipient] self.messageDisplay = re.search('./Messages/(.*).wav', self.message).group(1) self.login_gui.app.queueFunction(self.login_gui.app.setTitle, get_string("saved_messages")) self.login_gui.app.queueFunction( self.login_gui.app.setMessage, "mess", get_string("saved_messages") + "\n" + self.messageDisplay) elif text == "reply_message": print("Current recipient: " + str(self.sender)) self.login_gui.app.queueFunction(self.login_gui.app.setTitle, get_string("reply")) self.login_gui.app.queueFunction( self.login_gui.app.setMessage, "mess", get_string("reply_message", str(self.sender))) elif text == "recording": self.login_gui.app.queueFunction(self.login_gui.app.setTitle, get_string("recording")) self.login_gui.app.queueFunction(self.login_gui.app.setMessage, "mess", get_string("recording")) elif text == "done_recording": self.login_gui.app.queueFunction(self.login_gui.app.setTitle, get_string("done_recording")) self.login_gui.app.queueFunction(self.login_gui.app.setMessage, "mess", get_string("done_recording")) elif text == "playing": self.login_gui.app.queueFunction(self.login_gui.app.setTitle, get_string("playing")) self.login_gui.app.queueFunction( self.login_gui.app.setMessage, "mess", get_string("playing_from", str(self.sender))) elif text == "play_or_store": self.login_gui.app.queueFunction(self.login_gui.app.setTitle, get_string("new_message")) self.login_gui.app.queueFunction(self.login_gui.app.setMessage, "mess", get_string("play_or_store")) elif text == "next_message": self.login_gui.app.queueFunction(self.login_gui.app.setTitle, get_string("next_message")) self.login_gui.app.queueFunction(self.login_gui.app.setMessage, "mess", "message here!") elif text == "delete_message": self.login_gui.app.queueFunction(self.login_gui.app.setTitle, get_string("")) self.login_gui.app.queueFunction(self.login_gui.app.setMessage, "mess", get_string("delete_message")) def mute(self): print("mute") self.login_gui.app.setTitle(get_string("dont_disturb")) self.login_gui.app.queueFunction(self.login_gui.app.setButton, "Mute", get_string("unmute")) self.login_gui.app.queueFunction(self.login_gui.app.setMessage, "mess", get_string("not_disturbed")) def unmute(self): print("unmute") self.login_gui.app.queueFunction(self.login_gui.app.setButton, "Mute", get_string("mute")) def highlightNextMessage(self): print("highlightNextMessage") self.messageCounter += 1 def getMessage(self, message, sender): print("Get Message") self.isBuffer = True self.sender = sender #This makes audio message available in "playMessage". self.message = message #This makes audio message available in "playMessage". self.currentRecipientTopic = self.mqtt_client.phonebook[ self.sender.title()] def storeMessages(self): ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S') print("Store message") filename = self.sender.title() + "-" + st data = self.message self.stm_driver.send("saveFile", "fileManager", args=[filename, data]) def deleteMessages(self): print("delete message") def playNotification(self): print("Playing notification") self.stm_driver.send("start", "player", args=['notification.wav', False, False]) def playMessage(self): print("Play message") self.stm_driver.send("start", "player", args=[self.message, self.isBuffer, True]) def startRecording(self): print("Start Recording") self.stm_driver.send('start', 'recorder') def stopRecording(self): print("Stop Recording") self.stm_driver.send('stop', 'recorder')
import atexit from mqtt_client import MQTTClient # at exit function def cleanup(client): client.disconnect() client.loop_stop() # do turnstile stuff tester = MQTTClient() atexit.register(cleanup, tester) while True: # block topic = (raw_input("enter topic name:\n")).strip() msg = (raw_input("enter message:\n")).strip() tester.publish(topic, msg)
class OnReceive(Receiver): def on_message(self, client, userdata, message): global room_name msg = str(message.payload.decode("utf-8")) if message.topic == sensor_name + '/room/config': msg = json.loads(msg) room_name = msg['room'] update_config(msg) print(msg) # get_room_data() receiver = OnReceive() client = MQTTClient(receiver) client.start_loop() client.subscribe(sensor_name + '/room/config') if room_name is None: client.publish('sensor/registration', sensor_name + '/temperature') client.publish('sensor/registration', sensor_name + '/humidity') client.publish('sensor/registration', sensor_name + '/lux') try: while True: if room_name != None: temperature = str(get_temperature())
from mqtt_client import Receiver, MQTTClient import json, time, random, uuid class OnReceive(Receiver): def on_message(self, client, userdata, message): msg = str(message.payload.decode("utf-8")) # get_room_data() receiver = OnReceive() client = MQTTClient(receiver) client.start_loop() client.publish("30:AE:A4:DC:9A:38/setpoint", json.dumps({"setpoint": 30})) client.wait(2) client.stop_loop()