• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

01Studio MaixPy AI K21021.ESP8266和服务器相互发送数据

武飞扬头像
因心,三人水
帮助10

目录

服务器网址:

导包:

simple库

注册引脚:

构造GPIO口的对象:

配置服务器:

例程:

例程思路

服务器网址:

MQTT Websocket Client学新通http://mqtt.p2hp.com/websocket/

导包:

  1.  
    import network,time
  2.  
    from machine import UART,Timer
  3.  
    from Maix import GPIO
  4.  
    from fpioa_manager import fm
  5.  
    from simple import MQTTClient

simple库

  1.  
    '''
  2.  
    构建 MQTT 客户端对象。
  3.  
    【client_id】: 客户端 ID,具有唯一性;
  4.  
    【server】: 服务器地址,可以是 IP 或者网址;
  5.  
    【port】:服务器端口。(默认是 1883,服务器通常采用的端口,也可以自定义。)
  6.  
    '''
  7.  
    client=mqtt. MQTTClient (client_id, server, port)
  8.  
     
  9.  
    '''
  10.  
    连接到服务器。
  11.  
    '''
  12.  
    client.connect()
  13.  
     
  14.  
    '''
  15.  
    发布,向服务器发送数据。
  16.  
    【TOPIC】:主题编号;
  17.  
    【message】: 信息内容,例:'Hello 01Studio!'
  18.  
    '''
  19.  
    client.publish(TOPIC,message)
  20.  
     
  21.  
    '''
  22.  
    订阅,接收服务器发送的数据。
  23.  
    【TOPIC】:主题编号。
  24.  
    '''
  25.  
    client.subscribe(TOPIC)
  26.  
     
  27.  
    '''
  28.  
    设置回调函数。
  29.  
    【callback】:订阅后如果接收到信息,就执行相名称的回调函数。
  30.  
    '''
  31.  
    client.set_callback(callback)
  32.  
     
  33.  
    '''
  34.  
    检查订阅信息。如收到信息就执行设置过的回调函数 callback。
  35.  
    '''
  36.  
    client.check_msg()

注册引脚:

  1.  
    '''
  2.  
    【pin】芯片外部 IO
  3.  
    【function】芯片功能
  4.  
    【force】=True 则强制注册,清除之前的注册记录
  5.  
    '''
  6.  
    fm.register(pin,function,force=False)
  1.  
    fm.register(8, fm.fpioa.GPIOHS0, force=True)
  2.  
    fm.register(7, fm.fpioa.UART2_TX, force=True)
  3.  
    fm.register(6, fm.fpioa.UART2_RX, force=True)

构造GPIO口的对象:

  1.  
    '''
  2.  
    【ID】内部 GPIO 编号
  3.  
    【MODE】 GPIO 模式;
  4.  
    GPIO.IN :输入模式
  5.  
    GPIO.OUT :输出模式
  6.  
    【PULL】 GPIO.PULL_UP :上拉
  7.  
    GPIO.PULL_DOWN :下拉
  8.  
    GPIO.PULL_NONE :无
  9.  
    【value】GPIO 初始化电平
  10.  
    1:高电平
  11.  
    0:低电平
  12.  
    '''
  13.  
    GPIO(ID,MODE,PULL,VALUE)
  1.  
    wifi_en=GPIO(GPIO.GPIOHS0, GPIO.OUT)
  2.  
    uart = UART(UART.UART2,115200,timeout=1000,read_buf_len=4096)

配置服务器:

学新通

学新通 

学新通 

例程:

例程思路

