esp8266开发——使用micropython下的websocket

micropython 专栏收录该内容
0 篇文章 0 订阅

esp8266开发——使用micropython下的websocket

说明

  • micropython的标准库中包含了websocket的代码,但是我没有测试
  • 我直接修改了webrepl的部分关于websocket的代码,原版的代码里面是无法让chrome作为客户端连接的(在数据解包部分几乎没有实现)
  • 仍然有很多websocket标准,比如分包传输等没有实现

代码

  • websocket_helper.py 这个握手协议实现得非常简单
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
try:
    import ubinascii as binascii
except:
    import binascii
try:
    import uhashlib as hashlib
except:
    import hashlib
    
DEBUG = 0

def server_handshake(sock):
    clr = sock.makefile("rwb", 0)
    l = clr.readline()
    #sys.stdout.write(repr(l))
    webkey = None
    while 1:
        l = clr.readline()
        if not l:
            raise OSError("EOF in headers")
        if l == b"\r\n":
            break
    #    sys.stdout.write(l)
        h, v = [x.strip() for x in l.split(b":", 1)]
        if DEBUG:
            print((h, v))
        if h == b'Sec-WebSocket-Key':
            webkey = v
    if not webkey:
        raise OSError("Not a websocket request")
    if DEBUG:
        print("Sec-WebSocket-Key:", webkey, len(webkey))
    respkey = webkey + b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
    respkey = hashlib.sha1(respkey).digest()
    respkey = binascii.b2a_base64(respkey)[:-1]
    resp = b"""\
HTTP/1.1 101 Switching Protocols\r
Upgrade: websocket\r
Connection: Upgrade\r
Sec-WebSocket-Accept: %s\r
\r
""" % respkey
    if DEBUG:
        print(resp)
    sock.send(resp)
# Very simplified client handshake, works for MicroPython's
# websocket server implementation, but probably not for other
# servers.
def client_handshake(sock):
    cl = sock.makefile("rwb", 0)
    cl.write(b"""\
GET / HTTP/1.1\r
Host: echo.websocket.org\r
Connection: Upgrade\r
Upgrade: websocket\r
Sec-WebSocket-Key: foo\r
\r
""")
    l = cl.readline()
#    print(l)
    while 1:
        l = cl.readline()
        if l == b"\r\n":
            break
#        sys.stdout.write(l)
  • mywebsocket.py 这个主要是建立socket监听、接收websocket的数据,解码的操作。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import websocket_helper
try:
    import network
except:
    pass
import sys
import os
try:
    import ustruct as struct
except:
    import struct
    
DEBUG = False

class websocket:

    def __init__(self, s):
        self.s = s
        
    def write(self, data):
        l = len(data)
        if l < 126:
            # TODO: hardcoded "binary" type
            hdr = struct.pack(">BB", 0x82, l)
        else:
            hdr = struct.pack(">BBH", 0x82, 126, l)
        self.s.send(hdr)
        self.s.send(data)

    def recvexactly(self, sz):
        res = b""
        while sz:
            data = self.s.recv(sz)
            if not data:
                break
            res += data
            sz -= len(data)
        return res

    def read(self):
        while True:
            hdr = self.recvexactly(2)
            assert len(hdr) == 2
            firstbyte, secondbyte = struct.unpack(">BB", hdr)

            mskenable =  True if secondbyte & 0x80 else False
            length = secondbyte & 0x7f
            if DEBUG:
                print('test length=%d' % length)
                print('mskenable=' + str(mskenable))
            if length == 126:
                hdr = self.recvexactly(2)
                assert len(hdr) == 2
                (length,) = struct.unpack(">H", hdr)
            if length == 127:
                hdr = self.recvexactly(8)
                assert len(hdr) == 8
                (length,) = struct.unpack(">Q", hdr)
            if DEBUG:
                print('length=%d' % length)
            opcode =  firstbyte & 0x0f
            if opcode == 8:
                self.s.close()
                return ''
            fin = True if firstbyte&0x80 else False
            if DEBUG:
                print('fin='+str(fin))
                print('opcode=%d'%opcode)
            if mskenable:
                hdr = self.recvexactly(4)
                assert len(hdr) == 4
                (msk1,msk2,msk3,msk4) = struct.unpack(">BBBB", hdr)
                msk = [msk1,msk2,msk3,msk4]
            #print('msk'+str(msk))
            # debugmsg("Got unexpected websocket record of type %x, skipping it" % fl)
            data = []
            while length:
                skip = self.s.recv(length)
                # debugmsg("Skip data: %s" % skip)
                length -= len(skip)
                data.extend(skip)
            newdata = []
            #解码数据
            for i,item in enumerate(data):
                j = i % 4
                newdata.append(chr(data[i] ^ msk[j]))
            res = ''.join(newdata)
            return res
