【python】flask + flask_socketio + serial 实现串口控制视频的播放暂停

 一、环境安装:

                   pip3 install flask

                   pip3 install  flask_socketio

                   pip3 install pyserial

二、演示效果

【python】flask + flask_socketio + serial 实现串口控制视频的播放暂停_第1张图片

三、源码

后台源码

import time
import psutil
from threading import Lock
from flask import Flask, render_template
from flask_socketio import SocketIO

async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()

import serial
portx = "COM2"
bps = 9600
timex = 5
ser = serial.Serial(portx, int(bps), timeout=1, parity=serial.PARITY_NONE, stopbits=1)

def background_thread():
    if (ser.isOpen()):
        count = 0
        ming = 'no'
        while True:
            socketio.sleep(5)
            line = ser.readline()
            if line:
                ming = line.decode()
                print(line.decode())
                line = 0
            else:
                ming = 'no'
            count += 1
            socketio.emit('server_response',
                          {'data': [ming, count], 'count': count},
                          namespace='/test')
            # 注意:这里不需要客户端连接的上下文,默认 broadcast = True


@app.route('/')
def index():
    return render_template('index1.html', async_mode=socketio.async_mode)


@socketio.on('connect', namespace='/test')
def test_connect():
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=background_thread)


if __name__ == '__main__':
    socketio.run(app, debug=True)

前端界面




    
    串口控制视频
    
    
    
    




    

 

你可能感兴趣的:(Python,Python学习之路)