def main(): esp.osdebug(None) print("CPU frequency is {}".format(machine.freq())) machine.freq(80000000) print("CPU frequency is {}".format(machine.freq())) if wifi.connect(ssid, password): print("Starting webrepl") if webrepl.listen_s is None: webrepl.start() else: print("Webrepl already started") # pwm.init(pin=pwm_pin, frequency=pwm_frequency) client_id = wifi.station.config("dhcp_hostname") topic_sub = "shellies/shellyem3-ECFABCC7F0F4/emeter/0/power" topic_pub = "iot/sonoff/" + client_id + "/" mqtt.connect(client_id, mqtt_server, topic_sub, topic_pub, user=mqtt_user, password=mqtt_pass) else: print("Wifi did not connect") restart_and_reconnect()
def __init__(self, callback=None, context=None): mqtt.connect(GameSession.onMsg, self) self.id = random.randint(1, 1000000000) self.id = random.randint(1, 10) print("I am:", self.id) self.wants = False self.callback = callback self.context = context self.opponent = 0
def test_connect_success(self, config_mock, hostname_mock, mqtt_mock): """Tests successful connection to MQTT server.""" hostname_mock.return_value = "hostname" config_mock.return_value = dict(mqtt={"broker_url": "some_url"}) mqtt.connect(["domain1", "domain2"]) mqtt_mock.assert_has_calls( [mock.call().connect("some_url", port=None, keepalive=None)], any_order=True, )
def main(): #连接MQTT服务器 connect("45.32.7.217", 1883) #探测yeelight灯 yeelight = Yeelight() detection_thread = Thread(target=yeelight.bulbs_detection_loop) detection_thread.start() while True: str = input() if str: publish("chat", str) yeelight.RUNNING = False detection_thread.join()
def main(): esp.osdebug(None) common.set_adc_mode(common.ADC_MODE_VCC) vcc = machine.ADC(1).read() machine_id = ubinascii.hexlify(machine.unique_id()).decode("utf-8") print("Main function, VCC={}, hw_id={}".format(vcc, machine_id)) if machine.reset_cause() == machine.DEEPSLEEP_RESET: init_stepper(from_deep_sleep=True) else: init_stepper(from_deep_sleep=False) if wifi.connect(ssid, password): print("Starting webrepl") if webrepl.listen_s is None: webrepl.start() else: print("Webrepl already started") # settime() client_id = wifi.station.config("dhcp_hostname") topic_sub = "iot/micro/" + client_id topic_pub = "iot/sonoff/" + client_id result = mqtt.connect(client_id, mqtt_server, topic_sub, topic_pub, user=mqtt_user, password=mqtt_pass) if result == 'restart': print("Restarting due to connectivity error") else: print("Unknown action {}".format(result)) else: print("Wifi did not connect") restart_and_reconnect()
thingName = "ufscar_db_02" caPath = "/home/linaro/aula_05/rootCA.crt" certPath = "/home/linaro/aula_05/cert.pem" keyPath = "/home/linaro/aula_05/private.key" if __name__ == '__main__': connection_data = {} connection_data["client_id"] = clientId connection_data["ca"] = caPath connection_data["certificate"] = certPath connection_data["private_key"] = keyPath connection_data["endpoint"] = awshost connection_data["port"] = awsport mqtt_client = mqtt.connect(connection_data) try: while True: # Temperature temp = temperature.get() data = json.dumps({"d": {"temperature": temp}}) print("publishing: %s" % temp) (rc, mid) = mqtt_client.publish("dragon", data, qos=1) # Tilt t = tilt.get() if t == 1: data = json.dumps({"d": {"tilt": "tilted"}}) print("publishing: tilted") else: data = json.dumps({"d": {"tilt": "normal"}})
def test_connect_fails_mqtt_error(self, config_mock, mqtt_mock): """Tests failure for connect - ValueError.""" mqtt_mock.side_effect = ValueError("barf") config_mock.return_value = dict(mqtt={"broker_url": "some_url"}) with self.assertRaises(ValueError): mqtt.connect(["domain1", "domain2"])
def init_mqtt(mqtt): mqtt.connect() print("MQTT connection established")
def __init__(self, args): self.args = args mqtt.connect(not args.offline) self.modules = None self.states = {}
import wifi import mqtt import config import machine from machine import Pin import time import dht CONFIG = config.get() TEMP_TOPIC = CONFIG['temp_topic'] HUM_TOPIC = CONFIG['hum_topic'] wifi.connect(CONFIG) mqtt_client = mqtt.start(CONFIG) mqtt_client = mqtt.connect(mqtt_client) d = dht.DHT22(Pin(4)) while True: try: d.measure() temp = d.temperature() hum = d.humidity() mqtt_client.publish(str.encode(TEMP_TOPIC), str.encode(str(temp))) mqtt_client.publish(str.encode(HUM_TOPIC), str.encode(str(hum))) except OSError as e: machine.reset() time.sleep(5)
#!/usr/bin/env python # _*_ coding: utf-8 _*_ # @Time : 2021/5/8 17:12 # @Author : 詹荣瑞 # @File : crud.py # @desc : 本代码未经授权禁止商用 import datetime from sqlalchemy.orm import Session from database import models, schemas from mqtt import connect, subscribe, publish connect() subscribe() def get_user(db: Session, name: str): return db.query(models.User).filter(models.User.User_Name == name).first() def get_users(db: Session, skip: int = 0, limit: int = 100): return db.query(models.User).offset(skip).limit(limit).all() def create_user(db: Session, user: schemas.UserCreate): fake_hashed_password = user.User_Password db_user = models.User(User_ID=user.User_Name, User_Name=user.User_Name, User_Password=fake_hashed_password) db.add(db_user) db.commit() db.refresh(db_user)
import mqtt as mqtt import uuid # import sensorLDR as sensor client = mqtt.connect() iniciou = False resistenciaAtual = 0 processId = "" while True: # resistencia = sensor.capturar_resistencia() resistencia = 15001 if (iniciou == False): if (resistencia > 15000): iniciou = True processId = uuid.uuid1() client.publish( "Test", '{"ambiente" : 1, "processId" : "' + str(processId) + '", "ligado" : true }') else: if (resistencia < 15000): iniciou = False processId = processId client.publish( "Test", '{"ambiente" : 1, "processId" : "' + str(processId) + '", "ligado" : false }')
def connect(self): return mqtt.connect(self.authAddress, self.productKey, self.productSecret, self.deviceId, self.deviceSecret)
import command import environment as env import instruction import led import os import mqtt import tlc5947 import queuehandler mqtt = mqtt.Mqtt() mqtt.connect() led.mqtt = mqtt tlc5947 = tlc5947.tlc5947() def on_instruction(instruction): if (env.logLevel == env.DEBUG): print(f"on_instruction: {instruction}") tlc5947.handle(instruction) instructionHandler = queuehandler.handler() instructionHandler.set_callback(on_instruction) instructionHandler.loop_start() ledController = led.controller(tlc5947.numberOfLeds, instructionHandler) def on_command(command): if (env.logLevel == env.DEBUG):
def init_mqtt(mqtt): try: mqtt.connect() except: machine.reset() print("MQTT connection established")