print('my prog start...')
try:
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    sta_if.connect('Xiechuang-technology_5G','xc88888888')
    while True:
      if sta_if.ifconfig()[0] != '0.0.0.0':
        break
    print('succ connect wifi ap,get ipaddr:')
    print(sta_if.ifconfig())
except:
    pass
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('0.0.0.0', 8008))
sock.listen(5)
print('websokcet listen at 8008...')
while True:
    # 这里阻塞接收客户端
    conn, address = sock.accept()
    # 接收到socket
    print('client connect...:')
    print(address)
    websocket_helper.server_handshake(conn)
    ws = websocket(conn)
    print('websocket connect succ')
    # conn.send('hello friend')
    while True:
        text = ws.read()
        if text =='':
            break
        print(text)
  • 1
    点赞
  • 3
    评论
  • 11
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

<p> <span style="color:#FF0000;"><strong>micropython语法和python3一样,编写起来非常方便。如果你快速入门单片机玩物联网而且像轻松实现各种功能,那绝力推荐使用micropython。方便易懂易学。</strong></span> </p> <p> <span style="color:#FF0000;"><strong><br /> </strong></span> </p> <p> <span><span style="color:#FF0000;"><strong>同时如果你懂C语音,也可以用C写好函数并编译进micropython固件里然后进入micropython调用(非必须)。</strong></span></span> </p> <p> <span><span style="color:#FF0000;"><strong><br /> </strong></span></span> </p> <p> <span style="color:#FF0000;"><span><strong>能通过WIFI联网(2.1章),也能通过sim卡使用2G/3G/4G/5G联网(4.5章)。</strong></span></span> </p> <p> <span style="color:#FF0000;"><span><strong><br /> </strong></span></span> </p> <p> <span style="color:#FF0000;"><strong>为实现语音控制,本教程会教大家使用tensorflow利用神经网络训练自己的语音模型并应用。</strong></span> </p> <p> <span style="color:#FF0000;"><strong>为实现通过网页控制,本教程会教大家linux(debian10 nginx->uwsgi->python3->postgresql)网站前后台入门。</strong></span> </p> <p> <span style="color:#FF0000;"><strong>为记录单片机传输过来的数据, 本教程会教大家入门数据库。</strong></span> </p> <p> <span style="color:#FF0000;"><strong><br /> </strong></span> </p> <p> <span style="color:#FF0000;"><strong> </strong></span> </p> <p> <strong> <strong><span style="color:#000000;">本教程会通过通俗易懂的比喻来讲解各种原理与思路,并手把手编写程序来实现各项功能。</span></strong> </strong> </p> <strong> </strong> <p> <strong> <strong><span style="color:#000000;">micropython版本是 2019年6月发布的1.11;</span></strong> </strong> </p> <strong> </strong> <p> <span style="color:#FF0000;"><strong>更多内容请看视频列表。</strong></span> </p> <p> <span style="color:#FF0000;"><strong><br /> </strong></span> </p> <p> <span style="color:#FF0000;"><strong><strong> </strong></strong></span> </p> <p> <strong><strong> <strong><span style="color:#000000;">学习这门课程</span><span style="color:#E53333;">之前</span><span style="color:#000000;">你需要至少掌握:</span><br /> </strong> </strong></strong> </p> <strong><strong> </strong></strong> <p> <strong><strong> <strong><span style="color:#000000;">1: python3基础(变量, 循环, 函数, 常用库, 常用方法)。</span></strong> </strong></strong> </p> <strong><strong> </strong></strong> <p> <strong><strong> <br /> </strong></strong> </p> <strong><strong> </strong></strong> <p> <span style="color:#000000;"> </span> </p> <p> <span><strong> </strong></span> </p> <p> <strong> <span><strong>本视频使用到的零件与淘宝上大致价格:</strong></span> </strong> </p> <strong> </strong> <p> <strong> <span><strong>    1: 超声波传感器(3)</strong></span> </strong> </p> <strong> </strong> <p> <strong> <span><strong>    2: MAX9814麦克风放大模块(8)</strong></span> </strong> </p> <strong> </strong> <p> <strong> <span><strong>    3: DHT22(15)</strong></span> </strong> </p> <strong> </strong> <p> <strong> <span><strong>    4: LED(0.1)</strong></span> </strong> </p> <strong> </strong> <p> <strong> <span><strong>    5: 8路5V低电平触发继电器(12)</strong></span> </strong> </p> <strong> </strong> <p> <strong> <span><strong>    6: HX1838红外接收模块(2)</strong></span> </strong> </p> <strong> </strong> <p> <strong> <span><strong>    7:红外发射管(0.1),HX1838红外接收板(1)</strong></span> </strong> </p> <strong> </strong> <p> <strong> <span><strong>    other: 电表, 排线, 面包板(2)*2,ESP32(28)</strong></span> </strong> </p> <strong> </strong> <p> <br /> </p>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值