web调用串口数据,G2图表显示串口数据
本文技术参考:
在django中实现websocket,https://www.cnblogs.com/huguodong/p/6611602.html
pyserial初级使用,https://www.cnblogs.com/dongxiaodong/p/9992083.html
G2图表插件,https://antv.alipay.com/zh-cn/g2/3.x/demo/index.html
效果图:(将就看吧,不会做图,质量非常差)
本文主要讲述在web端显示串口数据,之前在网上看到很多web端调用串口数据的实现方法,基本都是使用ajax+c# or js调JS调用MSCOMM32.dll实现(只能在ie中运行,只有ie才能调用ActiveX控件),如果真正从web端调用串口数据是实现不了的。
所以我们利用python的pyserial模块对串口进行操作,获取到串口数据后,在django中使用djwebsock将数据实时传输到前端,这样我们就真正意义上实现了web端调用串口数据。
实现技术:pyserial + django + websocket
pyserial:该模块封装了python对串口的访问,为多平台的使用提供了统一的接口。
django:django是一个开放源代码的Web应用框架,由Python写成。
websocke:理解参考https://www.cnblogs.com/fuqiang88/p/5956363.html
viws.py
import json
import time
import serial # 导入模块
import threading
from django.http import HttpResponse
from django.shortcuts import render
from dwebsocket.decorators import accept_websocket, require_websocket
STRGLO = “” # 读取的数据
BOOL = True # 读取标志位
#读取代码本体实现
#@accept_websocket
def ReadData(request, ser, data2, ret):
global STRGLO,BOOL
# 循环接收数据,此为死循环,可用线程实现
print(type(data2))
print(data2)
data2 = bytes.fromhex(data2)
print(data2)
result = ser.write(data2) # 写数据
print(“写总字节数:”, result)
time.sleep(0.01)
data = []
while BOOL:
a = 0 # 结束while标志
if ser.in_waiting:
STRGLO = ser.read(ser.in_waiting).hex() # .decode(“gbk”)
FIRST = 0
end = 0
x = 0
for str_glo in STRGLO:
first = FIRST+end
end = first+2
x = x+1
data.append(int(STRGLO[first:end], 16))
request.websocket.send(json.dumps(int(STRGLO[first:end], 16)))
if(len(data) > 1):
if(data[len(data)-2]==13 and data[len(data)-1] == 10):
a = 1
print(“数据传输结束”)
if end == len(STRGLO):
break
if (a == 1):
print(“结束while”)
break
ser.close() # 关闭串口
#request.websocket.send(json.dumps(data))
#@accept_websocket
def DOpenPort(portx, bps, timeout, request, data2):
ret = False # portx 端口 bpx 波特率 timeout超时设置
try:
# 打开串口,并得到串口对象
ser = serial.Serial(portx, bps, timeout=timeout)
#判断是否打开成功
if(ser.is_open):
ret=True
threading.Thread(target=ReadData, args=(request, ser, data2, ret)).start()
except Exception as e:
print("—异常—:", e)
return ser, ret
@accept_websocket
def echo_two(request):
if not request.is_websocket(): # 判断是不是websocket连接
try: # 如果是普通的http方法
message = request.GET[‘message’]
return HttpResponse(message)
except:
return render(request, ‘login.html’)
else:
for message in request.websocket:
data2 = message.decode(‘utf-8’)
# request.websocket.send(message)#发送消息到客户端
#data = message.decode(‘utf-8’)
#print(type(data))
#print(data)
ser, ret = DOpenPort(“COM4”, 115200, None, request, data2)
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,height=device-height">
<title>实时更新数据的折线图</title>
<style>::-webkit-scrollbar{display:none;}html,body{overflow:hidden;height:100%;margin:0;}
</style>
</head>
<body>
<div style="width: 500px;" id="c1">
<div id="mountNode"></div>
</div>
<div style="margin-left: 50px">
<span>串口号:</span>
<select name="ComName" id="ComName" style="width:75px" >
<option value="1" >COM1</option>
<option value="2" >COM2</option>
<option value="3" selected >COM3</option>
<option value="4" >COM4</option>
</select>
<span>波特率:</span>
<select name="BaudRate" id="BaudRate" style="width:75px" >
<option value="9600" selected >9600</option>
<option value="57600" >57600</option>
<option value="115200" >115200</option>
</select>
<button type="button" id="port">配置串口</button>
<input type="text" id="message" />
<button type="button" id="connect_websocket">连接websocket</button>
<button type="button" id="send_message">发送数据</button>
<button type="button" id="close_websocket">关闭websocket</button>
</div>
<script>/Fixing iframe window.innerHeight 0 issue in Safari/document.body.clientHeight;</script>
<script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.g2-3.5.1/dist/g2.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
var data = [];
var chart = new G2.Chart({
container: 'mountNode',
forceFit: true,
width : 600, // 指定图表宽度
height : 400 // 指定图表高度
});
chart.source(data, {
time: {
alias: '时间',
tickCount: 6,
nice: false
},
temperature: {
alias: '数据',
min: 0,
max:270,
type:'linear'
},
type: {
type: 'cat'
}
});
chart.line().position('time*temperature').shape('smooth').size(0);
chart.render();
setInterval(function() {
}, 1000);
$(function () {
KaTeX parse error: Expected 'EOF', got '&' at position 2: (&̲#x27;#connect_w…('#messagecontainer').prepend('<p>' + e.data + '</p>');
};
// Call onopen directly if socket is already open
if (socket.readyState == WebSocket.OPEN) socket.onopen();
window.s = socket;
});
KaTeX parse error: Expected 'EOF', got '&' at position 2: (&̲#x27;#send_mess…('#message').val())
window.s.send(dataMessage);//通过websocket发送数据
}
});
$('#close_websocket').click(function () {
if (window.s) {
window.s.close();//关闭websocket
console.log('websocket已关闭');
}
});
$('#close_serial').click(function () {
$.ajax({
type:'post',
})
})
});
</script>
</body>
</html>
文章到此结束,代码部分只贴出了前端跟后端,django的相关配置就不描述了。
希望大家可以根据这篇文章拓展出更好的程序,有更多的收获。
第一次写博客,代码部分可能有没写好的地方,大家有好的建议随时提出。
QQ:577978679