学新通

  1.  
    '''
  2.  
    main.py
  3.  
     
  4.  
    说明:实现MQTT通信,实现接收服务器数据,再把服务器的数据发回去。
  5.  
    '''
  6.  
     
  7.  
    import network,time
  8.  
    from machine import UART,Timer
  9.  
    from Maix import GPIO
  10.  
    from fpioa_manager import fm
  11.  
    from simple import MQTTClient
  12.  
    import utime
  13.  
     
  14.  
    SSID='********' # WiFi 账号
  15.  
    KEY='********' # WiFi 密码
  16.  
     
  17.  
    ###### WiFi模块初始化 ######
  18.  
    #使能引脚初始化
  19.  
    fm.register(8, fm.fpioa.GPIOHS0, force=True)
  20.  
    wifi_en=GPIO(GPIO.GPIOHS0, GPIO.OUT)
  21.  
     
  22.  
    #串口初始化
  23.  
    fm.register(7, fm.fpioa.UART2_TX, force=True)
  24.  
    fm.register(6, fm.fpioa.UART2_RX, force=True)
  25.  
    uart = UART(UART.UART2,115200,timeout=1000,read_buf_len=4096)
  26.  
     
  27.  
    #WiFi使能函数
  28.  
    def wifi_enable(en):
  29.  
    global wifi_en
  30.  
    wifi_en.value(en)
  31.  
     
  32.  
    def wifi_init():
  33.  
    global uart
  34.  
    wifi_enable(0)
  35.  
    time.sleep_ms(200)
  36.  
    wifi_enable(1)
  37.  
    time.sleep(2)
  38.  
    uart = UART(UART.UART2,115200,timeout=1000, read_buf_len=4096)
  39.  
    tmp = uart.read()
  40.  
    uart.write("AT UART_CUR=921600,8,1,0,0\r\n")
  41.  
    print(uart.read())
  42.  
    uart = UART(UART.UART2,921600,timeout=1000, read_buf_len=10240) # important! baudrate too low or read_buf_len too small will loose data
  43.  
    uart.write("AT\r\n")
  44.  
    tmp = uart.read()
  45.  
    print(tmp)
  46.  
    if not tmp.endswith("OK\r\n"):
  47.  
    print("reset fail")
  48.  
    return None
  49.  
    try:
  50.  
    nic = network.ESP8285(uart)
  51.  
    except Exception:
  52.  
    return None
  53.  
    return nic
  54.  
     
  55.  
    ############################
  56.  
    ######### 主程序 ##########
  57.  
    ############################
  58.  
     
  59.  
    #构建WiFi对象并使能
  60.  
    wlan = wifi_init()
  61.  
     
  62.  
    #正在连接印提示
  63.  
    print("Trying to connect... (may take a while)...")
  64.  
     
  65.  
    #连接网络
  66.  
    wlan.connect(SSID,KEY)
  67.  
     
  68.  
    #打印IP相关信息
  69.  
    print(wlan.ifconfig())
  70.  
     
  71.  
    #发布数据任务
  72.  
    def MQTT_Send(tim):
  73.  
    try:
  74.  
    client.check_msg()
  75.  
    except OSError:
  76.  
    pass
  77.  
     
  78.  
    temp=0
  79.  
     
  80.  
    #设置MQTT回调函数,有信息时候执行
  81.  
    def MQTT_callback(topic, msg):
  82.  
    global temp
  83.  
    temp=temp 1
  84.  
    temp=temp%2
  85.  
    print('topic: {}'.format(topic))
  86.  
    print('msg: {}'.format(msg))
  87.  
    s=msg.decode('utf-8')
  88.  
    print(s)
  89.  
    if temp==1:
  90.  
    print("开始向服务器发送数据...")
  91.  
    client.publish(TOPIC, b'开始向服务器发送数据...')
  92.  
    client.publish(TOPIC, msg)
  93.  
     
  94.  
    SERVER = 'mqtt.p2hp.com'
  95.  
    PORT = 1883
  96.  
    CLIENT_ID = '01Studio-K210' # 客户端ID
  97.  
    TOPIC = '/public/01Studio/1' # TOPIC名称
  98.  
    client = MQTTClient(CLIENT_ID, SERVER, PORT)
  99.  
    print("a")
  100.  
    if client.connect():
  101.  
    print("a1")
  102.  
    else:
  103.  
    print("a4")
  104.  
    client.set_callback(MQTT_callback) #配置回调函数
  105.  
    print("a2")
  106.  
    client.subscribe(TOPIC) #订阅主题
  107.  
    print("a3")
  108.  
     
  109.  
    #定时器0初始化,周期1秒
  110.  
    tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PERIODIC,period=10, callback=MQTT_Send)
  111.  
     
  112.  
    i=0
  113.  
    while True:
  114.  
    pass
  1.  
    '''
  2.  
    simple.py
  3.  
     
  4.  
    需要提前将此文件发送到开发板
  5.  
    '''
  6.  
    import usocket as socket
  7.  
    import ustruct as struct
  8.  
    from ubinascii import hexlify
  9.  
     
  10.  
    class MQTTException(Exception):
  11.  
    pass
  12.  
     
  13.  
    class MQTTClient:
  14.  
     
  15.  
    def __init__(self, client_id, server, port=0, user=None, password=None, keepalive=0,
  16.  
    ssl=False, ssl_params={}):
  17.  
    if port == 0:
  18.  
    port = 8883 if ssl else 1883
  19.  
    self.client_id = client_id
  20.  
    self.sock = None
  21.  
    self.server = server
  22.  
    self.port = port
  23.  
    self.ssl = ssl
  24.  
    self.ssl_params = ssl_params
  25.  
    self.pid = 0
  26.  
    self.cb = None
  27.  
    self.user = user
  28.  
    self.pswd = password
  29.  
    self.keepalive = keepalive
  30.  
    self.lw_topic = None
  31.  
    self.lw_msg = None
  32.  
    self.lw_qos = 0
  33.  
    self.lw_retain = False
  34.  
     
  35.  
    def _send_str(self, s):
  36.  
    self.sock.write(struct.pack("!H", len(s)))
  37.  
    self.sock.write(s)
  38.  
     
  39.  
    def _recv_len(self):
  40.  
    n = 0
  41.  
    sh = 0
  42.  
    while 1:
  43.  
    b = self.sock.read(1)[0]
  44.  
    n |= (b & 0x7f) << sh
  45.  
    if not b & 0x80:
  46.  
    return n
  47.  
    sh = 7
  48.  
     
  49.  
    def set_callback(self, f):
  50.  
    self.cb = f
  51.  
     
  52.  
    def set_last_will(self, topic, msg, retain=False, qos=0):
  53.  
    assert 0 <= qos <= 2
  54.  
    assert topic
  55.  
    self.lw_topic = topic
  56.  
    self.lw_msg = msg
  57.  
    self.lw_qos = qos
  58.  
    self.lw_retain = retain
  59.  
     
  60.  
    def connect(self, clean_session=True):
  61.  
    self.sock = socket.socket()
  62.  
    addr = socket.getaddrinfo(self.server, self.port)[0][-1]
  63.  
    self.sock.connect(addr)
  64.  
    if self.ssl:
  65.  
    import ussl
  66.  
    self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
  67.  
    premsg = bytearray(b"\x10\0\0\0\0\0")
  68.  
    msg = bytearray(b"\x04MQTT\x04\x02\0\0")
  69.  
     
  70.  
    sz = 10 2 len(self.client_id)
  71.  
    msg[6] = clean_session << 1
  72.  
    if self.user is not None:
  73.  
    sz = 2 len(self.user) 2 len(self.pswd)
  74.  
    msg[6] |= 0xC0
  75.  
    if self.keepalive:
  76.  
    assert self.keepalive < 65536
  77.  
    msg[7] |= self.keepalive >> 8
  78.  
    msg[8] |= self.keepalive & 0x00FF
  79.  
    if self.lw_topic:
  80.  
    sz = 2 len(self.lw_topic) 2 len(self.lw_msg)
  81.  
    msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
  82.  
    msg[6] |= self.lw_retain << 5
  83.  
     
  84.  
    i = 1
  85.  
    while sz > 0x7f:
  86.  
    premsg[i] = (sz & 0x7f) | 0x80
  87.  
    sz >>= 7
  88.  
    i = 1
  89.  
    premsg[i] = sz
  90.  
     
  91.  
    self.sock.write(premsg, i 2)
  92.  
    self.sock.write(msg)
  93.  
    #print(hex(len(msg)), hexlify(msg, ":"))
  94.  
    self._send_str(self.client_id)
  95.  
    if self.lw_topic:
  96.  
    self._send_str(self.lw_topic)
  97.  
    self._send_str(self.lw_msg)
  98.  
    if self.user is not None:
  99.  
    self._send_str(self.user)
  100.  
    self._send_str(self.pswd)
  101.  
    resp = self.sock.read(4)
  102.  
    assert resp[0] == 0x20 and resp[1] == 0x02
  103.  
    if resp[3] != 0:
  104.  
    raise MQTTException(resp[3])
  105.  
    return resp[2] & 1
  106.  
     
  107.  
    def disconnect(self):
  108.  
    self.sock.write(b"\xe0\0")
  109.  
    self.sock.close()
  110.  
     
  111.  
    def ping(self):
  112.  
    self.sock.write(b"\xc0\0")
  113.  
     
  114.  
    def publish(self, topic, msg, retain=False, qos=0):
  115.  
    pkt = bytearray(b"\x30\0\0\0")
  116.  
    pkt[0] |= qos << 1 | retain
  117.  
    sz = 2 len(topic) len(msg)
  118.  
    if qos > 0:
  119.  
    sz = 2
  120.  
    assert sz < 2097152
  121.  
    i = 1
  122.  
    while sz > 0x7f:
  123.  
    pkt[i] = (sz & 0x7f) | 0x80
  124.  
    sz >>= 7
  125.  
    i = 1
  126.  
    pkt[i] = sz
  127.  
    #print(hex(len(pkt)), hexlify(pkt, ":"))
  128.  
    self.sock.write(pkt, i 1)
  129.  
    self._send_str(topic)
  130.  
    if qos > 0:
  131.  
    self.pid = 1
  132.  
    pid = self.pid
  133.  
    struct.pack_into("!H", pkt, 0, pid)
  134.  
    self.sock.write(pkt, 2)
  135.  
    self.sock.write(msg)
  136.  
    if qos == 1:
  137.  
    while 1:
  138.  
    op = self.wait_msg()
  139.  
    if op == 0x40:
  140.  
    sz = self.sock.read(1)
  141.  
    assert sz == b"\x02"
  142.  
    rcv_pid = self.sock.read(2)
  143.  
    rcv_pid = rcv_pid[0] << 8 | rcv_pid[1]
  144.  
    if pid == rcv_pid:
  145.  
    return
  146.  
    elif qos == 2:
  147.  
    assert 0
  148.  
     
  149.  
    def subscribe(self, topic, qos=0):
  150.  
    assert self.cb is not None, "Subscribe callback is not set"
  151.  
    pkt = bytearray(b"\x82\0\0\0")
  152.  
    self.pid = 1
  153.  
    struct.pack_into("!BH", pkt, 1, 2 2 len(topic) 1, self.pid)
  154.  
    #print(hex(len(pkt)), hexlify(pkt, ":"))
  155.  
    self.sock.write(pkt)
  156.  
    self._send_str(topic)
  157.  
    self.sock.write(qos.to_bytes(1, "little"))
  158.  
    while 1:
  159.  
    op = self.wait_msg()
  160.  
    if op == 0x90:
  161.  
    resp = self.sock.read(4)
  162.  
    #print(resp)
  163.  
    assert resp[1] == pkt[2] and resp[2] == pkt[3]
  164.  
    if resp[3] == 0x80:
  165.  
    raise MQTTException(resp[3])
  166.  
    return
  167.  
     
  168.  
    # Wait for a single incoming MQTT message and process it.
  169.  
    # Subscribed messages are delivered to a callback previously
  170.  
    # set by .set_callback() method. Other (internal) MQTT
  171.  
    # messages processed internally.
  172.  
    def wait_msg(self):
  173.  
    res = self.sock.read(1)
  174.  
    self.sock.setblocking(True)
  175.  
    if res is None:
  176.  
    return None
  177.  
    if res == b"":
  178.  
    raise OSError(-1)
  179.  
    if res == b"\xd0": # PINGRESP
  180.  
    sz = self.sock.read(1)[0]
  181.  
    assert sz == 0
  182.  
    return None
  183.  
    op = res[0]
  184.  
    if op & 0xf0 != 0x30:
  185.  
    return op
  186.  
    sz = self._recv_len()
  187.  
    topic_len = self.sock.read(2)
  188.  
    topic_len = (topic_len[0] << 8) | topic_len[1]
  189.  
    topic = self.sock.read(topic_len)
  190.  
    sz -= topic_len 2
  191.  
    if op & 6:
  192.  
    pid = self.sock.read(2)
  193.  
    pid = pid[0] << 8 | pid[1]
  194.  
    sz -= 2
  195.  
    msg = self.sock.read(sz)
  196.  
    self.cb(topic, msg)
  197.  
    if op & 6 == 2:
  198.  
    pkt = bytearray(b"\x40\x02\0\0")
  199.  
    struct.pack_into("!H", pkt, 2, pid)
  200.  
    self.sock.write(pkt)
  201.  
    elif op & 6 == 4:
  202.  
    assert 0
  203.  
     
  204.  
    # Checks whether a pending message from server is available.
  205.  
    # If not, returns immediately with None. Otherwise, does
  206.  
    # the same processing as wait_msg.
  207.  
    def check_msg(self):
  208.  
    self.sock.setblocking(False)
  209.  
    return self.wait_msg()

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfaggca
系列文章
更多 icon
同类精品
更多 icon
继续加载