目录

构建智能电灯

硬件

  • NodeMCU ESP8266
  • 三色LED模块
  • 继电器(开关)
  • 面包板
  • 杜邦线
  • USB数据线

NodeMCU 的管脚图

智能电灯的电路图

智能电灯

物联网开发平台

腾讯云物联网开发平台默认开通了一个公共实例,可以免费接入1000个设备,在实例中您可创建项目、产品和设备并进行管理。

平台使用流程

① 登录腾讯云物联网开发平台控制台

② 进入公共实例

③ 创建项目、产品

  1. 新建项目

  2. 保存

  3. 选择智能家居

  4. 新建产品

  5. 保存

④ 定义数据模板

进入智能电灯的数据模板

⑥ 交互开发

  • 配置小程序,快速入口配置

⑦ 设备调试

  1. 新建设备

  2. 设备的详细信息,用于开发的三元组(产品ID、设备名称、设备密钥)

  3. 新建设备的二维码,可以使用腾讯连连扫描快速增加。

软件实现

参考数据模板协议开发用于上报设备的状态和控制设备的指令。可由腾讯云物联网平台提供的生成小工具自动生成,想了解更多的详情,请查看MQTT.fx 快速接入指引

MQTT用户名和密码生成工具

配置您自己的信息

WiFi(用于联网)

  • ESSID
  • PASSWORD

IOT平台定义的设备信息

  • DEVICE_NAME(设备名称)
  • PRODUCT_ID(产品ID)
  • DEVICE_KEY(设备密钥)

MQTT

  • MQTT_USERNAME
  • MQTT_PASSWORD

