查看: 412|回复: 2

[教程] 使用Mind+ 掌控版 连接EasyIot

[复制链接]
开放的IOT平台目前非常多,但根据哥的经验,很多对初学者不是很友好,各种信息类型,各种触发器,想控制个远程开关的,需要学习大量背景知识。幸亏有EasyIOT,没有看来这个平台确实是市面上最简单的,所有的数据类型都是字符串。publish和subscribe 一到两个主题,即可完成简单的物联网监控和远程控制功能。

准备工作:
1. Mind+ 1.5.0及以上版本(传送到这里下载  http://mindplus.cc
2. 掌控板  我手上是1.0版本
3. 注册一个easyiot账号(传送到这里注册 http://iot.dfrobot.com.cn

开始干活:
第一步:安装Mind+,打开Mind+
   就不啰嗦拉,一路next即可

第二步:将掌控版插到电脑上
   用microUSB线连接,如果电脑上不能显示对应的串口号。安装串口驱动(Mind+内部集成了各类串口驱动)
   我的电脑已经安装过了,所以找到了COM7-CP210x,如果你的电脑找不到,点击一键安装串口驱动(需要管理员权限)。
截图201901102119054155.png


第三步: 切换到上传执行模式
截图201901102121154752.png

第四步:切换到micropython语言
截图201901102121519360.png
第五步:选择对应的串口,我的电脑就是COM7
  这时,如果你的掌控板没有micropython固件,MindPlus会自动给你烧录固件(注意有些掌控板子出厂缺少2个电阻,烧录过程中需要按下A按键再松开)。之后,Mind+就自动连接到了掌控版的micropython固件。
第六步:新建umqtt文件夹
截图201901102124566307.png 截图201901102125137020.png

第七步:在umqtt文件夹下新建文件simple.py
截图201901102126259858.png 截图201901102126433898.png
第八步:双击新建的simple.py文件,将下面的内容复制到里边,然后点击保存
截图201901102127355822.png
[Python] 纯文本查看 复制代码
import usocket as socket
import ustruct as struct
#from ubinascii import hexlify

class MQTTException(Exception):
    pass

class MQTTClient:

  def __init__(self, client_id, server, port=0, user=None, password=None, keepalive=0,ssl=False, ssl_params={}):
    if port == 0:
      port = 8883 if ssl else 1883
    self.client_id = client_id
    self.sock = None
    self.addr = socket.getaddrinfo(server, port)[0][-1]
    self.ssl = ssl
    self.ssl_params = ssl_params
    self.pid = 0
    self.cb = None
    self.user = user
    self.pswd = password
    self.keepalive = keepalive
    self.lw_topic = None
    self.lw_msg = None
    self.lw_qos = 0
    self.lw_retain = False

  def _send_str(self, s):
    self.sock.write(struct.pack("!H", len(s)))
    self.sock.write(s)

  def _recv_len(self):
    n = 0
    sh = 0
    while 1:
      b = self.sock.read(1)[0]
      n |= (b & 0x7f) << sh
      if not b & 0x80:
        return n
      sh += 7

  def set_callback(self, f):
    self.cb = f

  def set_last_will(self, topic, msg, retain=False, qos=0):
    assert 0 <= qos <= 2
    assert topic
    self.lw_topic = topic
    self.lw_msg = msg
    self.lw_qos = qos
    self.lw_retain = retain

  def connect(self, clean_session=True):
    self.sock = socket.socket()
    self.sock.connect(self.addr)
    if self.ssl:
      import ussl
      self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
    msg = bytearray(b"\x10\0\0\x04MQTT\x04\x02\0\0")
    msg[1] = 10 + 2 + len(self.client_id)
    msg[9] = clean_session << 1
    if self.user is not None:
      msg[1] += 2 + len(self.user) + 2 + len(self.pswd)
      msg[9] |= 0xC0
    if self.keepalive:
      assert self.keepalive < 65536
      msg[10] |= self.keepalive >> 8
      msg[11] |= self.keepalive & 0x00FF
    if self.lw_topic:
      msg[1] += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
      msg[9] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
      msg[9] |= self.lw_retain << 5
    self.sock.write(msg)
    #print(hex(len(msg)), hexlify(msg, ":"))
    self._send_str(self.client_id)
    if self.lw_topic:
      self._send_str(self.lw_topic)
      self._send_str(self.lw_msg)
    if self.user is not None:
      self._send_str(self.user)
      self._send_str(self.pswd)
    resp = self.sock.read(4)
    assert resp[0] == 0x20 and resp[1] == 0x02
    if resp[3] != 0:
      raise MQTTException(resp[3])
    return resp[2] & 1

  def disconnect(self):
    self.sock.write(b"\xe0\0")
    self.sock.close()

  def ping(self):
    self.sock.write(b"\xc0\0")

  def publish(self, topic, msg, retain=False, qos=0):
    pkt = bytearray(b"\x30\0\0\0")
    pkt[0] |= qos << 1 | retain
    sz = 2 + len(topic) + len(msg)
    if qos > 0:
      sz += 2
    assert sz < 2097152
    i = 1
    while sz > 0x7f:
      pkt[i] = (sz & 0x7f) | 0x80
      sz >>= 7
      i += 1
    pkt[i] = sz
    #print(hex(len(pkt)), hexlify(pkt, ":"))
    self.sock.write(pkt, i + 1)
    self._send_str(topic)
    if qos > 0:
      self.pid += 1
      pid = self.pid
      struct.pack_into("!H", pkt, 0, pid)
      self.sock.write(pkt, 2)
    self.sock.write(msg)
    if qos == 1:
      while 1:
        op = self.wait_msg()
        if op == 0x40:
          sz = self.sock.read(1)
          assert sz == b"\x02"
          rcv_pid = self.sock.read(2)
          rcv_pid = rcv_pid[0] << 8 | rcv_pid[1]
          if pid == rcv_pid:
            return
    elif qos == 2:
      assert 0

  def subscribe(self, topic, qos=0):
    assert self.cb is not None, "Subscribe callback is not set"
    pkt = bytearray(b"\x82\0\0\0")
    self.pid += 1
    struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid)
    #print(hex(len(pkt)), hexlify(pkt, ":"))
    self.sock.write(pkt)
    self._send_str(topic)
    self.sock.write(qos.to_bytes(1, "little"))
    while 1:
      op = self.wait_msg()
      if op == 0x90:
        resp = self.sock.read(4)
        #print(resp)
        assert resp[1] == pkt[2] and resp[2] == pkt[3]
        if resp[3] == 0x80:
          raise MQTTException(resp[3])
        return

  # Wait for a single incoming MQTT message and process it.
  # Subscribed messages are delivered to a callback previously
  # set by .set_callback() method. Other (internal) MQTT
  # messages processed internally.
  def wait_msg(self):
    res = self.sock.read(1)
    self.sock.setblocking(True)
    if res is None:
      return None
    if res == b"":
      raise OSError(-1)
    if res == b"\xd0":  # PINGRESP
      sz = self.sock.read(1)[0]
      assert sz == 0
      return None
    op = res[0]
    if op & 0xf0 != 0x30:
      return op
    sz = self._recv_len()
    topic_len = self.sock.read(2)
    topic_len = (topic_len[0] << 8) | topic_len[1]
    topic = self.sock.read(topic_len)
    sz -= topic_len + 2
    if op & 6:
      pid = self.sock.read(2)
      pid = pid[0] << 8 | pid[1]
      sz -= 2
    msg = self.sock.read(sz)
    self.cb(topic, msg)
    if op & 6 == 2:
      pkt = bytearray(b"\x40\x02\0\0")
      struct.pack_into("!H", pkt, 2, pid)
      self.sock.write(pkt)
    elif op & 6 == 4:
      assert 0

  # Checks whether a pending message from server is available.
  # If not, returns immediately with None. Otherwise, does
  # the same processing as wait_msg.
  def check_msg(self):
    self.sock.setblocking(False)
    return self.wait_msg()


第九步:在根目录下新建mqtt.py文件,将下面的文件内容拷贝到里边
[Python] 纯文本查看 复制代码
from mpython import *
from umqtt.simple import MQTTClient
from machine import Pin
import network
import time

SSID="替换成你的wifi名称"
PASSWORD="替换成你的wifi密码"


SERVER = "182.254.130.180"
CLIENT_ID = "nouse"
TOPIC = b"替换成你的TOPIC"
username='替换成你的easyiot用户名'
password='替换成你的easyiot用户密码'

state = 0
c=None
def sub_cb(topic, msg):
  global state
  print((topic, msg))
  oled.DispChar('                ',0,32)
  oled.DispChar('接收到'+str(msg,'utf-8'), 0, 32)
  oled.show()
  
def connectWifi(ssid,passwd):
  global wlan
  wlan=network.WLAN(network.STA_IF)         #create a wlan object
  wlan.active(True)                         #Activate the network interface
  wlan.disconnect()                         #Disconnect the last connected WiFi
  wlan.connect(ssid,passwd)                 #connect wifi
  while(wlan.ifconfig()[0]=='0.0.0.0'):
    time.sleep(1)


def button_a_callback(_):
  c.publish(TOPIC,"buttonA")
  
def button_b_callback(_):
  c.publish(TOPIC,"buttonB")

  
#Catch exceptions,stop program if interrupted accidentally in the 'try'
try:
  connectWifi(SSID,PASSWORD)
  server=SERVER
  c = MQTTClient(CLIENT_ID, server,0,username,password)     #create a mqtt client
  c.set_callback(sub_cb)                    #set callback
  c.connect()                               #connect mqtt
  c.subscribe(TOPIC)                        #client subscribes to a topic
  print("Connected to %s, subscribed to %s topic" % (server, TOPIC))

  button_a.irq(trigger=Pin.IRQ_FALLING, handler=button_a_callback)
  button_b.irq(trigger=Pin.IRQ_FALLING, handler=button_b_callback)
  oled.fill(0)
  oled.DispChar('连接'+server,0,0)
  oled.show()
  while True:
    c.wait_msg()                            #wait message 
finally:
  if(c is not None):
    c.disconnect()
  wlan.disconnect()
  wlan.active(False)


第十步:这是一个补充步骤,给那些还没用过的easyiot的人准备的,如果找到用户名 密码和topic
截图201901102134428967.png

点击发送消息

第十一步:右键运行mqtt.py,easyiot就玩起来拉
按下按键A,easyiot接收到了buttonA,按下按键B,easyiot接收到了buttonB。由于我们同时订阅了这个Topic,接收到的信息会下发给掌控板,输入消息,点击发送,可以从网页给掌控板发送消息
截图201901102138456156.png

截图201901102140573911.png 截图201901102141191041.png

rzyzzxw  版主

发表于 7 天前

本帖最后由 rzyzzxw 于 2019-1-11 09:43 编辑

好棒的教程,这样就可以玩DF 的IOT了。学习就是要高手带。
回复 支持 反对

使用道具 举报

rzegkly  初级技匠

发表于 7 天前

掌控在IOT方面有了新的玩法
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
wifi气象站

硬件清单

btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2019 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail