def MQTT_Init(): # 创建一个mqtt实例 c = MQTTClient(client_id=CLIENT_ID, server=SERVER, port=PORT, user=USER, password=PASSWORD, keepalive=30) # 必须要 keepalive=30 ,否则连接不上 # 设置消息回调 c.set_callback(sub_cb) # 建立连接 try: c.connect() except Exception as e: print('!!!,e=%s' % e) return # c.connect() # 订阅主题 c.subscribe(SUB_TOPIC.format(IMEI)) # 发布消息 Payload = '{"DeviceName":"{}","msg":"test publish"}'.format(IMEI) c.publish(PUB_TOPIC.format(IMEI), Payload) while True: c.wait_msg() if state == 1: break # 关闭连接 c.disconnect()
def envioMQTT(server=SERVER, topic="/foo", dato=None): try: c = MQTTClient(CLIENT_ID, server) c.connect() c.publish(topic, dato) sleep_ms(200) c.disconnect() #led.value(1) except Exception as e: pass
def envioMQTT(server=SERVER, topic="/foo", dato=None): try: c = MQTTClient(CLIENT_ID, server) c.connect() c.publish(topic, dato) sleep_ms(200) c.disconnect() #led.value(1) except Exception as e: pass
def recepcionMQTT(server=SERVER, topic=TOPIC3): c = MQTTClient(CLIENT_ID, server) # 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: c.wait_msg() finally: c.disconnect()
def recepcionMQTT(server=SERVER, topic=TOPIC3): c = MQTTClient(CLIENT_ID, server) # 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: c.wait_msg() finally: c.disconnect()
def sendmq(msg): UNIQUE_ID = ubinascii.hexlify(machine.unique_id()) MQTT_BROKER = "192.168.2.68" MQTT_PORT = 1883 MQTT_TOPIC = "iot-2/type/lopy/id/" + "buhardilla" + "/evt/presence1/fmt/json" print(MQTT_TOPIC) mqtt_client = MQTTClient(UNIQUE_ID, MQTT_BROKER, port=MQTT_PORT) mqtt_client.settimeout = settimeout mqtt_client.set_callback(t3_publication) mqtt_client.connect() result = mqtt_client.publish(MQTT_TOPIC, json.dumps(msg)) mqtt_client.disconnect() return result
def main(): client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT, AIO_USER, AIO_KEY) client.connect() for ao, vcc in zip(ao_pins, vcc_pins): feed = "feed_id" + ao print(feed) volts = (moist_sensor(ao, vcc) / 4.096) client.publish(feed, str(volts)) time.sleep(1) humid = int(humid_temp_sensor(True)[1]) client.publish(AIO_HUMIDITY_FEED, str(humid)) temp = int(humid_temp_sensor(True)[0]) client.publish(AIO_TEMPERATURE_FEED, str(temp)) client.disconnect()
def main(server="localhost"): c = MQTTClient("umqtt_client", server) c.set_callback(sub_cb) c.connect() c.subscribe(b"foo_topic") 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 main(server=SERVER): c = MQTTClient(CLIENT_ID, server) # 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)) np_clear() #np_status_blink() try: while 1: #micropython.mem_info() c.wait_msg() finally: c.disconnect()
def main(server="localhost"): c = MQTTClient(client_id=CLIENT_ID, server=SERVER, port=1883, user=USER, password=PASSWORD) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) 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()
class Mqtt_Class(): def __init__(self): # 创建一个mqtt实例 self.client_id = "868540051778302" self.downtopic = "quec/868540051778302/down" self.uptopic = "quec/868540051778302/up" self.mqttserver = "southbound.quectel.com" self.mqttport = 1883 self.uername = "868540051778302" self.passwd = "d40332b8211097ffbb0e2645c2efec95" self.mqtt_client = MQTTClient(self.client_id, self.mqttserver, self.mqttport, self.uername, self.passwd) def mqtt_recv_callback(self, topic, msg): print("Subscribe Recv: Topic={},Msg={}".format(topic.decode(), msg.decode())) q_recv_thread.recv_thread.recv_callback(topic, msg.decode()) def mqtt_set_recv_callback(self): # 设置消息回调 self.mqtt_client.set_callback(self.mqtt_recv_callback) def connect(self): #建立连接 self.mqtt_client.connect() def sub_topic(self, topic): # 订阅主题 self.mqtt_client.subscribe(topic) def put_msg(self, msg, qos=0): # 发布消息 self.mqtt_client.publish(self.uptopic, msg, qos) def wait_msg(self): self.mqtt_client.wait_msg() def disconnect(self): # 关闭连接 self.mqtt_client.disconnect()
def MQTT_Init(): # 创建一个mqtt实例 c = MQTTClient(client_id=CLIENT_ID, server=SERVER, port=PORT, user=USER, password=PASSWORD, keepalive=30) # 必须要 keepalive=30 ,否则连接不上 # 设置消息回调 c.set_callback(sub_cb) # 建立连接 c.connect() # 订阅主题 c.subscribe('$oc/devices/{}/sys/messages/down'.format(DEVICE_ID)) msg = b'''{ "services": [{ "service_id": "WaterMeterControl", "properties": { "state": "T:15c, H: 85% " }, "event_time": "20151212T121212Z" } ] }''' # 发布消息 c.publish('$oc/devices/{}/sys/properties/report'.format(DEVICE_ID), msg) while True: c.wait_msg() if state == 1: break # 关闭连接 c.disconnect()
print("------ Sending an ACK") lora_sock.send(ack_pkg) #msg="{\"value\":"+str(some_number)+"}") pycom.rgbled(colorgreen) # green time.sleep(1) # Do any extra processing required for the package. Keep in mind it should be as fast as posible # to make sure that the other clients are not waiting too long for their messages to be ac except ValueError: print(ValueError) pycom.rgbled(0x0F0000) print( "--------------------- An exception occurred(1) ! ---------------------" ) machine.reset() except Exception as e: pycom.rgbled(0x0F0000) print(e) print( "--------------------- An exception occurred(2) ! ---------------------" ) # machine.reset() finally: # If an exception is thrown ... client.disconnect() # ... disconnect the client and clean up. client = None wlan.disconnect() wlan = None pycom.rgbled(0x000022) # Status blue: stopped print("Disconnected from Bluemix")
class BluestoneMqtt(object): inst = None def __init__(self, client_id, server, port, user, password, sub_topic, pub_topic): BluestoneMqtt.inst = self self.bs_config = None self.bs_gpio = None self.bs_pwm = None self.bs_fota = None self.bs_uart = None self.sn = bluestone_common.BluestoneCommon.get_sn() self.client_id = client_id self.server = server self.port = port self.user = user self.password = password self.subscribe_topic = sub_topic self.publish_topic = pub_topic self.client = None self._is_sub_callback_running = False self._is_message_published = False def _init_mqtt(self): self.bs_config = bluestone_config.BluestoneConfig( 'bluestone_config.json') self.bs_data_config = bluestone_config.BluestoneConfig( 'bluestone_data.json') self.bs_gpio = bluestone_gpio.BluestoneGPIO() self.bs_pwm = bluestone_pwm.BluestonePWM() self.bs_fota = bluestone_fota.BluestoneFOTA() self.bs_uart = bluestone_uart.BlueStoneUart(None) # 创建一个MQTT实例 self.client = MQTTClient(client_id=self.client_id, server=self.server, port=self.port, user=self.user, password=self.password, keepalive=30) _mqtt_log.info( "Start a new mqtt client, id:{}, server:{}, port:{}".format( self.client_id, self.server, self.port)) self.client.set_callback(self._sub_callback) # 设置消息回调 self.client.connect() # 建立连接 #sub_topic = self.subscribe_topic.format(self.sn) _mqtt_log.info("Subscribe topic is {}".format(self.subscribe_topic)) self.client.subscribe(self.subscribe_topic) # 订阅主题 def _update_gpio_status(self, io_level_list): try: self.bs_data_config.update_config('gpio', io_level_list) message = {} message['gpio'] = io_level_list _mqtt_log.info("Data configuration is {}".format(message)) self.publish(message) except Exception as err: _mqtt_log.error( "Cannot update gpio level list, the error is {}".format(err)) def _handle_callback(self, key, config): result = False try: if key.startswith('uart'): # first payload then config payload = self.bs_config.get_value(config, "payload") if payload: self.bs_uart.uart_write(key, ujson.dumps(payload)) uart_config = self.bs_config.get_value(config, "config") if uart_config: self.bs_config.update_config(key, uart_config) self.bs_data_config.update_config(key, uart_config) result = True elif key.startswith('pwm'): id = self.bs_pwm.get_id_by_name(key) is_breathe = self.bs_config.get_int_value(config, "breathe") frequency = self.bs_config.get_int_value(config, "frequency") duty = self.bs_config.get_float_value(config, "duty") if is_breathe: self.bs_pwm.start_breathe(id, frequency) else: self.bs_pwm.start_once(id, frequency, duty) elif key.startswith('timer'): self.bs_config.update_config(key, config) self.bs_data_config.update_config(key, config) result = True elif key == 'gpio': io_level_list = self.bs_gpio.read_all() io_name_list = self.bs_gpio.get_io_name_list() for gpio_key in config.keys(): if gpio_key not in io_name_list: continue level = self.bs_config.get_int_value(config, gpio_key) if level is not None: id = self.bs_gpio.get_id_by_name(gpio_key) self.bs_gpio.write(id, level) io_level_list[gpio_key] = level self._update_gpio_status(io_level_list) elif key == 'fota': mode = self.bs_config.get_int_value(config, "mode") if mode == 0: url_list = self.bs_config.get_value(config, "url") self.bs_fota.start_fota_app(url_list) elif mode == 1: url = self.bs_config.get_value(config, "url") self.bs_fota.start_fota_firmware(url) result = True except Exception as err: _mqtt_log.error( "Cannot handle callback for mqtt, the error is {}".format(err)) return result def _sub_callback_internal(self, topic, msg): try: message = msg.decode() _mqtt_log.info("Subscribe received, topic={}, message={}".format( topic.decode(), message)) restart = False config_setting = ujson.loads(message) config_keys = config_setting.keys() for key in config_setting: config = config_setting[key] key_exist = self.bs_config.check_key_exist(key) if key_exist: if not restart: restart = self.bs_config.mqtt_check_key_restart(key) result = self._handle_callback(key, config) if result: restart = True if restart: restart = False _mqtt_log.info( "New configuration was received from mqtt, restarting system to take effect" ) Power.powerRestart() except Exception as err: _mqtt_log.error( "Cannot handle subscribe callback for mqtt, the error is {}". format(err)) finally: self._is_sub_callback_running = False # 云端消息响应回调函数 def _sub_callback(self, topic, msg): if self._is_sub_callback_running: _mqtt_log.error( "Subscribe callback function is running, skipping the new request" ) return self._is_sub_callback_running = True _thread.start_new_thread(self._sub_callback_internal, (topic, msg)) def _mqtt_publish(self, message): #pub_topic = self.publish_topic.format(self.sn) #message = {"Config":{},"message":"MQTT hello from Bluestone"} if self.client is not None: self.client.publish(self.publish_topic, message) self._is_message_published = True _mqtt_log.info("Publish topic is {}, message is {}".format( self.publish_topic, message)) def _wait_msg(self): while True: if self.client is not None: self.client.wait_msg() utime.sleep_ms(300) def is_message_published(self): return self._is_message_published def start(self): self._init_mqtt() _thread.start_new_thread(self._wait_msg, ()) def publish(self, message): network_state = bluestone_common.BluestoneCommon.get_network_state() if network_state != 1: _mqtt_log.error( "Cannot publish mqtt message, the network state is {}".format( network_state)) return #_mqtt_log.info("Publish message is {}".format(message)) #self._mqtt_publish(ujson.dumps(message)) self._is_message_published = False _thread.start_new_thread(self._mqtt_publish, ([ujson.dumps(message)])) def connect(self): if self.client is not None: self.client.connect() _mqtt_log.info("MQTT connected") def disconnect(self): if self.client is not None: self.client.disconnect() _mqtt_log.info("MQTT disconnected") def close(self): self.disconnect() self.client = None _mqtt_log.info("MQTT closed")
def sub_cb(topic, msg): global state print("subscribe recv:") print(topic, msg) state = 1 #创建一个 mqtt 实例 c = MQTTClient("umqtt_client", "mq.tongxinmao.com", '18830') #设置消息回调 c.set_callback(sub_cb) #建立连接 c.connect() #订阅主题 c.subscribe(b"/public/TEST/quecpython") print( "Connected to mq.tongxinmao.com, subscribed to /public/TEST/quecpython topic" ) #发布消息 c.publish(b"/public/TEST/quecpython", b"my name is Kingka!") print("Publish topic: /public/TEST/quecpython, msg: my name is Quecpython") while True: c.wait_msg() #阻塞函数,监听消息 if state == 1: break #关闭连接 c.disconnect()
# Config SERVER = "192.168.31.16" CLIENT_ID = hexlify(unique_id()) TOPIC1 = b"/cultivo/temp" TOPIC2 = b"/cultivo/hum" TOPIC3 = b"/sensor1/set/temp" TOPIC4 = b"/sensor1/set/hum" TOPIC5 = b"/cultivo/alarma" state = 0 client_mqtt = MQTTClient(CLIENT_ID, SERVER) # Envio client_mqtt.connect() client_mqtt.publish(TOPIC1, str(s_dht.temperature())) client_mqtt.publish(TOPIC2, str(s_dht.humidity())) sleep_ms(200) client_mqtt.disconnect() # Recepcion def sub_cb(topic, msg): global state print((topic, msg)) if msg == b"on": led.value(0) state = 1 elif msg == b"off": led.value(1) state = 0 elif msg == b"toggle": # LED is inversed, so setting it to current state # value will make it toggle
do_temp = not do_temp except Exception as e: print("FAILED") # Foloseste protocolul MQTT pentru a se conecta la Adafruit IO client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT, AIO_USER, AIO_KEY) client.connect() # Se conecteaza la Adafruit IO folosind MQTT pycom.rgbled(0x00ff00) while 1: client.check_msg() send_sensors() # Trimite temperatura si umiditate catre Adafruit IO for x in range (0, 5): time.sleep_ms(1000) blue, red = lt.light() print('{:5}-Blue {:5}-Red Range(0-65535)'.format(blue, red)) client.disconnect() client = None wlan.disconnect() wlan = None pycom.rgbled(0x000022)# Ledul se activeaza in culoara albastru : stop print("Disconnected from Adafruit IO.")
class MQTT: def __init__(self, led_control, device_name): """ Constructor """ self.led_control = led_control self.topic = mqtt_config['topic'] self.resp_topic = mqtt_config['resp_topic'] self.device_name = device_name def start(self): """ Initialize MQTT Connection """ print ("Creating client") self.client = MQTTClient( client_id = self.device_name, server = mqtt_config['address'], user = mqtt_config['username'], password = mqtt_config['user_key'], port = mqtt_config['port']) print ("Setting timeout") self.client.settimeout = self.set_timeout print ("Setting callback") self.client.set_callback(self.sub_cb) print ("Connecting mqtt", mqtt_config['address'], mqtt_config['username'], mqtt_config['user_key'], mqtt_config['port']) res = self.client.connect() if (res == -1): print ("Failed to connect") pycom.rgbled(0xB900B9) return print ("Subscribing") self.client.subscribe(topic=self.topic) self.client.set_last_will(self.resp_topic, "Bye") print ("Listening") pycom.rgbled(0x00ff00) Timer.Alarm(self.check_new_messages, 0.0075, periodic=True) gc.collect() def stop(self): """ Disconnect and stop listening """ self.client.disconnect() def send_data(self, data): self.client.publish(topic=self.resp_topic, msg=data) def sub_cb(self, topic, message): """ """ if message is None: return else: self.parse_input_data(message) def set_timeout(duration): """ """ pass def parse_input_data(self, data): """ Chooses correct response for new characteristic value """ decoded = data.decode('utf-8') #Echo data back to MQTT backend if "status" in decoded: resp_data = self.led_control.compose_status_response() self.send_data("resp:" + resp_data) return # print (decoded) self.send_data("resp:" + decoded) if ";" in decoded: self.led_control.set_route(decoded) return if ("," not in decoded): return data = decoded.split(",") #print (data) size = len(data) if (size == 0): print ("bad input") return if (size == 1): self.led_control.turn_off_leds() elif (size == 2): self.led_control.set_new_data((data[0], data[1], data[1], data[1])) elif (size == 4): self.led_control.set_new_data((data[0], data[1], data[2], data[3])) def check_new_messages(self, alarm): self.client.check_msg()
class GOES(): def __init__(self): self.screen_width = 200 self.screen_height = 280 self.keys = [Pin(p, Pin.IN) for p in [35, 36, 39, 34]] self.keymatch = ["Key1", "Key2", "Key3", "Key4"] self.board = [[[20, 20, 0], [40, 20, 0], [60, 20, 0], [80, 20, 0], [100, 20, 0], [120, 20, 0], [140, 20, 0], [160, 20, 0], [180, 20, 0], [200, 20, 0], [220, 20, 0]], [[20, 40, 0], [40, 40, 0], [60, 40, 0], [80, 40, 0], [100, 40, 0], [120, 40, 0], [140, 40, 0], [160, 40, 0], [180, 40, 0], [200, 40, 0], [220, 40, 0]], [[20, 60, 0], [40, 60, 0], [60, 60, 0], [80, 60, 0], [100, 60, 0], [120, 60, 0], [140, 60, 0], [160, 60, 0], [180, 60, 0], [200, 60, 0], [220, 60, 0]], [[20, 80, 0], [40, 80, 0], [60, 80, 0], [80, 80, 0], [100, 80, 0], [120, 80, 0], [140, 80, 0], [160, 80, 0], [180, 80, 0], [200, 80, 0], [220, 80, 0]], [[20, 100, 0], [40, 100, 0], [60, 100, 0], [80, 100, 0], [100, 100, 0], [120, 100, 0], [140, 100, 0], [160, 100, 0], [180, 100, 0], [200, 100, 0], [220, 100, 0]], [[20, 120, 0], [40, 120, 0], [60, 120, 0], [80, 120, 0], [100, 120, 0], [120, 120, 0], [140, 120, 0], [160, 120, 0], [180, 120, 0], [200, 120, 0], [220, 120, 0]], [[20, 140, 0], [40, 140, 0], [60, 140, 0], [80, 140, 0], [100, 140, 0], [120, 140, 0], [140, 140, 0], [160, 140, 0], [180, 140, 0], [200, 140, 0], [220, 140, 0]], [[20, 160, 0], [40, 160, 0], [60, 160, 0], [80, 160, 0], [100, 160, 0], [120, 160, 0], [140, 160, 0], [160, 160, 0], [180, 160, 0], [200, 160, 0], [220, 160, 0]], [[20, 180, 0], [40, 180, 0], [60, 180, 0], [80, 180, 0], [100, 180, 0], [120, 180, 0], [140, 180, 0], [160, 180, 0], [180, 180, 0], [200, 180, 0], [220, 180, 0]], [[20, 200, 0], [40, 200, 0], [60, 200, 0], [80, 200, 0], [100, 200, 0], [120, 200, 0], [140, 200, 0], [160, 200, 0], [180, 200, 0], [200, 200, 0], [220, 200, 0]], [[20, 220, 0], [40, 220, 0], [60, 220, 0], [80, 220, 0], [100, 220, 0], [120, 220, 0], [140, 220, 0], [160, 220, 0], [180, 220, 0], [200, 220, 0], [220, 220, 0]]] #初始化棋子坐标(x坐标,y坐标,颜色) self.startX = 20 self.startY = 20 self.selectXi = 5 self.selectYi = 5 self.displayInit() self.color = 0x00ff00 #player2棋子颜色为绿色 self.wifi_name = "NEUI" self.wifi_SSID = "NEUI3187" #MQTT服务端信息 self.SERVER = "112.125.89.85" #MQTT服务器地址 self.SERVER_PORT = 3881 #MQTT服务器端口 self.DEVICE_ID = "wc001" #设备ID self.TOPIC1 = b"/cloud-skids/online/dev/" + self.DEVICE_ID self.TOPIC2 = b"/cloud-skids/message/server/" + self.DEVICE_ID self.CLIENT_ID = "f25410646a8348f8a1726a3890ad8f73" self.uart = UART(1, baudrate=115200, bits=8, parity=0, rx=18, tx=19, stop=1) #设备状态 self.ON = "1" self.OFF = "0" self.d = " " self.c = MQTTClient(self.CLIENT_ID, self.SERVER, self.SERVER_PORT) def drawcross(self, x, y, lineColor): # 画选择位置的框 screen.drawline(x - 10, y - 10, x - 5, y - 10, 3, lineColor) screen.drawline(x - 10, y - 10, x - 10, y - 5, 3, lineColor) screen.drawline(x + 10, y - 10, x + 5, y - 10, 3, lineColor) screen.drawline(x + 10, y - 10, x + 10, y - 5, 3, lineColor) screen.drawline(x - 10, y + 10, x - 5, y + 10, 3, lineColor) screen.drawline(x - 10, y + 10, x - 10, y + 5, 3, lineColor) screen.drawline(x + 10, y + 10, x + 5, y + 10, 3, lineColor) screen.drawline(x + 10, y + 10, x + 10, y + 5, 3, lineColor) #画棋盘网格 def grid(self): x = 20 y = 20 for i in range(11): screen.drawline(x, 20, x, 220, 3, 0x000000) x += 20 for j in range(11): screen.drawline(20, y, 220, y, 3, 0x000000) y += 20 def do_connect(self): sta_if = network.WLAN(network.STA_IF) #STA模式 ap_if = network.WLAN(network.AP_IF) #AP模式 if ap_if.active(): ap_if.active(False) #关闭AP if not sta_if.isconnected(): print('Connecting to network...') sta_if.active(True) #激活STA sta_if.connect(self.wifi_name, self.wifi_SSID) #WiFi的SSID和密码 while not sta_if.isconnected(): pass print('Network config:', sta_if.ifconfig()) gc.collect() def esp(self): self.c.set_callback(self.sub_cb) #设置回调 self.c.connect() print("连接到服务器:%s" % self.SERVER) self.c.publish(self.TOPIC1, self.ON) #发布“1”到TOPIC1 self.c.subscribe(self.TOPIC2) #订阅TOPIC #display.text("从微信取得信息", 20, 20, 0xf000, 0xffff) def sub_cb(self, topic, message): #从服务器接受信息 message = message.decode() print("服务器发来信息:%s" % message) #global count t = int(message) #根据接收到的信息解析棋子位置 j = t // 11 i = t % 11 x = self.board[j][i][0] y = self.board[j][i][1] if self.board[j][i][2] == 0: self.put_circle_back(x, y, 10, 0x000000) #在解析出的位置上画黑色棋子 self.board[j][i][2] = 2 #将棋子标记为黑色 self.is_win(i, j, self.board[j][i][2]) #判断胜负 def put_circle_back(self, x, y, r, color): #画圆形棋子 a = 0 #选定原点距离圆心距离 b = r #在原点所画交叉线长度 di = 3 - (r << 1) #辅助判断画圆是否结束 while (a <= b): #选定原点画交叉线 screen.drawline(x - b, y - a, x + b, y - a, 3, color) screen.drawline(x - a, y, x - a, y + b, 3, color) screen.drawline(x - b, y - a, x, y - a, 3, color) screen.drawline(x - a, y - b, x - a, y, 3, color) screen.drawline(x, y + a, x + b, y + a, 3, color) screen.drawline(x + a, y - b, x + a, y, 3, color) screen.drawline(x + a, y, x + a, y + b, 3, color) screen.drawline(x - b, y + a, x, y + a, 3, color) a += 1 #改变原点位置 if (di < 0): #辅助判断画圆是否结束,计算下一步所画交叉线长度 di += 4 * a + 6 else: di += 10 + 4 * (a - b) b -= 1 screen.drawline(x + a, y, x + a, y + b, 3, color) def selectInit(self): #选择初始化 # 变量初始化 self.selectXi = 5 self.selectYi = 5 x = self.board[self.selectYi][self.selectXi][0] y = self.board[self.selectYi][self.selectXi][1] # 选择初始化 self.drawcross(x, y, 0xff0000) # 界面初始化 def displayInit(self): #开始游戏初始化 screen.clear() self.grid() for self.selectYi in range(11): for self.selectXi in range(11): self.board[self.selectYi][self.selectXi][2] = 0 self.selectInit() def is_win(self, i, j, k): #判断胜负 start_y = 0 end_y = 10 if j - 4 >= 0: start_y = j - 4 if j + 4 <= 10: end_y = j + 4 count = 0 for pos_y in range(start_y, end_y + 1): #判断纵向胜负 if self.board[pos_y][i][2] == k and k == 1: count += 1 if count >= 5: text.draw("绿色方胜", 88, 160, 0xff0000) else: count = 0 for pos_y in range(start_y, end_y + 1): if self.board[pos_y][i][2] == k and k == 2: count += 1 if count >= 5: text.draw("黑色方胜", 88, 160, 0xff0000) else: count = 0 start_x = 0 end_x = 10 if i - 4 >= 0: start_x = i - 4 if i + 4 <= 10: end_x = i + 4 count = 0 for pos_x in range(start_x, end_x + 1): #判断横向胜负 if self.board[j][pos_x][2] == k and k == 1: count += 1 if count >= 5: text.draw("绿色方胜", 88, 160, 0xff0000) else: count = 0 for pos_x in range(start_x, end_x + 1): if self.board[j][pos_x][2] == k and k == 2: count += 1 if count >= 5: text.draw("黑色方胜", 88, 160, 0xff0000) else: count = 0 count = 0 s = j - i start = start_y end = end_x + s if j > i: start = start_x + s end = end_y for index in range(start, end + 1): #判断斜方向胜负(左上右下) if self.board[index][index - s][2] == k and k == 1: count += 1 if count >= 5: text.draw("绿色方胜", 88, 160, 0xff0000) else: count = 0 for index in range(start, end + 1): if self.board[index][index - s][2] == k and k == 2: count += 1 if count >= 5: text.draw("黑色方胜", 88, 160, 0xff0000) else: count = 0 count = 0 s = j + i if j + i <= 10: start = start_y end = s - start_x if j + i > 10: start = s - 10 end = 10 if s >= 4 and s <= 16: for index in range(start, end + 1): #判断斜方向胜负(左下右上) if self.board[index][s - index][2] == k and k == 1: count += 1 if count >= 5: text.draw("绿色方胜", 88, 160, 0xff0000) else: count = 0 for index in range(start, end + 1): if self.board[index][s - index][2] == k and k == 2: count += 1 if count >= 5: text.draw("黑色方胜", 88, 160, 0xff0000) else: count = 0 def keyboardEvent(self, key): # 右移选择键 if self.keymatch[key] == "Key1": # 取消前一个选择 x = self.board[self.selectYi][self.selectXi][0] y = self.board[self.selectYi][self.selectXi][1] self.drawcross(x, y, 0xffffff) # 选择右边一个 self.selectXi = (self.selectXi + 1) % 11 x = self.board[self.selectYi][self.selectXi][0] y = self.board[self.selectYi][self.selectXi][1] self.drawcross(x, y, 0xff0000) # 纵向移动键 elif self.keymatch[key] == "Key2": # 取消前一个选择 x = self.board[self.selectYi][self.selectXi][0] y = self.board[self.selectYi][self.selectXi][1] self.drawcross(x, y, 0xffffff) # 选择下边一个 self.selectYi = (self.selectYi + 1) % 11 x = self.board[self.selectYi][self.selectXi][0] y = self.board[self.selectYi][self.selectXi][1] self.drawcross(x, y, 0xff0000) # 确认键 elif self.keymatch[key] == "Key3": x = self.board[self.selectYi][self.selectXi][0] y = self.board[self.selectYi][self.selectXi][1] if self.board[self.selectYi][self.selectXi][2] == 0: self.put_circle_back(x, y, 10, self.color) #画绿色棋子 self.board[self.selectYi][self.selectXi][2] = 1 #将棋子标记为绿色 s = (self.selectYi) * 11 + (self.selectXi) self.d = str(s) self.c.publish(self.TOPIC2, self.d) #向服务器发送棋子位置信息 self.is_win(self.selectXi, self.selectYi, self.board[self.selectYi][self.selectXi][2]) elif self.keymatch[key] == "Key4": self.displayInit() def start(self): try: while True: self.c.check_msg() #检查是否收到信息 i = 0 #用来辅助判断那个按键被按下 j = -1 for k in self.keys: if (k.value() == 0): #如果按键被按下 if i != j: j = i self.keyboardEvent(i) #触发相应按键对应事件 i = i + 1 if (i > 3): i = 0 time.sleep_ms(200) # 按键去抖 finally: self.c.disconnect() print("MQTT连接断开")
def mqtt_send(topic, message): client = MQTTClient('iot-envsensor', 'MQTT_SERVER_HOSTNAME') client.connect() client.publish(topic, message) client.disconnect()
class Monitoreo(): "Clase padre, Monitoreo del dispositivo para micropython: " def __init__(self, pin_dht=4, sensor="DHT22"): self.pin_DHT = pin_dht self.sensor_type = sensor self.alarm_state = 0 self.pin_alarma = machine.Pin( 16, machine.Pin.OUT) # Configure Pin: Alarma (OUT) self.pin_stopAlarm = machine.Pin( 5, machine.Pin.OUT) # Configure Pin: Stop Alarm (IN) self.count_alarma = 0 self.alarma = 0 self.time_active = 0 self.dataWrite = 0 # Almacena los datos, On:1 | Off:0 self.break_loop = 1 # variable para romper el loop self.interrupt_mode = 0 # interrupciones: On:1 | Off:0 self.debug_mode = 0 # Debug On:1 | Off:0 self.sensorConected() def sensorConected(self, sensor="DHT22"): "Conmuta entre los diferentes sensores: DHT11/DHT22" if self.sensor_type == "DHT22": self.s_dht = dht.DHT22(machine.Pin(self.pin_DHT)) elif self.sensor_type == "DHT11": self.s_dht = dht.DHT11(machine.Pin(self.pin_DHT)) else: if self.debug_mode == 1: print( "Sensor inadecuado, elija entre las opciones: DHT11 o DHT22" ) # debug self.pin_led_debug.value( not self.pin_led_debug.value()) # Debug visual def pinEndUp(self): "Rompe el loop por hardware, Pin:[High = break]" pass def debugMode(self, mode=0): "Activa/Desactiva El debug visual y de consola, On:1 | Off:0" self.debug_mode = mode if self.debug_mode == 1: esp.osdebug(1) # turn on/off vendor O/S debugging messages self.pin_led_debug = machine.Pin(2, machine.Pin.OUT) # Debug visual else: esp.osdebug(0) def saveData(self, mode=0): "Guarda los datos en un archivo, On:1 | Off:0" self.dataWrite = mode if self.dataWrite == 1: self.dataWrite = 2 self.file = open('data.txt', 'w') self.file.write("TEMP, HUM\n") elif self.dataWrite == 2: self.file.write( str(self.s_dht.temperature()) + ", \ " + str(self.s_dht.humidity()) + "\n") elif self.dataWrite == 0: self.dataWrite = 3 self.file = open('data.txt', 'w') self.file.write("Data storage off\n") self.file.close() def readData(self): "Obtiene de lso sensores los datos de Temperatura/Humedad" self.s_dht.measure() if self.debug_mode == 1: print("Temperatura ", self.s_dht.temperature()) # Debug print("Humedad ", self.s_dht.humidity()) # Debug self.pin_led_debug.value( not self.pin_led_debug.value()) # Debug visual def actuators(self): "Activa la logica de los Actuadores" # if self.pin_stopAlarm.value() == 1: # MQTT Or Pin # self.alarma = 0 if self.s_dht.temperature() == 3 and self.s_dht.humidity() >= 85: self.alarma = 1 self.time_active = 60 elif self.s_dht.temperature() == 1 and self.s_dht.humidity() >= 92: self.pin_alarma = 1 self.time_active = 300 if self.alarma == 1 and self.count_alarma <= self.time_active: self.pin_alarma.high() self.count_alarma += 1 if self.count_alarma == self.time_active: self.pin_alarma.low() self.count_alarma = 0 if self.debug_mode == 1: print("Estado del actuador en: " + self.value(16) + " Pin No.", self.pin_alarma) self.pin_led_debug.value( not self.pin_led_debug.value()) # Debug visual else: self.count_alarma = 0 def sleepMode(self): " Duerme el dispositivo" pass def wifi(self, mode=1): "Activa/Desactiva el Wifi " self.wifi_switch = mode if self.wifi_switch == 1: self.configWifi() self.wifiStation() elif self.wifi_switch == 1: self.sta_if.active(False) def configWifi(self): "Metodo usado para configurar los parametros de la Red Wifi: SSID y PASSWORD" pass def wifiAP(self): "Crea un punto de acceso wifi, actua como anfitri?n" pass def wifiStation(self): "Hace de estaci?n (wifi) y se conecta con a un servidor u otro dispositivo" import network # Config WIFISSID = "Cultivo_pi" # <-----------------CONFIGURE: SDID de Red wifi WIFIPASS = "******" # <-----------------CONFIGURE: PASSWORD de Red wifi self.sta_if = network.WLAN(network.STA_IF) if not self.sta_if.isconnected(): print('connecting to network...') self.sta_if.active(True) self.sta_if.connect(WIFISSID, WIFIPASS) while not self.sta_if.isconnected(): print('network config:', self.sta_if.ifconfig()) def MQTTclient(self): "Protocolo MQTT en modo cliente, Configuración" from ubinascii import hexlify from machine import unique_id from umqtt import MQTTClient # import socket library (umqtt) # Config SERVER = "172.24.1.1" # <----------------------------CONFIGURE: BROKER CLIENT_ID = hexlify(unique_id()) self.TOPIC1 = b"/cultivo/temp" self.TOPIC2 = b"/cultivo/hum" self.TOPIC3 = b"/sensor1/set/temp" self.TOPIC4 = b"/sensor1/set/hum" self.TOPIC5 = b"/sensor1/alarma" self.client_mqtt = MQTTClient(CLIENT_ID, SERVER) def MQTTSend(self): "Envio Datos mediante el protocolo MQTT" try: self.client_mqtt.connect() self.client_mqtt.publish(self.TOPIC1, str(self.s_dht.temperature())) self.client_mqtt.publish(self.TOPIC2, str(self.s_dht.humidity())) time.sleep_ms(200) self.client_mqtt.disconnect() except Exception as e: pass def MQTTReceive(self): "Metodo que recibe datos enviados a traves del protocolo MQTT" self.alarm_state = 1 - self.alarm_state # Subscribed messages will be delivered to this callback self.client_mqtt.set_callback(self.sub_cb) self.client_mqtt.connect() self.client_mqtt.subscribe(self.TOPIC5) def sub_cb(self, topic, msg): "Recepcion MQTT" print((topic, msg)) if msg == b"on": self.pin_led_debug.value(0) self.alarm_state = 1 elif msg == b"off": self.pin_led_debug.value(1) self.alarm_state = 0 elif msg == b"toggle": self.pin_led_debug.value(self.alarm_state) def interruptMode(self, mode=0): "Activa/Desactiva las interrupciones, por tiempo y por cambio de flanco, On:1 | Off:0" self.interrupt_mode = mode if self.interrupt_mode == 1: self.p_interrupt = machine.Pin( 3, machine.Pin.IN) # Interupt por cambio de flanco # Flanco de bajada y flanco de subida rising and falling edge() self.p_interrupt.irq(trigger=machine.Pin.IRQ_RISING | machine.Pin.IRQ_FALLING, handler=self.callback) def callback(self, p): "Metodo que se ejecuta una vez ocurrida la interrupci?n" # print('pin change', p) self.break_loop = 0 def loop(self): "Bucle principal infinito" while True: # beak: interrupt, Pin change # Sleep Off self.readData() # Lectura de sensores # self.saveData() # si esta activa, almacena datos self.MQTTSend() # Enviar datos mediante el protocolo MQTT # self.client_mqtt.wait_msg() # Recibe datos mediante el Protocolo MQTT # self.actuators() # Sleep On time.sleep(1) # self.pinEndUp() # micropython.mem_info() self.saveData()
ticks = count_ticks() / 10 digital_freq = int(1 / (ticks * 0.0000125)) # calculate frequency in kHz print(ticks * 12.5, "ns =", ticks * 12.5 / 1000, "us ~ ", digital_freq, "kHz") gc.enable() sensor_digitalpower.off() # save energy sensor_analogpower.on() time.sleep(2) print("publishing via MQTT") payload = b"field1=" + str( adc0.read()) # read analog sensor value from ADC0 payload += b"&field4=" + str(digital_freq) if not debug: payload = payload + b"&field2=" + str( dhtSensor.temperature()) + b"&field3=" + str( dhtSensor.humidity()) localclient.publish("test/value", payload) # publish locally time.sleep(5) # keep board online for 5 seconds if not debug: localclient.disconnect() sensor_analogpower.off() if not debug: print("deepsleep", dsSeconds, "seconds") remoteclient.publish(remotetopic, payload) # publish to ThingSpeak remoteclient.disconnect() rtc.alarm(rtc.ALARM0, dsSeconds * 1000) # set the RTC alarm machine.deepsleep() # let board deepsleep
class adafruit: def __init__(self, config, data_collector, logger): self.sensor = data_collector self.Config = config self.Logger = logger self.AIO_SERVER = config["adafruit"]["AIO_SERVER"] self.AIO_PORT = config["adafruit"]["AIO_PORT"] self.AIO_USER = config["adafruit"]["AIO_USER"] self.AIO_KEY = config["adafruit"]["AIO_KEY"] self.AIO_CLIENT_ID = ubinascii.hexlify(machine.unique_id()) self.AIO_CONTROL_FEED = config["adafruit"]["AIO_CONTROL_FEED"] self.AIO_MOVEMENT_FEED = config["adafruit"]["AIO_MOVEMENT_FEED"] self.AIO_GPS_FEED = config["adafruit"]["AIO_GPS_FEED"] self.AIO_ACCELERATION_FEED = config["adafruit"][ "AIO_ACCELERATION_FEED"] self.last_random_sent_ticks = config["adafruit"][ "last_random_sent_ticks"] self.post_per_minute = config["adafruit"]["post_per_minute"] """Finding and connecting to network""" self.wlan = WLAN(mode=WLAN.STA) nets = self.wlan.scan() print("Scanning for Wifi") for net in nets: for knowNet in self.Config["network"]: if net.ssid == knowNet["name"]: print(net.ssid + ' found!') self.wlan.connect(net.ssid, auth=(net.sec, knowNet["password"]), timeout=5000) while not self.wlan.isconnected(): machine.idle() # save power while waiting print('WLAN connection succeeded!') break self.client = MQTTClient(self.AIO_CLIENT_ID, self.AIO_SERVER, self.AIO_PORT, self.AIO_USER, self.AIO_KEY) def runAdafruit(self): Time = utime.localtime(None) currentTime = str(Time[1]) + "/" + str(Time[2]) + "/" + str( Time[0]) + " at " + str(Time[3]) + ":" + str(Time[4]) + ":" + str( Time[5]) self.Logger.log("Session began at " + currentTime) #Subscribed messages will be delivered to this callback self.client.set_callback(self.sub_cb) print('Connecting to io.adafruit.com') time.sleep(10) self.client.connect() self.client.subscribe(self.AIO_CONTROL_FEED) print("Connected to %s, subscribed to %s topic" % (self.AIO_SERVER, self.AIO_CONTROL_FEED)) pycom.rgbled(0x0000FF) # Blue try: while 1: self.client.check_msg() self.sendMovement() finally: self.client.disconnect() self.client = None self.wlan.disconnect() self.wlan = None pycom.rgbled(0x000022) print("Disconnected from Adafruit IO.") #responds to messages from Adafruit IO def sub_cb(self, topic, msg): print((topic, msg)) if msg == b"ON": pycom.rgbled(0xffffff) elif msg == b"OFF": pycom.rgbled(0x000000) else: print("Unknown message") #Sends messages to Adafuit IO def sendMovement(self): #Waits 2 seconds to send data to avoid Adadruit IO if ((time.ticks_ms() - self.last_random_sent_ticks) < (1000 / (self.post_per_minute) / 60)): return angle = self.sensor.getAngle() acceleration = self.sensor.getAcceleration() gps = self.sensor.getGPS() if (str(gps[0]) == "None"): gps = "0,40.808679,-77.855693,0" else: gps = "0," + str(gps[0]) + "," + str(gps[1]) + ",0" print("Publishing: {0} to {1}, {2} to {3}, {4} to {5} ... ".format( angle, self.AIO_MOVEMENT_FEED, acceleration, self.AIO_ACCELERATION_FEED, gps, self.AIO_GPS_FEED), end='') try: self.client.publish(topic=self.AIO_MOVEMENT_FEED, msg=str(angle)) self.client.publish(topic=self.AIO_ACCELERATION_FEED, msg=str(acceleration)) self.client.publish(topic=self.AIO_GPS_FEED, msg=str(gps)) print("DONE") except Exception as e: print(e) print("FAILED") finally: self.last_random_sent_ticks = time.ticks_ms()
class pics(): def __init__(self): self.keys = [Pin(p, Pin.IN) for p in [35, 36, 39, 34]] self.keymatch = ["Key1", "Key2", "Key3", "Key4"] self.select = 1 self.displayInit() self.wifi_name = "NEUI" self.wifi_SSID = "NEUI3187" #MQTT服务端信息 self.SERVER = "192.168.5.121" #MQTT服务器地址 self.SERVER_PORT = 1883 #MQTT服务器端口 self.contentEVICE_ID = "wc001" #设备ID self.TOPIC1 = b"/cloud-skids/online/dev/" + self.contentEVICE_ID self.TOPIC2 = b"/cloud-skids/message/server/" + self.contentEVICE_ID self.CLIENT_ID = "7e035cd4-15b4-4d4b-a706-abdb8151c57d" self.uart = UART(1, baudrate=115200, bits=8, parity=0, rx=18, tx=19, stop=1) #设备状态 self.ON = "1" self.OFF = "0" self.content = " " #初始化要发送的信息 self.client = MQTTClient(self.CLIENT_ID, self.SERVER, self.SERVER_PORT) #定义一个mqtt实例 def drawInterface(self): #界面初始化 bmp1 = ubitmap.BitmapFromFile("pic/boy") bmp2 = ubitmap.BitmapFromFile("pic/girl") bmp1.draw(20, 200) #显示boy图片 bmp2.draw(140, 200) #显示girl图片 screen.drawline(0, 160, 240, 160, 2, 0xff0000) def do_connect(self): sta_if = network.WLAN(network.STA_IF) #STA模式 ap_if = network.WLAN(network.AP_IF) #AP模式 if ap_if.active(): ap_if.active(False) #关闭AP if not sta_if.isconnected(): print('Connecting to network...') sta_if.active(True) #激活STA sta_if.connect(self.wifi_name, self.wifi_SSID) #WiFi的SSID和密码 while not sta_if.isconnected(): pass print('Network config:', sta_if.ifconfig()) gc.collect() def selectInit(self): #选择表情初始化 screen.drawline(20, 200, 92, 200, 2, 0xff0000) screen.drawline(92, 200, 92, 272, 2, 0xff0000) screen.drawline(92, 272, 20, 272, 2, 0xff0000) screen.drawline(20, 272, 20, 200, 2, 0xff0000) def displayInit(self): #初始化 screen.clear() self.drawInterface() self.selectInit() def esp(self): self.client.set_callback(self.sub_cb) #设置回调 self.client.connect() print("连接到服务器:%s" % self.SERVER) self.client.publish(self.TOPIC1, self.ON) #发布“1”到TOPIC1 self.client.subscribe(self.TOPIC2) #订阅TOPIC #display.text("从微信取得信息", 20, 20, 0xf000, 0xffff) def keyboardEvent(self, key): if self.keymatch[key] == "Key1": #右移键,选择要发送的表情 if self.select % 2 == 1: #用红色框选中boy表情 screen.drawline(20, 200, 92, 200, 2, 0xffffff) screen.drawline(92, 200, 92, 272, 2, 0xffffff) screen.drawline(92, 272, 20, 272, 2, 0xffffff) screen.drawline(20, 272, 20, 200, 2, 0xffffff) screen.drawline(140, 200, 212, 200, 2, 0xff0000) screen.drawline(212, 200, 212, 272, 2, 0xff0000) screen.drawline(212, 272, 140, 272, 2, 0xff0000) screen.drawline(140, 272, 140, 200, 2, 0xff0000) self.select += 1 else: #用红色框选中girl表情 screen.drawline(140, 200, 212, 200, 2, 0xffffff) screen.drawline(212, 200, 212, 272, 2, 0xffffff) screen.drawline(212, 272, 140, 272, 2, 0xffffff) screen.drawline(140, 272, 140, 200, 2, 0xffffff) screen.drawline(20, 200, 92, 200, 2, 0xff0000) screen.drawline(92, 200, 92, 272, 2, 0xff0000) screen.drawline(92, 272, 20, 272, 2, 0xff0000) screen.drawline(20, 272, 20, 200, 2, 0xff0000) self.select += 1 if self.keymatch[key] == "Key3": #发送表情按键 if self.select % 2 == 1: #显示已发送boy表情 bmp1 = ubitmap.BitmapFromFile("pic/boy") bmp1.draw(140, 40) self.content = "001" self.client.publish(self.TOPIC2, self.content) #给服务器发送boy表情的号码 else: #显示已发送girl表情 bmp2 = ubitmap.BitmapFromFile("pic/girl") bmp2.draw(140, 40) self.content = "002" self.client.publish(self.TOPIC2, self.content) #给服务器发送girl表情的号码 def sub_cb(self, topic, message): #从服务器接受信息 message = message.decode() print("服务器发来信息:%s" % message) #global count if message == "001": #收到boy表情号码显示boy表情 bmp1 = ubitmap.BitmapFromFile("pic/boy") bmp1.draw(140, 40) elif message == "002": #收到girl表情号码显示girl表情 bmp1 = ubitmap.BitmapFromFile("pic/girl") bmp1.draw(140, 40) def start(self): try: while True: self.client.check_msg() #检查是否收到信息 i = 0 #用来辅助判断那个按键被按下 j = -1 for k in self.keys: #检查按键是否被按下 if (k.value() == 0): ##如果按键被按下 if i != j: j = i self.keyboardEvent(i) #触发相应按键对应事件 i = i + 1 if (i > 3): i = 0 time.sleep_ms(130) finally: self.client.disconnect() print("MQTT连接断开")
class Device(object): """ Losant MQTT Device class Used to communicate as a particular device over MQTT to Losant and report device state and receive commands. """ mqtt_endpoint = "broker.losant.com" def __init__(self, device_id, key, secret): self._device_id = device_id self._key = key self._secret = secret self._mqtt_client = None self._initial_connect = False def is_connected(self): """ Returns if the client is currently connected to Losant """ # pylint: disable=W0212 return self._mqtt_client and self._mqtt_client.sock def connect(self): """ Attempts to establish a connection to Losant. Will be blocking or non-blocking depending on the value of the 'blocking' argument. When non-blocking, the 'loop' function must be called to perform network activity. """ if self._mqtt_client: return self._initial_connect = True port = 1883 self._mqtt_client = MQTTClient(self._device_id, self.mqtt_endpoint, port, self._key, self._secret) print("Connecting to Losant as {}".format(self._device_id)) resp = self._mqtt_client.connect() self._cb_client_connect(resp) def close(self): """ Closes the connection to Losant """ if self._mqtt_client: self._mqtt_client.disconnect() def send_state(self, state): """ Reports the given state to Losant for this device """ print("Sending state for {}".format(self._device_id)) if not self._mqtt_client: return False payload = json.dumps({"data": state}) self._mqtt_client.publish(self._state_topic(), payload) # ============================================================ # Private functions # ============================================================ def _command_topic(self): return "losant/{0}/command".format(self._device_id) def _state_topic(self): return "losant/{0}/state".format(self._device_id) def _cb_client_connect(self, response_code): if response_code == 0: return print("{} failed to connect, with mqtt error {}".format( self._device_id, response_code)) if response_code in (1, 2, 4, 5): raise Exception( "Invalid Losant credentials - error code {0}".format( response_code))