代码

  • wifi.py
    import network
    ESSID = ""
    PASSWORD = ""
    def connect(essid=ESSID, password=PASSWORD):
      wlan = network.WLAN(network.STA_IF)
      wlan.active(True)
      if not wlan.isconnected():
          print('connecting to network...')
          wlan.connect(essid, password)
          while not wlan.isconnected():
              pass
      print('network config:', wlan.ifconfig())
    
  • led.py
    from machine import PWM
    from machine import Pin
    class LED():
      """
      LED模块
      """
      def __init__(self, rpin, gpin, bpin, freq=1000):
          """
          构造函数
          :param pin: 接LED的管脚,必须支持PWM
          :param freq: PWM的默认频率是1000
          """
          self.pin_red = Pin(rpin)
          self.pin_green = Pin(gpin)
          self.pin_blue = Pin(bpin)
    
          self.led_red = PWM(self.pin_red, freq = freq)
          self.led_green = PWM(self.pin_green, freq = freq)
          self.led_blue = PWM(self.pin_blue, freq = freq)
    
      def rgb_light(self, red, green, blue, brightness):
          if red in range(256) and \
              green in range(256) and \
              blue in range(256) and \
              0.0 <= brightness and \
              brightness <=1.0:
              self.led_red.duty(int(red/255*brightness*1023))
              self.led_green.duty(int(green/255*brightness*1023))
              self.led_blue.duty(int(blue/255*brightness*1023))
          else:
              print("red green blue must between 0 and 255, and brightness from 0.0 to 1.0")
            
      def deinit(self):
          """
          析构函数
          """
          self.led_red.deinit()
          self.led_green.deinit()
          self.led_blue.deinit()
    
  • relay.py
    from machine import Pin
    class Relay():
      """
      继电器,开关
      """
      def __init__(self, pin):
          self.relaypin = Pin(pin, Pin.OUT)
    
      def set_state(self, state):
          self.relaypin.value(state)
    
  • tencent_mqtt.py
    import time
    import ujson
    from umqtt.simple import MQTTClient
    from led import LED
    from relay import Relay
    """
    QCloud Device Info
    """
    DEVICE_NAME = ""
    PRODUCT_ID = ""
    DEVICE_KEY = ""
    """
    MQTT topic
    """
    MQTT_DEVICE_CONTROL_TOPIC = "$thing/down/property/"+PRODUCT_ID+"/"+DEVICE_NAME
    MQTT_DEVICE_STATUS_TOPIC = "$$thing/up/property/"+PRODUCT_ID+"/"+DEVICE_NAME
    MQTT_SERVER = PRODUCT_ID + ".iotcloud.tencentdevices.com"
    MQTT_PORT = 1883
    MQTT_CLIENT_ID = PRODUCT_ID+DEVICE_NAME
    MQTT_USERNAME = ""
    MQTT_PASSWORD = ""
    class SmartLigth():
      def __init__(self):
          self.led = LED(5, 4, 0)
          self.relay = Relay(16)
    
          self.power_switch = 1   #开关(0=off, 1=on)
          self.color = 0          #颜色(0=red, 1=green, 2=blue)
          self.brightness = 100   #亮度(0-100)
          self.name = ''          #灯位置名称
    class TencentMQTT():
      light = SmartLigth()
    
      def __init__(self):
          self.mqtt_client = None
    
      def connect(self):
          self.mqtt_client = MQTTClient(MQTT_CLIENT_ID, MQTT_SERVER, MQTT_PORT, MQTT_USERNAME, MQTT_PASSWORD, 60)
          self.mqtt_client.set_callback(TencentMQTT.control)
          self.mqtt_client.connect()
     
      """
      接收订阅的消息(用于远程控制)
      """
      @staticmethod
      def control(topic, msg):
          light = TencentMQTT.light
          msg_json = ujson.loads(msg)
    
          if msg_json['method'] == 'control':
              params = msg_json['params']
    
              power_switch = params.get('power_switch')
              if power_switch is not None:
                  light.power_switch = power_switch
                  light.relay.set_state(power_switch)
                
              brightness = params.get('brightness')
              if brightness is not None:
                  light.brightness = brightness
    
              color = params.get('color')
              if color is not None:
                  light.color = color
                
              name = params.get('name')
              if name is not None:
                  light.name = name
    
              if color != None or brightness != None:
                  light.led.rgb_light(
                      255 if light.color==0 else 0, 
                      255 if light.color==1 else 0, 
                      255 if light.color==2 else 0, 
                      light.brightness/100.0)
    
      """
      发送设备的状态消息
      """
      def report(self):
          msg = {
              "method": "report",
              "clientToken": "clientToken-0123456789",
              "params": {
                  "color": self.light.color,
                  "name": self.light.name,
                  "power_switch": self.light.power_switch,
                  "brightness": self.light.brightness
              }   
          }
    
          self.mqtt_client.publish(MQTT_DEVICE_STATUS_TOPIC.encode(), ujson.dumps(msg).encode())
    
      """
      初始化,用于打开电灯。
      """
      def light_on(self):
          msg = {
              "method": "control",
              "clientToken": "clientToken-0123456789",
              "params": {
                  "color": self.light.color,
                  "name": self.light.name,
                  "power_switch": self.light.power_switch,
                  "brightness": self.light.brightness
              }
          }
    
          self.control(MQTT_DEVICE_CONTROL_TOPIC.encode(), ujson.dumps(msg).encode())
    
      """
      消息循环
      """
      def loop(self):
          self.mqtt_client.subscribe(MQTT_DEVICE_CONTROL_TOPIC.encode())
    
          # 初始化电灯
          self.light_on()
    
          up_time = 1000
          time_sleep = 50
          time_count = 0
          while True:
              self.mqtt_client.check_msg()
    
              time_count += time_sleep
              if (time_count >= up_time):
                  self.report()
                  time_count = 0
    
              time.sleep_ms(time_sleep)
    
  • main.py
    import wifi
    from tencent_mqtt import TencentMQTT
    if __name__ == '__main__':
      wifi.connect()
        
      mqtt = TencentMQTT()
      mqtt.connect()
    
      mqtt.loop()
    

程序写入开发板

$ ./pyboard.py --device /dev/cu.usbserial-0001 -f cp relay.py led.py wifi.py main.py tencent_mqtt.py :
cp relay.py :relay.py
cp led.py :led.py
cp wifi.py :wifi.py
cp main.py :main.py
cp tencent_mqtt.py :tencent_mqtt.py

远程控制

在微信中打开腾讯连连小程序,扫描下面智能电灯的二维码。

智能电灯的控制界面

参考资料