def mqtt_connect(): global client try: tools.debug("Connecting MQTT", "v") client = MQTTClient("gtw001_" + str(int(utime.time())), globalVars.mqtt_url, user=globalVars.mqtt_user, password=globalVars.mqtt_psw, port=1883) client.set_callback(response_callback) client.connect() client.subscribe(topic=globalVars.mqtt_topic) return client except BaseException as e: checkError("Error connecting to MQTT", e)
def Conexion_MQTT(): client_id = b"Covid_" + ubinascii.hexlify(unique_id()) #client_id = b"covid" mqtt_server = 'mantenimiento.elite.local' port_mqtt = 1883 user_mqtt = None #Si su servidor no necesita usuario escribe None sin comillas pswd_mqtt = None #Si su servidor no necesita contraseña escribe None sin comillas client = MQTTClient(client_id, mqtt_server, port_mqtt, user_mqtt, pswd_mqtt) client.set_callback(form_sub) client.connect() client.subscribe(b'SAL_DA') client.subscribe(b'HORA') print('Conectado a %s' % mqtt_server) return client
def setup_mqtt(): global client client = MQTTClient(client_id=config.CLIENT_ID, server=config.AWS_HOST, port=config.AWS_PORT, keepalive=10000, ssl=True, ssl_params={ "certfile": config.AWS_CLIENT_CERT, "keyfile": config.AWS_PRIVATE_KEY, "ca_certs": config.AWS_ROOT_CA }) client.set_callback(sub_callback) client.connect() client.subscribe(config.TOPIC)
def main(): print("starting") time.sleep(1.0) # Since open-drain on() means relays OFF and off() means Relays ON RELAY1.on() RELAY2.on() client = MQTTClient("relays1", "192.168.1.145", port=1883) client.settimeout = settimeout client.connect() client.set_callback(switch) client.subscribe("switching/#") while True: client.check_msg() print("waiting") time.sleep(1.0)
def main(server="test.mosquitto.org"): c = MQTTClient("umqtt_clientc", server) c.set_callback(sub_cb) c.connect() c.subscribe(b"mhermans/lights/#") while True: if True: # Blocking wait for message c.wait_msg() else: # Non-blocking wait for message c.check_msg() # Then need to sleep to avoid 100% CPU usage (in a real # app other useful actions would be performed instead) time.sleep(1) c.disconnect()
def mqtt_listen(server=MQTT_BROKER): global mqttc mqttc = MQTTClient("umqtt_client", server) mqttc.set_callback(sub_cb) mqttc.connect() mqttc.subscribe(b"sensor/#") while True: if True: # Blocking wait for message mqttc.wait_msg() else: # Non-blocking wait for message mqttc.check_msg() # Then need to sleep to avoid 100% CPU usage (in a real # app other useful actions would be performed instead) time.sleep(1) mqttc.disconnect()
def run(self): # Setup MQTT client client = MQTTClient(client_id=self.io_id, server="io.adafruit.com", user=self.io_user, password=self.io_key, port=self.port) client.set_callback(self.message_callback) client.connect() client.subscribe(topic="{0}/feeds/sensors".format(self.io_user)) while True: if self.sensor_on: # transitory time for i in range(0, 9): self.read_data() utime.sleep(2) data = self.read_data() client.publish(topic="{0}/feeds/temperature".format( self.io_user), msg=str("{0:0.1f}".format(data[0]))) client.publish(topic="{0}/feeds/humidity".format(self.io_user), msg=str("{0:0.1f}".format(data[1]))) client.publish(topic="{0}/feeds/pressure".format(self.io_user), msg=str("{0:0.1f}".format(data[2] / 100))) if self.battery: client.publish(topic="{0}/feeds/battery".format( self.io_user), msg=str("{0:0.1f}".format(data[3]))) print(" >{0} - battery: {1}".format(data[0:3], data[3])) else: print(" >{0}".format(data[0:3])) utime.sleep(self.update_frequency) client.check_msg() utime.sleep(1)
def run_gate(): global on_for_update c = MQTTClient("gate_client", secrets.MQTT_BROKER) c.set_callback(device_control) try: c.connect(clean_session=False) c.publish(topic.GATE_STATUS, msg_payload()) c.subscribe(topic.GATE_UPDATE, qos=1) c.check_msg() c.disconnect() flash_led(LED1) except OSError as e: print("mqtt error", e) if not on_for_update: switch_off() webrepl.start()
class Board: def __init__(self, components): self.led = components["pycom_led"]() self.validate_components() self.mqtt = MQTTClient("b1", "<host>", user="******", password="******", port=1883) def validate_components(self): set_intensity = getattr(self.led, "set_intensity", None) if set_intensity is None or not callable(set_intensity): raise Exception("led missing method set_intensity") set_status = getattr(self.led, "set_status", None) if set_status is None or not callable(set_status): raise Exception("led missing method set_status") def process_message(self, topic, msg): topic_str = topic.decode("utf-8") msg_str = msg.decode("utf-8") if topic_str == "b1/led/intensity": self.led.set_intensity(float(msg_str)) if topic_str == "b1/led/status": self.led.set_status(msg_str) def run(self): self.mqtt.set_callback(self.process_message) self.mqtt.connect() self.mqtt.subscribe("b1/led/intensity") self.mqtt.subscribe("b1/led/status") alarms = [] try: while True: self.mqtt.wait_msg() machine.idle() finally: for alarm in alarms: alarm.cancel() self.mqtt.disconnect()
def main(server=SERVER): c = MQTTClient(CLIENT_ID, server, user="******", password="******", port=1883) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) print("Connected to %s, subscribed to %s topic" % (server, TOPIC)) try: while 1: c.wait_msg() oled.fill(0) oled.text('Waiting msg.', 10, 10) oled.text('string', 10, 32) oled.show() finally: c.disconnect()
def run(self, wlan): # Setup MQTT client client = MQTTClient(client_id=self.io_id, server="io.adafruit.com", user=self.io_user, password=self.io_key, port=self.port) client.set_callback(self.message_callback) client.connect() client.subscribe(topic="{0}/feeds/sensors".format(self.io_user)) while True: if self.sensor_on and wlan.isconnected(): data = self.read_data() print(" >", data) client.publish(topic="{0}/feeds/tank-1".format(self.io_user), msg=str(data)) utime.sleep(self.update_frequency) elif not wlan.isconnected(): machine.reset() client.check_msg() utime.sleep(1)
def send_server(): global sd from network import WLAN from mqtt import MQTTClient import machine import time def sub_cb(topic, msg): print(msg) wlan = WLAN(mode=WLAN.STA) wlan.connect("Android", auth=(WLAN.WPA2, "123456789a"), timeout=5000) while not wlan.isconnected(): machine.idle() print("Connected to Wifi\n") client = MQTTClient("FiPy", "129.241.91.125", user="******", password="******", port=1883) client.set_callback(sub_cb) client.connect() client.subscribe(topic="Fuelfighter") last = None packetTemp = None copy_counter = 0 while True: stime = (ut() + 500) // 1000 if "server.txt" in ls('/sd') and stime != last: last = stime file = open('/sd/server.txt', 'r') packet = file.read() file.close() if packet != packetTemp: client.publish(topic="Fuelfighter", msg=packet) client.check_msg()
def thinx_mqtt(): restore_device_info() if not THINX_API_KEY: print("* THiNX: MQTT init failed...") return print("* THiNX: Initializing MQTT client " + THINX_UDID + " / " + THINX_API_KEY) mqtt_client = MQTTClient(thinx_device_mac(), THINX_MQTT_URL, THINX_MQTT_PORT, THINX_DEVICE_OWNER, THINX_API_KEY, keepalive=0, ssl=False, ssl_params={}) mqtt_client.settimeout = thinx_mqtt_timeout mqtt_client.set_callback = thinx_mqtt_callback mqtt_client.set_last_will(mqtt_status_channel(), thx_disconnected_response, retain=True, qos=0) if mqtt_client.connect(): mqtt_connected = True mqtt_client.subscribe(mqtt_device_channel(), MQTT_DEVICE_QOS) mqtt_client.subscribe(mqtt_status_channel(), MQTT_QOS) mqtt_client.publish(mqtt_status_channel(), thx_connected_response, MQTT_RETAIN, MQTT_QOS) if mqtt_connected == False: print("* THiNX: Re/connecting MQTT to " + THINX_MQTT_URL + "...") if mqtt_client.connect(): mqtt_connected = True mqtt_client.subscribe(mqtt_device_channel(), MQTT_DEVICE_QOS) mqtt_client.subscribe(mqtt_status_channel(), MQTT_QOS) mqtt_client.publish(mqtt_status_channel(), thx_connected_response, MQTT_RETAIN, MQTT_QOS)
def settimeout(duration): pass def on_message(topic, msg): print("Received msg: ", str(msg), "with topic: ", str(topic)) ### if __name__ == "__main__": ufun.connect_to_wifi(wifi_ssid, wifi_passwd) client = MQTTClient("marcoLaptop", broker_addr, 1883) client.set_callback(on_message) print("Connecting to broker: " + broker_addr) try: client.connect() except OSError: print("Cannot connect to broker: " + broker_addr) sys.exit() print("Connected to broker: " + broker_addr) client.subscribe('sensors/#') print('Waiting messages...') while 1: client.check_msg()
time.sleep(SAMPLING_STEP) res = 0 for s in samples: res += s res /= SAMPLES_COUNT client.publish(topic=AMBIENT_LIGHT_PUBLISH_TOPIC, msg=res) print(res) client = MQTTClient(DEVICE_ID, SERVER, PORT) client.set_callback(subscribe_request_ambient_light) client.connect() client.subscribe(AMBIENT_LIGHT_REQUEST_TOPIC) print("Connected to %s, subscribed to %s" % (SERVER, AMBIENT_LIGHT_REQUEST_TOPIC)) pycom.rgbled(0x006000) # Status green: connected successfully to broker try: while 1: client.check_msg() finally: client.disconnect() client = None wlan.disconnect() wlan = None pycom.rgbled(0x000022) # Status blue: stopped print("Disconnected from server and wlan")
#define subscription callback def mqtt_cb(topic, msg): if topic == "crpalka/control": if msg == "force_stop": mqtt_override = 1 mqtt_override_val = 0 elif msg == "force_run": mqtt_override = 1 mqtt_override_val = 1 elif msg == "deactivate": mqtt_override = 0 mqtt_override_val = None client.set_callback(mqtt_cb) client.connect() client.subscribe(topic="crpalka/control") # enter main loop while True: #publish messages client.publish(topic="youraccount/feeds/lights", msg="OFF") # check for MQTT messages client.check_msg() # sleep for 1 s time.sleep(1)
class HVACPIDController(object): logger = None mqtt = None temp = None fan = None power = None config = None state = None temp_outdoors = 0 mode = 'auto' manual = False control_enable = False hvac_state = {} next_iteration = None def __init__(self): self.logger = logging.getLogger('hvac-pid') self.logger.info('Starting hvac-pid') self.config = Config() self.util = Util() # PID options pid_options = self.config.getPIDOptions(self.mode) temp_options = self.config.getTempOptions(self.mode) # Temp self.temp = Temp(**{**temp_options, **pid_options}) # Fan self.fan = Fan() # Power self.power = Power() # Occupancy state self.state = State(**self.config.getStateOptions()) # MQTT self.topic_prefix = os.getenv('MQTT_PID_TOPIC_PREFIX') self.mqtt = MQTTClient(os.getenv('MQTT_CLIENT_ID'), os.getenv('MQTT_BROKER_HOST')) self.mqtt.connect() # subscribe self.mqtt.subscribe(os.getenv('MQTT_TEMP_TOPIC'), 0, self.temp_update_callback) self.mqtt.subscribe(os.getenv('MQTT_TEMP_OUTDOORS_TOPIC'), 0, self.temp_outdoors_update_callback) self.mqtt.subscribe(os.getenv('MQTT_HVAC_STATE_TOPIC'), 0, self.hvac_callback) self.mqtt.subscribe(self.topic_prefix + '/mode/set', 0, self.set_mode) self.mqtt.subscribe(self.topic_prefix + '/temperature/set', 0, self.set_temp) self.mqtt.subscribe(self.topic_prefix + '/fan/set', 0, self.set_fan) self.mqtt.subscribe(os.getenv('MQTT_HVAC_OCCUPANCY_STATE_TOPIC'), 0, self.set_occupancy_state) self.logger.info('MQTT connected') self.publish_temp() self.publish_mode() self.publish_fan() self.next_iteration = datetime.now() + timedelta(minutes=2) # wait a bit before enabling control time.sleep(5) self.control_enable = True def iterate(self): if self.manual: self.logger.info('Manual mode, skipping PID iteration') else: compensated_request_temp = self.state.compensateRequestTemp( self.temp.temp_request, self.temp_outdoors) max_set_temp = ceil(self.temp.temp_absolute) + 3 # temp hax # limit min temp when outdoors is < -10 if self.temp_outdoors < -10: self.temp.setLimits( floor(compensated_request_temp) - 1, max_set_temp) self.logger.debug( 'Limiting min temp to %g when outdoor temp is %g', self.temp.temp_min, self.temp_outdoors) else: self.temp.setLimits(self.config.getSetTempMin(), max_set_temp) self.temp.iteratePID(compensated_request_temp) self.fan.calculate(self.temp.pid_offset, self.mode) self.power.calculate(self.temp.temp_request, self.temp.temp_measure, self.mode, self.temp_outdoors) if not self.power.state: self.temp.reset() self.publish_state() def temp_update_callback(self, client, userdata, message): payload_json = json.loads(message.payload.decode('utf-8')) if 'temperature' in payload_json: temp = payload_json['temperature'] else: temp = payload_json['tempc'] if 'humidity' in payload_json: humidity = payload_json['humidity'] else: humidity = payload_json['hum'] if self.mode == 'cool': dew_point = self.util.dewPoint(temp, humidity) self.temp.setMeasurement(round(dew_point, 2), temp) else: self.temp.setMeasurement(temp, temp) def temp_outdoors_update_callback(self, client, userdata, message): payload_json = json.loads(message.payload.decode('utf-8')) self.temp_outdoors = float(payload_json['temperature']) def hvac_callback(self, client, userdata, message): payload_json = json.loads(message.payload.decode('utf-8')) self.logger.info('Received hvac state change %s', payload_json) self.hvac_state = payload_json def setHVAC(self): if self.control_enable: topic = os.getenv('MQTT_HVAC_TOPIC') new_state = { 'power': self.power.state, 'mode': self.mode.upper(), 'temperature': self.temp.temp_set, 'fan': self.fan.speed, } is_state_changed = (new_state['power'] and self.hvac_state != new_state) is_power_state_changed = ( self.hvac_state and new_state['power'] != self.hvac_state['power']) old_state_doesnt_exists = (not self.hvac_state) if is_state_changed or is_power_state_changed or old_state_doesnt_exists: message = json.dumps(new_state) self.logger.debug('Controlling HVAC with command %s', message) self.mqtt.publish(topic, message, 1) else: self.logger.debug('HVAC state unchanged %s', self.hvac_state) else: self.logger.debug('Controlling HVAC disabled') def set_mode(self, client, userdata, message): mode = message.payload.decode('utf-8') previous_mode = self.mode # reset PID if switching between modes if previous_mode != mode: pid_options = self.config.getPIDOptions(mode) temp_options = self.config.getTempOptions(mode) self.temp = Temp(**{**temp_options, **pid_options}) if mode == 'off': self.manual = True self.mode = 'auto' self.power.state = False self.logger.info('Set mode to off') if mode == 'auto': self.manual = True self.power.state = True self.mode = 'auto' self.temp.temp_set = self.temp.temp_request self.logger.info('Set mode to manual') elif mode == 'heat': self.manual = False self.mode = mode self.logger.info('Set mode to %s', self.mode) elif mode == 'cool': self.manual = False self.mode = mode self.temp.temp_set = self.temp.temp_absolute self.logger.info('Set mode to %s', self.mode) self.state.setMode(mode) self.publish_mode() self.setHVAC() self.set_next_iteration(2) def publish_mode(self): if not self.control_enable: return topic = self.topic_prefix + '/mode/state' if self.manual: if self.power.state == False: mode = 'off' else: mode = 'manual' elif self.mode == 'auto': mode = 'manual' else: mode = self.mode self.mqtt.publish(topic, mode, 1, True) def set_temp(self, client, userdata, message): temp = round(float(message.payload.decode('utf-8')), 2) if temp >= float(os.getenv('REQUEST_MIN_TEMP', 0)) and temp <= float( os.getenv('REQUEST_MAX_TEMP', 100)): self.temp.setRequest(temp) if self.manual: self.temp.temp_set = self.temp.temp_request else: self.temp.reset() self.publish_temp() self.setHVAC() def publish_temp(self): if not self.control_enable: return self.mqtt.publish(self.topic_prefix + '/temperature/state', self.temp.temp_request, 1, True) self.mqtt.publish(self.topic_prefix + '/measured_temperature', self.temp.temp_measure, 1, True) def set_fan(self, client, userdata, message): fan = message.payload.decode('utf-8') if fan != "auto": fan_int = int(fan) if self.manual and fan_int >= 0 and fan_int <= 5: self.fan.speed = fan_int self.publish_fan() self.setHVAC() self.logger.info('Manually set fan speed to %s/5', self.fan.speed) def publish_fan(self): if not self.control_enable: return topic = self.topic_prefix + '/fan/state' if self.manual: fan = self.fan.speed else: fan = 'auto' self.mqtt.publish(topic, fan, 1, True) def publish_state(self): if not self.control_enable: return topic = os.getenv('MQTT_PID_TOPIC_PREFIX') + '/state' message = json.dumps({ 'mode': self.mode, 'manual': self.manual, 'temperature_request': float(self.temp.temp_request), 'temperature_set': float(self.temp.temp_set), 'temperature_measure': float(self.temp.temp_measure), 'temperature_error': float(self.temp.pid.previous_error), 'set_temperature_lower_limit': float(self.temp.temp_min), 'set_temperature_upper_limit': float(self.temp.temp_max), 'fan': int(self.fan.speed if self.power.state else 0), 'power': self.power.state, 'Kp': float(self.temp.pid.Kp), 'Ki': float(self.temp.pid.Ki), 'Kd': float(self.temp.pid.Kd), 'integral': float(self.temp.pid.integral), 'integral_max': float(self.temp.pid.integral_max), 'pid_offset': float(self.temp.pid_offset), 'pid_result': float(self.temp.pid_result), }) self.mqtt.publish(topic, message, 1) def set_occupancy_state(self, client, userdata, message): state = message.payload.decode('utf-8') prev_state = self.state.state self.state.setState(state) self.logger.info('Setting occupancy state to %s', self.state.state) # only reset if going or returning away state if prev_state == 'away' or self.state.state == 'away': self.temp.reset() self.set_next_iteration(2) def set_next_iteration(self, interval): self.next_iteration = datetime.now() + timedelta(minutes=interval) self.logger.info('Next iteration at %s', self.next_iteration)
pass def on_message(topic, msg): print("topic is: " + str(topic)) print("msg is: " + str(msg)) wlan = WLAN(mode=WLAN.STA) nets = wlan.scan() for net in nets: if net.ssid == wifi_ssid: print("Network " + wifi_ssid + " found!") wlan.connect(net.ssid, auth=(net.sec, wifi_passwd), timeout=5000) while not wlan.isconnected(): #machine.idle() # save power while waiting idle() # save power while waiting print("WLAN connection succeeded!") print (wlan.ifconfig()) break client = MQTTClient(MYDEVID, broker_addr, 1883) if not client.connect(): print ("Connected to broker: " + broker_addr) client.set_callback(on_message) client.subscribe("sensors/") print("Checking messages ...") while 1: client.check_msg()
def settimeout(duration): pass def on_message(topic, msg): print("Received msg: ", str(msg), "with topic: ", str(topic)) ### if __name__ == "__main__": ufun.connect_to_wifi(wifi_ssid, wifi_passwd) client = MQTTClient(dev_id, broker_addr, 1883) client.set_callback(on_message) print("Connecting to broker: " + broker_addr) try: client.connect() except OSError: print("Cannot connect to broker: " + broker_addr) sys.exit() print("Connected to broker: " + broker_addr) client.subscribe('THE_TOPIC_TO_BE_USED') print('Waiting messages...') while 1: client.check_msg()
import time def sub_cb(topic, msg): print(msg) wlan = WLAN(mode=WLAN.STA) wlan.connect("A4-WiFi", auth=(WLAN.WPA2, "AFourtech@321$"), timeout=5000) while not wlan.isconnected(): machine.idle() print("Connected to WiFi\n") client = MQTTClient("device_id", "192.168.3.144", port=1883) client.set_callback(sub_cb) client.connect() client.subscribe(topic="youraccount/feeds/lights") while True: print(s.recv(64)) time.sleep(2) # if s.recv(64) == b'Ping': # s.send('Pong') time.sleep(5) print("Sending ON MQTT") client.publish(topic="cona", msg=s.recv(64)) client.check_msg() time.sleep(1)
#wlan.connect("c-base-botnet", auth=(WLAN.WPA2, "wifipassword"), timeout=5000) while not wlan.isconnected(): machine.idle() print("Connected to Wifi\n") client = MQTTClient("windsensor_0", "192.168.178.98", user="", password="", port=1883) #client = MQTTClient("windsensor_0", "mqtt.cbrp3.c-base.org",user="", password="", port=1883) client.set_callback(sub_cb) client.connect() client.subscribe(topic="/hackerfleet/sensors/windsensor/control") print("Connected to MQTT") speedInterrupts = 0 directionInterrupts = 0 speedTicks = 0 directionTicks = 0 def callbackSpeed(pin): global speedInterrupts speedInterrupts += 1
with open('config.json') as f: config = json.load(f) topic_pub = 'devices/loqotia-sensors' topic_sub = 'devices/loqotia-sensors/control' broker_url = 'devpi' client_name = ubinascii.hexlify(hashlib.md5(machine.unique_id()).digest()) c = MQTTClient(client_name, broker_url, user=config["user_mqtt"], password=config["pass_mqtt"]) c.set_callback(sub_cb) c.connect() c.subscribe(topic_sub) rtc = RTC() def fetch_data(): while True: temp, hum = temphumid.read_data() c.publish( topic_pub, '{"loqotia-sensor": {"Darkness":' + str(ldr.read_ldr()) + ',"Temperature":' + str(temp) + ',"Humidity":' + str(hum) + '}}') time.sleep(300)
payload = msg.decode('utf-8') data = json.loads(payload) proove_remote.transmit(state=data['on'], channel=data['channel'], device_id=data['deviceId'], transmitter_id=data['transmitterId']) if __name__ == "__main__": proove_remote = Proove(gpio_config['tx_pin']) client.set_callback(on_message) client.connect() client.subscribe(topic=mqtt_config['subscription_topic']) print(' [*] Waiting for messages...') while True: try: client.check_msg() except: print(' [-] Failed to ping....') print(' [*] Reconnecting to WIFI / MQTT.') connect_wifi(known_nets) client.connect() wdt.feed() time.sleep(0.1)
'cert_reqs': ssl.CERT_REQUIRED, 'ca_certs': 'cert/my-ca.pem' } client = MQTTClient("device", MQTT_BROKER, port=1883, ssl=True, ssl_params=PARAMS) client.set_callback(subscribe_callback) print("Connecting to MQTT broker...") try: client.connect() client.subscribe(topic=MQTT_TOPIC) client.subscribe(topic=MQTT_TOPIC2) client.subscribe(topic=MQTT_TOPIC3) print("Done") CONNECT = True except OSError: print("Cannot connect to MQTT broker...") CONNECT = False while CONNECT: temp = sensor.temperature() humid_ambient = sensor.humid_ambient(temp) pressure = sensor2.pressure() print("Sending Data to MQTT broker")
def on_message(topic, msg): print("topic is: " + str(topic)) print("msg is: " + str(msg)) wlan = WLAN(mode=WLAN.STA) nets = wlan.scan() for net in nets: if net.ssid == wifi_ssid: print("Network " + wifi_ssid + " found!") wlan.connect(net.ssid, auth=(net.sec, wifi_passwd), timeout=5000) while not wlan.isconnected(): #machine.idle() # save power while waiting idle() # save power while waiting print("WLAN connection succeeded!") print(wlan.ifconfig()) break client = MQTTClient(MYDEVID, broker_addr, 1883) if not client.connect(): print("Connected to broker: " + broker_addr) client.set_callback(on_message) client.subscribe("lopy/sensor") print("Checking messages ...") while 1: client.check_msg()
mqtt.check_msg() if now - last_ping >= 60 * 1000: ## TODO change back to 60 print("pinging") last_ping = now try: mqtt.ping() except OSError: print("got an oserror, connecting again") connect(mqtt) # mqtt.publish(channel, b"hello world") next_tick = 0 if res == 0: last_ping = pyb.millis() mqtt.subscribe(channel) mqtt.publish(channel, b"hello world") while True: pyb.wfi() # Wait For Input -- only waits 1ms ugfx.poll() now = pyb.millis() if (next_tick <= now): next_tick = now + TICK_EVERY_MS on_tick(now) # mqtt.disconnect() # while True: # pyb.wfi() # if buttons.is_triggered("BTN_MENU") or buttons.is_triggered("BTN_A") or buttons.is_triggered("BTN_B") or buttons.is_triggered("JOY_CENTER"):
def main(): global colour global connected_wifi c = MQTTClient(CLIENT_ID, SERVER, user=USERNAME, password=PASSWORD, port=PORT) c.set_callback(sub_cb) c.connect() np[0] = (100,100,100) np.write() c.subscribe(COLOUR_TOPIC) c.subscribe(TEST_TOPIC) c.publish(PUB_TOPIC, "I have connected to "+connected_wifi+" and waiting for a colour code!") while True: c.check_msg() if state ==1: if button.value() == 0: time.sleep_ms(20) while button.value() == 0: for x in range(0, 125): if button.value() == 0: colour = (125,x,0) np[0] = colour np.write() time.sleep_ms(10) for x in range(125, -1, -1): if button.value() == 0: colour = (x,125,0) np[0] = colour np.write() time.sleep_ms for x in range(0, 125): if button.value() == 0: colour = (0,125,x) np[0] = colour np.write() time.sleep_ms(10) for x in range(125, -1, -1): if button.value() == 0: colour = (0,x,125) np[0] = colour np.write() time.sleep_ms(10) for x in range(0, 125): if button.value() == 0: colour = (x,0,125) np[0] = colour np.write() time.sleep_ms(10) for x in range(125, -1, -1): if button.value() == 0: colour = (125,0,x) np[0] = colour np.write() time.sleep_ms(10) message = "{\"red\":" +str(colour[0]) + ", \"green\": " + str(colour[1]) + ",\"blue\": " + str(colour[2])+"}" c.publish(COLOUR_TOPIC, message) time.sleep_ms(50) if state ==2: rainbow() c.disconnect() np[0] = (0,0,0) np.write()
c.publish("sendmsg", str(total).encode("utf-8")) elif msg == b"all": m = str(tem) + "," + str(hum) + "," + str(lux) + "," + str(total) c.publish("sendmsg", m.encode("utf-8")) else: c.publish("sendmsg", b"error command") try: connect_WIFI(SSID, PASSWORD) server = SERVER c = MQTTClient(CLIENT_ID, server, SERVER_PORT, username, password) # 连接MQTT服务 c.set_callback(handlemsg) # 回调函数 c.connect() c.subscribe("test_subscribe") # 订阅 c.publish("sendmsg", "") # 发布 while True: # 第一间教室 # 统计人数 if num1.value() == 1: while num1.value(): if num2.value() == 1: total += 1 print(total) while num1.value() | num2.value(): pass break if num2.value() == 1: while num2.value():
wifi_ssid = "raspiWLAN" wifi_passwd = '' broker_addr = "test.mosquitto.org" def settimeout(duration): pass def on_message(topic, msg): print("topic is: " + str(topic)) print("msg is: " + str(msg)) ### if __name__ == "__main__": ufun.connect_to_wifi(wifi_ssid, wifi_passwd) client = MQTTClient("dev_id", broker_addr, 1883) client.set_callback(on_message) if not client.connect(): print("Connected to broker: " + broker_addr) client.subscribe('lopy/lights') print('Waiting messages...') while 1: client.wait_msg()
class RoomThermostat(object): mqtt = None config = None hass = None mode = {} target = {} temp = {} def __init__(self): self.logger = logging.getLogger('room-thermostat') self.logger.info('Starting room thermostat') # Config self.config = Config('./config.yaml') # HomeAssistant self.hass = HomeAssistant() # MQTT self.mqtt = MQTTClient(self.config.mqtt['client_id'], self.config.mqtt['host'], self.config.mqtt['port']) self.mqtt.will(f"roomthermostat/availability", 'offline') self.mqtt.connect() self.publishAvailable() for room in self.config.rooms: self.subscribeRoom(room) self.publishAutoDiscovery() def subscribeRoom(self, room): # temperature_command_topic self.mqtt.subscribe( f"roomthermostat/{room['name_snakecase']}/temperature/set", self.temperatureCommand) # mode_command_topic self.mqtt.subscribe( f"roomthermostat/{room['name_snakecase']}/mode/set", self.modeCommand) # measurement_topic self.mqtt.subscribe(room['measurement_topic'], self.measurement) def publishAutoDiscovery(self): for room in self.config.rooms: self.logger.info(f"Publishing auto discovery for '{room['name']}'") self.mqtt.publish(*self.hass.buildDiscoveryMessage(room)) def publishAvailable(self): self.logger.info(f"Publishing availability") self.mqtt.publish(f"roomthermostat/availability", 'online') def publishMode(self, name, mode): self.logger.info(f"Publishing mode for '{name}'") self.mqtt.publish(f"roomthermostat/{name}/mode", mode) def publishTarget(self, name, temperature): self.logger.info(f"Publishing target temperature for '{name}'") self.mqtt.publish(f"roomthermostat/{name}/temperature", str(temperature)) def publishTemperature(self, name, temperature): self.logger.info(f"Publishing temperature for '{name}'") self.mqtt.publish(f"roomthermostat/{name}/current_temperature", str(temperature)) def publishEnableHeating(self, room): self.logger.info( f"Publishing enable heating for '{room['name_snakecase']}'") self.mqtt.publish(room['control_topic'], "on") self.publishAction(room['name_snakecase'], self.mode[room['name_snakecase']], True) def publishDisableHeating(self, room): self.logger.info( f"Publishing disable heating for '{room['name_snakecase']}'") self.mqtt.publish(room['control_topic'], "off") self.publishAction(room['name_snakecase'], self.mode[room['name_snakecase']], False) def publishAction(self, name, mode, relayOn): if mode == 'off': action = 'off' elif relayOn == True: action = 'heating' elif relayOn == False: action = 'idle' else: self.logger.error( f"Cannot publish action for '{name}', mode: '{mode}', relayOn: '{relayOn}'" ) return self.logger.info(f"Publishing action for '{name}'") self.mqtt.publish(f"roomthermostat/{name}/action", action) def temperatureCommand(self, client, userdata, message): name = self._parseRoomNameFromTopic(message.topic) temperature = float(message.payload.decode('utf-8')) if temperature >= 15 and temperature <= 25: self.logger.info( f"Received target temperature '{temperature}' for '{name}'") self.target[name] = temperature self.publishTarget(name, self.target[name]) self.iterateRoom(self._findRoomByName(name)) else: self.logger.error( f"Invalid target temperature '{temperature}' for '{name}'") def modeCommand(self, client, userdata, message): name = self._parseRoomNameFromTopic(message.topic) mode = message.payload.decode('utf-8') if mode in ['heat', 'off']: self.logger.info(f"Received mode '{mode}' for '{name}'") self.mode[name] = mode self.publishMode(name, self.mode[name]) self.iterateRoom(self._findRoomByName(name)) else: self.logger.error(f"Unknown mode '{mode}' for '{name}'") def measurement(self, client, userdata, message): topic = message.topic payload_json = json.loads(message.payload.decode('utf-8')) newMeasurement = float(payload_json['temperature']) for room in self.config.rooms: name = room['name_snakecase'] if room['measurement_topic'] == topic and ( name not in self.temp or self.temp[name] != newMeasurement): self.logger.info( f"Received new measurement '{newMeasurement}' for '{name}'" ) self.temp[name] = newMeasurement self.iterateRoom(room) def _parseRoomNameFromTopic(self, topic): pattern = re.compile('roomthermostat/([a-z0-9_-]+)/(.+)/set') match = pattern.match(topic) return match.group(1) def _findRoomByName(self, name): for room in self.config.rooms: if room['name'] == name or room['name_snakecase'] == name: return room return None def iterateRoom(self, room): name = room['name_snakecase'] # initialize with home temperature if not name in self.target: self.target[name] = room['temperatures']['home'] self.publishTarget(name, self.target[name]) if not name in self.temp or not name in self.mode: return else: self.publishTemperature(name, self.temp[name]) diff = self.temp[name] - self.target[name] mode = self.mode[name] if mode != 'heat': # turn relay off self.logger.info( f"Turning off heating in '{room['name']}', mode: '{mode}' diff: {diff:.2f}" ) self.publishDisableHeating(room) elif diff > 1.0: # turn relay off self.logger.info( f"Turning off heating in '{room['name']}', mode: '{mode}' diff: {diff:.2f}" ) self.publishDisableHeating(room) elif diff < 1.0: # turn relay on self.logger.info( f"Turning on heating in '{room['name']}', mode: '{mode}' diff: {diff:.2f}" ) self.publishEnableHeating(room) else: # keep current relay state return