添加现有代码V1.6
This commit is contained in:
@@ -0,0 +1,4 @@
|
|||||||
|
.vscode
|
||||||
|
/*.bin
|
||||||
|
/*.tmp
|
||||||
|
config/
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
This is a MicroPython board
|
||||||
|
|
||||||
|
You can get started right away by writing your Python code in 'main.py'.
|
||||||
|
|
||||||
|
For a serial prompt:
|
||||||
|
- Windows: you need to go to 'Device manager', right click on the unknown device,
|
||||||
|
then update the driver software, using the 'pybcdc.inf' file found on this drive.
|
||||||
|
Then use a terminal program like Hyperterminal or putty.
|
||||||
|
- Mac OS X: use the command: screen /dev/tty.usbmodem*
|
||||||
|
- Linux: use the command: screen /dev/ttyACM0
|
||||||
|
|
||||||
|
For online docs please visit http://docs.micropython.org/
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# boot.py -- run on boot to configure USB and filesystem
|
||||||
|
# Put app code in main.py
|
||||||
|
print('boot.py start')
|
||||||
|
from math import e
|
||||||
|
import machine
|
||||||
|
import pyb
|
||||||
|
|
||||||
|
pyb.Pin(pyb.Pin.cpu.E4, pyb.Pin.OUT_PP).value(0) # 看门狗
|
||||||
|
|
||||||
|
import time
|
||||||
|
try:
|
||||||
|
#复位网上芯片
|
||||||
|
a8 = machine.Pin(pyb.Pin.cpu.A8, machine.Pin.OUT)
|
||||||
|
a8.value(0)
|
||||||
|
time.sleep_ms(10)
|
||||||
|
a8.value(1)
|
||||||
|
except Exception as e:
|
||||||
|
print('boot.py error:', e)
|
||||||
|
|
||||||
|
pyb.Pin(pyb.Pin.cpu.E4, pyb.Pin.OUT_PP).value(1) # 看门狗
|
||||||
|
|
||||||
|
pyb.main('main.py') # main script to run after this one
|
||||||
|
#pyb.usb_mode('VCP+MSC') # act as a serial and a storage device
|
||||||
|
#pyb.usb_mode('VCP+HID') # act as a serial device and a mouse
|
||||||
|
import network
|
||||||
|
network.country('CN') # ISO 3166-1 Alpha-2 code, eg US, GB, DE, AU or XX for worldwide
|
||||||
|
network.hostname('CPY_SCANNER') # DHCP/mDNS hostname
|
||||||
|
|
||||||
|
|
||||||
|
from json_config import read_config
|
||||||
|
|
||||||
|
conf = read_config()
|
||||||
|
|
||||||
|
pyb.Pin(pyb.Pin.cpu.E4, pyb.Pin.OUT_PP).value(0) # 看门狗
|
||||||
|
|
||||||
|
time.sleep(0.2)
|
||||||
|
lan = network.LAN(phy_addr=1)
|
||||||
|
lan.active(True)
|
||||||
|
|
||||||
|
if conf['daq_test']:
|
||||||
|
lan.ifconfig(('192.168.100.200', '255.255.255.0', '192.168.100.1', '8.8.8.8'))
|
||||||
|
else:
|
||||||
|
lan.ifconfig((conf['ip'], '255.255.255.0', '192.168.100.1', '8.8.8.8'))
|
||||||
|
|
||||||
|
print(lan.ifconfig())
|
||||||
|
|
||||||
|
#import webserver
|
||||||
|
#webserver.main()
|
||||||
|
|
||||||
|
print('boot.py end')
|
||||||
|
|
||||||
|
|
||||||
|
pyb.Pin(pyb.Pin.cpu.E4, pyb.Pin.OUT_PP).value(1) # 看门狗
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
# cpydaq模块使用示例
|
||||||
|
import gc
|
||||||
|
import pyb
|
||||||
|
import cpydaq
|
||||||
|
import time
|
||||||
|
import urandom
|
||||||
|
|
||||||
|
CPY_PROT_CMD_HEARTBEAT = 0x01
|
||||||
|
CPY_PROT_CMD_VERSION = 0x02
|
||||||
|
CPY_PROT_CMD_PARAM_READ = 0x03
|
||||||
|
CPY_PROT_CMD_PARAM_WRITE = 0x04
|
||||||
|
CPY_PROT_CMD_SAMPLE_LEN = 0x05
|
||||||
|
CPY_PROT_CMD_SAMPLE_DATA = 0x06
|
||||||
|
CPY_PROT_CMD_IAP = 0x07
|
||||||
|
CPY_PROT_CMD_BOOT_BLOCKING = 0x08
|
||||||
|
CPY_PROT_CMD_JUMP_APP = 0x09
|
||||||
|
CPY_PROT_CMD_RESET = 0x0A
|
||||||
|
CPY_PROT_CMD_OTP_READ = 0x0B
|
||||||
|
CPY_PROT_CMD_OTP_WRITE = 0x0C
|
||||||
|
CPY_PROT_CMD_RESET_FACTORY = 0x0D
|
||||||
|
|
||||||
|
CPY_PROT_CMD_ACK = 0x80
|
||||||
|
CPY_PROT_CMD_ERROR = 0xC0
|
||||||
|
|
||||||
|
max_packet_len = 16 * 1024
|
||||||
|
|
||||||
|
relay_pin = pyb.Pin(pyb.Pin.cpu.E1, pyb.Pin.OUT)
|
||||||
|
sample_pin = pyb.Pin(pyb.Pin.cpu.E0, pyb.Pin.OUT)
|
||||||
|
pwr_pin = pyb.Pin(pyb.Pin.cpu.C11, pyb.Pin.OUT)
|
||||||
|
|
||||||
|
relay_pin.value(1)
|
||||||
|
sample_pin.value(1)
|
||||||
|
pwr_pin.value(0)
|
||||||
|
|
||||||
|
def daq_set_relay(state):
|
||||||
|
if state:
|
||||||
|
relay_pin.value(0)
|
||||||
|
else:
|
||||||
|
relay_pin.value(1)
|
||||||
|
|
||||||
|
def daq_set_sample(state):
|
||||||
|
if state:
|
||||||
|
sample_pin.value(0)
|
||||||
|
else:
|
||||||
|
sample_pin.value(1)
|
||||||
|
|
||||||
|
def daq_sample_by_time(timeout=1000):
|
||||||
|
daq_set_sample(True)
|
||||||
|
time.sleep_ms(timeout)
|
||||||
|
daq_set_sample(False)
|
||||||
|
|
||||||
|
def daq_init():
|
||||||
|
cpydaq.init(max_packet_len)
|
||||||
|
|
||||||
|
def daq_check_recv(timeout):
|
||||||
|
start_time = time.ticks_ms()
|
||||||
|
while True:
|
||||||
|
time.sleep_ms(2)
|
||||||
|
response = cpydaq.check_recv()
|
||||||
|
if response is not None:
|
||||||
|
return response
|
||||||
|
if time.ticks_ms() > timeout + start_time:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def daq_exec_cmd(cmd, data=None, timeout=1000):
|
||||||
|
# 完全重写函数,确保不使用任何可能导致关键字参数混淆的语法
|
||||||
|
if data is None:
|
||||||
|
send_data = b"\x00\x00\x00\x00"
|
||||||
|
else:
|
||||||
|
send_data = data
|
||||||
|
# 调用cpydaq.start_recv() - 不传递任何参数
|
||||||
|
cpydaq.start_recv()
|
||||||
|
# 调用cpydaq.send_packet() - 只传递位置参数
|
||||||
|
cpydaq.send_packet(cmd, send_data)
|
||||||
|
# 调用daq_check_recv() - 只传递位置参数
|
||||||
|
response = daq_check_recv(timeout)
|
||||||
|
|
||||||
|
return response
|
||||||
|
|
||||||
|
def daq_read_version(timeout=100):
|
||||||
|
response = daq_exec_cmd(CPY_PROT_CMD_VERSION, None, timeout)
|
||||||
|
if response is None:
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
recv_cmd, recv_data = response
|
||||||
|
if recv_cmd == CPY_PROT_CMD_VERSION | CPY_PROT_CMD_ACK:
|
||||||
|
ver = recv_data.decode()
|
||||||
|
print(ver)
|
||||||
|
return ver
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def daq_reset_factory(timeout=100):
|
||||||
|
response = daq_exec_cmd(CPY_PROT_CMD_RESET_FACTORY, None, timeout)
|
||||||
|
return response
|
||||||
|
|
||||||
|
def daq_read_param(timeout=100):
|
||||||
|
param = {}
|
||||||
|
response = daq_exec_cmd(CPY_PROT_CMD_PARAM_READ, None, timeout)
|
||||||
|
if response is None:
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
recv_cmd, recv_data = response
|
||||||
|
if recv_cmd == CPY_PROT_CMD_PARAM_READ | CPY_PROT_CMD_ACK:
|
||||||
|
param["usAdcPeriod"] = int.from_bytes(recv_data[0:2], "little")
|
||||||
|
param["usAdcinterval"] = int.from_bytes(recv_data[2:4], "little")
|
||||||
|
param["ucUseEncoder"] = recv_data[4]
|
||||||
|
param["ucAverageCount"] = recv_data[5]
|
||||||
|
return param
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def daq_read_otp(timeout=100):
|
||||||
|
info = {}
|
||||||
|
response = daq_exec_cmd(CPY_PROT_CMD_OTP_READ, None, timeout)
|
||||||
|
if response is None:
|
||||||
|
return {}
|
||||||
|
else:
|
||||||
|
recv_cmd, recv_data = response
|
||||||
|
if recv_cmd == CPY_PROT_CMD_OTP_READ | CPY_PROT_CMD_ACK and len(recv_data) == 96:
|
||||||
|
try:
|
||||||
|
data = bytearray(recv_data)
|
||||||
|
# print(data.hex())
|
||||||
|
#去除0x00和0xFF
|
||||||
|
for i in range(len(data)):
|
||||||
|
if data[i] == 0x00 or data[i] == 0xFF:
|
||||||
|
data[i] = 0x20
|
||||||
|
info["model"] = data[0:32].decode().strip()
|
||||||
|
info["date"] = data[32:64].decode().strip()
|
||||||
|
info["sn"] = data[64:96].decode().strip()
|
||||||
|
return info
|
||||||
|
except:
|
||||||
|
return {}
|
||||||
|
else:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def daq_write_otp(info, timeout=100):
|
||||||
|
data = bytearray()
|
||||||
|
|
||||||
|
# 处理model字段
|
||||||
|
model_bytes = info["model"].encode()[:32] # 最多32字节
|
||||||
|
data.extend(model_bytes)
|
||||||
|
data.extend(b"\x00" * (32 - len(model_bytes))) # 不足32字节用0x00填充
|
||||||
|
|
||||||
|
# 处理date字段
|
||||||
|
date_bytes = info["date"].encode()[:32]
|
||||||
|
data.extend(date_bytes)
|
||||||
|
data.extend(b"\x00" * (32 - len(date_bytes)))
|
||||||
|
|
||||||
|
# 处理sn字段
|
||||||
|
sn_bytes = info["sn"].encode()[:32]
|
||||||
|
data.extend(sn_bytes)
|
||||||
|
data.extend(b"\x00" * (32 - len(sn_bytes)))
|
||||||
|
|
||||||
|
# print(data.hex())
|
||||||
|
response = daq_exec_cmd(CPY_PROT_CMD_OTP_WRITE, data, timeout)
|
||||||
|
if response is None:
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
recv_cmd, recv_data = response
|
||||||
|
if recv_cmd == CPY_PROT_CMD_OTP_WRITE | CPY_PROT_CMD_ACK:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
print(f"写入OTP失败, 响应: {recv_data.decode()}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def daq_write_param(param, timeout=100):
|
||||||
|
data = bytearray()
|
||||||
|
data.extend(param["usAdcPeriod"].to_bytes(2, "little"))
|
||||||
|
data.extend(param["usAdcinterval"].to_bytes(2, "little"))
|
||||||
|
data.append(param["ucUseEncoder"])
|
||||||
|
data.append(param["ucAverageCount"])
|
||||||
|
|
||||||
|
#打印hex data
|
||||||
|
print(f"发送参数:{data.hex()}")
|
||||||
|
|
||||||
|
response = daq_exec_cmd(CPY_PROT_CMD_PARAM_WRITE, data, timeout)
|
||||||
|
|
||||||
|
if response is None:
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
recv_cmd = response[0]
|
||||||
|
if recv_cmd == CPY_PROT_CMD_PARAM_WRITE | CPY_PROT_CMD_ACK:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def daq_set_default_param():
|
||||||
|
# 创建参数字典
|
||||||
|
param = {}
|
||||||
|
param["usAdcPeriod"] = 1000
|
||||||
|
param["usAdcinterval"] = 40
|
||||||
|
param["ucUseEncoder"] = 1
|
||||||
|
param["ucAverageCount"] = 5
|
||||||
|
# 明确使用位置参数调用daq_write_param,不使用任何关键字参数
|
||||||
|
return daq_write_param(param)
|
||||||
|
|
||||||
|
def daq_set_timer_sample_param():
|
||||||
|
# 创建参数字典
|
||||||
|
param = {}
|
||||||
|
param["usAdcPeriod"] = 1000
|
||||||
|
param["usAdcinterval"] = 40
|
||||||
|
param["ucUseEncoder"] = 0
|
||||||
|
param["ucAverageCount"] = 5
|
||||||
|
# 明确使用位置参数调用daq_write_param,不使用任何关键字参数
|
||||||
|
return daq_write_param(param)
|
||||||
|
|
||||||
|
def daq_otp_test():
|
||||||
|
info = {}
|
||||||
|
info['model']='TGX-DAQ-01-RS485'
|
||||||
|
info['date']='2026/02/28'
|
||||||
|
info['sn']='1001'
|
||||||
|
daq_write_otp(info)
|
||||||
|
info = daq_read_otp()
|
||||||
|
print(info)
|
||||||
|
|
||||||
|
def daq_check_is_online():
|
||||||
|
start_time = time.ticks_ms()
|
||||||
|
response = daq_exec_cmd(CPY_PROT_CMD_HEARTBEAT, None, 10)
|
||||||
|
if response is None:
|
||||||
|
print("超时未收到响应")
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
recv_cmd, recv_data = response
|
||||||
|
if recv_cmd == CPY_PROT_CMD_HEARTBEAT | CPY_PROT_CMD_ACK:
|
||||||
|
#recv_data[0:4]表示时间
|
||||||
|
#recv_data[4:6]表示温度
|
||||||
|
# tim_ms = int.from_bytes(recv_data[0:4], "little")
|
||||||
|
temp = int.from_bytes(recv_data[4:6], "little")
|
||||||
|
# print(f"时间: {tim_ms}ms, 温度: {temp / 10.0:.1f}°C")
|
||||||
|
# print(f'used time {time.ticks_ms() - start_time}ms')
|
||||||
|
return temp
|
||||||
|
else:
|
||||||
|
print(f"收到错误响应: 命令=0x{recv_cmd:02X}, 数据{len(recv_data)}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def daq_reset():
|
||||||
|
response = daq_exec_cmd(CPY_PROT_CMD_RESET, None, 100)
|
||||||
|
if response is None:
|
||||||
|
print("超时未收到响应")
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
recv_cmd, recv_data = response
|
||||||
|
if recv_cmd == CPY_PROT_CMD_RESET | CPY_PROT_CMD_ACK:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
print(f"收到错误响应: 命令=0x{recv_cmd:02X}, 数据{len(recv_data)}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def daq_blocking_bootloader(block):
|
||||||
|
data = bytearray()
|
||||||
|
if block:
|
||||||
|
data.append(0x01)
|
||||||
|
else:
|
||||||
|
data.append(0x00)
|
||||||
|
response = daq_exec_cmd(CPY_PROT_CMD_BOOT_BLOCKING, data, 100)
|
||||||
|
if response is None:
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
recv_cmd = response[0]
|
||||||
|
if recv_cmd == CPY_PROT_CMD_BOOT_BLOCKING | CPY_PROT_CMD_ACK:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def daq_get_sample_len(timeout=100):
|
||||||
|
response = daq_exec_cmd(CPY_PROT_CMD_SAMPLE_LEN, None, timeout)
|
||||||
|
if response is None:
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
recv_cmd = response[0]
|
||||||
|
if recv_cmd == CPY_PROT_CMD_SAMPLE_LEN | CPY_PROT_CMD_ACK:
|
||||||
|
return int.from_bytes(response[1][0:2], "little")
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def daq_get_sample_data(timeout=100):
|
||||||
|
response = daq_exec_cmd(CPY_PROT_CMD_SAMPLE_DATA, None, timeout)
|
||||||
|
if response is None:
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
recv_cmd = response[0]
|
||||||
|
if recv_cmd == CPY_PROT_CMD_SAMPLE_DATA | CPY_PROT_CMD_ACK:
|
||||||
|
return response[1]
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
#压力测试
|
||||||
|
def daq_pressure_test():
|
||||||
|
count = 0
|
||||||
|
for i in range(1000):
|
||||||
|
payload_len = i + 1
|
||||||
|
payload = bytes([urandom.randint(0, 255) for _ in range(payload_len)])
|
||||||
|
|
||||||
|
response = daq_exec_cmd(CPY_PROT_CMD_HEARTBEAT, payload)
|
||||||
|
|
||||||
|
if response is None:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
recv_cmd, recv_data = response
|
||||||
|
#print(f"接收成功: 命令=0x{recv_cmd:02X}, 数据{len(recv_data)}")
|
||||||
|
count += 1
|
||||||
|
|
||||||
|
#手动触发垃圾回收
|
||||||
|
gc.collect()
|
||||||
|
gc.collect()
|
||||||
|
print(f"发送{i + 1}条心跳包 成功接收{count}条响应")
|
||||||
|
|
||||||
+150
@@ -0,0 +1,150 @@
|
|||||||
|
# cpydaq模块使用示例
|
||||||
|
import gc
|
||||||
|
import pyb
|
||||||
|
import cpydaq
|
||||||
|
import time
|
||||||
|
import urandom
|
||||||
|
import os
|
||||||
|
|
||||||
|
from daq import *
|
||||||
|
|
||||||
|
|
||||||
|
IAP_CMD_ERASE = 0x01
|
||||||
|
IAP_CMD_WRITE = 0x02
|
||||||
|
IAP_CMD_CHECK = 0x03
|
||||||
|
|
||||||
|
def daq_iap_erase(size):
|
||||||
|
packet = bytearray()
|
||||||
|
packet.append(IAP_CMD_ERASE)
|
||||||
|
packet.extend(int.to_bytes(size, 4, "little")) #参数1 总大小
|
||||||
|
packet.extend(int.to_bytes(0, 4, "little")) #参数2 保留
|
||||||
|
packet.extend(int.to_bytes(0, 4, "little")) #参数3 保留
|
||||||
|
packet.extend(int.to_bytes(0, 4, "little")) #参数4 保留
|
||||||
|
|
||||||
|
packet.extend(int.to_bytes(0, 2, "little")) #数据长度
|
||||||
|
|
||||||
|
ret = daq_exec_cmd(CPY_PROT_CMD_IAP, packet)
|
||||||
|
if ret is None:
|
||||||
|
print("超时未收到响应")
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
recv_cmd, recv_data = ret
|
||||||
|
if recv_cmd == CPY_PROT_CMD_IAP | CPY_PROT_CMD_ACK:
|
||||||
|
print(f"擦除成功: ", recv_data.decode())
|
||||||
|
return True
|
||||||
|
elif recv_cmd == CPY_PROT_CMD_IAP | CPY_PROT_CMD_ERROR:
|
||||||
|
print(f"擦除失败: ", recv_data.decode())
|
||||||
|
return None
|
||||||
|
|
||||||
|
def daq_iap_write(address, data):
|
||||||
|
packet = bytearray()
|
||||||
|
packet.append(IAP_CMD_WRITE)
|
||||||
|
packet.extend(int.to_bytes(address, 4, "little")) #参数1 地址
|
||||||
|
packet.extend(int.to_bytes(len(data), 4, "little")) #参数2 数据长度
|
||||||
|
packet.extend(int.to_bytes(0, 4, "little")) #参数3 保留
|
||||||
|
packet.extend(int.to_bytes(0, 4, "little")) #参数4 保留
|
||||||
|
|
||||||
|
packet.extend(data)
|
||||||
|
|
||||||
|
ret = daq_exec_cmd(CPY_PROT_CMD_IAP, packet, timeout=1000)
|
||||||
|
if ret is None:
|
||||||
|
print("超时未收到响应")
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
recv_cmd, recv_data = ret
|
||||||
|
if recv_cmd == CPY_PROT_CMD_IAP | CPY_PROT_CMD_ACK:
|
||||||
|
print(f"写入成功: ", recv_data.decode())
|
||||||
|
return True
|
||||||
|
elif recv_cmd == CPY_PROT_CMD_IAP | CPY_PROT_CMD_ERROR:
|
||||||
|
print(f"写入失败: ", recv_data.decode())
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
print(f"收到错误响应: 命令=0x{recv_cmd:02X}, 数据{len(recv_data)}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
wdt_pin = pyb.Pin(pyb.Pin.cpu.E4, pyb.Pin.OUT_PP)
|
||||||
|
wdt_pin.value(0)
|
||||||
|
wdt_pin_val = False
|
||||||
|
|
||||||
|
def watch_dog_feed():
|
||||||
|
global wdt_pin_val
|
||||||
|
if wdt_pin_val:
|
||||||
|
wdt_pin_val = False
|
||||||
|
wdt_pin.value(0)
|
||||||
|
else:
|
||||||
|
wdt_pin_val = True
|
||||||
|
wdt_pin.value(1)
|
||||||
|
|
||||||
|
def iap_start(bin_file):
|
||||||
|
# 用os.stat判断文件是否存在,不存在则返回
|
||||||
|
gc.collect()
|
||||||
|
try:
|
||||||
|
ret = os.stat(bin_file)
|
||||||
|
file_size = ret[6]
|
||||||
|
print(f"文件大小: {file_size}")
|
||||||
|
if file_size == 0 or file_size > 128 * 1024:
|
||||||
|
print("文件为空或大小超过128KB")
|
||||||
|
return None
|
||||||
|
except OSError:
|
||||||
|
print(f"文件不存在: {bin_file}")
|
||||||
|
return None
|
||||||
|
watch_dog_feed()
|
||||||
|
pwr_pin.value(1)
|
||||||
|
time.sleep_ms(500)
|
||||||
|
watch_dog_feed()
|
||||||
|
pwr_pin.value(0)
|
||||||
|
time.sleep_ms(1000)
|
||||||
|
|
||||||
|
watch_dog_feed()
|
||||||
|
|
||||||
|
daq_version = daq_read_version()
|
||||||
|
if daq_version is None:
|
||||||
|
print("读取版本失败")
|
||||||
|
else:
|
||||||
|
print(f"当前版本: {daq_version}")
|
||||||
|
|
||||||
|
daq_init()
|
||||||
|
if not daq_blocking_bootloader(True):
|
||||||
|
print("进入引导程序失败")
|
||||||
|
return None
|
||||||
|
print("进入引导程序成功")
|
||||||
|
watch_dog_feed()
|
||||||
|
daq_iap_erase(file_size)
|
||||||
|
|
||||||
|
# 文件可能很大,分包读取,分包写入,每包最大4096字节
|
||||||
|
with open(bin_file, "rb") as f:
|
||||||
|
address = 0
|
||||||
|
while True:
|
||||||
|
watch_dog_feed()
|
||||||
|
data = f.read(4096)
|
||||||
|
if not data:
|
||||||
|
break
|
||||||
|
cnt = 0
|
||||||
|
for _ in range(3):
|
||||||
|
if daq_iap_write(address, data):
|
||||||
|
break
|
||||||
|
print("写入失败,重试")
|
||||||
|
cnt += 1
|
||||||
|
|
||||||
|
if cnt >= 3:
|
||||||
|
print("写入失败,停止升级")
|
||||||
|
break
|
||||||
|
|
||||||
|
print(f"写入成功: {len(data)}字节")
|
||||||
|
address += len(data)
|
||||||
|
|
||||||
|
if address >= file_size:
|
||||||
|
print("升级完成")
|
||||||
|
time.sleep_ms(200)
|
||||||
|
watch_dog_feed()
|
||||||
|
daq_reset()
|
||||||
|
time.sleep_ms(200)
|
||||||
|
watch_dog_feed()
|
||||||
|
return True
|
||||||
|
|
||||||
|
time.sleep_ms(100)
|
||||||
|
gc.collect()
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
+229
@@ -0,0 +1,229 @@
|
|||||||
|
import gc
|
||||||
|
import json
|
||||||
|
import binascii
|
||||||
|
|
||||||
|
from daq import *
|
||||||
|
from json_config import read_config
|
||||||
|
from net import httpc_post_data, udp_send, udp_recv
|
||||||
|
from webserver_daq_test import send_ws,send_ws_list
|
||||||
|
|
||||||
|
run_flag = False
|
||||||
|
|
||||||
|
daq_sample_start_time = 0
|
||||||
|
daq_sample_len = 0
|
||||||
|
daq_online = 0
|
||||||
|
daq_temp = 0
|
||||||
|
|
||||||
|
xray_pin = pyb.Pin(pyb.Pin.cpu.C0, pyb.Pin.OUT_PP)
|
||||||
|
xray_pin.value(0)
|
||||||
|
|
||||||
|
wdt_pin = pyb.Pin(pyb.Pin.cpu.E4, pyb.Pin.OUT_PP)
|
||||||
|
wdt_pin.value(0)
|
||||||
|
|
||||||
|
config = read_config()
|
||||||
|
|
||||||
|
daq_info = {}
|
||||||
|
|
||||||
|
def watch_dog_feed():
|
||||||
|
if wdt_pin.value() == 0:
|
||||||
|
wdt_pin.value(1)
|
||||||
|
else:
|
||||||
|
wdt_pin.value(0)
|
||||||
|
|
||||||
|
def update_status():
|
||||||
|
status = {
|
||||||
|
'id': config['code'],
|
||||||
|
'run': run_flag,
|
||||||
|
'online': daq_online > 0,
|
||||||
|
'temp': daq_temp,
|
||||||
|
'info': daq_info
|
||||||
|
}
|
||||||
|
packet = json.dumps(status)
|
||||||
|
|
||||||
|
send_ws_list('/dev/daq/status', packet)
|
||||||
|
# print(f'发送状态: {status}')
|
||||||
|
|
||||||
|
def prepare_before_scanning():
|
||||||
|
global daq_sample_start_time
|
||||||
|
daq_set_relay(True)
|
||||||
|
xray_pin.value(1)
|
||||||
|
loop_wait(1000)
|
||||||
|
daq_sample_start_time = time.ticks_ms()
|
||||||
|
daq_set_sample(True)
|
||||||
|
|
||||||
|
def sweep_after_scaning():
|
||||||
|
global daq_sample_start_time
|
||||||
|
|
||||||
|
daq_set_sample(False)
|
||||||
|
xray_pin.value(0)
|
||||||
|
daq_sample_time = time.ticks_diff(time.ticks_ms(), daq_sample_start_time)
|
||||||
|
loop_wait(300)
|
||||||
|
daq_set_relay(False)
|
||||||
|
print(f'采集完成, 耗时: {daq_sample_time}ms')
|
||||||
|
daq_sample_start_time = 0
|
||||||
|
|
||||||
|
|
||||||
|
def loop_wait(timeout):
|
||||||
|
start_time = time.ticks_ms()
|
||||||
|
update_time = start_time
|
||||||
|
while True:
|
||||||
|
if time.ticks_diff(time.ticks_ms(), start_time) > timeout:
|
||||||
|
break
|
||||||
|
time.sleep_ms(10)
|
||||||
|
if time.ticks_diff(time.ticks_ms(), update_time) > 300:
|
||||||
|
update_status()
|
||||||
|
update_time = time.ticks_ms()
|
||||||
|
udp_data_check()
|
||||||
|
watch_dog_feed()
|
||||||
|
|
||||||
|
def read_daq():
|
||||||
|
data_len = daq_get_sample_len()
|
||||||
|
if data_len is None or data_len == 0:
|
||||||
|
return None
|
||||||
|
print(f'数据长度: {data_len}')
|
||||||
|
recv_data = daq_get_sample_data()
|
||||||
|
if recv_data is None:
|
||||||
|
print("读取数据失败")
|
||||||
|
else:
|
||||||
|
l = len(recv_data)
|
||||||
|
print(f"接收数据: {l/4}个点,总长{l}字节")
|
||||||
|
return recv_data
|
||||||
|
|
||||||
|
def read_and_send_data():
|
||||||
|
gc.collect()
|
||||||
|
recv_data = read_daq()
|
||||||
|
if recv_data is None:
|
||||||
|
print('读取数据失败')
|
||||||
|
return
|
||||||
|
packet = {
|
||||||
|
'data': binascii.b2a_base64(recv_data).decode('utf-8')
|
||||||
|
}
|
||||||
|
recv_data = None
|
||||||
|
gc.collect()
|
||||||
|
print(gc.mem_free())
|
||||||
|
|
||||||
|
if send_ws_list('/dev/daq/data', packet):
|
||||||
|
print('发送数据成功')
|
||||||
|
else:
|
||||||
|
print('发送数据失败')
|
||||||
|
print()
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
def udp_data_check():
|
||||||
|
global run_flag, daq_sample_len
|
||||||
|
__udp_cmd = udp_recv()
|
||||||
|
if not __udp_cmd:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
msg = json.loads(__udp_cmd.decode('utf-8'))
|
||||||
|
cmd = msg['cmd']
|
||||||
|
except:
|
||||||
|
print('命令格式错误')
|
||||||
|
return
|
||||||
|
|
||||||
|
if cmd == 'start':
|
||||||
|
try:
|
||||||
|
daq_sample_len = int(msg['len'])
|
||||||
|
except:
|
||||||
|
print('参数格式错误')
|
||||||
|
return
|
||||||
|
run_flag = True
|
||||||
|
print('start cmd')
|
||||||
|
elif cmd == 'stop':
|
||||||
|
run_flag = False
|
||||||
|
print('stop cmd')
|
||||||
|
elif cmd == 'daq_set_sn':
|
||||||
|
try:
|
||||||
|
sn = msg['sn']
|
||||||
|
info = {}
|
||||||
|
info['date'] = sn.split('-')[0]
|
||||||
|
info['sn'] = sn.split('-')[-1]
|
||||||
|
info['model'] = config['model']
|
||||||
|
daq_write_otp(info)
|
||||||
|
time.sleep_ms(100)
|
||||||
|
daq_info.update(daq_read_otp())
|
||||||
|
except Exception as e:
|
||||||
|
print(f'设置SN失败: {e}')
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
print(f"未知命令{cmd}")
|
||||||
|
return
|
||||||
|
|
||||||
|
_daq_check_time = 0
|
||||||
|
def check_daq_state():
|
||||||
|
global daq_online, daq_temp, _daq_check_time
|
||||||
|
if time.ticks_diff(time.ticks_ms(), _daq_check_time) < 1000:
|
||||||
|
return
|
||||||
|
_daq_check_time = time.ticks_ms()
|
||||||
|
temp = daq_check_is_online()
|
||||||
|
if temp is not None:
|
||||||
|
daq_temp = temp
|
||||||
|
daq_online = 2
|
||||||
|
else:
|
||||||
|
if daq_online > 0:
|
||||||
|
daq_online -= 1
|
||||||
|
|
||||||
|
def check_sample_cmd():
|
||||||
|
global daq_sample_start_time, run_flag
|
||||||
|
if daq_sample_start_time == 0:
|
||||||
|
if run_flag:
|
||||||
|
prepare_before_scanning()
|
||||||
|
else:
|
||||||
|
check_daq_state()
|
||||||
|
else:
|
||||||
|
if not run_flag or time.ticks_diff(time.ticks_ms(), daq_sample_start_time) > daq_sample_len:
|
||||||
|
sweep_after_scaning()
|
||||||
|
|
||||||
|
read_and_send_data()
|
||||||
|
run_flag = False
|
||||||
|
daq_sample_start_time = 0
|
||||||
|
time.sleep_ms(1000)
|
||||||
|
|
||||||
|
|
||||||
|
# 运行测试
|
||||||
|
def daq_test_loop():
|
||||||
|
global run_flag, daq_sample_start_time, daq_sample_len
|
||||||
|
run_flag = False
|
||||||
|
daq_sample_start_time = 0
|
||||||
|
daq_sample_len = 1000
|
||||||
|
|
||||||
|
watch_dog_feed()
|
||||||
|
|
||||||
|
daq_init()
|
||||||
|
|
||||||
|
watch_dog_feed()
|
||||||
|
|
||||||
|
daq_info.update(daq_read_otp())
|
||||||
|
daq_info.update({'param': daq_read_param()})
|
||||||
|
daq_info['version'] = daq_read_version()
|
||||||
|
|
||||||
|
status_update_time = time.ticks_ms()
|
||||||
|
|
||||||
|
if daq_info['param']:
|
||||||
|
if daq_info['param'].get('ucUseEncoder', -1) != 0:
|
||||||
|
daq_set_timer_sample_param()
|
||||||
|
daq_info.update({'param': daq_read_param()})
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
if time.ticks_diff(time.ticks_ms(), status_update_time) > 1000:
|
||||||
|
update_status()
|
||||||
|
status_update_time = time.ticks_ms()
|
||||||
|
watch_dog_feed()
|
||||||
|
check_sample_cmd()
|
||||||
|
loop_wait(10)
|
||||||
|
# pyb.info()
|
||||||
|
# print("gc collect")
|
||||||
|
# gc.collect()
|
||||||
|
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
xray_pin.value(0)
|
||||||
|
daq_set_relay(False)
|
||||||
|
daq_set_sample(False)
|
||||||
|
print("测试结束")
|
||||||
|
run_flag = False
|
||||||
|
|
||||||
|
break
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
daq_test_loop()
|
||||||
+257
@@ -0,0 +1,257 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
HTTP服务器,用于接收客户端发送的multipart/form-data格式数据
|
||||||
|
支持JSON元数据和二进制数据的混合传输
|
||||||
|
"""
|
||||||
|
|
||||||
|
import http.server
|
||||||
|
import socketserver
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
import base64
|
||||||
|
import io
|
||||||
|
import socket
|
||||||
|
|
||||||
|
class MultipartFormDataParser:
|
||||||
|
"""解析multipart/form-data格式数据的工具类"""
|
||||||
|
|
||||||
|
def __init__(self, boundary, data):
|
||||||
|
"""初始化解析器
|
||||||
|
|
||||||
|
Args:
|
||||||
|
boundary: multipart边界字符串
|
||||||
|
data: 原始请求体数据
|
||||||
|
"""
|
||||||
|
self.boundary = boundary.encode('utf-8')
|
||||||
|
self.data = data
|
||||||
|
self.parts = []
|
||||||
|
|
||||||
|
def parse(self):
|
||||||
|
"""解析数据,提取各个部分"""
|
||||||
|
# 分割数据
|
||||||
|
parts = self.data.split(b'--' + self.boundary)
|
||||||
|
|
||||||
|
for part in parts:
|
||||||
|
if not part or part.strip() == b'--':
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 分割头部和内容
|
||||||
|
try:
|
||||||
|
header, content = part.split(b'\r\n\r\n', 1)
|
||||||
|
content = content.rstrip(b'\r\n')
|
||||||
|
|
||||||
|
# 解析头部信息
|
||||||
|
part_info = self._parse_header(header)
|
||||||
|
part_info['content'] = content
|
||||||
|
|
||||||
|
self.parts.append(part_info)
|
||||||
|
except ValueError:
|
||||||
|
# 格式错误的部分,跳过
|
||||||
|
continue
|
||||||
|
|
||||||
|
return self.parts
|
||||||
|
|
||||||
|
def _parse_header(self, header):
|
||||||
|
"""解析单个部分的头部信息"""
|
||||||
|
header_str = header.decode('utf-8')
|
||||||
|
lines = header_str.split('\r\n')
|
||||||
|
|
||||||
|
part_info = {
|
||||||
|
'name': None,
|
||||||
|
'filename': None,
|
||||||
|
'content_type': 'text/plain'
|
||||||
|
}
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
if line.startswith('Content-Disposition:'):
|
||||||
|
# 解析Content-Disposition头
|
||||||
|
for param in line.split(';')[1:]:
|
||||||
|
param = param.strip()
|
||||||
|
if param.startswith('name='):
|
||||||
|
part_info['name'] = param.split('=', 1)[1].strip('"')
|
||||||
|
elif param.startswith('filename='):
|
||||||
|
part_info['filename'] = param.split('=', 1)[1].strip('"')
|
||||||
|
elif line.startswith('Content-Type:'):
|
||||||
|
# 解析Content-Type头
|
||||||
|
part_info['content_type'] = line.split(':', 1)[1].strip()
|
||||||
|
|
||||||
|
return part_info
|
||||||
|
|
||||||
|
class DataReceiveHandler(http.server.BaseHTTPRequestHandler):
|
||||||
|
"""处理数据接收的HTTP请求处理器"""
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
"""处理POST请求"""
|
||||||
|
try:
|
||||||
|
# 1. 获取请求头信息
|
||||||
|
content_type = self.headers.get('Content-Type', '')
|
||||||
|
content_length = int(self.headers.get('Content-Length', 0))
|
||||||
|
|
||||||
|
# 2. 检查是否为multipart/form-data格式
|
||||||
|
if not content_type.startswith('multipart/form-data'):
|
||||||
|
self._send_response(400, 'Bad Request', {'error': 'Content-Type must be multipart/form-data'})
|
||||||
|
return
|
||||||
|
|
||||||
|
# 3. 提取boundary
|
||||||
|
boundary = content_type.split('boundary=')[1]
|
||||||
|
|
||||||
|
# 4. 读取请求体数据 - 添加超时和连接检查
|
||||||
|
raw_data = b''
|
||||||
|
bytes_read = 0
|
||||||
|
chunk_size = 8192 # 分块读取,减少内存占用
|
||||||
|
|
||||||
|
while bytes_read < content_length:
|
||||||
|
try:
|
||||||
|
# 设置超时,避免无限等待
|
||||||
|
self.request.settimeout(30.0)
|
||||||
|
|
||||||
|
# 计算剩余需要读取的字节数
|
||||||
|
remaining = min(chunk_size, content_length - bytes_read)
|
||||||
|
chunk = self.rfile.read(remaining)
|
||||||
|
|
||||||
|
if not chunk: # 连接已关闭
|
||||||
|
print(f"[警告] 客户端 {self.client_address} 断开连接,已读取 {bytes_read}/{content_length} 字节")
|
||||||
|
return
|
||||||
|
|
||||||
|
raw_data += chunk
|
||||||
|
bytes_read += len(chunk)
|
||||||
|
|
||||||
|
except socket.timeout:
|
||||||
|
print(f"[警告] 读取请求体超时,客户端: {self.client_address}")
|
||||||
|
return
|
||||||
|
except (ConnectionAbortedError, ConnectionResetError) as e:
|
||||||
|
print(f"[警告] 与客户端 {self.client_address} 的连接已断开: {e}")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 5. 解析multipart数据
|
||||||
|
parser = MultipartFormDataParser(boundary, raw_data)
|
||||||
|
parts = parser.parse()
|
||||||
|
|
||||||
|
# 6. 提取元数据和二进制数据
|
||||||
|
metadata = None
|
||||||
|
binary_data = None
|
||||||
|
|
||||||
|
for part in parts:
|
||||||
|
if part['name'] == 'metadata':
|
||||||
|
# 解析JSON元数据
|
||||||
|
try:
|
||||||
|
metadata = json.loads(part['content'].decode('utf-8'))
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
print(f"[错误] JSON元数据解析失败: {e}")
|
||||||
|
self._send_response(400, 'Bad Request', {'error': 'Invalid JSON metadata'})
|
||||||
|
return
|
||||||
|
elif part['name'] == 'data':
|
||||||
|
# 获取二进制数据
|
||||||
|
binary_data = part['content']
|
||||||
|
|
||||||
|
# 7. 验证数据完整性
|
||||||
|
if not metadata or not binary_data:
|
||||||
|
self._send_response(400, 'Bad Request', {'error': 'Missing required data parts'})
|
||||||
|
return
|
||||||
|
|
||||||
|
# 8. 处理数据(保存到文件)
|
||||||
|
self._process_received_data(metadata, binary_data)
|
||||||
|
|
||||||
|
# 9. 返回成功响应
|
||||||
|
response_data = {
|
||||||
|
'status': 'success',
|
||||||
|
'message': 'Data received successfully'
|
||||||
|
}
|
||||||
|
|
||||||
|
self._send_response(200, 'OK', response_data)
|
||||||
|
|
||||||
|
except (ConnectionAbortedError, ConnectionResetError) as e:
|
||||||
|
# 处理连接错误
|
||||||
|
print(f"[警告] 与客户端 {self.client_address} 的连接已断开: {e}")
|
||||||
|
# 不要尝试发送响应,因为连接已经关闭
|
||||||
|
except socket.timeout as e:
|
||||||
|
# 处理超时错误
|
||||||
|
print(f"[警告] 与客户端 {self.client_address} 的连接超时: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
# 处理其他异常
|
||||||
|
try:
|
||||||
|
self._send_response(500, 'Internal Server Error', {'error': str(e)})
|
||||||
|
except (ConnectionAbortedError, ConnectionResetError):
|
||||||
|
# 如果发送响应时连接已断开,不做处理
|
||||||
|
pass
|
||||||
|
print(f"[错误] 处理请求时发生错误,客户端: {self.client_address}, 错误: {e}")
|
||||||
|
|
||||||
|
def _process_received_data(self, metadata, binary_data):
|
||||||
|
"""处理接收到的数据
|
||||||
|
|
||||||
|
Args:
|
||||||
|
metadata: JSON元数据
|
||||||
|
binary_data: 二进制数据
|
||||||
|
"""
|
||||||
|
# 创建数据保存目录
|
||||||
|
save_dir = os.path.join(os.getcwd(), 'received_data')
|
||||||
|
os.makedirs(save_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# 生成唯一文件名
|
||||||
|
file_id = str(uuid.uuid4())
|
||||||
|
|
||||||
|
# 保存二进制数据
|
||||||
|
binary_filename = os.path.join(save_dir, f'{file_id}.bin')
|
||||||
|
with open(binary_filename, 'wb') as f:
|
||||||
|
f.write(binary_data)
|
||||||
|
|
||||||
|
# 保存元数据
|
||||||
|
metadata_filename = os.path.join(save_dir, f'{file_id}.json')
|
||||||
|
with open(metadata_filename, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(metadata, f, ensure_ascii=False, indent=2)
|
||||||
|
|
||||||
|
# 打印接收信息
|
||||||
|
print(f"\n=== 接收到数据 ===")
|
||||||
|
print(f"元数据: {json.dumps(metadata, ensure_ascii=False)}")
|
||||||
|
print(f"二进制数据大小: {len(binary_data)} bytes")
|
||||||
|
print(f"保存路径: {binary_filename}")
|
||||||
|
print(f"元数据路径: {metadata_filename}")
|
||||||
|
print(f"=== 接收完成 ===")
|
||||||
|
|
||||||
|
def _send_response(self, status_code, status_text, response_data):
|
||||||
|
"""发送HTTP响应
|
||||||
|
|
||||||
|
Args:
|
||||||
|
status_code: HTTP状态码
|
||||||
|
status_text: HTTP状态文本
|
||||||
|
response_data: 响应数据(JSON格式)
|
||||||
|
"""
|
||||||
|
self.send_response(status_code, status_text)
|
||||||
|
self.send_header('Content-Type', 'application/json')
|
||||||
|
self.send_header('Access-Control-Allow-Origin', '*') # 允许跨域请求
|
||||||
|
self.end_headers()
|
||||||
|
|
||||||
|
response_json = json.dumps(response_data, ensure_ascii=False)
|
||||||
|
self.wfile.write(response_json.encode('utf-8'))
|
||||||
|
|
||||||
|
def log_message(self, format, *args):
|
||||||
|
"""自定义日志格式"""
|
||||||
|
print(f"[{self.log_date_time_string()}] {format % args}")
|
||||||
|
|
||||||
|
def run_server(host='0.0.0.0', port=10008):
|
||||||
|
"""启动HTTP服务器
|
||||||
|
|
||||||
|
Args:
|
||||||
|
host: 服务器监听地址
|
||||||
|
port: 服务器监听端口
|
||||||
|
"""
|
||||||
|
# 创建服务器
|
||||||
|
with socketserver.TCPServer((host, port), DataReceiveHandler) as httpd:
|
||||||
|
print(f"HTTP服务器启动成功")
|
||||||
|
print(f"监听地址: {host}")
|
||||||
|
print(f"监听端口: {port}")
|
||||||
|
print(f"请使用POST请求发送multipart/form-data格式数据到: http://{host}:{port}/")
|
||||||
|
print("\n按 Ctrl+C 停止服务器")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 启动服务器循环
|
||||||
|
httpd.serve_forever()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\n服务器正在停止...")
|
||||||
|
httpd.server_close()
|
||||||
|
print("服务器已停止")
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
# 运行服务器
|
||||||
|
run_server()
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
|
||||||
|
CONFIG_PATH = '/flash/config/dev.json'
|
||||||
|
|
||||||
|
def read_config():
|
||||||
|
try:
|
||||||
|
with open(CONFIG_PATH, 'r') as f:
|
||||||
|
conf = json.load(f)
|
||||||
|
except:
|
||||||
|
conf = {
|
||||||
|
"id": 1,
|
||||||
|
"ip": "192.168.100.21",
|
||||||
|
"code": "1#SCANNER"
|
||||||
|
}
|
||||||
|
return conf
|
||||||
|
|
||||||
|
def save_config(conf):
|
||||||
|
try:
|
||||||
|
with open(CONFIG_PATH, 'w') as f:
|
||||||
|
json.dump(conf, f)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# main.py -- put your code here!
|
||||||
|
import time, gc, pyb
|
||||||
|
|
||||||
|
|
||||||
|
print('main.py start')
|
||||||
|
|
||||||
|
from json_config import read_config
|
||||||
|
conf = read_config()
|
||||||
|
|
||||||
|
# 看门狗
|
||||||
|
pyb.Pin(pyb.Pin.cpu.E4, pyb.Pin.OUT_PP).value(0)
|
||||||
|
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
# gc.threshold(10*1024)
|
||||||
|
|
||||||
|
if conf['daq_test']:
|
||||||
|
from webserver_daq_test import ws_run
|
||||||
|
ws_run()
|
||||||
|
else:
|
||||||
|
from webserver import ws_run
|
||||||
|
ws_run()
|
||||||
|
|
||||||
|
|
||||||
|
# 看门狗
|
||||||
|
pyb.Pin(pyb.Pin.cpu.E4, pyb.Pin.OUT_PP).value(1)
|
||||||
|
|
||||||
|
|
||||||
|
# 主线程休眠片刻(确保子线程启动),然后退出,进入 REPL
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
# 看门狗
|
||||||
|
pyb.Pin(pyb.Pin.cpu.E4, pyb.Pin.OUT_PP).value(0)
|
||||||
|
|
||||||
|
# from daq_iap import iap_start
|
||||||
|
# iap_start("/flash/daq_app_V8.5.0_26-03-07_09-12.bin")
|
||||||
|
|
||||||
|
if conf['daq_test']:
|
||||||
|
from daq_test import daq_test_loop
|
||||||
|
daq_test_loop()
|
||||||
|
else:
|
||||||
|
from scanner import scanner_loop
|
||||||
|
scanner_loop()
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
"""
|
||||||
|
MWMotor轮询模式核心功能测试
|
||||||
|
测试使用轮询模式实现基本的电机控制功能
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pyb
|
||||||
|
import time
|
||||||
|
import math as Math
|
||||||
|
from mwmotor import MWMotor, POLL_MODE, VELOCITY_CONTROL, RAMP_RATE_INPUT, AXIS_STATE_CLOSED_LOOP_CONTROL, POSITION_CONTROL, TRAPEZOIDAL_CURVE_INPUT
|
||||||
|
|
||||||
|
mw_pwr_pin = pyb.Pin(pyb.Pin.cpu.C12, pyb.Pin.OUT_PP)
|
||||||
|
origin_pos = 0
|
||||||
|
|
||||||
|
# 1. 初始化CAN总线 - 按照FDCAN HAL参数配置
|
||||||
|
print("步骤1: 初始化CAN总线...")
|
||||||
|
# FDCAN参数: NominalPrescaler=12, NominalTimeSeg1=3, NominalTimeSeg2=3, SyncJumpWidth=1
|
||||||
|
# 对应波特率计算: 48MHz / (12 * (1 + 3 + 3)) = 500kHz
|
||||||
|
__can = pyb.CAN(2, pyb.CAN.NORMAL, baudrate=500000, sample_point = 80) # 精确匹配FDCAN HAL参数
|
||||||
|
|
||||||
|
# 设置CAN滤波器:接收ID范围0x00000000到0x000007FF
|
||||||
|
__can.setfilter(0, pyb.CAN.RANGE, 0, (0x0000, 0x07FF)) # 标准帧滤波器
|
||||||
|
|
||||||
|
|
||||||
|
# 2. 创建电机对象
|
||||||
|
__motor = MWMotor(__can, 1) # bus_id=1, node_id=0
|
||||||
|
print("✓ 电机对象创建成功")
|
||||||
|
|
||||||
|
def motor_poweron():
|
||||||
|
mw_pwr_pin.low()
|
||||||
|
|
||||||
|
def motor_poweroff():
|
||||||
|
mw_pwr_pin.high()
|
||||||
|
|
||||||
|
def motor_init():
|
||||||
|
motor_poweron()
|
||||||
|
|
||||||
|
time.sleep_ms(1000)
|
||||||
|
|
||||||
|
# 3. 设置为轮询模式
|
||||||
|
__motor.set_poll_mode(POLL_MODE)
|
||||||
|
print(f"✓ 设置为轮询模式: {__motor.get_poll_mode() == 1}")
|
||||||
|
|
||||||
|
# 4. 设置模式为斜坡速度控制模式
|
||||||
|
print("设置控制器模式为斜坡速度控制...")
|
||||||
|
__motor.set_controller_mode(VELOCITY_CONTROL, RAMP_RATE_INPUT)
|
||||||
|
count = __motor.poll()
|
||||||
|
print(f"✓ 处理了 {count} 条CAN消息")
|
||||||
|
|
||||||
|
|
||||||
|
# 5. 进入闭环控制状态
|
||||||
|
print("设置电机状态为闭环控制...")
|
||||||
|
__motor.set_axis_state(AXIS_STATE_CLOSED_LOOP_CONTROL)
|
||||||
|
count = __motor.poll()
|
||||||
|
print(f"✓ 处理了 {count} 条CAN消息")
|
||||||
|
|
||||||
|
|
||||||
|
def motor_stop():
|
||||||
|
global speed
|
||||||
|
speed = 0
|
||||||
|
# 8. 输入控制速度
|
||||||
|
print(f"设置电机速度为{speed} rad/s...")
|
||||||
|
__motor.vel_control(speed, 0.0) # 速度10 rad/s, 转矩前馈0
|
||||||
|
|
||||||
|
#用户单位mm/s
|
||||||
|
def __speed_convert_user2device(spd):
|
||||||
|
return spd *9.67/60 * 3 / Math.pi
|
||||||
|
|
||||||
|
def __speed_convert_device2user(spd):
|
||||||
|
return spd *60 /9.67 * Math.pi / 3
|
||||||
|
|
||||||
|
#用户单位mm
|
||||||
|
def __pos_convert_user2device(pos):
|
||||||
|
return pos * 9.67 / 20 / Math.pi
|
||||||
|
|
||||||
|
def __pos_convert_device2user(pos):
|
||||||
|
return pos / 9.67 * 20 * Math.pi
|
||||||
|
|
||||||
|
def motor_speed_set(spd):
|
||||||
|
print(f"设置电机速度为{__speed_convert_user2device(spd)} rad/s...")
|
||||||
|
__motor.vel_control(__speed_convert_user2device(-spd), 1.0) # 速度10 rad/s, 转矩前馈0
|
||||||
|
|
||||||
|
def motor_pos_set(pos):
|
||||||
|
mpos = __pos_convert_user2device(-pos) + origin_pos
|
||||||
|
__motor.set_controller_mode(POSITION_CONTROL, TRAPEZOIDAL_CURVE_INPUT)
|
||||||
|
__motor.set_traj_vel_limit(__speed_convert_user2device(20))
|
||||||
|
__motor.set_traj_accel_limits(10, 10)
|
||||||
|
__motor.pos_control(mpos, 0, 0)
|
||||||
|
|
||||||
|
def motor_set_mode_speed():
|
||||||
|
__motor.set_traj_vel_limit(__speed_convert_user2device(40))
|
||||||
|
__motor.set_traj_accel_limits(100, 100)
|
||||||
|
__motor.set_controller_mode(VELOCITY_CONTROL, RAMP_RATE_INPUT)
|
||||||
|
motor_speed_set(0)
|
||||||
|
|
||||||
|
def motor_poll():
|
||||||
|
count = __motor.poll()
|
||||||
|
if count > 0:
|
||||||
|
try:
|
||||||
|
pos, vel = __motor.get_encoder_estimates()
|
||||||
|
motor_speed = __speed_convert_device2user(vel)
|
||||||
|
motor_pos = __pos_convert_device2user(pos - origin_pos)
|
||||||
|
return (-motor_pos, -motor_speed)
|
||||||
|
except:
|
||||||
|
print("读取电机状态失败")
|
||||||
|
return (None, None)
|
||||||
|
|
||||||
|
def is_at_origin():
|
||||||
|
pos_estimate, vel = __motor.get_encoder_estimates()
|
||||||
|
motor_poll()
|
||||||
|
for i in range(3):
|
||||||
|
__motor.estop()
|
||||||
|
time.sleep_ms(50)
|
||||||
|
__motor.clear_errors()
|
||||||
|
time.sleep_ms(5)
|
||||||
|
__motor.set_axis_state(AXIS_STATE_CLOSED_LOOP_CONTROL)
|
||||||
|
time.sleep_ms(5)
|
||||||
|
__motor.set_axis_state(AXIS_STATE_CLOSED_LOOP_CONTROL)
|
||||||
|
time.sleep_ms(5)
|
||||||
|
__motor.set_axis_state(AXIS_STATE_CLOSED_LOOP_CONTROL)
|
||||||
|
time.sleep_ms(10)
|
||||||
|
new_pos_estimate, _ = __motor.get_encoder_estimates()
|
||||||
|
motor_poll()
|
||||||
|
if abs(new_pos_estimate - pos_estimate) < 0.05:
|
||||||
|
# print(new_pos_estimate, pos_estimate, new_pos_estimate - pos_estimate)
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
# print(False, new_pos_estimate, pos_estimate, new_pos_estimate - pos_estimate)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def move_to_origin():
|
||||||
|
global origin_pos
|
||||||
|
tim = time.time()
|
||||||
|
while not is_at_origin():
|
||||||
|
if time.time() - tim > 10:
|
||||||
|
print("Move to bottom timeout")
|
||||||
|
False
|
||||||
|
origin_pos, _ = __motor.get_encoder_estimates()
|
||||||
|
print("origin_pos", origin_pos)
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 运行测试
|
||||||
|
if __name__ == "__main__":
|
||||||
|
motor_init()
|
||||||
|
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
motor_poll()
|
||||||
|
time.sleep_ms(10)
|
||||||
|
# lw_check()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
motor_speed_set(0)
|
||||||
|
print("测试结束")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
import urequests
|
||||||
|
import gc
|
||||||
|
import socket
|
||||||
|
import _thread
|
||||||
|
import time
|
||||||
|
import json
|
||||||
|
import network
|
||||||
|
|
||||||
|
local_ip = network.LAN().ifconfig()[0]
|
||||||
|
controller_ip = "192.168.100.10"
|
||||||
|
http_server_port = 10008
|
||||||
|
udp_port_up = 11200
|
||||||
|
|
||||||
|
udp_port_local = 11300
|
||||||
|
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
udp_socket.settimeout(0)
|
||||||
|
udp_socket.bind((local_ip, udp_port_local))
|
||||||
|
|
||||||
|
local_cmd = None
|
||||||
|
local_cmd_flag = False
|
||||||
|
|
||||||
|
def httpc_post_data_json_bin(info, data):
|
||||||
|
"""发送混合格式数据:JSON元数据 + 二进制data"""
|
||||||
|
import usocket
|
||||||
|
|
||||||
|
# 1. 构建multipart边界(随机字符串,避免与data内容冲突)
|
||||||
|
boundary = "----WebKitFormBoundary" + "a1b2c3d4e5f6"
|
||||||
|
|
||||||
|
# 2. 构建JSON元数据部分(轻量,RAM占用小)
|
||||||
|
json_part = (
|
||||||
|
f"--{boundary}\r\n"
|
||||||
|
'Content-Disposition: form-data; name="metadata"\r\n'
|
||||||
|
'Content-Type: application/json\r\n'
|
||||||
|
'\r\n' # 空行分隔头和内容
|
||||||
|
f"{json.dumps(info)}\r\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. 构建二进制数据部分头(仅头部,不包含data本身)
|
||||||
|
bin_part_header = (
|
||||||
|
f"--{boundary}\r\n"
|
||||||
|
'Content-Disposition: form-data; name="data"; filename="binary_data.bin"\r\n'
|
||||||
|
'Content-Type: application/octet-stream\r\n'
|
||||||
|
'\r\n' # 空行分隔头和内容
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. 构建结束边界
|
||||||
|
end_boundary = f"\r\n--{boundary}--\r\n"
|
||||||
|
|
||||||
|
# 5. 计算总长度
|
||||||
|
content_length = len(json_part) + len(bin_part_header) + len(data) + len(end_boundary)
|
||||||
|
|
||||||
|
# 6. 构建HTTP请求头(逐步发送,避免大字符串占用RAM)
|
||||||
|
sock = usocket.socket()
|
||||||
|
if not sock:
|
||||||
|
print('创建socket失败')
|
||||||
|
return False
|
||||||
|
sock.settimeout(0.10)
|
||||||
|
|
||||||
|
controller_ip = '192.168.100.10'
|
||||||
|
|
||||||
|
try:
|
||||||
|
sock.connect((controller_ip, http_server_port))
|
||||||
|
except:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 8. 接收响应(可选)
|
||||||
|
try:
|
||||||
|
sock.settimeout(0.5)
|
||||||
|
# 发送请求行
|
||||||
|
sock.write(b"POST /api/endpoint HTTP/1.1\r\n")
|
||||||
|
|
||||||
|
# 发送固定头
|
||||||
|
sock.write(f"Host: {controller_ip}\r\n".encode())
|
||||||
|
sock.write(b"Connection: close\r\n")
|
||||||
|
|
||||||
|
# 发送Content-Type和Content-Length
|
||||||
|
sock.write(f"Content-Type: multipart/form-data; boundary={boundary}\r\n".encode())
|
||||||
|
sock.write(f"Content-Length: {content_length}\r\n\r\n".encode())
|
||||||
|
|
||||||
|
# 7. 分块发送数据(核心优化:避免构建完整请求体)
|
||||||
|
sock.write(json_part.encode()) # 发送JSON元数据
|
||||||
|
sock.write(bin_part_header.encode())# 发送二进制数据头
|
||||||
|
sock.write(data) # 直接发送二进制data(无额外编码)
|
||||||
|
sock.write(end_boundary.encode()) # 发送结束边界
|
||||||
|
|
||||||
|
response = sock.readline()
|
||||||
|
print('response:', response)
|
||||||
|
except:
|
||||||
|
print('接收响应失败')
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
sock.close()
|
||||||
|
|
||||||
|
if not response:
|
||||||
|
print('接收响应失败')
|
||||||
|
return False
|
||||||
|
|
||||||
|
return b"200 OK" in response
|
||||||
|
|
||||||
|
#data为字节数组或者字符串
|
||||||
|
def httpc_post_data(data):
|
||||||
|
try:
|
||||||
|
default_header = {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
}
|
||||||
|
response = urequests.post(f"http://{controller_ip}:{http_server_port}", data=data, headers=default_header)
|
||||||
|
|
||||||
|
return response.status_code == 200
|
||||||
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
response.close()
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
def udp_send(data):
|
||||||
|
try:
|
||||||
|
udp_socket.sendto(data, (controller_ip, udp_port_up))
|
||||||
|
return True
|
||||||
|
except:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def local_cmd_handle(data):
|
||||||
|
global local_cmd, local_cmd_flag
|
||||||
|
if data:
|
||||||
|
local_cmd = data
|
||||||
|
local_cmd_flag = True
|
||||||
|
|
||||||
|
def udp_recv():
|
||||||
|
global local_cmd, local_cmd_flag
|
||||||
|
if local_cmd_flag:
|
||||||
|
local_cmd_flag = False
|
||||||
|
return local_cmd
|
||||||
|
|
||||||
|
try:
|
||||||
|
data, addr = udp_socket.recvfrom(1024)
|
||||||
|
if data:
|
||||||
|
print('recv:', data)
|
||||||
|
return data
|
||||||
|
except:
|
||||||
|
return None
|
||||||
|
|
||||||
|
__exit_flag = False
|
||||||
|
|
||||||
|
def udp_recv_thread(handler):
|
||||||
|
udp_socket.settimeout(1)
|
||||||
|
while not __exit_flag:
|
||||||
|
time.sleep_ms(1000)
|
||||||
|
data = udp_recv()
|
||||||
|
print('udp recv timeout')
|
||||||
|
|
||||||
|
if data is None:
|
||||||
|
continue
|
||||||
|
if handler is None:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
handler(data)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
udp_socket.close()
|
||||||
|
|
||||||
|
def stop_udp_thread():
|
||||||
|
global __exit_flag
|
||||||
|
__exit_flag = True
|
||||||
|
|
||||||
|
def start_udp_thread(handler):
|
||||||
|
_thread.stack_size(20 * 1024)
|
||||||
|
return _thread.start_new_thread(udp_recv_thread, (handler,))
|
||||||
|
|
||||||
+92
@@ -0,0 +1,92 @@
|
|||||||
|
; Windows USB CDC ACM Setup File
|
||||||
|
; Based on INF files which were:
|
||||||
|
; Copyright (c) 2000 Microsoft Corporation
|
||||||
|
; Copyright (C) 2007 Microchip Technology Inc.
|
||||||
|
; Likely to be covered by the MLPL as found at:
|
||||||
|
; <http://msdn.microsoft.com/en-us/cc300389.aspx#MLPL>.
|
||||||
|
|
||||||
|
[Version]
|
||||||
|
Signature="$Windows NT$"
|
||||||
|
Class=Ports
|
||||||
|
ClassGuid={4D36E978-E325-11CE-BFC1-08002BE10318}
|
||||||
|
Provider=%MFGNAME%
|
||||||
|
LayoutFile=layout.inf
|
||||||
|
DriverVer=03/11/2010,5.1.2600.3
|
||||||
|
|
||||||
|
[Manufacturer]
|
||||||
|
%MFGNAME%=DeviceList, NTamd64
|
||||||
|
|
||||||
|
[DestinationDirs]
|
||||||
|
DefaultDestDir=12
|
||||||
|
|
||||||
|
;---------------------------------------------------------------------
|
||||||
|
; Windows 2000/XP/Server2003/Vista/Server2008/7 - 32bit Sections
|
||||||
|
|
||||||
|
[DriverInstall.nt]
|
||||||
|
include=mdmcpq.inf
|
||||||
|
CopyFiles=DriverCopyFiles.nt
|
||||||
|
AddReg=DriverInstall.nt.AddReg
|
||||||
|
|
||||||
|
[DriverCopyFiles.nt]
|
||||||
|
usbser.sys,,,0x20
|
||||||
|
|
||||||
|
[DriverInstall.nt.AddReg]
|
||||||
|
HKR,,DevLoader,,*ntkern
|
||||||
|
HKR,,NTMPDriver,,usbser.sys
|
||||||
|
HKR,,EnumPropPages32,,"MsPorts.dll,SerialPortPropPageProvider"
|
||||||
|
|
||||||
|
[DriverInstall.nt.Services]
|
||||||
|
AddService=usbser, 0x00000002, DriverService.nt
|
||||||
|
|
||||||
|
[DriverService.nt]
|
||||||
|
DisplayName=%SERVICE%
|
||||||
|
ServiceType=1
|
||||||
|
StartType=3
|
||||||
|
ErrorControl=1
|
||||||
|
ServiceBinary=%12%\usbser.sys
|
||||||
|
|
||||||
|
;---------------------------------------------------------------------
|
||||||
|
; Windows XP/Server2003/Vista/Server2008/7 - 64bit Sections
|
||||||
|
|
||||||
|
[DriverInstall.NTamd64]
|
||||||
|
include=mdmcpq.inf
|
||||||
|
CopyFiles=DriverCopyFiles.NTamd64
|
||||||
|
AddReg=DriverInstall.NTamd64.AddReg
|
||||||
|
|
||||||
|
[DriverCopyFiles.NTamd64]
|
||||||
|
usbser.sys,,,0x20
|
||||||
|
|
||||||
|
[DriverInstall.NTamd64.AddReg]
|
||||||
|
HKR,,DevLoader,,*ntkern
|
||||||
|
HKR,,NTMPDriver,,usbser.sys
|
||||||
|
HKR,,EnumPropPages32,,"MsPorts.dll,SerialPortPropPageProvider"
|
||||||
|
|
||||||
|
[DriverInstall.NTamd64.Services]
|
||||||
|
AddService=usbser, 0x00000002, DriverService.NTamd64
|
||||||
|
|
||||||
|
[DriverService.NTamd64]
|
||||||
|
DisplayName=%SERVICE%
|
||||||
|
ServiceType=1
|
||||||
|
StartType=3
|
||||||
|
ErrorControl=1
|
||||||
|
ServiceBinary=%12%\usbser.sys
|
||||||
|
|
||||||
|
;---------------------------------------------------------------------
|
||||||
|
; Vendor and Product ID Definitions
|
||||||
|
|
||||||
|
[SourceDisksFiles]
|
||||||
|
[SourceDisksNames]
|
||||||
|
[DeviceList]
|
||||||
|
%DESCRIPTION%=DriverInstall, USB\VID_f055&PID_9800&MI_00, USB\VID_f055&PID_9800&MI_01, USB\VID_f055&PID_9801&MI_00, USB\VID_f055&PID_9801&MI_01, USB\VID_f055&PID_9802
|
||||||
|
|
||||||
|
[DeviceList.NTamd64]
|
||||||
|
%DESCRIPTION%=DriverInstall, USB\VID_f055&PID_9800&MI_00, USB\VID_f055&PID_9800&MI_01, USB\VID_f055&PID_9801&MI_00, USB\VID_f055&PID_9801&MI_01, USB\VID_f055&PID_9802
|
||||||
|
|
||||||
|
;---------------------------------------------------------------------
|
||||||
|
; String Definitions
|
||||||
|
|
||||||
|
[Strings]
|
||||||
|
MFGFILENAME="pybcdc"
|
||||||
|
MFGNAME="MicroPython"
|
||||||
|
DESCRIPTION="Pyboard USB Comm Port"
|
||||||
|
SERVICE="USB Serial Driver"
|
||||||
+501
@@ -0,0 +1,501 @@
|
|||||||
|
import gc
|
||||||
|
import json
|
||||||
|
import binascii
|
||||||
|
|
||||||
|
from daq import *
|
||||||
|
from motor import *
|
||||||
|
from json_config import read_config, save_config
|
||||||
|
from net import httpc_post_data, udp_send, udp_recv, httpc_post_data_json_bin
|
||||||
|
from webserver import ws_send_status, ws_send_data
|
||||||
|
|
||||||
|
# 定义电机状态枚举类
|
||||||
|
class ScannerState:
|
||||||
|
STOP = 'stop'
|
||||||
|
MOVING_UP = 'moving_up'
|
||||||
|
MOVING_DOWN = 'moving_down'
|
||||||
|
STOP_AT_UPPER = 'stop_at_upper'
|
||||||
|
STOP_AT_BOTTOM = 'stop_at_bottom'
|
||||||
|
STOP_AT_ORIGIN = 'stop_at_origin'
|
||||||
|
|
||||||
|
motor_ready = False
|
||||||
|
daq_temp = 0
|
||||||
|
daq_online = 0
|
||||||
|
daq_version = ''
|
||||||
|
|
||||||
|
motor_state = ScannerState.STOP
|
||||||
|
motor_speed = 0
|
||||||
|
motor_pos = 0
|
||||||
|
|
||||||
|
bottom_pos = 0
|
||||||
|
upper_pos = 0
|
||||||
|
|
||||||
|
reset_flag = False
|
||||||
|
run_flag = False
|
||||||
|
|
||||||
|
scan_count = 0xFFFFFFFF
|
||||||
|
scan_poeriod = 6000
|
||||||
|
|
||||||
|
lw_upper = pyb.Pin(pyb.Pin.cpu.B14, pyb.Pin.IN)
|
||||||
|
lw_lower = pyb.Pin(pyb.Pin.cpu.B15, pyb.Pin.IN)
|
||||||
|
|
||||||
|
xray_pin = pyb.Pin(pyb.Pin.cpu.C0, pyb.Pin.OUT_PP)
|
||||||
|
xray_pin.value(0)
|
||||||
|
|
||||||
|
wdt_pin = pyb.Pin(pyb.Pin.cpu.E4, pyb.Pin.OUT_PP)
|
||||||
|
wdt_pin.value(0)
|
||||||
|
wdt_pin_val = False
|
||||||
|
|
||||||
|
try:
|
||||||
|
config = read_config()
|
||||||
|
scan_period = config['scan_period']
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def watch_dog_feed():
|
||||||
|
global wdt_pin_val
|
||||||
|
if wdt_pin_val:
|
||||||
|
wdt_pin_val = False
|
||||||
|
wdt_pin.value(0)
|
||||||
|
else:
|
||||||
|
wdt_pin_val = True
|
||||||
|
wdt_pin.value(1)
|
||||||
|
|
||||||
|
def update_status():
|
||||||
|
status = {
|
||||||
|
'id': config['code'],
|
||||||
|
'run_flag' : run_flag,
|
||||||
|
'run_time' : time.ticks_ms(),
|
||||||
|
'state': str(motor_state), # 转换为字符串发送
|
||||||
|
'speed': motor_speed,
|
||||||
|
'pos': motor_pos,
|
||||||
|
'upper_pos': upper_pos,
|
||||||
|
'bottom_pos': bottom_pos,
|
||||||
|
'scan_range': upper_pos - bottom_pos,
|
||||||
|
'daq_temp' : daq_temp,
|
||||||
|
'daq_version' : daq_version,
|
||||||
|
'daq_online' : daq_online > 0
|
||||||
|
}
|
||||||
|
packet = json.dumps(status)
|
||||||
|
if not udp_send(packet.encode('utf-8')):
|
||||||
|
print('发送状态失败')
|
||||||
|
ws_send_status('/dev/status/scanner', packet)
|
||||||
|
# print('发送状态成功', packet)
|
||||||
|
|
||||||
|
def move_to(dir,timeout):
|
||||||
|
global motor_state, motor_speed, motor_pos
|
||||||
|
if dir == 'up':
|
||||||
|
if lw_upper.value() == 0:
|
||||||
|
return False
|
||||||
|
motor_state = ScannerState.MOVING_UP
|
||||||
|
motor_speed_set(40)
|
||||||
|
elif dir == 'down':
|
||||||
|
if lw_lower.value() == 0:
|
||||||
|
return False
|
||||||
|
motor_state = ScannerState.MOVING_DOWN
|
||||||
|
motor_speed_set(-40)
|
||||||
|
else:
|
||||||
|
print(f"未知方向{dir}")
|
||||||
|
return False
|
||||||
|
start_time = time.ticks_ms()
|
||||||
|
update_time = start_time
|
||||||
|
update_status()
|
||||||
|
while True:
|
||||||
|
pos, speed = motor_poll()
|
||||||
|
if not (speed is None):
|
||||||
|
motor_speed = speed
|
||||||
|
if not (pos is None):
|
||||||
|
motor_pos = pos
|
||||||
|
time.sleep_ms(5)
|
||||||
|
if time.ticks_diff(time.ticks_ms(), update_time) > 300:
|
||||||
|
update_status()
|
||||||
|
update_time = time.ticks_ms()
|
||||||
|
if dir == 'up' and lw_upper.value() == 0:
|
||||||
|
motor_speed_set(0)
|
||||||
|
motor_state = ScannerState.STOP_AT_UPPER
|
||||||
|
update_status()
|
||||||
|
return True
|
||||||
|
if dir == 'down' and lw_lower.value() == 0:
|
||||||
|
motor_speed_set(0)
|
||||||
|
motor_state = ScannerState.STOP_AT_BOTTOM
|
||||||
|
update_status()
|
||||||
|
return True
|
||||||
|
if time.ticks_diff(time.ticks_ms(), start_time) > timeout:
|
||||||
|
print(f"移动到{dir}超时")
|
||||||
|
motor_speed_set(0)
|
||||||
|
motor_state = ScannerState.STOP
|
||||||
|
update_status()
|
||||||
|
return False
|
||||||
|
udp_data_check()
|
||||||
|
watch_dog_feed()
|
||||||
|
|
||||||
|
|
||||||
|
def move_to_top(timeout):
|
||||||
|
global upper_pos
|
||||||
|
if move_to('up', timeout):
|
||||||
|
loop_wait(500)
|
||||||
|
upper_pos = motor_pos
|
||||||
|
print("bottom pos update", motor_pos)
|
||||||
|
|
||||||
|
def move_to_bottom(timeout):
|
||||||
|
global bottom_pos
|
||||||
|
if move_to('down', timeout):
|
||||||
|
loop_wait(500)
|
||||||
|
bottom_pos = motor_pos
|
||||||
|
print("bottom pos update", motor_pos)
|
||||||
|
|
||||||
|
def loop_wait(timeout):
|
||||||
|
global motor_speed, motor_pos
|
||||||
|
start_time = time.ticks_ms()
|
||||||
|
update_time = start_time
|
||||||
|
while True:
|
||||||
|
pos, speed = motor_poll()
|
||||||
|
if not (speed is None):
|
||||||
|
motor_speed = speed
|
||||||
|
if not (pos is None):
|
||||||
|
motor_pos = pos
|
||||||
|
if time.ticks_diff(time.ticks_ms(), start_time) > timeout:
|
||||||
|
break
|
||||||
|
time.sleep_ms(10)
|
||||||
|
if time.ticks_diff(time.ticks_ms(), update_time) > 200:
|
||||||
|
update_status()
|
||||||
|
update_time = time.ticks_ms()
|
||||||
|
watch_dog_feed()
|
||||||
|
udp_data_check()
|
||||||
|
|
||||||
|
def move_to_pos(pos, timeout):
|
||||||
|
motor_pos_set(pos)
|
||||||
|
tim = time.ticks_ms()
|
||||||
|
while True:
|
||||||
|
loop_wait(100)
|
||||||
|
watch_dog_feed()
|
||||||
|
if abs(motor_pos - pos) < 0.2:
|
||||||
|
break
|
||||||
|
if time.ticks_diff(time.ticks_ms(), tim) > timeout:
|
||||||
|
break
|
||||||
|
loop_wait(300)
|
||||||
|
motor_set_mode_speed()
|
||||||
|
loop_wait(300)
|
||||||
|
if abs(motor_pos - pos) < 0.2:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def read_daq():
|
||||||
|
data_len = daq_get_sample_len()
|
||||||
|
if data_len is None or data_len == 0:
|
||||||
|
print("读取数据长度失败或者没有数据")
|
||||||
|
return None
|
||||||
|
print(f"数据长度: {data_len}")
|
||||||
|
recv_data = daq_get_sample_data()
|
||||||
|
if recv_data is None:
|
||||||
|
print("读取数据失败")
|
||||||
|
else:
|
||||||
|
l = len(recv_data)
|
||||||
|
print(f"接收数据: {l},移动距离: {l * 0.04 / 4}mm")
|
||||||
|
return recv_data
|
||||||
|
|
||||||
|
def make_data_packet(direction, data):
|
||||||
|
content = {
|
||||||
|
'direction': direction,
|
||||||
|
'id': config['code'],
|
||||||
|
'data': binascii.b2a_base64(data).decode('utf-8')
|
||||||
|
}
|
||||||
|
return content
|
||||||
|
|
||||||
|
def read_and_send_data_json():
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
recv_data = read_daq()
|
||||||
|
if recv_data is None:
|
||||||
|
return
|
||||||
|
if motor_state == ScannerState.STOP_AT_UPPER:
|
||||||
|
direction = 'UP'
|
||||||
|
elif motor_state == ScannerState.STOP_AT_BOTTOM:
|
||||||
|
direction = 'DOWN'
|
||||||
|
else:
|
||||||
|
print('电机位置异常,取消数据发送')
|
||||||
|
return
|
||||||
|
packet = make_data_packet(direction, recv_data)
|
||||||
|
recv_data = None
|
||||||
|
# gc.collect()
|
||||||
|
|
||||||
|
packet = json.dumps(packet)
|
||||||
|
# print(gc.mem_free(), len(packet))
|
||||||
|
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
if httpc_post_data(packet):
|
||||||
|
print('发送数据成功')
|
||||||
|
else:
|
||||||
|
print('发送数据失败')
|
||||||
|
print()
|
||||||
|
|
||||||
|
def read_and_send_data():
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
recv_data = read_daq()
|
||||||
|
if recv_data is None:
|
||||||
|
return
|
||||||
|
if motor_state == ScannerState.STOP_AT_UPPER:
|
||||||
|
direction = 'UP'
|
||||||
|
elif motor_state == ScannerState.STOP_AT_BOTTOM:
|
||||||
|
direction = 'DOWN'
|
||||||
|
else:
|
||||||
|
print('电机位置异常,取消数据发送')
|
||||||
|
return
|
||||||
|
|
||||||
|
tim = time.ticks_ms()
|
||||||
|
if httpc_post_data_json_bin({'direction': direction, 'id': config['code'], 'data_len': len(recv_data)}, recv_data):
|
||||||
|
print('http发送数据成功')
|
||||||
|
else:
|
||||||
|
print('http发送数据失败')
|
||||||
|
print(f"http发送数据耗时: {time.ticks_diff(time.ticks_ms(), tim)}ms")
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
if ws_send_data('/dev/data/scanner', recv_data):
|
||||||
|
print('ws发送数据成功')
|
||||||
|
else:
|
||||||
|
print('ws发送数据失败')
|
||||||
|
|
||||||
|
print(gc.mem_free())
|
||||||
|
gc.collect()
|
||||||
|
|
||||||
|
class CommandException(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def udp_data_check():
|
||||||
|
global reset_flag, run_flag, scan_count, scan_period
|
||||||
|
|
||||||
|
__udp_cmd = udp_recv()
|
||||||
|
if not __udp_cmd:
|
||||||
|
return
|
||||||
|
if not motor_ready:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
cmd_obj = json.loads(__udp_cmd.decode('utf-8'))
|
||||||
|
cmd = cmd_obj['cmd']
|
||||||
|
except:
|
||||||
|
print('命令格式错误')
|
||||||
|
return
|
||||||
|
|
||||||
|
if cmd == 'reset':
|
||||||
|
run_flag = False
|
||||||
|
reset_flag = True
|
||||||
|
print('reset cmd')
|
||||||
|
raise CommandException()
|
||||||
|
elif cmd == 'start':
|
||||||
|
try:
|
||||||
|
if cmd_obj['count'] > 0:
|
||||||
|
scan_count = cmd_obj['count']
|
||||||
|
if cmd_obj['period'] >= 4000 and cmd_obj['period'] <= 60 * 1000:
|
||||||
|
scan_period = cmd_obj['period']
|
||||||
|
if config['scan_period'] != scan_period:
|
||||||
|
config.update('scan_period', scan_period)
|
||||||
|
save_config(config)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
if scan_count <= 0:
|
||||||
|
scan_count = 0xFFFFFFFF
|
||||||
|
if run_flag and not reset_flag:
|
||||||
|
if motor_state == ScannerState.STOP_AT_BOTTOM \
|
||||||
|
or motor_state == ScannerState.STOP_AT_UPPER:
|
||||||
|
print('start rightnow')
|
||||||
|
raise CommandException()
|
||||||
|
return
|
||||||
|
|
||||||
|
if not run_flag:
|
||||||
|
reset_flag = False
|
||||||
|
run_flag = True
|
||||||
|
print('start cmd')
|
||||||
|
raise CommandException()
|
||||||
|
elif cmd == 'emer_stop':
|
||||||
|
if not run_flag:
|
||||||
|
return
|
||||||
|
run_flag = False
|
||||||
|
print('stop cmd')
|
||||||
|
raise CommandException()
|
||||||
|
elif cmd == 'stop':
|
||||||
|
run_flag = False
|
||||||
|
print('stop cmd')
|
||||||
|
else:
|
||||||
|
print(f"未知命令{cmd}")
|
||||||
|
return
|
||||||
|
|
||||||
|
def prepare_before_scanning():
|
||||||
|
daq_set_relay(True)
|
||||||
|
xray_pin.value(1)
|
||||||
|
loop_wait(1000)
|
||||||
|
daq_set_sample(True)
|
||||||
|
|
||||||
|
def sweep_after_scaning():
|
||||||
|
daq_set_sample(False)
|
||||||
|
xray_pin.value(0)
|
||||||
|
loop_wait(200)
|
||||||
|
daq_set_relay(False)
|
||||||
|
|
||||||
|
def scan():
|
||||||
|
if motor_state == ScannerState.STOP_AT_BOTTOM:
|
||||||
|
print('scan up')
|
||||||
|
prepare_before_scanning()
|
||||||
|
move_to_top(5000)
|
||||||
|
sweep_after_scaning()
|
||||||
|
read_and_send_data()
|
||||||
|
|
||||||
|
elif motor_state == ScannerState.STOP_AT_UPPER:
|
||||||
|
print('scan down')
|
||||||
|
prepare_before_scanning()
|
||||||
|
move_to_bottom(5000)
|
||||||
|
sweep_after_scaning()
|
||||||
|
read_and_send_data()
|
||||||
|
|
||||||
|
def daq_sample_with_time(tim = 2500):
|
||||||
|
prepare_before_scanning()
|
||||||
|
loop_wait(tim)
|
||||||
|
sweep_after_scaning()
|
||||||
|
|
||||||
|
gc.collect()
|
||||||
|
recv_data = read_daq()
|
||||||
|
if recv_data is None:
|
||||||
|
print("data empty")
|
||||||
|
return
|
||||||
|
packet = make_data_packet("UP", recv_data)
|
||||||
|
recv_data = None
|
||||||
|
gc.collect()
|
||||||
|
packet = json.dumps(packet)
|
||||||
|
print(gc.mem_free())
|
||||||
|
|
||||||
|
if httpc_post_data(packet):
|
||||||
|
print('发送数据成功')
|
||||||
|
else:
|
||||||
|
print('发送数据失败')
|
||||||
|
print()
|
||||||
|
|
||||||
|
def scanner_loop():
|
||||||
|
global motor_ready, motor_state, run_flag, reset_flag, scan_count, scan_period, daq_online, daq_temp, daq_version
|
||||||
|
motor_init()
|
||||||
|
daq_init()
|
||||||
|
|
||||||
|
watch_dog_feed()
|
||||||
|
|
||||||
|
daq_set_relay(False)
|
||||||
|
|
||||||
|
daq_version = daq_read_version()
|
||||||
|
if daq_version is None:
|
||||||
|
print("读取版本失败")
|
||||||
|
|
||||||
|
param = daq_read_param()
|
||||||
|
print(param)
|
||||||
|
if param and param.get('ucUseEncoder', -1) != 1:
|
||||||
|
daq_set_default_param()
|
||||||
|
param = None
|
||||||
|
|
||||||
|
loop_wait(1000)
|
||||||
|
|
||||||
|
if lw_lower.value() != 0:
|
||||||
|
move_to_bottom(5000)
|
||||||
|
loop_wait(500)
|
||||||
|
|
||||||
|
move_to_top(5000)
|
||||||
|
loop_wait(500)
|
||||||
|
|
||||||
|
move_to_bottom(5000)
|
||||||
|
loop_wait(500)
|
||||||
|
|
||||||
|
move_to_origin()
|
||||||
|
motor_state = ScannerState.STOP_AT_ORIGIN
|
||||||
|
|
||||||
|
print('back to origin')
|
||||||
|
print("bottom pos", bottom_pos)
|
||||||
|
print("upper pos", upper_pos)
|
||||||
|
|
||||||
|
motor_ready = True
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
if run_flag:
|
||||||
|
gc.collect()
|
||||||
|
tim = time.ticks_ms()
|
||||||
|
scan()
|
||||||
|
if scan_count > 0:
|
||||||
|
scan_count = scan_count - 1
|
||||||
|
if scan_count <= 0:
|
||||||
|
run_flag = False
|
||||||
|
if run_flag:
|
||||||
|
delta = scan_poeriod - time.ticks_diff(time.ticks_ms(), tim)
|
||||||
|
if delta < 1000:
|
||||||
|
wait_time = 1000
|
||||||
|
else:
|
||||||
|
wait_time = delta
|
||||||
|
|
||||||
|
loop_wait(wait_time)
|
||||||
|
else:
|
||||||
|
temp = daq_check_is_online()
|
||||||
|
if temp is not None:
|
||||||
|
daq_temp = temp
|
||||||
|
daq_online = 2
|
||||||
|
else:
|
||||||
|
if daq_online > 0:
|
||||||
|
daq_online -= 1
|
||||||
|
loop_wait(1000)
|
||||||
|
gc.collect()
|
||||||
|
# print(gc.mem_free())
|
||||||
|
# pyb.info()
|
||||||
|
# print("gc collect")
|
||||||
|
# gc.collect()
|
||||||
|
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
motor_speed_set(0)
|
||||||
|
xray_pin.value(0)
|
||||||
|
daq_set_relay(False)
|
||||||
|
daq_set_sample(False)
|
||||||
|
print("测试结束")
|
||||||
|
run_flag = False
|
||||||
|
reset_flag = False
|
||||||
|
|
||||||
|
break
|
||||||
|
except CommandException:
|
||||||
|
print("cmd exception")
|
||||||
|
if reset_flag:
|
||||||
|
xray_pin.value(0)
|
||||||
|
daq_set_relay(False)
|
||||||
|
daq_set_sample(False)
|
||||||
|
motor_speed_set(0)
|
||||||
|
loop_wait(200)
|
||||||
|
move_to_bottom(5000)
|
||||||
|
loop_wait(200)
|
||||||
|
move_to_origin()
|
||||||
|
motor_state = ScannerState.STOP_AT_ORIGIN
|
||||||
|
print('back to origin')
|
||||||
|
reset_flag = False
|
||||||
|
update_status()
|
||||||
|
else:
|
||||||
|
if run_flag:
|
||||||
|
print(motor_state)
|
||||||
|
|
||||||
|
if motor_state == ScannerState.STOP_AT_ORIGIN:
|
||||||
|
if bottom_pos > 1:
|
||||||
|
print("move to bottom")
|
||||||
|
if move_to_pos(bottom_pos, 5000):
|
||||||
|
motor_state = ScannerState.STOP_AT_BOTTOM
|
||||||
|
loop_wait(300)
|
||||||
|
print("pos", motor_pos)
|
||||||
|
elif motor_pos < 1:
|
||||||
|
motor_state = ScannerState.STOP_AT_BOTTOM
|
||||||
|
elif motor_state == ScannerState.STOP:
|
||||||
|
if motor_pos > bottom_pos + 1:
|
||||||
|
move_to_bottom(5000)
|
||||||
|
if move_to_pos(bottom_pos, 5000):
|
||||||
|
motor_state = ScannerState.STOP_AT_BOTTOM
|
||||||
|
loop_wait(300)
|
||||||
|
else:
|
||||||
|
xray_pin.value(0)
|
||||||
|
daq_set_relay(False)
|
||||||
|
daq_set_sample(False)
|
||||||
|
motor_speed_set(0)
|
||||||
|
print('stop')
|
||||||
|
motor_state = ScannerState.STOP
|
||||||
|
update_status()
|
||||||
|
|
||||||
|
|
||||||
|
# 运行测试
|
||||||
|
if __name__ == "__main__":
|
||||||
|
scanner_loop()
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
|
||||||
|
"""
|
||||||
|
The MIT License (MIT)
|
||||||
|
Copyright © 2024 Jean-Christophe Bos (jczic.bos@gmail.com)
|
||||||
|
"""
|
||||||
|
|
||||||
|
print()
|
||||||
|
print(' -------------------------')
|
||||||
|
print(' - Python MicroWebSrv2 -')
|
||||||
|
print(' - version 2.1.0 -')
|
||||||
|
print(' - by JC`zic -')
|
||||||
|
print(' -------------------------')
|
||||||
|
print()
|
||||||
|
|
||||||
|
from .libs.XAsyncSockets import *
|
||||||
|
from .libs.urlUtils import *
|
||||||
|
from .webRoute import *
|
||||||
|
from .microWebSrv2 import *
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,5 @@
|
|||||||
|
rm /download/bootloader.bin
|
||||||
|
wget http://file.ofs.com/hv/bootloader.bin /download/bootloader.bin
|
||||||
|
fal probe bootloader
|
||||||
|
fal erase 0 0x40000
|
||||||
|
fal write 0 /download/bootloader.bin
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
rm /download/firmware.bin
|
||||||
|
wget http://file.ofs.com/hv/hv_firmware.bin /download/firmware.bin
|
||||||
|
fal probe ota
|
||||||
|
fal erase 0 0xC0000
|
||||||
|
fal write 0 /download/firmware.bin
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import _thread
|
||||||
|
import json
|
||||||
|
import gc
|
||||||
|
|
||||||
|
from script.umodbus.serial import ModbusRTU
|
||||||
|
|
||||||
|
uart_id = 4
|
||||||
|
|
||||||
|
slave_addr = 10 # address on bus as client
|
||||||
|
|
||||||
|
client = ModbusRTU(
|
||||||
|
addr=slave_addr, # address on bus
|
||||||
|
baudrate=115200, # optional, default 9600
|
||||||
|
# data_bits=8, # optional, default 8
|
||||||
|
# stop_bits=1, # optional, default 1
|
||||||
|
# parity=None, # optional, default None
|
||||||
|
# ctrl_pin=12, # optional, control DE/RE
|
||||||
|
uart_id=uart_id # optional, default 1, see port specific documentation
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
register_definitions = {
|
||||||
|
"COILS": {
|
||||||
|
"control": {
|
||||||
|
"register": 0,
|
||||||
|
"len": 10,
|
||||||
|
"val": [0,0,0,0,0,0,0,0,0,0],
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"HREGS": {
|
||||||
|
"params": {
|
||||||
|
"register": 0,
|
||||||
|
"len": 10,
|
||||||
|
"val": [0,0,0,0,0,0,0,0,0,0],
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ISTS": {
|
||||||
|
"status": {
|
||||||
|
"register": 0,
|
||||||
|
"len": 10,
|
||||||
|
"val": [0,0,0,0,0,0,0,0,0,0]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"IREGS": {
|
||||||
|
"input": {
|
||||||
|
"register": 0,
|
||||||
|
"len": 10,
|
||||||
|
"val": [0,0,0,0,0,0,0,0,0,0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# use the defined values of each register type provided by register_definitions
|
||||||
|
client.setup_registers(registers=register_definitions)
|
||||||
|
|
||||||
|
print(client)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
result = client.process()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print('KeyboardInterrupt, stopping RTU client...')
|
||||||
|
break
|
||||||
|
except Exception as e:
|
||||||
|
print('Exception during execution: {}'.format(e))
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
fal probe ota
|
||||||
|
fal erase 0 0xC0000
|
||||||
|
fal write 0 /download/firmware.bin
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: UTF-8 -*-
|
||||||
|
|
||||||
|
from .version import __version__
|
||||||
@@ -0,0 +1,392 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
#
|
||||||
|
# Copyright (c) 2019, Pycom Limited.
|
||||||
|
#
|
||||||
|
# This software is licensed under the GNU GPL version 3 or any
|
||||||
|
# later version, with permitted additional terms. For more information
|
||||||
|
# see the Pycom Licence v1.0 document supplied with this file, or
|
||||||
|
# available at https://www.pycom.io/opensource/licensing
|
||||||
|
#
|
||||||
|
|
||||||
|
# system packages
|
||||||
|
import struct
|
||||||
|
|
||||||
|
# custom packages
|
||||||
|
from . import const as Const
|
||||||
|
from . import functions
|
||||||
|
|
||||||
|
# typing not natively supported on MicroPython
|
||||||
|
from .typing import List, Optional, Tuple, Union
|
||||||
|
|
||||||
|
|
||||||
|
class Request(object):
|
||||||
|
"""Deconstruct request data received via TCP or Serial"""
|
||||||
|
def __init__(self, interface, data: bytearray) -> None:
|
||||||
|
self._itf = interface
|
||||||
|
self.unit_addr = data[0]
|
||||||
|
self.function, self.register_addr = struct.unpack_from('>BH', data, 1)
|
||||||
|
|
||||||
|
if self.function in [Const.READ_COILS, Const.READ_DISCRETE_INPUTS]:
|
||||||
|
self.quantity = struct.unpack_from('>H', data, 4)[0]
|
||||||
|
|
||||||
|
if self.quantity < 0x0001 or self.quantity > 0x07D0:
|
||||||
|
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||||
|
|
||||||
|
self.data = None
|
||||||
|
elif self.function in [Const.READ_HOLDING_REGISTERS, Const.READ_INPUT_REGISTER]:
|
||||||
|
self.quantity = struct.unpack_from('>H', data, 4)[0]
|
||||||
|
|
||||||
|
if self.quantity < 0x0001 or self.quantity > 0x007D:
|
||||||
|
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||||
|
|
||||||
|
self.data = None
|
||||||
|
elif self.function == Const.WRITE_SINGLE_COIL:
|
||||||
|
self.quantity = None
|
||||||
|
self.data = data[4:6]
|
||||||
|
|
||||||
|
# allowed values: 0x0000 or 0xFF00
|
||||||
|
if (self.data[0] not in [0x00, 0xFF]) or self.data[1] != 0x00:
|
||||||
|
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||||
|
elif self.function == Const.WRITE_SINGLE_REGISTER:
|
||||||
|
self.quantity = None
|
||||||
|
self.data = data[4:6]
|
||||||
|
# all values allowed
|
||||||
|
elif self.function == Const.WRITE_MULTIPLE_COILS:
|
||||||
|
self.quantity = struct.unpack_from('>H', data, 4)[0]
|
||||||
|
if self.quantity < 0x0001 or self.quantity > 0x07D0:
|
||||||
|
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||||
|
self.data = data[7:]
|
||||||
|
if len(self.data) != ((self.quantity - 1) // 8) + 1:
|
||||||
|
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||||
|
elif self.function == Const.WRITE_MULTIPLE_REGISTERS:
|
||||||
|
self.quantity = struct.unpack_from('>H', data, 4)[0]
|
||||||
|
if self.quantity < 0x0001 or self.quantity > 0x007B:
|
||||||
|
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||||
|
self.data = data[7:]
|
||||||
|
if len(self.data) != self.quantity * 2:
|
||||||
|
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||||
|
else:
|
||||||
|
# Not implemented functions
|
||||||
|
self.quantity = None
|
||||||
|
self.data = data[4:]
|
||||||
|
|
||||||
|
def send_response(self,
|
||||||
|
values: Optional[list] = None,
|
||||||
|
signed: bool = True) -> None:
|
||||||
|
"""
|
||||||
|
Send a response via the configured interface.
|
||||||
|
|
||||||
|
:param values: The values
|
||||||
|
:type values: Optional[list]
|
||||||
|
:param signed: Indicates if signed values are used
|
||||||
|
:type signed: bool
|
||||||
|
"""
|
||||||
|
self._itf.send_response(self.unit_addr,
|
||||||
|
self.function,
|
||||||
|
self.register_addr,
|
||||||
|
self.quantity,
|
||||||
|
self.data,
|
||||||
|
values,
|
||||||
|
signed)
|
||||||
|
|
||||||
|
def send_exception(self, exception_code: int) -> None:
|
||||||
|
"""
|
||||||
|
Send an exception response.
|
||||||
|
|
||||||
|
:param exception_code: The exception code
|
||||||
|
:type exception_code: int
|
||||||
|
"""
|
||||||
|
self._itf.send_exception_response(self.unit_addr,
|
||||||
|
self.function,
|
||||||
|
exception_code)
|
||||||
|
|
||||||
|
|
||||||
|
class ModbusException(Exception):
|
||||||
|
"""Exception for signaling modbus errors"""
|
||||||
|
def __init__(self, function_code: int, exception_code: int) -> None:
|
||||||
|
self.function_code = function_code
|
||||||
|
self.exception_code = exception_code
|
||||||
|
|
||||||
|
|
||||||
|
class CommonModbusFunctions(object):
|
||||||
|
"""Common Modbus functions"""
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def read_coils(self,
|
||||||
|
slave_addr: int,
|
||||||
|
starting_addr: int,
|
||||||
|
coil_qty: int) -> List[bool]:
|
||||||
|
"""
|
||||||
|
Read coils (COILS).
|
||||||
|
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param starting_addr: The coil starting address
|
||||||
|
:type starting_addr: int
|
||||||
|
:param coil_qty: The amount of coils to read
|
||||||
|
:type coil_qty: int
|
||||||
|
|
||||||
|
:returns: State of read coils as list
|
||||||
|
:rtype: List[bool]
|
||||||
|
"""
|
||||||
|
modbus_pdu = functions.read_coils(starting_address=starting_addr,
|
||||||
|
quantity=coil_qty)
|
||||||
|
|
||||||
|
response = self._send_receive(slave_addr=slave_addr,
|
||||||
|
modbus_pdu=modbus_pdu,
|
||||||
|
count=True)
|
||||||
|
|
||||||
|
status_pdu = functions.bytes_to_bool(byte_list=response,
|
||||||
|
bit_qty=coil_qty)
|
||||||
|
|
||||||
|
return status_pdu
|
||||||
|
|
||||||
|
def read_discrete_inputs(self,
|
||||||
|
slave_addr: int,
|
||||||
|
starting_addr: int,
|
||||||
|
input_qty: int) -> List[bool]:
|
||||||
|
"""
|
||||||
|
Read discrete inputs (ISTS).
|
||||||
|
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param starting_addr: The discrete input starting address
|
||||||
|
:type starting_addr: int
|
||||||
|
:param input_qty: The amount of discrete inputs to read
|
||||||
|
:type input_qty: int
|
||||||
|
|
||||||
|
:returns: State of read discrete inputs as list
|
||||||
|
:rtype: List[bool]
|
||||||
|
"""
|
||||||
|
modbus_pdu = functions.read_discrete_inputs(
|
||||||
|
starting_address=starting_addr,
|
||||||
|
quantity=input_qty)
|
||||||
|
|
||||||
|
response = self._send_receive(slave_addr=slave_addr,
|
||||||
|
modbus_pdu=modbus_pdu,
|
||||||
|
count=True)
|
||||||
|
|
||||||
|
status_pdu = functions.bytes_to_bool(byte_list=response,
|
||||||
|
bit_qty=input_qty)
|
||||||
|
|
||||||
|
return status_pdu
|
||||||
|
|
||||||
|
def read_holding_registers(self,
|
||||||
|
slave_addr: int,
|
||||||
|
starting_addr: int,
|
||||||
|
register_qty: int,
|
||||||
|
signed: bool = True) -> Tuple[int, ...]:
|
||||||
|
"""
|
||||||
|
Read holding registers (HREGS).
|
||||||
|
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param starting_addr: The holding register starting address
|
||||||
|
:type starting_addr: int
|
||||||
|
:param register_qty: The amount of holding registers to read
|
||||||
|
:type register_qty: int
|
||||||
|
:param signed: Indicates if signed
|
||||||
|
:type signed: bool
|
||||||
|
|
||||||
|
:returns: State of read holding register as tuple
|
||||||
|
:rtype: Tuple[int, ...]
|
||||||
|
"""
|
||||||
|
modbus_pdu = functions.read_holding_registers(
|
||||||
|
starting_address=starting_addr,
|
||||||
|
quantity=register_qty)
|
||||||
|
|
||||||
|
response = self._send_receive(slave_addr=slave_addr,
|
||||||
|
modbus_pdu=modbus_pdu,
|
||||||
|
count=True)
|
||||||
|
|
||||||
|
register_value = functions.to_short(byte_array=response, signed=signed)
|
||||||
|
|
||||||
|
return register_value
|
||||||
|
|
||||||
|
def read_input_registers(self,
|
||||||
|
slave_addr: int,
|
||||||
|
starting_addr: int,
|
||||||
|
register_qty: int,
|
||||||
|
signed: bool = True) -> Tuple[int, ...]:
|
||||||
|
"""
|
||||||
|
Read input registers (IREGS).
|
||||||
|
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param starting_addr: The input register starting address
|
||||||
|
:type starting_addr: int
|
||||||
|
:param register_qty: The amount of input registers to read
|
||||||
|
:type register_qty: int
|
||||||
|
:param signed: Indicates if signed
|
||||||
|
:type signed: bool
|
||||||
|
|
||||||
|
:returns: State of read input register as tuple
|
||||||
|
:rtype: Tuple[int, ...]
|
||||||
|
"""
|
||||||
|
modbus_pdu = functions.read_input_registers(
|
||||||
|
starting_address=starting_addr,
|
||||||
|
quantity=register_qty)
|
||||||
|
|
||||||
|
response = self._send_receive(slave_addr=slave_addr,
|
||||||
|
modbus_pdu=modbus_pdu,
|
||||||
|
count=True)
|
||||||
|
|
||||||
|
register_value = functions.to_short(byte_array=response, signed=signed)
|
||||||
|
|
||||||
|
return register_value
|
||||||
|
|
||||||
|
def write_single_coil(self,
|
||||||
|
slave_addr: int,
|
||||||
|
output_address: int,
|
||||||
|
output_value: Union[int, bool]) -> bool:
|
||||||
|
"""
|
||||||
|
Update a single coil.
|
||||||
|
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param output_address: The output address
|
||||||
|
:type output_address: int
|
||||||
|
:param output_value: The output value
|
||||||
|
:type output_value: Union[int, bool]
|
||||||
|
|
||||||
|
:returns: Result of operation
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
modbus_pdu = functions.write_single_coil(output_address=output_address,
|
||||||
|
output_value=output_value)
|
||||||
|
|
||||||
|
response = self._send_receive(slave_addr=slave_addr,
|
||||||
|
modbus_pdu=modbus_pdu,
|
||||||
|
count=False)
|
||||||
|
|
||||||
|
if response is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
operation_status = functions.validate_resp_data(
|
||||||
|
data=response,
|
||||||
|
function_code=Const.WRITE_SINGLE_COIL,
|
||||||
|
address=output_address,
|
||||||
|
value=output_value,
|
||||||
|
signed=False)
|
||||||
|
|
||||||
|
return operation_status
|
||||||
|
|
||||||
|
def write_single_register(self,
|
||||||
|
slave_addr: int,
|
||||||
|
register_address: int,
|
||||||
|
register_value: int,
|
||||||
|
signed: bool = True) -> bool:
|
||||||
|
"""
|
||||||
|
Update a single register.
|
||||||
|
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param register_address: The register address
|
||||||
|
:type register_address: int
|
||||||
|
:param register_value: The register value
|
||||||
|
:type register_value: int
|
||||||
|
:param signed: Indicates if signed
|
||||||
|
:type signed: bool
|
||||||
|
|
||||||
|
:returns: Result of operation
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
modbus_pdu = functions.write_single_register(
|
||||||
|
register_address=register_address,
|
||||||
|
register_value=register_value,
|
||||||
|
signed=signed)
|
||||||
|
|
||||||
|
response = self._send_receive(slave_addr=slave_addr,
|
||||||
|
modbus_pdu=modbus_pdu,
|
||||||
|
count=False)
|
||||||
|
|
||||||
|
if response is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
operation_status = functions.validate_resp_data(
|
||||||
|
data=response,
|
||||||
|
function_code=Const.WRITE_SINGLE_REGISTER,
|
||||||
|
address=register_address,
|
||||||
|
value=register_value,
|
||||||
|
signed=signed)
|
||||||
|
|
||||||
|
return operation_status
|
||||||
|
|
||||||
|
def write_multiple_coils(self,
|
||||||
|
slave_addr: int,
|
||||||
|
starting_address: int,
|
||||||
|
output_values: List[Union[int, bool]]) -> bool:
|
||||||
|
"""
|
||||||
|
Update multiple coils.
|
||||||
|
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param starting_address: The address of the first coil
|
||||||
|
:type starting_address: int
|
||||||
|
:param output_values: The output values
|
||||||
|
:type output_values: List[Union[int, bool]]
|
||||||
|
|
||||||
|
:returns: Result of operation
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
modbus_pdu = functions.write_multiple_coils(
|
||||||
|
starting_address=starting_address,
|
||||||
|
value_list=output_values)
|
||||||
|
|
||||||
|
response = self._send_receive(slave_addr=slave_addr,
|
||||||
|
modbus_pdu=modbus_pdu,
|
||||||
|
count=False)
|
||||||
|
|
||||||
|
if response is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
operation_status = functions.validate_resp_data(
|
||||||
|
data=response,
|
||||||
|
function_code=Const.WRITE_MULTIPLE_COILS,
|
||||||
|
address=starting_address,
|
||||||
|
quantity=len(output_values))
|
||||||
|
|
||||||
|
return operation_status
|
||||||
|
|
||||||
|
def write_multiple_registers(self,
|
||||||
|
slave_addr: int,
|
||||||
|
starting_address: int,
|
||||||
|
register_values: List[int],
|
||||||
|
signed: bool = True) -> bool:
|
||||||
|
"""
|
||||||
|
Update multiple registers.
|
||||||
|
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param starting_address: The starting address
|
||||||
|
:type starting_address: int
|
||||||
|
:param register_values: The register values
|
||||||
|
:type register_values: List[int]
|
||||||
|
:param signed: Indicates if signed
|
||||||
|
:type signed: bool
|
||||||
|
|
||||||
|
:returns: Result of operation
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
modbus_pdu = functions.write_multiple_registers(
|
||||||
|
starting_address=starting_address,
|
||||||
|
register_values=register_values,
|
||||||
|
signed=signed)
|
||||||
|
|
||||||
|
response = self._send_receive(slave_addr=slave_addr,
|
||||||
|
modbus_pdu=modbus_pdu,
|
||||||
|
count=False)
|
||||||
|
|
||||||
|
if response is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
operation_status = functions.validate_resp_data(
|
||||||
|
data=response,
|
||||||
|
function_code=Const.WRITE_MULTIPLE_REGISTERS,
|
||||||
|
address=starting_address,
|
||||||
|
quantity=len(register_values),
|
||||||
|
signed=signed
|
||||||
|
)
|
||||||
|
|
||||||
|
return operation_status
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
#
|
||||||
|
# Copyright (c) 2019, Pycom Limited.
|
||||||
|
#
|
||||||
|
# This software is licensed under the GNU GPL version 3 or any
|
||||||
|
# later version, with permitted additional terms. For more information
|
||||||
|
# see the Pycom Licence v1.0 document supplied with this file, or
|
||||||
|
# available at https://www.pycom.io/opensource/licensing
|
||||||
|
#
|
||||||
|
# Description summary taken from
|
||||||
|
# https://modbus.org/docs/Modbus_Application_Protocol_V1_1b3.pdf
|
||||||
|
|
||||||
|
from micropython import const
|
||||||
|
|
||||||
|
# function codes
|
||||||
|
# defined as const(), see https://github.com/micropython/micropython/issues/573
|
||||||
|
#: Read contiguous status of coils
|
||||||
|
READ_COILS = const(0x01) # COILS, [0, 1]
|
||||||
|
#: Read contiguous status of discrete inputs
|
||||||
|
READ_DISCRETE_INPUTS = const(0x02) # ISTS, [0, 1]
|
||||||
|
#: Read the contents of a contiguous block of holding registers
|
||||||
|
READ_HOLDING_REGISTERS = const(0x03) # HREGS, [0, 65535]
|
||||||
|
#: Read contiguous input registers
|
||||||
|
READ_INPUT_REGISTER = const(0x04) # IREGS, [0, 65535]
|
||||||
|
|
||||||
|
#: Write a single coil output status to ON or OFF
|
||||||
|
WRITE_SINGLE_COIL = const(0x05) # COILS, [0, 1]
|
||||||
|
#: Write a single holding register
|
||||||
|
WRITE_SINGLE_REGISTER = const(0x06) # HREGS, [0, 65535]
|
||||||
|
#: Force each coil in a sequence of coils to either ON or OFF
|
||||||
|
WRITE_MULTIPLE_COILS = const(0x0F) # COILS, [0, 1]
|
||||||
|
#: Write a block of contiguous registers
|
||||||
|
WRITE_MULTIPLE_REGISTERS = const(0x10) # HREGS, [0, 65535]
|
||||||
|
|
||||||
|
"""
|
||||||
|
Modify the contents of a specified holding register using a combination of an
|
||||||
|
AND mask, an OR mask, and the register's current contents
|
||||||
|
"""
|
||||||
|
MASK_WRITE_REGISTER = const(0x16)
|
||||||
|
"""
|
||||||
|
Perform a combination of one read operation and one write operation in a
|
||||||
|
single MODBUS transaction
|
||||||
|
"""
|
||||||
|
READ_WRITE_MULTIPLE_REGISTERS = const(0x17)
|
||||||
|
|
||||||
|
#: Read the contents of a First-In-First-Out (FIFO) queue of register
|
||||||
|
READ_FIFO_QUEUE = const(0x18)
|
||||||
|
|
||||||
|
#: Perform a file record read
|
||||||
|
READ_FILE_RECORD = const(0x14)
|
||||||
|
#: Perform a file record write
|
||||||
|
WRITE_FILE_RECORD = const(0x15)
|
||||||
|
|
||||||
|
#: Read the contents of eight Exception Status outputs
|
||||||
|
READ_EXCEPTION_STATUS = const(0x07)
|
||||||
|
#: Provide series of tests for checking the communication system (serial only)
|
||||||
|
DIAGNOSTICS = const(0x08)
|
||||||
|
#: Get status word and an event count from the remote device com event counter
|
||||||
|
GET_COM_EVENT_COUNTER = const(0x0B)
|
||||||
|
#: Get a status word, event count, message count, and a field of event bytes
|
||||||
|
GET_COM_EVENT_LOG = const(0x0C)
|
||||||
|
#: Read the description of the type, the current status, and other informations
|
||||||
|
REPORT_SERVER_ID = const(0x11)
|
||||||
|
#: Encapsulated Interface Transport
|
||||||
|
READ_DEVICE_IDENTIFICATION = const(0x2B)
|
||||||
|
|
||||||
|
# exception codes
|
||||||
|
#: Function code received in query is not an allowable action for the server
|
||||||
|
ILLEGAL_FUNCTION = const(0x01)
|
||||||
|
#: Data address received in query is not an allowable address for the server
|
||||||
|
ILLEGAL_DATA_ADDRESS = const(0x02)
|
||||||
|
#: A value contained in the query is not an allowable value for the server
|
||||||
|
ILLEGAL_DATA_VALUE = const(0x03)
|
||||||
|
"""
|
||||||
|
An unrecoverable error occurred while the server was attempting to perform the
|
||||||
|
requested action
|
||||||
|
"""
|
||||||
|
SERVER_DEVICE_FAILURE = const(0x04)
|
||||||
|
#: Response is returned to prevent a timeout error from occurring in the client
|
||||||
|
ACKNOWLEDGE = const(0x05)
|
||||||
|
#: Server is engaged in processing a long duration program command
|
||||||
|
SERVER_DEVICE_BUSY = const(0x06)
|
||||||
|
#: Server attempted to read record file, but detected a parity error in memory
|
||||||
|
MEMORY_PARITY_ERROR = const(0x08)
|
||||||
|
"""
|
||||||
|
Gateway was unable to allocate an internal communication path from the input
|
||||||
|
port to the output port for processing the request
|
||||||
|
"""
|
||||||
|
GATEWAY_PATH_UNAVAILABLE = const(0x0A)
|
||||||
|
#: No response was obtained from the target device
|
||||||
|
DEVICE_FAILED_TO_RESPOND = const(0x0B)
|
||||||
|
|
||||||
|
# Protocol Data Unit (PDU) constants
|
||||||
|
#: CRC length
|
||||||
|
CRC_LENGTH = const(0x02)
|
||||||
|
#: Error code offset
|
||||||
|
ERROR_BIAS = const(0x80)
|
||||||
|
#: High Data Response length
|
||||||
|
RESPONSE_HDR_LENGTH = const(0x02)
|
||||||
|
#: Error response length
|
||||||
|
ERROR_RESP_LEN = const(0x05)
|
||||||
|
#: Fixed response length
|
||||||
|
FIXED_RESP_LEN = const(0x08)
|
||||||
|
#: Modbus Application Protocol High Data Response length
|
||||||
|
MBAP_HDR_LENGTH = const(0x07)
|
||||||
|
|
||||||
|
#: CRC16 lookup table
|
||||||
|
CRC16_TABLE = (
|
||||||
|
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601,
|
||||||
|
0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01, 0x0CC0,
|
||||||
|
0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81,
|
||||||
|
0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941,
|
||||||
|
0x1B00, 0xDBC1, 0xDA81, 0x1A40, 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01,
|
||||||
|
0x1DC0, 0x1C80, 0xDC41, 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0,
|
||||||
|
0x1680, 0xD641, 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081,
|
||||||
|
0x1040, 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
|
||||||
|
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, 0x3C00,
|
||||||
|
0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, 0xFA01, 0x3AC0,
|
||||||
|
0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840, 0x2800, 0xE8C1, 0xE981,
|
||||||
|
0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, 0xEE01, 0x2EC0, 0x2F80, 0xEF41,
|
||||||
|
0x2D00, 0xEDC1, 0xEC81, 0x2C40, 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700,
|
||||||
|
0xE7C1, 0xE681, 0x2640, 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0,
|
||||||
|
0x2080, 0xE041, 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281,
|
||||||
|
0x6240, 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
|
||||||
|
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, 0xAA01,
|
||||||
|
0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840, 0x7800, 0xB8C1,
|
||||||
|
0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, 0xBE01, 0x7EC0, 0x7F80,
|
||||||
|
0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, 0xB401, 0x74C0, 0x7580, 0xB541,
|
||||||
|
0x7700, 0xB7C1, 0xB681, 0x7640, 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101,
|
||||||
|
0x71C0, 0x7080, 0xB041, 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0,
|
||||||
|
0x5280, 0x9241, 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481,
|
||||||
|
0x5440, 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
|
||||||
|
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, 0x8801,
|
||||||
|
0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, 0x4E00, 0x8EC1,
|
||||||
|
0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581,
|
||||||
|
0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 0x8201, 0x42C0, 0x4380, 0x8341,
|
||||||
|
0x4100, 0x81C1, 0x8081, 0x4040
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Code to generate the CRC-16 lookup table:
|
||||||
|
# def generate_crc16_table():
|
||||||
|
# crc_table = []
|
||||||
|
# for byte in range(256):
|
||||||
|
# crc = 0x0000
|
||||||
|
# for _ in range(8):
|
||||||
|
# if (byte ^ crc) & 0x0001:
|
||||||
|
# crc = (crc >> 1) ^ 0xa001
|
||||||
|
# else:
|
||||||
|
# crc >>= 1
|
||||||
|
# byte >>= 1
|
||||||
|
# crc_table.append(crc)
|
||||||
|
# return crc_table
|
||||||
@@ -0,0 +1,462 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
#
|
||||||
|
# Copyright (c) 2019, Pycom Limited.
|
||||||
|
#
|
||||||
|
# This software is licensed under the GNU GPL version 3 or any
|
||||||
|
# later version, with permitted additional terms. For more information
|
||||||
|
# see the Pycom Licence v1.0 document supplied with this file, or
|
||||||
|
# available at https://www.pycom.io/opensource/licensing
|
||||||
|
#
|
||||||
|
|
||||||
|
# system packages
|
||||||
|
import struct
|
||||||
|
|
||||||
|
# custom packages
|
||||||
|
from . import const as Const
|
||||||
|
|
||||||
|
# typing not natively supported on MicroPython
|
||||||
|
from .typing import List, Optional, Union
|
||||||
|
|
||||||
|
|
||||||
|
def read_coils(starting_address: int, quantity: int) -> bytes:
|
||||||
|
"""
|
||||||
|
Create Modbus Protocol Data Unit for reading coils.
|
||||||
|
|
||||||
|
:param starting_address: The starting address
|
||||||
|
:type starting_address: int
|
||||||
|
:param quantity: Quantity of coils
|
||||||
|
:type quantity: int
|
||||||
|
|
||||||
|
:returns: Packed Modbus message
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
if not (1 <= quantity <= 2000):
|
||||||
|
raise ValueError('Invalid number of coils')
|
||||||
|
|
||||||
|
return struct.pack('>BHH', Const.READ_COILS, starting_address, quantity)
|
||||||
|
|
||||||
|
|
||||||
|
def read_discrete_inputs(starting_address: int, quantity: int) -> bytes:
|
||||||
|
"""
|
||||||
|
Create Modbus Protocol Data Unit for reading discrete inputs.
|
||||||
|
|
||||||
|
:param starting_address: The starting address
|
||||||
|
:type starting_address: int
|
||||||
|
:param quantity: Quantity of coils
|
||||||
|
:type quantity: int
|
||||||
|
|
||||||
|
:returns: Packed Modbus message
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
if not (1 <= quantity <= 2000):
|
||||||
|
raise ValueError('Invalid number of discrete inputs')
|
||||||
|
|
||||||
|
return struct.pack('>BHH',
|
||||||
|
Const.READ_DISCRETE_INPUTS,
|
||||||
|
starting_address,
|
||||||
|
quantity)
|
||||||
|
|
||||||
|
|
||||||
|
def read_holding_registers(starting_address: int, quantity: int) -> bytes:
|
||||||
|
"""
|
||||||
|
Create Modbus Protocol Data Unit for reading holding registers.
|
||||||
|
|
||||||
|
:param starting_address: The starting address
|
||||||
|
:type starting_address: int
|
||||||
|
:param quantity: Quantity of coils
|
||||||
|
:type quantity: int
|
||||||
|
|
||||||
|
:returns: Packed Modbus message
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
if not (1 <= quantity <= 125):
|
||||||
|
raise ValueError('Invalid number of holding registers')
|
||||||
|
|
||||||
|
return struct.pack('>BHH',
|
||||||
|
Const.READ_HOLDING_REGISTERS,
|
||||||
|
starting_address,
|
||||||
|
quantity)
|
||||||
|
|
||||||
|
|
||||||
|
def read_input_registers(starting_address: int, quantity: int) -> bytes:
|
||||||
|
"""
|
||||||
|
Create Modbus Protocol Data Unit for reading input registers.
|
||||||
|
|
||||||
|
:param starting_address: The starting address
|
||||||
|
:type starting_address: int
|
||||||
|
:param quantity: Quantity of coils
|
||||||
|
:type quantity: int
|
||||||
|
|
||||||
|
:returns: Packed Modbus message
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
if not (1 <= quantity <= 125):
|
||||||
|
raise ValueError('Invalid number of input registers')
|
||||||
|
|
||||||
|
return struct.pack('>BHH',
|
||||||
|
Const.READ_INPUT_REGISTER,
|
||||||
|
starting_address,
|
||||||
|
quantity)
|
||||||
|
|
||||||
|
|
||||||
|
def write_single_coil(output_address: int,
|
||||||
|
output_value: Union[int, bool]) -> bytes:
|
||||||
|
"""
|
||||||
|
Create Modbus message to update single coil
|
||||||
|
|
||||||
|
:param output_address: The output address
|
||||||
|
:type output_address: int
|
||||||
|
:param output_value: The output value
|
||||||
|
:type output_value: Union[int, bool]
|
||||||
|
|
||||||
|
:returns: Packed Modbus message
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
if output_value not in [0x0000, 0xFF00, False, True, 0, 1]:
|
||||||
|
raise ValueError('Illegal coil value')
|
||||||
|
|
||||||
|
if output_value not in [0x0000, 0xFF00]:
|
||||||
|
if output_value:
|
||||||
|
output_value = 0xFF00
|
||||||
|
else:
|
||||||
|
output_value = 0x0000
|
||||||
|
|
||||||
|
return struct.pack('>BHH',
|
||||||
|
Const.WRITE_SINGLE_COIL,
|
||||||
|
output_address,
|
||||||
|
output_value)
|
||||||
|
|
||||||
|
|
||||||
|
def write_single_register(register_address: int,
|
||||||
|
register_value: int,
|
||||||
|
signed: bool = True) -> bytes:
|
||||||
|
"""
|
||||||
|
Create Modbus message to writes a single register
|
||||||
|
|
||||||
|
:param register_address: The register address
|
||||||
|
:type register_address: int
|
||||||
|
:param register_value: The register value
|
||||||
|
:type register_value: int
|
||||||
|
:param signed: Flag whether data is signed or not
|
||||||
|
:type signed: bool
|
||||||
|
|
||||||
|
:returns: Packed Modbus message
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
fmt = 'h' if signed else 'H'
|
||||||
|
|
||||||
|
return struct.pack('>BH' + fmt,
|
||||||
|
Const.WRITE_SINGLE_REGISTER,
|
||||||
|
register_address,
|
||||||
|
register_value)
|
||||||
|
|
||||||
|
|
||||||
|
def write_multiple_coils(starting_address: int,
|
||||||
|
value_list: List[Union[int, bool]]) -> bytes:
|
||||||
|
"""
|
||||||
|
Create Modbus message to update multiple coils
|
||||||
|
|
||||||
|
:param starting_address: The starting address
|
||||||
|
:type starting_address: int
|
||||||
|
:param value_list: The list of output values
|
||||||
|
:type value_list: List[Union[int, bool]]
|
||||||
|
|
||||||
|
:returns: Packed Modbus message
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
if not (1 <= len(value_list) <= 0x07B0):
|
||||||
|
raise ValueError('Invalid quantity of outputs')
|
||||||
|
|
||||||
|
sectioned_list = [value_list[i:i + 8] for i in range(0, len(value_list), 8)] # noqa: E501
|
||||||
|
|
||||||
|
output_value = []
|
||||||
|
for index, byte in enumerate(sectioned_list):
|
||||||
|
# see https://github.com/brainelectronics/micropython-modbus/issues/22
|
||||||
|
# output = sum(v << i for i, v in enumerate(byte))
|
||||||
|
output = 0
|
||||||
|
for bit in byte:
|
||||||
|
output = (output << 1) | bit
|
||||||
|
output_value.append(output)
|
||||||
|
|
||||||
|
fmt = 'B' * len(output_value)
|
||||||
|
quantity = len(value_list)
|
||||||
|
byte_count = quantity // 8
|
||||||
|
if quantity % 8:
|
||||||
|
byte_count += 1
|
||||||
|
|
||||||
|
return struct.pack('>BHHB' + fmt,
|
||||||
|
Const.WRITE_MULTIPLE_COILS,
|
||||||
|
starting_address,
|
||||||
|
quantity,
|
||||||
|
byte_count,
|
||||||
|
*output_value)
|
||||||
|
|
||||||
|
|
||||||
|
def write_multiple_registers(starting_address: int,
|
||||||
|
register_values: List[int],
|
||||||
|
signed: bool = True) -> bytes:
|
||||||
|
"""
|
||||||
|
Create Modbus message to update multiple coils
|
||||||
|
|
||||||
|
:param starting_address: The starting address
|
||||||
|
:type starting_address: int
|
||||||
|
:param register_values: The list of output value
|
||||||
|
:type register_values: List[int, bool]
|
||||||
|
:param signed: Flag whether data is signed or not
|
||||||
|
:type signed: bool
|
||||||
|
|
||||||
|
:returns: Packed Modbus message
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
if not (1 <= len(register_values) <= 123):
|
||||||
|
raise ValueError('Invalid number of registers')
|
||||||
|
|
||||||
|
quantity = len(register_values)
|
||||||
|
byte_count = quantity * 2
|
||||||
|
fmt = ('h' if signed else 'H') * quantity
|
||||||
|
|
||||||
|
return struct.pack('>BHHB' + fmt,
|
||||||
|
Const.WRITE_MULTIPLE_REGISTERS,
|
||||||
|
starting_address,
|
||||||
|
quantity,
|
||||||
|
byte_count,
|
||||||
|
*register_values)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_resp_data(data: bytes,
|
||||||
|
function_code: int,
|
||||||
|
address: int,
|
||||||
|
value: int = None,
|
||||||
|
quantity: int = None,
|
||||||
|
signed: bool = True) -> bool:
|
||||||
|
"""
|
||||||
|
Validate the response data.
|
||||||
|
|
||||||
|
:param data: The data
|
||||||
|
:type data: bytes
|
||||||
|
:param function_code: The function code
|
||||||
|
:type function_code: int
|
||||||
|
:param address: The address
|
||||||
|
:type address: int
|
||||||
|
:param value: The value
|
||||||
|
:type value: int
|
||||||
|
:param quantity: The quantity
|
||||||
|
:type quantity: int
|
||||||
|
:param signed: Indicates if signed
|
||||||
|
:type signed: bool
|
||||||
|
|
||||||
|
:returns: True if valid, False otherwise
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
fmt = '>H' + ('h' if signed else 'H')
|
||||||
|
|
||||||
|
if function_code in [Const.WRITE_SINGLE_COIL, Const.WRITE_SINGLE_REGISTER]:
|
||||||
|
resp_addr, resp_value = struct.unpack(fmt, data)
|
||||||
|
|
||||||
|
# if bool(True) or int(1) is used as "output_value" of
|
||||||
|
# "write_single_coil" it will be internally converted to int(0xFF00),
|
||||||
|
# see Modbus specification, which is actually int(65280).
|
||||||
|
# Due to the non binary, but real value comparison of "value" and
|
||||||
|
# "resp_value", it would never match without the next two lines
|
||||||
|
# see #21
|
||||||
|
if function_code == Const.WRITE_SINGLE_COIL:
|
||||||
|
resp_value = bool(resp_value)
|
||||||
|
value = bool(value)
|
||||||
|
|
||||||
|
if (address == resp_addr) and (value == resp_value):
|
||||||
|
return True
|
||||||
|
elif function_code in [Const.WRITE_MULTIPLE_COILS,
|
||||||
|
Const.WRITE_MULTIPLE_REGISTERS]:
|
||||||
|
resp_addr, resp_qty = struct.unpack(fmt, data)
|
||||||
|
|
||||||
|
if (address == resp_addr) and (quantity == resp_qty):
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def response(function_code: int,
|
||||||
|
request_register_addr: int,
|
||||||
|
request_register_qty: int,
|
||||||
|
request_data: list,
|
||||||
|
value_list: Optional[list] = None,
|
||||||
|
signed: bool = True) -> bytes:
|
||||||
|
"""
|
||||||
|
Construct a Modbus response Protocol Data Unit
|
||||||
|
|
||||||
|
:param function_code: The function code
|
||||||
|
:type function_code: int
|
||||||
|
:param request_register_addr: The request register address
|
||||||
|
:type request_register_addr: int
|
||||||
|
:param request_register_qty: The request register qty
|
||||||
|
:type request_register_qty: int
|
||||||
|
:param request_data: The request data
|
||||||
|
:type request_data: list
|
||||||
|
:param value_list: The values
|
||||||
|
:type value_list: Optional[list]
|
||||||
|
:param signed: Indicates if signed
|
||||||
|
:type signed: bool
|
||||||
|
|
||||||
|
:returns: Protocol data unit
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
if function_code in [Const.READ_COILS, Const.READ_DISCRETE_INPUTS]:
|
||||||
|
sectioned_list = [value_list[i:i + 8] for i in range(0, len(value_list), 8)] # noqa: E501
|
||||||
|
|
||||||
|
output_value = []
|
||||||
|
for index, byte in enumerate(sectioned_list):
|
||||||
|
# see https://github.com/brainelectronics/micropython-modbus/issues/22
|
||||||
|
# output = sum(v << i for i, v in enumerate(byte))
|
||||||
|
# see https://github.com/brainelectronics/micropython-modbus/issues/38
|
||||||
|
output = 0
|
||||||
|
for bit in byte:
|
||||||
|
output = (output << 1) | bit
|
||||||
|
output_value.append(output)
|
||||||
|
|
||||||
|
fmt = 'B' * len(output_value)
|
||||||
|
return struct.pack('>BB' + fmt,
|
||||||
|
function_code,
|
||||||
|
((len(value_list) - 1) // 8) + 1,
|
||||||
|
*output_value)
|
||||||
|
|
||||||
|
elif function_code in [Const.READ_HOLDING_REGISTERS,
|
||||||
|
Const.READ_INPUT_REGISTER]:
|
||||||
|
quantity = len(value_list)
|
||||||
|
|
||||||
|
if not (0x0001 <= quantity <= 0x007D):
|
||||||
|
raise ValueError('invalid number of registers')
|
||||||
|
|
||||||
|
if signed is True or signed is False:
|
||||||
|
fmt = ('h' if signed else 'H') * quantity
|
||||||
|
else:
|
||||||
|
fmt = ''
|
||||||
|
for s in signed:
|
||||||
|
fmt += 'h' if s else 'H'
|
||||||
|
|
||||||
|
return struct.pack('>BB' + fmt,
|
||||||
|
function_code,
|
||||||
|
quantity * 2,
|
||||||
|
*value_list)
|
||||||
|
|
||||||
|
elif function_code in [Const.WRITE_SINGLE_COIL,
|
||||||
|
Const.WRITE_SINGLE_REGISTER]:
|
||||||
|
return struct.pack('>BHBB',
|
||||||
|
function_code,
|
||||||
|
request_register_addr,
|
||||||
|
*request_data)
|
||||||
|
|
||||||
|
elif function_code in [Const.WRITE_MULTIPLE_COILS,
|
||||||
|
Const.WRITE_MULTIPLE_REGISTERS]:
|
||||||
|
return struct.pack('>BHH',
|
||||||
|
function_code,
|
||||||
|
request_register_addr,
|
||||||
|
request_register_qty)
|
||||||
|
|
||||||
|
|
||||||
|
def exception_response(function_code: int, exception_code: int) -> bytes:
|
||||||
|
"""
|
||||||
|
Create Modbus exception response
|
||||||
|
|
||||||
|
:param function_code: The function code
|
||||||
|
:type function_code: int
|
||||||
|
:param exception_code: The exception code
|
||||||
|
:type exception_code: int
|
||||||
|
|
||||||
|
:returns: Packed Modbus message
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
return struct.pack('>BB', Const.ERROR_BIAS + function_code, exception_code)
|
||||||
|
|
||||||
|
|
||||||
|
def bytes_to_bool(byte_list: bytes, bit_qty: Optional[int] = 1) -> List[bool]:
|
||||||
|
"""
|
||||||
|
Convert bytes to list of boolean values
|
||||||
|
|
||||||
|
:param byte_list: The byte list
|
||||||
|
:type byte_list: bytes
|
||||||
|
:param bit_qty: Amount of bits received
|
||||||
|
:type bit_qty: Optional[int]
|
||||||
|
|
||||||
|
:returns: Boolean representation
|
||||||
|
:rtype: List[bool]
|
||||||
|
"""
|
||||||
|
bool_list = []
|
||||||
|
|
||||||
|
for index, byte in enumerate(byte_list):
|
||||||
|
this_qty = bit_qty
|
||||||
|
|
||||||
|
if this_qty >= 8:
|
||||||
|
this_qty = 8
|
||||||
|
|
||||||
|
# evil hack for missing keyword support in MicroPython format()
|
||||||
|
fmt = '{:0' + str(this_qty) + 'b}'
|
||||||
|
|
||||||
|
bool_list.extend([bool(int(x)) for x in fmt.format(byte)])
|
||||||
|
|
||||||
|
bit_qty -= 8
|
||||||
|
|
||||||
|
return bool_list
|
||||||
|
|
||||||
|
|
||||||
|
def to_short(byte_array: bytes, signed: bool = True) -> bytes:
|
||||||
|
"""
|
||||||
|
Convert bytes to tuple of integer values
|
||||||
|
|
||||||
|
:param byte_array: The byte array
|
||||||
|
:type byte_array: bytes
|
||||||
|
:param signed: Indicates if signed
|
||||||
|
:type signed: bool
|
||||||
|
|
||||||
|
:returns: Integer representation
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
response_quantity = int(len(byte_array) / 2)
|
||||||
|
fmt = '>' + (('h' if signed else 'H') * response_quantity)
|
||||||
|
|
||||||
|
return struct.unpack(fmt, byte_array)
|
||||||
|
|
||||||
|
|
||||||
|
def float_to_bin(num: float) -> bin:
|
||||||
|
"""
|
||||||
|
Convert floating point value to binary
|
||||||
|
|
||||||
|
See IEEE 754
|
||||||
|
|
||||||
|
:param num: The number
|
||||||
|
:type num: float
|
||||||
|
|
||||||
|
:returns: Binary representation
|
||||||
|
:rtype: bin
|
||||||
|
"""
|
||||||
|
# no "zfill" available in MicroPython
|
||||||
|
# return bin(struct.unpack('!I', struct.pack('!f', num))[0])[2:].zfill(32)
|
||||||
|
|
||||||
|
return '{:0>{w}}'.format(
|
||||||
|
bin(struct.unpack('!I', struct.pack('!f', num))[0])[2:],
|
||||||
|
w=32)
|
||||||
|
|
||||||
|
|
||||||
|
def bin_to_float(binary: str) -> float:
|
||||||
|
"""
|
||||||
|
Convert binary string to floating point value
|
||||||
|
|
||||||
|
:param binary: The binary string
|
||||||
|
:type binary: str
|
||||||
|
|
||||||
|
:returns: Converted floating point value
|
||||||
|
:rtype: float
|
||||||
|
"""
|
||||||
|
return struct.unpack('!f', struct.pack('!I', int(binary, 2)))[0]
|
||||||
|
|
||||||
|
|
||||||
|
def int_to_bin(num: int) -> str:
|
||||||
|
"""
|
||||||
|
Convert integer to binary
|
||||||
|
|
||||||
|
:param num: The number
|
||||||
|
:type num: int
|
||||||
|
|
||||||
|
:returns: Binary representation of given input
|
||||||
|
:rtype: str
|
||||||
|
"""
|
||||||
|
return "{0:b}".format(num)
|
||||||
@@ -0,0 +1,873 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: UTF-8 -*-
|
||||||
|
|
||||||
|
"""
|
||||||
|
Modbus register abstraction class
|
||||||
|
|
||||||
|
Used to add, remove, set and get values or states of a register or coil.
|
||||||
|
Additional helper properties and functions like getters for changed registers
|
||||||
|
are available as well.
|
||||||
|
|
||||||
|
This class is inherited by the Modbus client implementations
|
||||||
|
:py:class:`umodbus.serial.ModbusRTU` and :py:class:`umodbus.tcp.ModbusTCP`
|
||||||
|
"""
|
||||||
|
|
||||||
|
# system packages
|
||||||
|
import time
|
||||||
|
|
||||||
|
# custom packages
|
||||||
|
from . import functions
|
||||||
|
from . import const as Const
|
||||||
|
from .common import Request
|
||||||
|
|
||||||
|
# typing not natively supported on MicroPython
|
||||||
|
from .typing import Callable, dict_keys, List, Optional, Union
|
||||||
|
|
||||||
|
|
||||||
|
class Modbus(object):
|
||||||
|
"""
|
||||||
|
Modbus register abstraction
|
||||||
|
|
||||||
|
:param itf: Abstraction interface
|
||||||
|
:type itf: Callable
|
||||||
|
:param addr_list: List of addresses
|
||||||
|
:type addr_list: List[int]
|
||||||
|
"""
|
||||||
|
def __init__(self, itf, addr_list: List[int]) -> None:
|
||||||
|
self._itf = itf
|
||||||
|
self._addr_list = addr_list
|
||||||
|
|
||||||
|
# modbus register types with their default value
|
||||||
|
self._available_register_types = ['COILS', 'HREGS', 'IREGS', 'ISTS']
|
||||||
|
self._register_dict = dict()
|
||||||
|
for reg_type in self._available_register_types:
|
||||||
|
self._register_dict[reg_type] = dict()
|
||||||
|
self._default_vals = dict(zip(self._available_register_types,
|
||||||
|
[False, 0, 0, False]))
|
||||||
|
|
||||||
|
# registers which can be set by remote device
|
||||||
|
self._changeable_register_types = ['COILS', 'HREGS']
|
||||||
|
self._changed_registers = dict()
|
||||||
|
for reg_type in self._changeable_register_types:
|
||||||
|
self._changed_registers[reg_type] = dict()
|
||||||
|
|
||||||
|
def process(self) -> bool:
|
||||||
|
"""
|
||||||
|
Process the Modbus requests.
|
||||||
|
|
||||||
|
:returns: Result of processing, True on success, False otherwise
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
reg_type = None
|
||||||
|
req_type = None
|
||||||
|
|
||||||
|
request = self._itf.get_request(unit_addr_list=self._addr_list,
|
||||||
|
timeout=0)
|
||||||
|
if request is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
if request.function == Const.READ_COILS:
|
||||||
|
# Coils (setter+getter) [0, 1]
|
||||||
|
# function 01 - read single register
|
||||||
|
reg_type = 'COILS'
|
||||||
|
req_type = 'READ'
|
||||||
|
elif request.function == Const.READ_DISCRETE_INPUTS:
|
||||||
|
# Ists (only getter) [0, 1]
|
||||||
|
# function 02 - read input status (discrete inputs/digital input)
|
||||||
|
reg_type = 'ISTS'
|
||||||
|
req_type = 'READ'
|
||||||
|
elif request.function == Const.READ_HOLDING_REGISTERS:
|
||||||
|
# Hregs (setter+getter) [0, 65535]
|
||||||
|
# function 03 - read holding register
|
||||||
|
reg_type = 'HREGS'
|
||||||
|
req_type = 'READ'
|
||||||
|
elif request.function == Const.READ_INPUT_REGISTER:
|
||||||
|
# Iregs (only getter) [0, 65535]
|
||||||
|
# function 04 - read input registers
|
||||||
|
reg_type = 'IREGS'
|
||||||
|
req_type = 'READ'
|
||||||
|
elif (request.function == Const.WRITE_SINGLE_COIL or
|
||||||
|
request.function == Const.WRITE_MULTIPLE_COILS):
|
||||||
|
# Coils (setter+getter) [0, 1]
|
||||||
|
# function 05 - write single coil
|
||||||
|
# function 15 - write multiple coil
|
||||||
|
reg_type = 'COILS'
|
||||||
|
req_type = 'WRITE'
|
||||||
|
elif (request.function == Const.WRITE_SINGLE_REGISTER or
|
||||||
|
request.function == Const.WRITE_MULTIPLE_REGISTERS):
|
||||||
|
# Hregs (setter+getter) [0, 65535]
|
||||||
|
# function 06 - write holding register
|
||||||
|
# function 16 - write multiple holding register
|
||||||
|
reg_type = 'HREGS'
|
||||||
|
req_type = 'WRITE'
|
||||||
|
else:
|
||||||
|
request.send_exception(Const.ILLEGAL_FUNCTION)
|
||||||
|
|
||||||
|
if reg_type:
|
||||||
|
if req_type == 'READ':
|
||||||
|
self._process_read_access(request=request, reg_type=reg_type)
|
||||||
|
elif req_type == 'WRITE':
|
||||||
|
self._process_write_access(request=request, reg_type=reg_type)
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _create_response(self,
|
||||||
|
request: Request,
|
||||||
|
reg_type: str) -> Union[List[bool], List[int]]:
|
||||||
|
"""
|
||||||
|
Create a response.
|
||||||
|
|
||||||
|
:param request: The request
|
||||||
|
:type request: Request
|
||||||
|
:param reg_type: The register type
|
||||||
|
:type reg_type: str
|
||||||
|
|
||||||
|
:returns: Values of this register
|
||||||
|
:rtype: Union[List[bool], List[int]]
|
||||||
|
"""
|
||||||
|
data = []
|
||||||
|
default_value = {'val': 0}
|
||||||
|
reg_dict = self._register_dict[reg_type]
|
||||||
|
|
||||||
|
if reg_type in ['COILS', 'ISTS']:
|
||||||
|
default_value = {'val': False}
|
||||||
|
|
||||||
|
for addr in range(request.register_addr,
|
||||||
|
request.register_addr + request.quantity):
|
||||||
|
value = reg_dict.get(addr, default_value)['val']
|
||||||
|
|
||||||
|
if isinstance(value, (list, tuple)):
|
||||||
|
data.extend(value)
|
||||||
|
else:
|
||||||
|
data.append(value)
|
||||||
|
|
||||||
|
# caution LSB vs MSB
|
||||||
|
# [
|
||||||
|
# 1, 0, 1, 1, 0, 0, 1, 1, # 0xB3
|
||||||
|
# 1, 1, 0, 1, 0, 1, 1, 0, # 0xD6
|
||||||
|
# 1, 0, 1 # 0x5
|
||||||
|
# ]
|
||||||
|
# but should be, documented at #38, see
|
||||||
|
# https://github.com/brainelectronics/micropython-modbus/issues/38
|
||||||
|
# this is only an issue of data provisioning as client/slave,
|
||||||
|
# it has thereby NOT to be fixed in
|
||||||
|
# :py:function:`umodbus.functions.bytes_to_bool`
|
||||||
|
# [
|
||||||
|
# 1, 1, 0, 0, 1, 1, 0, 1, # 0xCD
|
||||||
|
# 0, 1, 1, 0, 1, 0, 1, 1, # 0x6B
|
||||||
|
# 1, 0, 1 # 0x5
|
||||||
|
# ]
|
||||||
|
# 27 .... 20
|
||||||
|
# CD 1100 1101
|
||||||
|
#
|
||||||
|
# 35 .... 28
|
||||||
|
# 6B 0110 1011
|
||||||
|
#
|
||||||
|
# 43 .... 36
|
||||||
|
# 05 0000 0101
|
||||||
|
#
|
||||||
|
# 1011 0011 1101 0110 1010 0000
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
def _process_read_access(self, request: Request, reg_type: str) -> None:
|
||||||
|
"""
|
||||||
|
Process read access to register
|
||||||
|
|
||||||
|
:param request: The request
|
||||||
|
:type request: Request
|
||||||
|
:param reg_type: The register type
|
||||||
|
:type reg_type: str
|
||||||
|
"""
|
||||||
|
address = request.register_addr
|
||||||
|
|
||||||
|
if address in self._register_dict[reg_type]:
|
||||||
|
|
||||||
|
if self._register_dict[reg_type][address].get('on_get_cb', 0):
|
||||||
|
vals = self._create_response(request=request,
|
||||||
|
reg_type=reg_type)
|
||||||
|
_cb = self._register_dict[reg_type][address]['on_get_cb']
|
||||||
|
_cb(reg_type=reg_type, address=address, val=vals)
|
||||||
|
|
||||||
|
vals = self._create_response(request=request, reg_type=reg_type)
|
||||||
|
request.send_response(vals)
|
||||||
|
else:
|
||||||
|
request.send_exception(Const.ILLEGAL_DATA_ADDRESS)
|
||||||
|
|
||||||
|
def _process_write_access(self, request: Request, reg_type: str) -> None:
|
||||||
|
"""
|
||||||
|
Process write access to register
|
||||||
|
|
||||||
|
:param request: The request
|
||||||
|
:type request: Request
|
||||||
|
:param reg_type: The register type
|
||||||
|
:type reg_type: str
|
||||||
|
"""
|
||||||
|
address = request.register_addr
|
||||||
|
val = 0
|
||||||
|
valid_register = False
|
||||||
|
|
||||||
|
if address in self._register_dict[reg_type]:
|
||||||
|
if request.data is None:
|
||||||
|
request.send_exception(Const.ILLEGAL_DATA_VALUE)
|
||||||
|
return
|
||||||
|
|
||||||
|
if reg_type == 'COILS':
|
||||||
|
valid_register = True
|
||||||
|
|
||||||
|
if request.function == Const.WRITE_SINGLE_COIL:
|
||||||
|
val = request.data[0]
|
||||||
|
if 0x00 < val < 0xFF:
|
||||||
|
valid_register = False
|
||||||
|
request.send_exception(Const.ILLEGAL_DATA_VALUE)
|
||||||
|
else:
|
||||||
|
val = [(val == 0xFF)]
|
||||||
|
elif request.function == Const.WRITE_MULTIPLE_COILS:
|
||||||
|
tmp = int.from_bytes(request.data, "big")
|
||||||
|
val = [
|
||||||
|
bool(tmp & (1 << n)) for n in range(request.quantity)
|
||||||
|
]
|
||||||
|
|
||||||
|
if valid_register:
|
||||||
|
self.set_coil(address=address, value=val)
|
||||||
|
elif reg_type == 'HREGS':
|
||||||
|
valid_register = True
|
||||||
|
val = list(functions.to_short(byte_array=request.data,
|
||||||
|
signed=False))
|
||||||
|
|
||||||
|
if request.function in [Const.WRITE_SINGLE_REGISTER,
|
||||||
|
Const.WRITE_MULTIPLE_REGISTERS]:
|
||||||
|
self.set_hreg(address=address, value=val)
|
||||||
|
else:
|
||||||
|
# nothing except holding registers or coils can be set
|
||||||
|
request.send_exception(Const.ILLEGAL_FUNCTION)
|
||||||
|
|
||||||
|
if valid_register:
|
||||||
|
request.send_response()
|
||||||
|
self._set_changed_register(reg_type=reg_type,
|
||||||
|
address=address,
|
||||||
|
value=val)
|
||||||
|
if self._register_dict[reg_type][address].get('on_set_cb', 0):
|
||||||
|
_cb = self._register_dict[reg_type][address]['on_set_cb']
|
||||||
|
_cb(reg_type=reg_type, address=address, val=val)
|
||||||
|
else:
|
||||||
|
request.send_exception(Const.ILLEGAL_DATA_ADDRESS)
|
||||||
|
|
||||||
|
def add_coil(self,
|
||||||
|
address: int,
|
||||||
|
value: Union[bool, List[bool]] = False,
|
||||||
|
on_set_cb: Callable[[str, int, Union[List[bool], List[int]]],
|
||||||
|
None] = None,
|
||||||
|
on_get_cb: Callable[[str, int, Union[List[bool], List[int]]],
|
||||||
|
None] = None) -> None:
|
||||||
|
"""
|
||||||
|
Add a coil to the modbus register dictionary.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
:param value: The default value
|
||||||
|
:type value: Union[bool, List[bool]], optional
|
||||||
|
:param on_set_cb: Callback on setting the coil
|
||||||
|
:type on_set_cb: Callable[
|
||||||
|
[str, int, Union[List[bool], List[int]]],
|
||||||
|
None
|
||||||
|
]
|
||||||
|
:param on_get_cb: Callback on getting the coil
|
||||||
|
:type on_get_cb: Callable[
|
||||||
|
[str, int, Union[List[bool], List[int]]],
|
||||||
|
None
|
||||||
|
]
|
||||||
|
"""
|
||||||
|
self._set_reg_in_dict(reg_type='COILS',
|
||||||
|
address=address,
|
||||||
|
value=value,
|
||||||
|
on_set_cb=on_set_cb,
|
||||||
|
on_get_cb=on_get_cb)
|
||||||
|
|
||||||
|
def remove_coil(self, address: int) -> Union[None, bool, List[bool]]:
|
||||||
|
"""
|
||||||
|
Remove a coil from the modbus register dictionary.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
|
||||||
|
:returns: Register value, None if register did not exist in dict
|
||||||
|
:rtype: Union[None, bool, List[bool]]
|
||||||
|
"""
|
||||||
|
return self._remove_reg_from_dict(reg_type='COILS', address=address)
|
||||||
|
|
||||||
|
def set_coil(self,
|
||||||
|
address: int,
|
||||||
|
value: Union[bool, List[bool]] = False) -> None:
|
||||||
|
"""
|
||||||
|
Set the coil value.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
:param value: The default value
|
||||||
|
:type value: Union[bool, List[bool]], optional
|
||||||
|
"""
|
||||||
|
self._set_reg_in_dict(reg_type='COILS',
|
||||||
|
address=address,
|
||||||
|
value=value)
|
||||||
|
|
||||||
|
def get_coil(self, address: int) -> Union[bool, List[bool]]:
|
||||||
|
"""
|
||||||
|
Get the coil value.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: bool
|
||||||
|
|
||||||
|
:returns: Coil value
|
||||||
|
:rtype: Union[bool, List[bool]]
|
||||||
|
"""
|
||||||
|
return self._get_reg_in_dict(reg_type='COILS',
|
||||||
|
address=address)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def coils(self) -> dict_keys:
|
||||||
|
"""
|
||||||
|
Get the configured coils.
|
||||||
|
|
||||||
|
:returns: The dictionary keys.
|
||||||
|
:rtype: dict_keys
|
||||||
|
"""
|
||||||
|
return self._get_regs_of_dict(reg_type='COILS')
|
||||||
|
|
||||||
|
def add_hreg(self,
|
||||||
|
address: int,
|
||||||
|
value: Union[int, List[int]] = 0,
|
||||||
|
on_set_cb: Callable[[str, int, List[int]], None] = None,
|
||||||
|
on_get_cb: Callable[[str, int, List[int]], None] = None) -> None:
|
||||||
|
"""
|
||||||
|
Add a holding register to the modbus register dictionary.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
:param value: The default value
|
||||||
|
:type value: Union[int, List[int]], optional
|
||||||
|
:param on_set_cb: Callback on setting the holding register
|
||||||
|
:type on_set_cb: Callable[[str, int, List[int]], None]
|
||||||
|
:param on_get_cb: Callback on getting the holding register
|
||||||
|
:type on_get_cb: Callable[[str, int, List[int]], None]
|
||||||
|
"""
|
||||||
|
self._set_reg_in_dict(reg_type='HREGS',
|
||||||
|
address=address,
|
||||||
|
value=value,
|
||||||
|
on_set_cb=on_set_cb,
|
||||||
|
on_get_cb=on_get_cb)
|
||||||
|
|
||||||
|
def remove_hreg(self, address: int) -> Union[None, int, List[int]]:
|
||||||
|
"""
|
||||||
|
Remove a holding register from the modbus register dictionary.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
|
||||||
|
:returns: Register value, None if register did not exist in dict
|
||||||
|
:rtype: Union[None, int, List[int]]
|
||||||
|
"""
|
||||||
|
return self._remove_reg_from_dict(reg_type='HREGS', address=address)
|
||||||
|
|
||||||
|
def set_hreg(self, address: int, value: Union[int, List[int]] = 0) -> None:
|
||||||
|
"""
|
||||||
|
Set the holding register value.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
:param value: The default value
|
||||||
|
:type value: int or list of int, optional
|
||||||
|
"""
|
||||||
|
self._set_reg_in_dict(reg_type='HREGS',
|
||||||
|
address=address,
|
||||||
|
value=value)
|
||||||
|
|
||||||
|
def get_hreg(self, address: int) -> Union[int, List[int]]:
|
||||||
|
"""
|
||||||
|
Get the holding register value.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
|
||||||
|
:returns: Holding register value
|
||||||
|
:rtype: Union[int, List[int]]
|
||||||
|
"""
|
||||||
|
return self._get_reg_in_dict(reg_type='HREGS',
|
||||||
|
address=address)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def hregs(self) -> dict_keys:
|
||||||
|
"""
|
||||||
|
Get the configured holding registers.
|
||||||
|
|
||||||
|
:returns: The dictionary keys.
|
||||||
|
:rtype: dict_keys
|
||||||
|
"""
|
||||||
|
return self._get_regs_of_dict(reg_type='HREGS')
|
||||||
|
|
||||||
|
def add_ist(self,
|
||||||
|
address: int,
|
||||||
|
value: Union[bool, List[bool]] = False,
|
||||||
|
on_get_cb: Callable[[str, int, Union[List[bool], List[int]]],
|
||||||
|
None] = None) -> None:
|
||||||
|
"""
|
||||||
|
Add a discrete input register to the modbus register dictionary.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
:param value: The default value
|
||||||
|
:type value: bool or list of bool, optional
|
||||||
|
:param on_get_cb: Callback on getting the discrete input register
|
||||||
|
:type on_get_cb: Callable[
|
||||||
|
[str, int, Union[List[bool], List[int]]],
|
||||||
|
None
|
||||||
|
]
|
||||||
|
"""
|
||||||
|
self._set_reg_in_dict(reg_type='ISTS',
|
||||||
|
address=address,
|
||||||
|
value=value,
|
||||||
|
on_get_cb=on_get_cb)
|
||||||
|
|
||||||
|
def remove_ist(self, address: int) -> Union[None, bool, List[bool]]:
|
||||||
|
"""
|
||||||
|
Remove a discrete input register from the modbus register dictionary.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
|
||||||
|
:returns: Register value, None if register did not exist in dict
|
||||||
|
:rtype: Union[None, bool, List[bool]]
|
||||||
|
"""
|
||||||
|
return self._remove_reg_from_dict(reg_type='ISTS', address=address)
|
||||||
|
|
||||||
|
def set_ist(self, address: int, value: bool = False) -> None:
|
||||||
|
"""
|
||||||
|
Set the discrete input register value.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
:param value: The default value
|
||||||
|
:type value: bool or list of bool, optional
|
||||||
|
"""
|
||||||
|
self._set_reg_in_dict(reg_type='ISTS',
|
||||||
|
address=address,
|
||||||
|
value=value)
|
||||||
|
|
||||||
|
def get_ist(self, address: int) -> Union[bool, List[bool]]:
|
||||||
|
"""
|
||||||
|
Get the discrete input register value.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
|
||||||
|
:returns: Discrete input register value
|
||||||
|
:rtype: Union[bool, List[bool]]
|
||||||
|
"""
|
||||||
|
return self._get_reg_in_dict(reg_type='ISTS',
|
||||||
|
address=address)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ists(self) -> dict_keys:
|
||||||
|
"""
|
||||||
|
Get the configured discrete input registers.
|
||||||
|
|
||||||
|
:returns: The dictionary keys.
|
||||||
|
:rtype: dict_keys
|
||||||
|
"""
|
||||||
|
return self._get_regs_of_dict(reg_type='ISTS')
|
||||||
|
|
||||||
|
def add_ireg(self,
|
||||||
|
address: int,
|
||||||
|
value: Union[int, List[int]] = 0,
|
||||||
|
on_get_cb: Callable[[str, int, Union[List[bool], List[int]]],
|
||||||
|
None] = None) -> None:
|
||||||
|
"""
|
||||||
|
Add an input register to the modbus register dictionary.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
:param value: The default value
|
||||||
|
:type value: Union[int, List[int]], optional
|
||||||
|
:param on_get_cb: Callback on getting the input register
|
||||||
|
:type on_get_cb: Callable[
|
||||||
|
[str, int, Union[List[bool], List[int]]],
|
||||||
|
None
|
||||||
|
]
|
||||||
|
"""
|
||||||
|
self._set_reg_in_dict(reg_type='IREGS',
|
||||||
|
address=address,
|
||||||
|
value=value,
|
||||||
|
on_get_cb=on_get_cb)
|
||||||
|
|
||||||
|
def remove_ireg(self, address: int) -> Union[None, int, List[int]]:
|
||||||
|
"""
|
||||||
|
Remove an input register from the modbus register dictionary.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
|
||||||
|
:returns: Register value, None if register did not exist in dict
|
||||||
|
:rtype: Union[None, int, List[int]]
|
||||||
|
"""
|
||||||
|
return self._remove_reg_from_dict(reg_type='IREGS', address=address)
|
||||||
|
|
||||||
|
def set_ireg(self, address: int, value: Union[int, List[int]] = 0) -> None:
|
||||||
|
"""
|
||||||
|
Set the input register value.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
:param value: The default value
|
||||||
|
:type value: Union[int, List[int]], optional
|
||||||
|
"""
|
||||||
|
self._set_reg_in_dict(reg_type='IREGS',
|
||||||
|
address=address,
|
||||||
|
value=value)
|
||||||
|
|
||||||
|
def get_ireg(self, address: int) -> Union[int, List[int]]:
|
||||||
|
"""
|
||||||
|
Get the input register value.
|
||||||
|
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
|
||||||
|
:returns: Input register value
|
||||||
|
:rtype: Union[int, List[int]]
|
||||||
|
"""
|
||||||
|
return self._get_reg_in_dict(reg_type='IREGS',
|
||||||
|
address=address)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def iregs(self) -> dict_keys:
|
||||||
|
"""
|
||||||
|
Get the configured input registers.
|
||||||
|
|
||||||
|
:returns: The dictionary keys.
|
||||||
|
:rtype: dict_keys
|
||||||
|
"""
|
||||||
|
return self._get_regs_of_dict(reg_type='IREGS')
|
||||||
|
|
||||||
|
def _set_reg_in_dict(self,
|
||||||
|
reg_type: str,
|
||||||
|
address: int,
|
||||||
|
value: Union[bool, int, List[bool], List[int]],
|
||||||
|
on_set_cb: Callable[[str, int, Union[List[bool],
|
||||||
|
List[int]]],
|
||||||
|
None] = None,
|
||||||
|
on_get_cb: Callable[[str, int, Union[List[bool],
|
||||||
|
List[int]]],
|
||||||
|
None] = None) -> None:
|
||||||
|
"""
|
||||||
|
Set the register value in the dictionary of registers.
|
||||||
|
|
||||||
|
:param reg_type: The register type
|
||||||
|
:type reg_type: str
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
:param value: The value(s) of the register(s)
|
||||||
|
:type value: Union[bool, int, List[bool], List[int]]
|
||||||
|
:param on_set_cb: Callback on setting the register
|
||||||
|
:type on_get_cb: Callable[
|
||||||
|
[str, int, Union[List[bool], List[int]]],
|
||||||
|
None
|
||||||
|
]
|
||||||
|
:param on_get_cb: Callback on getting the register
|
||||||
|
:type on_get_cb: Callable[
|
||||||
|
[str, int, Union[List[bool], List[int]]],
|
||||||
|
None
|
||||||
|
]
|
||||||
|
|
||||||
|
:raise KeyError: No register at specified address found
|
||||||
|
"""
|
||||||
|
if not self._check_valid_register(reg_type=reg_type):
|
||||||
|
raise KeyError('{} is not a valid register type of {}'.
|
||||||
|
format(reg_type, self._available_register_types))
|
||||||
|
|
||||||
|
if isinstance(value, (list, tuple)):
|
||||||
|
# flatten the list and add single registers only
|
||||||
|
for idx, val in enumerate(value):
|
||||||
|
this_addr = address + idx
|
||||||
|
self._set_single_reg_in_dict(reg_type=reg_type,
|
||||||
|
address=this_addr,
|
||||||
|
value=val,
|
||||||
|
on_set_cb=on_set_cb,
|
||||||
|
on_get_cb=on_get_cb)
|
||||||
|
else:
|
||||||
|
self._set_single_reg_in_dict(reg_type=reg_type,
|
||||||
|
address=address,
|
||||||
|
value=value,
|
||||||
|
on_set_cb=on_set_cb,
|
||||||
|
on_get_cb=on_get_cb)
|
||||||
|
|
||||||
|
def _set_single_reg_in_dict(self,
|
||||||
|
reg_type: str,
|
||||||
|
address: int,
|
||||||
|
value: Union[bool, int],
|
||||||
|
on_set_cb: Callable[
|
||||||
|
[str, int, Union[List[bool], List[int]]],
|
||||||
|
None
|
||||||
|
] = None,
|
||||||
|
on_get_cb: Callable[
|
||||||
|
[str, int, Union[List[bool], List[int]]],
|
||||||
|
None
|
||||||
|
] = None) -> None:
|
||||||
|
"""
|
||||||
|
Set a register value in the dictionary of registers.
|
||||||
|
|
||||||
|
:param reg_type: The register type
|
||||||
|
:type reg_type: str
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
:param value: The value of the register
|
||||||
|
:type value: Union[bool, int]
|
||||||
|
:param on_set_cb: Callback on setting the register
|
||||||
|
:type on_get_cb: Callable[
|
||||||
|
[str, int, Union[List[bool], List[int]]],
|
||||||
|
None
|
||||||
|
]
|
||||||
|
:param on_get_cb: Callback on getting the register
|
||||||
|
:type on_get_cb: Callable[
|
||||||
|
[str, int, Union[List[bool], List[int]]],
|
||||||
|
None
|
||||||
|
]
|
||||||
|
"""
|
||||||
|
data = {'val': value}
|
||||||
|
|
||||||
|
# if the register exists already in the register dict a "set_*"
|
||||||
|
# function might have called this functions
|
||||||
|
if address in self._register_dict[reg_type]:
|
||||||
|
# try to get the (already) registered callback function from the
|
||||||
|
# register dict of this address with the this time call function
|
||||||
|
# parameter callback value as fallback
|
||||||
|
on_set_cb = self._register_dict[reg_type][address].get('on_set_cb',
|
||||||
|
on_set_cb)
|
||||||
|
|
||||||
|
on_get_cb = self._register_dict[reg_type][address].get('on_get_cb',
|
||||||
|
on_get_cb)
|
||||||
|
|
||||||
|
if callable(on_set_cb):
|
||||||
|
data['on_set_cb'] = on_set_cb
|
||||||
|
|
||||||
|
if callable(on_get_cb):
|
||||||
|
data['on_get_cb'] = on_get_cb
|
||||||
|
|
||||||
|
self._register_dict[reg_type][address] = data
|
||||||
|
|
||||||
|
def _remove_reg_from_dict(self,
|
||||||
|
reg_type: str,
|
||||||
|
address: int) -> Union[None, bool, int, List[bool], List[int]]:
|
||||||
|
"""
|
||||||
|
Remove the register from the dictionary of registers.
|
||||||
|
|
||||||
|
:param reg_type: The register type
|
||||||
|
:type reg_type: str
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
|
||||||
|
:raise KeyError: No register at specified address found
|
||||||
|
:returns: Register value, None if register did not exist in dict
|
||||||
|
:rtype: Union[None, bool, int, List[bool], List[int]]
|
||||||
|
"""
|
||||||
|
if not self._check_valid_register(reg_type=reg_type):
|
||||||
|
raise KeyError('{} is not a valid register type of {}'.
|
||||||
|
format(reg_type, self._available_register_types))
|
||||||
|
|
||||||
|
return self._register_dict[reg_type].pop(address, None)
|
||||||
|
|
||||||
|
def _get_reg_in_dict(self,
|
||||||
|
reg_type: str,
|
||||||
|
address: int) -> Union[bool, int, List[bool], List[int]]:
|
||||||
|
"""
|
||||||
|
Get the register value from the dictionary of registers.
|
||||||
|
|
||||||
|
:param reg_type: The register type
|
||||||
|
:type reg_type: str
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
|
||||||
|
:raise KeyError: No register at specified address found
|
||||||
|
:returns: Register value
|
||||||
|
:rtype: Union[bool, int, List[bool], List[int]]
|
||||||
|
"""
|
||||||
|
if not self._check_valid_register(reg_type=reg_type):
|
||||||
|
raise KeyError('{} is not a valid register type of {}'.
|
||||||
|
format(reg_type, self._available_register_types))
|
||||||
|
|
||||||
|
if address in self._register_dict[reg_type]:
|
||||||
|
return self._register_dict[reg_type][address]['val']
|
||||||
|
else:
|
||||||
|
raise KeyError('No {} available for the register address {}'.
|
||||||
|
format(reg_type, address))
|
||||||
|
|
||||||
|
def _get_regs_of_dict(self, reg_type: str) -> dict_keys:
|
||||||
|
"""
|
||||||
|
Get all configured registers of specified register type.
|
||||||
|
|
||||||
|
:param reg_type: The register type
|
||||||
|
:type reg_type: str
|
||||||
|
|
||||||
|
:raise KeyError: No register at specified address found
|
||||||
|
:returns: The configured registers of the specified register type.
|
||||||
|
:rtype: dict_keys
|
||||||
|
"""
|
||||||
|
if not self._check_valid_register(reg_type=reg_type):
|
||||||
|
raise KeyError('{} is not a valid register type of {}'.
|
||||||
|
format(reg_type, self._available_register_types))
|
||||||
|
|
||||||
|
return self._register_dict[reg_type].keys()
|
||||||
|
|
||||||
|
def _check_valid_register(self, reg_type: str) -> bool:
|
||||||
|
"""
|
||||||
|
Check register type to be a valid modbus register
|
||||||
|
|
||||||
|
:param reg_type: The register type
|
||||||
|
:type reg_type: str
|
||||||
|
|
||||||
|
:returns: Flag whether register type is valid
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
if reg_type in self._available_register_types:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
@property
|
||||||
|
def changed_registers(self) -> dict:
|
||||||
|
"""
|
||||||
|
Get the changed registers.
|
||||||
|
|
||||||
|
:returns: The changed registers.
|
||||||
|
:rtype: dict
|
||||||
|
"""
|
||||||
|
return self._changed_registers
|
||||||
|
|
||||||
|
@property
|
||||||
|
def changed_coils(self) -> dict:
|
||||||
|
"""
|
||||||
|
Get the changed coil registers.
|
||||||
|
|
||||||
|
:returns: The changed coil registers.
|
||||||
|
:rtype: dict
|
||||||
|
"""
|
||||||
|
return self._changed_registers['COILS']
|
||||||
|
|
||||||
|
@property
|
||||||
|
def changed_hregs(self) -> dict:
|
||||||
|
"""
|
||||||
|
Get the changed holding registers.
|
||||||
|
|
||||||
|
:returns: The changed holding registers.
|
||||||
|
:rtype: dict
|
||||||
|
"""
|
||||||
|
return self._changed_registers['HREGS']
|
||||||
|
|
||||||
|
def _set_changed_register(self,
|
||||||
|
reg_type: str,
|
||||||
|
address: int,
|
||||||
|
value: Union[bool, int, List[bool], List[int]]) -> None:
|
||||||
|
"""
|
||||||
|
Set the register value in the dictionary of changed registers.
|
||||||
|
|
||||||
|
:param reg_type: The register type
|
||||||
|
:type reg_type: str
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
:param value: The value
|
||||||
|
:type value: Union[bool, int, List[bool], List[int]]
|
||||||
|
|
||||||
|
:raise KeyError: Register can not be changed externally
|
||||||
|
"""
|
||||||
|
if reg_type in self._changeable_register_types:
|
||||||
|
if isinstance(value, (list, tuple)):
|
||||||
|
for idx, val in enumerate(value):
|
||||||
|
content = {'val': val, 'time': time.ticks_ms()}
|
||||||
|
self._changed_registers[reg_type][address + idx] = content
|
||||||
|
else:
|
||||||
|
content = {'val': value, 'time': time.ticks_ms()}
|
||||||
|
self._changed_registers[reg_type][address] = content
|
||||||
|
else:
|
||||||
|
raise KeyError('{} can not be changed externally'.format(reg_type))
|
||||||
|
|
||||||
|
def _remove_changed_register(self,
|
||||||
|
reg_type: str,
|
||||||
|
address: int,
|
||||||
|
timestamp: int) -> bool:
|
||||||
|
"""
|
||||||
|
Remove the register from the dictionary of changed registers.
|
||||||
|
|
||||||
|
:param reg_type: The register type
|
||||||
|
:type reg_type: str
|
||||||
|
:param address: The address (ID) of the register
|
||||||
|
:type address: int
|
||||||
|
:param timestamp: The timestamp of the change in milliseconds
|
||||||
|
:type timestamp: int
|
||||||
|
|
||||||
|
:raise KeyError: No register at specified address found
|
||||||
|
:returns: Result of removing register from dict
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
result = False
|
||||||
|
|
||||||
|
if reg_type in self._changeable_register_types:
|
||||||
|
_changed_register_timestamp = self._changed_registers[reg_type][address]['time']
|
||||||
|
|
||||||
|
if _changed_register_timestamp == timestamp:
|
||||||
|
self._changed_registers[reg_type].pop(address, None)
|
||||||
|
result = True
|
||||||
|
else:
|
||||||
|
raise KeyError('{} is not a valid register type of {}'.
|
||||||
|
format(reg_type, self._changeable_register_types))
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
def setup_registers(self,
|
||||||
|
registers: dict = dict(),
|
||||||
|
use_default_vals: Optional[bool] = False) -> None:
|
||||||
|
"""
|
||||||
|
Setup all registers of the client
|
||||||
|
|
||||||
|
:param registers: The registers
|
||||||
|
:type registers: dict
|
||||||
|
:param use_default_vals: Flag to use dummy default values
|
||||||
|
:type use_default_vals: Optional[bool]
|
||||||
|
"""
|
||||||
|
if len(registers):
|
||||||
|
for reg_type, default_val in self._default_vals.items():
|
||||||
|
if reg_type in registers:
|
||||||
|
for reg, val in registers[reg_type].items():
|
||||||
|
address = val['register']
|
||||||
|
|
||||||
|
if use_default_vals:
|
||||||
|
if 'len' in val:
|
||||||
|
value = [default_val] * val['len']
|
||||||
|
else:
|
||||||
|
value = default_val
|
||||||
|
else:
|
||||||
|
value = val['val']
|
||||||
|
|
||||||
|
on_set_cb = val.get('on_set_cb', None)
|
||||||
|
on_get_cb = val.get('on_get_cb', None)
|
||||||
|
|
||||||
|
if reg_type == 'COILS':
|
||||||
|
self.add_coil(address=address,
|
||||||
|
value=value,
|
||||||
|
on_set_cb=on_set_cb,
|
||||||
|
on_get_cb=on_get_cb)
|
||||||
|
elif reg_type == 'HREGS':
|
||||||
|
self.add_hreg(address=address,
|
||||||
|
value=value,
|
||||||
|
on_set_cb=on_set_cb,
|
||||||
|
on_get_cb=on_get_cb)
|
||||||
|
elif reg_type == 'ISTS':
|
||||||
|
self.add_ist(address=address,
|
||||||
|
value=value,
|
||||||
|
on_get_cb=on_get_cb) # only getter
|
||||||
|
elif reg_type == 'IREGS':
|
||||||
|
self.add_ireg(address=address,
|
||||||
|
value=value,
|
||||||
|
on_get_cb=on_get_cb) # only getter
|
||||||
|
else:
|
||||||
|
# invalid register type
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,476 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
#
|
||||||
|
# Copyright (c) 2019, Pycom Limited.
|
||||||
|
#
|
||||||
|
# This software is licensed under the GNU GPL version 3 or any
|
||||||
|
# later version, with permitted additional terms. For more information
|
||||||
|
# see the Pycom Licence v1.0 document supplied with this file, or
|
||||||
|
# available at https://www.pycom.io/opensource/licensing
|
||||||
|
#
|
||||||
|
|
||||||
|
# system packages
|
||||||
|
from machine import UART
|
||||||
|
from machine import Pin
|
||||||
|
import struct
|
||||||
|
import time
|
||||||
|
|
||||||
|
# custom packages
|
||||||
|
from . import const as Const
|
||||||
|
from . import functions
|
||||||
|
from .common import Request, CommonModbusFunctions
|
||||||
|
from .common import ModbusException
|
||||||
|
from .modbus import Modbus
|
||||||
|
|
||||||
|
# typing not natively supported on MicroPython
|
||||||
|
from .typing import List, Optional, Union
|
||||||
|
|
||||||
|
|
||||||
|
class ModbusRTU(Modbus):
|
||||||
|
"""
|
||||||
|
Modbus RTU client class
|
||||||
|
|
||||||
|
:param addr: The address of this device on the bus
|
||||||
|
:type addr: int
|
||||||
|
:param baudrate: The baudrate, default 9600
|
||||||
|
:type baudrate: int
|
||||||
|
:param data_bits: The data bits, default 8
|
||||||
|
:type data_bits: int
|
||||||
|
:param stop_bits: The stop bits, default 1
|
||||||
|
:type stop_bits: int
|
||||||
|
:param parity: The parity, default None
|
||||||
|
:type parity: Optional[int]
|
||||||
|
:param pins: The pins as list [TX, RX]
|
||||||
|
:type pins: List[Union[int, Pin], Union[int, Pin]]
|
||||||
|
:param ctrl_pin: The control pin
|
||||||
|
:type ctrl_pin: int
|
||||||
|
:param uart_id: The ID of the used UART
|
||||||
|
:type uart_id: int
|
||||||
|
"""
|
||||||
|
def __init__(self,
|
||||||
|
addr: int,
|
||||||
|
baudrate: int = 9600,
|
||||||
|
data_bits: int = 8,
|
||||||
|
stop_bits: int = 1,
|
||||||
|
parity: Optional[int] = None,
|
||||||
|
pins: List[Union[int, Pin], Union[int, Pin]] = None,
|
||||||
|
ctrl_pin: int = None,
|
||||||
|
uart_id: int = 1):
|
||||||
|
super().__init__(
|
||||||
|
# set itf to Serial object, addr_list to [addr]
|
||||||
|
Serial(uart_id=uart_id,
|
||||||
|
baudrate=baudrate,
|
||||||
|
data_bits=data_bits,
|
||||||
|
stop_bits=stop_bits,
|
||||||
|
parity=parity,
|
||||||
|
pins=pins,
|
||||||
|
ctrl_pin=ctrl_pin),
|
||||||
|
[addr]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Serial(CommonModbusFunctions):
|
||||||
|
def __init__(self,
|
||||||
|
uart_id: int = 1,
|
||||||
|
baudrate: int = 9600,
|
||||||
|
data_bits: int = 8,
|
||||||
|
stop_bits: int = 1,
|
||||||
|
parity=None,
|
||||||
|
pins: List[Union[int, Pin], Union[int, Pin]] = None,
|
||||||
|
ctrl_pin: int = None):
|
||||||
|
"""
|
||||||
|
Setup Serial/RTU Modbus
|
||||||
|
|
||||||
|
:param uart_id: The ID of the used UART
|
||||||
|
:type uart_id: int
|
||||||
|
:param baudrate: The baudrate, default 9600
|
||||||
|
:type baudrate: int
|
||||||
|
:param data_bits: The data bits, default 8
|
||||||
|
:type data_bits: int
|
||||||
|
:param stop_bits: The stop bits, default 1
|
||||||
|
:type stop_bits: int
|
||||||
|
:param parity: The parity, default None
|
||||||
|
:type parity: Optional[int]
|
||||||
|
:param pins: The pins as list [TX, RX]
|
||||||
|
:type pins: List[Union[int, Pin], Union[int, Pin]]
|
||||||
|
:param ctrl_pin: The control pin
|
||||||
|
:type ctrl_pin: int
|
||||||
|
"""
|
||||||
|
# UART flush function is introduced in Micropython v1.20.0
|
||||||
|
self._has_uart_flush = callable(getattr(UART, "flush", None))
|
||||||
|
if ctrl_pin is not None and ctrl_pin < 0:
|
||||||
|
self._uart = UART(uart_id,
|
||||||
|
baudrate=baudrate,
|
||||||
|
bits=data_bits,
|
||||||
|
parity=parity,
|
||||||
|
stop=stop_bits,
|
||||||
|
# timeout_chars=2, # WiPy only
|
||||||
|
pins=pins, # WiPy only
|
||||||
|
flow=-ctrl_pin
|
||||||
|
)
|
||||||
|
ctrl_pin = None
|
||||||
|
else:
|
||||||
|
self._uart = UART(uart_id,
|
||||||
|
baudrate=baudrate,
|
||||||
|
bits=data_bits,
|
||||||
|
parity=parity,
|
||||||
|
stop=stop_bits,
|
||||||
|
# timeout_chars=2, # WiPy only
|
||||||
|
pins=pins # WiPy only
|
||||||
|
)
|
||||||
|
|
||||||
|
if ctrl_pin is not None:
|
||||||
|
self._ctrlPin = Pin(ctrl_pin, mode=Pin.OUT)
|
||||||
|
else:
|
||||||
|
self._ctrlPin = None
|
||||||
|
|
||||||
|
# timing of 1 character in microseconds (us)
|
||||||
|
self._t1char = (1000000 * (data_bits + stop_bits + 2)) // baudrate
|
||||||
|
|
||||||
|
# inter-frame delay in microseconds (us)
|
||||||
|
# - <= 19200 bps: 3.5x timing of 1 character
|
||||||
|
# - > 19200 bps: 1750 us
|
||||||
|
if baudrate <= 19200:
|
||||||
|
self._inter_frame_delay = (self._t1char * 3500) // 1000
|
||||||
|
else:
|
||||||
|
self._inter_frame_delay = 1750
|
||||||
|
|
||||||
|
def _calculate_crc16(self, data: bytearray) -> bytes:
|
||||||
|
"""
|
||||||
|
Calculates the CRC16.
|
||||||
|
|
||||||
|
:param data: The data
|
||||||
|
:type data: bytearray
|
||||||
|
|
||||||
|
:returns: The crc 16.
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
crc = 0xFFFF
|
||||||
|
|
||||||
|
for char in data:
|
||||||
|
crc = (crc >> 8) ^ Const.CRC16_TABLE[((crc) ^ char) & 0xFF]
|
||||||
|
|
||||||
|
return struct.pack('<H', crc)
|
||||||
|
|
||||||
|
def _exit_read(self, response: bytearray) -> bool:
|
||||||
|
"""
|
||||||
|
Return on modbus read error
|
||||||
|
|
||||||
|
:param response: The response
|
||||||
|
:type response: bytearray
|
||||||
|
|
||||||
|
:returns: State of basic read response evaluation,
|
||||||
|
True if entire response has been read
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
response_len = len(response)
|
||||||
|
if response_len >= 2 and response[1] >= Const.ERROR_BIAS:
|
||||||
|
if response_len < Const.ERROR_RESP_LEN:
|
||||||
|
return False
|
||||||
|
elif response_len >= 3 and (Const.READ_COILS <= response[1] <= Const.READ_INPUT_REGISTER):
|
||||||
|
expected_len = Const.RESPONSE_HDR_LENGTH + 1 + response[2] + Const.CRC_LENGTH
|
||||||
|
if response_len < expected_len:
|
||||||
|
return False
|
||||||
|
elif response_len < Const.FIXED_RESP_LEN:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _uart_read(self) -> bytearray:
|
||||||
|
"""
|
||||||
|
Read incoming slave response from UART
|
||||||
|
|
||||||
|
:returns: Read content
|
||||||
|
:rtype: bytearray
|
||||||
|
"""
|
||||||
|
response = bytearray()
|
||||||
|
|
||||||
|
# TODO: use some kind of hint or user-configurable delay
|
||||||
|
# to determine this loop counter
|
||||||
|
for x in range(1, 120):
|
||||||
|
rx = self._uart.read()
|
||||||
|
if rx is not None:
|
||||||
|
# WiPy only
|
||||||
|
# response.extend(self._uart.readall())
|
||||||
|
response.extend(rx)
|
||||||
|
|
||||||
|
# variable length function codes may require multiple reads
|
||||||
|
if self._exit_read(response):
|
||||||
|
break
|
||||||
|
|
||||||
|
# wait for the maximum time between two frames
|
||||||
|
time.sleep_us(self._inter_frame_delay)
|
||||||
|
|
||||||
|
return response
|
||||||
|
|
||||||
|
def _uart_read_frame(self, timeout: Optional[int] = None) -> bytearray:
|
||||||
|
"""
|
||||||
|
Read a Modbus frame
|
||||||
|
|
||||||
|
:param timeout: The timeout
|
||||||
|
:type timeout: Optional[int]
|
||||||
|
|
||||||
|
:returns: Received message
|
||||||
|
:rtype: bytearray
|
||||||
|
"""
|
||||||
|
received_bytes = bytearray()
|
||||||
|
|
||||||
|
if self._uart.any() <= 0:
|
||||||
|
return received_bytes
|
||||||
|
|
||||||
|
# set default timeout to at twice the inter-frame delay
|
||||||
|
if timeout == 0 or timeout is None:
|
||||||
|
timeout = 2 * self._inter_frame_delay # in microseconds
|
||||||
|
|
||||||
|
start_us = time.ticks_us()
|
||||||
|
#print(start_us)
|
||||||
|
|
||||||
|
# stay inside this while loop at least for the timeout time
|
||||||
|
while (time.ticks_diff(time.ticks_us(), start_us) <= timeout):
|
||||||
|
# check amount of available characters
|
||||||
|
if self._uart.any() > 0:
|
||||||
|
# remember this time in microseconds
|
||||||
|
last_byte_ts = time.ticks_us()
|
||||||
|
|
||||||
|
# do not stop reading and appending the result to the buffer
|
||||||
|
# until the time between two frames elapsed
|
||||||
|
while True:
|
||||||
|
# WiPy only
|
||||||
|
# r = self._uart.readall()
|
||||||
|
time.sleep_us(100)
|
||||||
|
r = self._uart.read()
|
||||||
|
|
||||||
|
# if something has been read after the first iteration of
|
||||||
|
# this inner while loop (within self._inter_frame_delay)
|
||||||
|
if r is not None and len(r) > 0:
|
||||||
|
# append the new read stuff to the buffer
|
||||||
|
received_bytes.extend(r)
|
||||||
|
|
||||||
|
# update the timestamp of the last byte being read
|
||||||
|
last_byte_ts = time.ticks_us()
|
||||||
|
#print(last_byte_ts, received_bytes)
|
||||||
|
if time.ticks_diff(time.ticks_us(), last_byte_ts) >= self._inter_frame_delay:
|
||||||
|
break
|
||||||
|
# if something has been read before the overall timeout is reached
|
||||||
|
if len(received_bytes) > 0:
|
||||||
|
#print(time.ticks_diff(time.ticks_us(), start_us))
|
||||||
|
return received_bytes
|
||||||
|
|
||||||
|
#print(time.ticks_diff(time.ticks_us(), start_us))
|
||||||
|
# return the result in case the overall timeout has been reached
|
||||||
|
return received_bytes
|
||||||
|
|
||||||
|
def _send(self, modbus_pdu: bytes, slave_addr: int) -> None:
|
||||||
|
"""
|
||||||
|
Send Modbus frame via UART
|
||||||
|
|
||||||
|
If a flow control pin has been setup, it will be controlled accordingly
|
||||||
|
|
||||||
|
:param modbus_pdu: The modbus Protocol Data Unit
|
||||||
|
:type modbus_pdu: bytes
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
"""
|
||||||
|
# modbus_adu: Modbus Application Data Unit
|
||||||
|
# consists of the Modbus PDU, with slave address prepended and checksum appended
|
||||||
|
modbus_adu = bytearray()
|
||||||
|
modbus_adu.append(slave_addr)
|
||||||
|
modbus_adu.extend(modbus_pdu)
|
||||||
|
modbus_adu.extend(self._calculate_crc16(modbus_adu))
|
||||||
|
|
||||||
|
if self._ctrlPin:
|
||||||
|
self._ctrlPin.on()
|
||||||
|
# wait until the control pin really changed
|
||||||
|
# 85-95us (ESP32 @ 160/240MHz)
|
||||||
|
time.sleep_us(200)
|
||||||
|
|
||||||
|
# the timing of this part is critical:
|
||||||
|
# - if we disable output too early,
|
||||||
|
# the command will not be received in full
|
||||||
|
# - if we disable output too late,
|
||||||
|
# the incoming response will lose some data at the beginning
|
||||||
|
# easiest to just wait for the bytes to be sent out on the wire
|
||||||
|
|
||||||
|
send_start_time = time.ticks_us()
|
||||||
|
# 360-400us @ 9600-115200 baud (measured) (ESP32 @ 160/240MHz)
|
||||||
|
self._uart.write(modbus_adu)
|
||||||
|
send_finish_time = time.ticks_us()
|
||||||
|
|
||||||
|
if self._has_uart_flush:
|
||||||
|
self._uart.flush()
|
||||||
|
time.sleep_us(self._t1char)
|
||||||
|
else:
|
||||||
|
sleep_time_us = (
|
||||||
|
self._t1char * len(modbus_adu) - # total frame time in us
|
||||||
|
time.ticks_diff(send_finish_time, send_start_time) +
|
||||||
|
100 # only required at baudrates above 57600, but hey 100us
|
||||||
|
)
|
||||||
|
time.sleep_us(sleep_time_us)
|
||||||
|
|
||||||
|
if self._ctrlPin:
|
||||||
|
self._ctrlPin.off()
|
||||||
|
|
||||||
|
def _send_receive(self,
|
||||||
|
modbus_pdu: bytes,
|
||||||
|
slave_addr: int,
|
||||||
|
count: bool) -> bytes:
|
||||||
|
"""
|
||||||
|
Send a modbus message and receive the reponse.
|
||||||
|
|
||||||
|
:param modbus_pdu: The modbus Protocol Data Unit
|
||||||
|
:type modbus_pdu: bytes
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param count: The count
|
||||||
|
:type count: bool
|
||||||
|
|
||||||
|
:returns: Validated response content
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
# flush the Rx FIFO buffer
|
||||||
|
self._uart.read()
|
||||||
|
|
||||||
|
self._send(modbus_pdu=modbus_pdu, slave_addr=slave_addr)
|
||||||
|
|
||||||
|
return self._validate_resp_hdr(response=self._uart_read(),
|
||||||
|
slave_addr=slave_addr,
|
||||||
|
function_code=modbus_pdu[0],
|
||||||
|
count=count)
|
||||||
|
|
||||||
|
def _validate_resp_hdr(self,
|
||||||
|
response: bytearray,
|
||||||
|
slave_addr: int,
|
||||||
|
function_code: int,
|
||||||
|
count: bool) -> bytes:
|
||||||
|
"""
|
||||||
|
Validate the response header.
|
||||||
|
|
||||||
|
:param response: The response
|
||||||
|
:type response: bytearray
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param function_code: The function code
|
||||||
|
:type function_code: int
|
||||||
|
:param count: The count
|
||||||
|
:type count: bool
|
||||||
|
|
||||||
|
:returns: Modbus response content
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
if len(response) == 0:
|
||||||
|
raise OSError('no data received from slave')
|
||||||
|
|
||||||
|
resp_crc = response[-Const.CRC_LENGTH:]
|
||||||
|
expected_crc = self._calculate_crc16(
|
||||||
|
response[0:len(response) - Const.CRC_LENGTH]
|
||||||
|
)
|
||||||
|
|
||||||
|
if ((resp_crc[0] is not expected_crc[0]) or
|
||||||
|
(resp_crc[1] is not expected_crc[1])):
|
||||||
|
raise OSError('invalid response CRC')
|
||||||
|
|
||||||
|
if (response[0] != slave_addr):
|
||||||
|
raise ValueError('wrong slave address')
|
||||||
|
|
||||||
|
if (response[1] == (function_code + Const.ERROR_BIAS)):
|
||||||
|
raise ValueError('slave returned exception code: {:d}'.
|
||||||
|
format(response[2]))
|
||||||
|
|
||||||
|
hdr_length = (Const.RESPONSE_HDR_LENGTH + 1) if count else \
|
||||||
|
Const.RESPONSE_HDR_LENGTH
|
||||||
|
|
||||||
|
return response[hdr_length:len(response) - Const.CRC_LENGTH]
|
||||||
|
|
||||||
|
def send_response(self,
|
||||||
|
slave_addr: int,
|
||||||
|
function_code: int,
|
||||||
|
request_register_addr: int,
|
||||||
|
request_register_qty: int,
|
||||||
|
request_data: list,
|
||||||
|
values: Optional[list] = None,
|
||||||
|
signed: bool = True) -> None:
|
||||||
|
"""
|
||||||
|
Send a response to a client.
|
||||||
|
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param function_code: The function code
|
||||||
|
:type function_code: int
|
||||||
|
:param request_register_addr: The request register address
|
||||||
|
:type request_register_addr: int
|
||||||
|
:param request_register_qty: The request register qty
|
||||||
|
:type request_register_qty: int
|
||||||
|
:param request_data: The request data
|
||||||
|
:type request_data: list
|
||||||
|
:param values: The values
|
||||||
|
:type values: Optional[list]
|
||||||
|
:param signed: Indicates if signed
|
||||||
|
:type signed: bool
|
||||||
|
"""
|
||||||
|
modbus_pdu = functions.response(
|
||||||
|
function_code=function_code,
|
||||||
|
request_register_addr=request_register_addr,
|
||||||
|
request_register_qty=request_register_qty,
|
||||||
|
request_data=request_data,
|
||||||
|
value_list=values,
|
||||||
|
signed=signed
|
||||||
|
)
|
||||||
|
self._send(modbus_pdu=modbus_pdu, slave_addr=slave_addr)
|
||||||
|
|
||||||
|
def send_exception_response(self,
|
||||||
|
slave_addr: int,
|
||||||
|
function_code: int,
|
||||||
|
exception_code: int) -> None:
|
||||||
|
"""
|
||||||
|
Send an exception response to a client.
|
||||||
|
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param function_code: The function code
|
||||||
|
:type function_code: int
|
||||||
|
:param exception_code: The exception code
|
||||||
|
:type exception_code: int
|
||||||
|
"""
|
||||||
|
modbus_pdu = functions.exception_response(
|
||||||
|
function_code=function_code,
|
||||||
|
exception_code=exception_code)
|
||||||
|
self._send(modbus_pdu=modbus_pdu, slave_addr=slave_addr)
|
||||||
|
|
||||||
|
def get_request(self,
|
||||||
|
unit_addr_list: List[int],
|
||||||
|
timeout: Optional[int] = None) -> Union[Request, None]:
|
||||||
|
"""
|
||||||
|
Check for request within the specified timeout
|
||||||
|
|
||||||
|
:param unit_addr_list: The unit address list
|
||||||
|
:type unit_addr_list: Optional[list]
|
||||||
|
:param timeout: The timeout
|
||||||
|
:type timeout: Optional[int]
|
||||||
|
|
||||||
|
:returns: A request object or None.
|
||||||
|
:rtype: Union[Request, None]
|
||||||
|
"""
|
||||||
|
req = self._uart_read_frame(timeout=timeout)
|
||||||
|
|
||||||
|
if len(req) < 8:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if req[0] not in unit_addr_list:
|
||||||
|
return None
|
||||||
|
|
||||||
|
req_crc = req[-Const.CRC_LENGTH:]
|
||||||
|
req_no_crc = req[:-Const.CRC_LENGTH]
|
||||||
|
expected_crc = self._calculate_crc16(req_no_crc)
|
||||||
|
|
||||||
|
if (req_crc[0] != expected_crc[0]) or (req_crc[1] != expected_crc[1]):
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
request = Request(interface=self, data=req_no_crc)
|
||||||
|
except ModbusException as e:
|
||||||
|
self.send_exception_response(
|
||||||
|
slave_addr=req[0],
|
||||||
|
function_code=e.function_code,
|
||||||
|
exception_code=e.exception_code)
|
||||||
|
return None
|
||||||
|
|
||||||
|
return request
|
||||||
@@ -0,0 +1,416 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
#
|
||||||
|
# Copyright (c) 2019, Pycom Limited.
|
||||||
|
#
|
||||||
|
# This software is licensed under the GNU GPL version 3 or any
|
||||||
|
# later version, with permitted additional terms. For more information
|
||||||
|
# see the Pycom Licence v1.0 document supplied with this file, or
|
||||||
|
# available at https://www.pycom.io/opensource/licensing
|
||||||
|
#
|
||||||
|
|
||||||
|
# system packages
|
||||||
|
# import random
|
||||||
|
import struct
|
||||||
|
import socket
|
||||||
|
import time
|
||||||
|
|
||||||
|
# custom packages
|
||||||
|
from . import functions
|
||||||
|
from . import const as Const
|
||||||
|
from .common import Request, CommonModbusFunctions
|
||||||
|
from .common import ModbusException
|
||||||
|
from .modbus import Modbus
|
||||||
|
|
||||||
|
# typing not natively supported on MicroPython
|
||||||
|
from .typing import Optional, Tuple, Union
|
||||||
|
|
||||||
|
|
||||||
|
class ModbusTCP(Modbus):
|
||||||
|
"""Modbus TCP client class"""
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__(
|
||||||
|
# set itf to TCPServer object, addr_list to None
|
||||||
|
TCPServer(),
|
||||||
|
None
|
||||||
|
)
|
||||||
|
|
||||||
|
def bind(self,
|
||||||
|
local_ip: str,
|
||||||
|
local_port: int = 502,
|
||||||
|
max_connections: int = 10) -> None:
|
||||||
|
"""
|
||||||
|
Bind IP and port for incomming requests
|
||||||
|
|
||||||
|
:param local_ip: IP of this device listening for requests
|
||||||
|
:type local_ip: str
|
||||||
|
:param local_port: Port of this device
|
||||||
|
:type local_port: int
|
||||||
|
:param max_connections: Number of maximum connections
|
||||||
|
:type max_connections: int
|
||||||
|
"""
|
||||||
|
self._itf.bind(local_ip, local_port, max_connections)
|
||||||
|
|
||||||
|
def get_bound_status(self) -> bool:
|
||||||
|
"""
|
||||||
|
Get the IP and port binding status.
|
||||||
|
|
||||||
|
:returns: The bound status, True if already bound, False otherwise.
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
return self._itf.get_is_bound()
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class TCP(CommonModbusFunctions):
|
||||||
|
"""
|
||||||
|
TCP class handling socket connections and parsing the Modbus data
|
||||||
|
|
||||||
|
:param slave_ip: IP of this device listening for requests
|
||||||
|
:type slave_ip: str
|
||||||
|
:param slave_port: Port of this device
|
||||||
|
:type slave_port: int
|
||||||
|
:param timeout: Socket timeout in seconds
|
||||||
|
:type timeout: float
|
||||||
|
"""
|
||||||
|
def __init__(self,
|
||||||
|
slave_ip: str,
|
||||||
|
slave_port: int = 502,
|
||||||
|
timeout: float = 5.0):
|
||||||
|
self._sock = socket.socket()
|
||||||
|
self.trans_id_ctr = 0
|
||||||
|
|
||||||
|
# print(socket.getaddrinfo(slave_ip, slave_port))
|
||||||
|
# [(2, 1, 0, '192.168.178.47', ('192.168.178.47', 502))]
|
||||||
|
self._sock.connect(socket.getaddrinfo(slave_ip, slave_port)[0][-1])
|
||||||
|
|
||||||
|
self._sock.settimeout(timeout)
|
||||||
|
|
||||||
|
def _create_mbap_hdr(self,
|
||||||
|
slave_addr: int,
|
||||||
|
modbus_pdu: bytes) -> Tuple[bytes, int]:
|
||||||
|
"""
|
||||||
|
Create a Modbus header.
|
||||||
|
|
||||||
|
:param slave_addr: The slave identifier
|
||||||
|
:type slave_addr: int
|
||||||
|
:param modbus_pdu: The modbus Protocol Data Unit
|
||||||
|
:type modbus_pdu: bytes
|
||||||
|
|
||||||
|
:returns: Modbus header and unique transaction ID
|
||||||
|
:rtype: Tuple[bytes, int]
|
||||||
|
"""
|
||||||
|
# only available on WiPy
|
||||||
|
# trans_id = machine.rng() & 0xFFFF
|
||||||
|
# use builtin function to generate random 24 bit integer
|
||||||
|
# trans_id = random.getrandbits(24) & 0xFFFF
|
||||||
|
# use incrementing counter as it's faster
|
||||||
|
trans_id = self.trans_id_ctr
|
||||||
|
self.trans_id_ctr += 1
|
||||||
|
|
||||||
|
mbap_hdr = struct.pack(
|
||||||
|
'>HHHB', trans_id, 0, len(modbus_pdu) + 1, slave_addr)
|
||||||
|
|
||||||
|
return mbap_hdr, trans_id
|
||||||
|
|
||||||
|
def _validate_resp_hdr(self,
|
||||||
|
response: bytearray,
|
||||||
|
trans_id: int,
|
||||||
|
slave_addr: int,
|
||||||
|
function_code: int,
|
||||||
|
count: bool = False) -> bytes:
|
||||||
|
"""
|
||||||
|
Validate the response header.
|
||||||
|
|
||||||
|
:param response: The response
|
||||||
|
:type response: bytearray
|
||||||
|
:param trans_id: The transaction identifier
|
||||||
|
:type trans_id: int
|
||||||
|
:param slave_addr: The slave identifier
|
||||||
|
:type slave_addr: int
|
||||||
|
:param function_code: The function code
|
||||||
|
:type function_code: int
|
||||||
|
:param count: The count
|
||||||
|
:type count: bool
|
||||||
|
|
||||||
|
:returns: Modbus response content
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
rec_tid, rec_pid, rec_len, rec_uid, rec_fc = struct.unpack(
|
||||||
|
'>HHHBB', response[:Const.MBAP_HDR_LENGTH + 1])
|
||||||
|
|
||||||
|
if (trans_id != rec_tid):
|
||||||
|
raise ValueError('wrong transaction ID')
|
||||||
|
|
||||||
|
if (rec_pid != 0):
|
||||||
|
raise ValueError('invalid protocol ID')
|
||||||
|
|
||||||
|
if (slave_addr != rec_uid):
|
||||||
|
raise ValueError('wrong slave ID')
|
||||||
|
|
||||||
|
if (rec_fc == (function_code + Const.ERROR_BIAS)):
|
||||||
|
raise ValueError('slave returned exception code: {:d}'.
|
||||||
|
format(rec_fc))
|
||||||
|
|
||||||
|
hdr_length = (Const.MBAP_HDR_LENGTH + 2) if count else \
|
||||||
|
(Const.MBAP_HDR_LENGTH + 1)
|
||||||
|
|
||||||
|
return response[hdr_length:]
|
||||||
|
|
||||||
|
def _send_receive(self,
|
||||||
|
slave_addr: int,
|
||||||
|
modbus_pdu: bytes,
|
||||||
|
count: bool) -> bytes:
|
||||||
|
"""
|
||||||
|
Send a modbus message and receive the reponse.
|
||||||
|
|
||||||
|
:param slave_addr: The slave identifier
|
||||||
|
:type slave_addr: int
|
||||||
|
:param modbus_pdu: The modbus PDU
|
||||||
|
:type modbus_pdu: bytes
|
||||||
|
:param count: The count
|
||||||
|
:type count: bool
|
||||||
|
|
||||||
|
:returns: Modbus data
|
||||||
|
:rtype: bytes
|
||||||
|
"""
|
||||||
|
mbap_hdr, trans_id = self._create_mbap_hdr(slave_addr=slave_addr,
|
||||||
|
modbus_pdu=modbus_pdu)
|
||||||
|
self._sock.send(mbap_hdr + modbus_pdu)
|
||||||
|
|
||||||
|
response = self._sock.recv(256)
|
||||||
|
modbus_data = self._validate_resp_hdr(response=response,
|
||||||
|
trans_id=trans_id,
|
||||||
|
slave_addr=slave_addr,
|
||||||
|
function_code=modbus_pdu[0],
|
||||||
|
count=count)
|
||||||
|
|
||||||
|
return modbus_data
|
||||||
|
|
||||||
|
|
||||||
|
class TCPServer(object):
|
||||||
|
"""Modbus TCP host class"""
|
||||||
|
def __init__(self):
|
||||||
|
self._sock = None
|
||||||
|
self._client_sock = None
|
||||||
|
self._is_bound = False
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_bound(self) -> bool:
|
||||||
|
"""
|
||||||
|
Get the IP and port binding status
|
||||||
|
|
||||||
|
:returns: True if bound to IP and port, False otherwise
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
return self._is_bound
|
||||||
|
|
||||||
|
def get_is_bound(self) -> bool:
|
||||||
|
"""
|
||||||
|
Get the IP and port binding status, legacy support.
|
||||||
|
|
||||||
|
:returns: True if bound to IP and port, False otherwise
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
return self._is_bound
|
||||||
|
|
||||||
|
def bind(self,
|
||||||
|
local_ip: str,
|
||||||
|
local_port: int = 502,
|
||||||
|
max_connections: int = 10):
|
||||||
|
"""
|
||||||
|
Bind IP and port for incomming requests
|
||||||
|
|
||||||
|
:param local_ip: IP of this device listening for requests
|
||||||
|
:type local_ip: str
|
||||||
|
:param local_port: Port of this device
|
||||||
|
:type local_port: int
|
||||||
|
:param max_connections: Number of maximum connections
|
||||||
|
:type max_connections: int
|
||||||
|
"""
|
||||||
|
if self._client_sock:
|
||||||
|
self._client_sock.close()
|
||||||
|
|
||||||
|
if self._sock:
|
||||||
|
self._sock.close()
|
||||||
|
|
||||||
|
self._sock = socket.socket()
|
||||||
|
|
||||||
|
# print(socket.getaddrinfo(local_ip, local_port))
|
||||||
|
# [(2, 1, 0, '192.168.178.47', ('192.168.178.47', 502))]
|
||||||
|
self._sock.bind(socket.getaddrinfo(local_ip, local_port)[0][-1])
|
||||||
|
|
||||||
|
self._sock.listen(max_connections)
|
||||||
|
|
||||||
|
self._is_bound = True
|
||||||
|
|
||||||
|
def _send(self, modbus_pdu: bytes, slave_addr: int) -> None:
|
||||||
|
"""
|
||||||
|
Send Modbus Protocol Data Unit to slave
|
||||||
|
|
||||||
|
:param modbus_pdu: The Modbus Protocol Data Unit
|
||||||
|
:type modbus_pdu: bytes
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
"""
|
||||||
|
size = len(modbus_pdu)
|
||||||
|
fmt = 'B' * size
|
||||||
|
adu = struct.pack('>HHHB' + fmt, self._req_tid, 0, size + 1, slave_addr, *modbus_pdu)
|
||||||
|
self._client_sock.send(adu)
|
||||||
|
|
||||||
|
def send_response(self,
|
||||||
|
slave_addr: int,
|
||||||
|
function_code: int,
|
||||||
|
request_register_addr: int,
|
||||||
|
request_register_qty: int,
|
||||||
|
request_data: list,
|
||||||
|
values: Optional[list] = None,
|
||||||
|
signed: bool = True) -> None:
|
||||||
|
"""
|
||||||
|
Send a response to a client.
|
||||||
|
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param function_code: The function code
|
||||||
|
:type function_code: int
|
||||||
|
:param request_register_addr: The request register address
|
||||||
|
:type request_register_addr: int
|
||||||
|
:param request_register_qty: The request register qty
|
||||||
|
:type request_register_qty: int
|
||||||
|
:param request_data: The request data
|
||||||
|
:type request_data: list
|
||||||
|
:param values: The values
|
||||||
|
:type values: Optional[list]
|
||||||
|
:param signed: Indicates if signed
|
||||||
|
:type signed: bool
|
||||||
|
"""
|
||||||
|
modbus_pdu = functions.response(function_code,
|
||||||
|
request_register_addr,
|
||||||
|
request_register_qty,
|
||||||
|
request_data,
|
||||||
|
values,
|
||||||
|
signed)
|
||||||
|
self._send(modbus_pdu, slave_addr)
|
||||||
|
|
||||||
|
def send_exception_response(self,
|
||||||
|
slave_addr: int,
|
||||||
|
function_code: int,
|
||||||
|
exception_code: int) -> None:
|
||||||
|
"""
|
||||||
|
Send an exception response to a client.
|
||||||
|
|
||||||
|
:param slave_addr: The slave address
|
||||||
|
:type slave_addr: int
|
||||||
|
:param function_code: The function code
|
||||||
|
:type function_code: int
|
||||||
|
:param exception_code: The exception code
|
||||||
|
:type exception_code: int
|
||||||
|
"""
|
||||||
|
modbus_pdu = functions.exception_response(function_code,
|
||||||
|
exception_code)
|
||||||
|
self._send(modbus_pdu, slave_addr)
|
||||||
|
|
||||||
|
def _accept_request(self,
|
||||||
|
accept_timeout: float,
|
||||||
|
unit_addr_list: list) -> Union[Request, None]:
|
||||||
|
"""
|
||||||
|
Accept, read and decode a socket based request
|
||||||
|
|
||||||
|
:param accept_timeout: The socket accept timeout
|
||||||
|
:type accept_timeout: float
|
||||||
|
:param unit_addr_list: The unit address list
|
||||||
|
:type unit_addr_list: list
|
||||||
|
"""
|
||||||
|
self._sock.settimeout(accept_timeout)
|
||||||
|
new_client_sock = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
new_client_sock, client_address = self._sock.accept()
|
||||||
|
except OSError as e:
|
||||||
|
if e.args[0] != 110: # 110 = timeout expired
|
||||||
|
raise e
|
||||||
|
|
||||||
|
if new_client_sock is not None:
|
||||||
|
if self._client_sock is not None:
|
||||||
|
self._client_sock.close()
|
||||||
|
|
||||||
|
self._client_sock = new_client_sock
|
||||||
|
|
||||||
|
# recv() timeout, setting to 0 might lead to the following error
|
||||||
|
# "Modbus request error: [Errno 11] EAGAIN"
|
||||||
|
# This is a socket timeout error
|
||||||
|
self._client_sock.settimeout(0.5)
|
||||||
|
|
||||||
|
if self._client_sock is not None:
|
||||||
|
try:
|
||||||
|
req = self._client_sock.recv(128)
|
||||||
|
|
||||||
|
if len(req) == 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
req_header_no_uid = req[:Const.MBAP_HDR_LENGTH - 1]
|
||||||
|
self._req_tid, req_pid, req_len = struct.unpack('>HHH', req_header_no_uid)
|
||||||
|
req_uid_and_pdu = req[Const.MBAP_HDR_LENGTH - 1:Const.MBAP_HDR_LENGTH + req_len - 1]
|
||||||
|
except OSError:
|
||||||
|
# MicroPython raises an OSError instead of socket.timeout
|
||||||
|
# print("Socket OSError aka TimeoutError: {}".format(e))
|
||||||
|
return None
|
||||||
|
except Exception:
|
||||||
|
# print("Modbus request error:", e)
|
||||||
|
self._client_sock.close()
|
||||||
|
self._client_sock = None
|
||||||
|
return None
|
||||||
|
|
||||||
|
if (req_pid != 0):
|
||||||
|
# print("Modbus request error: PID not 0")
|
||||||
|
self._client_sock.close()
|
||||||
|
self._client_sock = None
|
||||||
|
return None
|
||||||
|
|
||||||
|
if ((unit_addr_list is not None) and (req_uid_and_pdu[0] not in unit_addr_list)):
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
return Request(self, req_uid_and_pdu)
|
||||||
|
except ModbusException as e:
|
||||||
|
self.send_exception_response(req[0],
|
||||||
|
e.function_code,
|
||||||
|
e.exception_code)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def get_request(self,
|
||||||
|
unit_addr_list: Optional[list] = None,
|
||||||
|
timeout: int = None) -> Union[Request, None]:
|
||||||
|
"""
|
||||||
|
Check for request within the specified timeout
|
||||||
|
|
||||||
|
:param unit_addr_list: The unit address list
|
||||||
|
:type unit_addr_list: Optional[list]
|
||||||
|
:param timeout: The timeout
|
||||||
|
:type timeout: int
|
||||||
|
|
||||||
|
:returns: A request object or None.
|
||||||
|
:rtype: Union[Request, None]
|
||||||
|
|
||||||
|
:raises Exception: If no socket is configured and bound
|
||||||
|
"""
|
||||||
|
if self._sock is None:
|
||||||
|
raise Exception('Modbus TCP server not bound')
|
||||||
|
|
||||||
|
if timeout > 0:
|
||||||
|
start_ms = time.ticks_ms()
|
||||||
|
elapsed = 0
|
||||||
|
while True:
|
||||||
|
if self._client_sock is None:
|
||||||
|
accept_timeout = None if timeout is None else (timeout - elapsed) / 1000
|
||||||
|
else:
|
||||||
|
accept_timeout = 0
|
||||||
|
req = self._accept_request(accept_timeout, unit_addr_list)
|
||||||
|
if req:
|
||||||
|
return req
|
||||||
|
elapsed = time.ticks_diff(start_ms, time.ticks_ms())
|
||||||
|
if elapsed > timeout:
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
return self._accept_request(0, unit_addr_list)
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: UTF-8 -*-
|
||||||
|
|
||||||
|
"""
|
||||||
|
Fake classes of typing module.
|
||||||
|
|
||||||
|
https://github.com/micropython/micropython-lib/issues/190
|
||||||
|
|
||||||
|
https://github.com/micropython/micropython-lib/blob/3d779b8ceab5b65b9f70accbcbb15ab3509eceb7/typing/typing.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class _Subscriptable():
|
||||||
|
def __getitem__(self, item):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
_subscriptable = _Subscriptable()
|
||||||
|
|
||||||
|
|
||||||
|
class Any:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class NoReturn:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ClassVar:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
Union = _subscriptable
|
||||||
|
|
||||||
|
|
||||||
|
Optional = _subscriptable
|
||||||
|
|
||||||
|
|
||||||
|
class Generic:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class NamedTuple:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Hashable:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Awaitable:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Coroutine:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class AsyncIterable:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class AsyncIterator:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Iterable:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Iterator:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Reversible:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Sized:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Container:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Collection:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# class Callable:
|
||||||
|
# pass
|
||||||
|
Callable = _subscriptable
|
||||||
|
|
||||||
|
|
||||||
|
class AbstractSet:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class MutableSet:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Mapping:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class MutableMapping:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Sequence:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class MutableSequence:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ByteString:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
Tuple = _subscriptable
|
||||||
|
|
||||||
|
|
||||||
|
List = _subscriptable
|
||||||
|
|
||||||
|
|
||||||
|
class Deque:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Set:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class dict_keys:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class FrozenSet:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class MappingView:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class KeysView:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ItemsView:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ValuesView:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ContextManager:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class AsyncContextManager:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
Dict = _subscriptable
|
||||||
|
|
||||||
|
|
||||||
|
class DefaultDict:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Counter:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ChainMap:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Generator:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class AsyncGenerator:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Type:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def cast(typ, val):
|
||||||
|
return val
|
||||||
|
|
||||||
|
|
||||||
|
def _overload_dummy(*args, **kwds):
|
||||||
|
"""Helper for @overload to raise when called."""
|
||||||
|
raise NotImplementedError(
|
||||||
|
"You should not call an overloaded function. "
|
||||||
|
"A series of @overload-decorated functions "
|
||||||
|
"outside a stub module should always be followed "
|
||||||
|
"by an implementation that is not @overload-ed."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def overload():
|
||||||
|
return _overload_dummy
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: UTF-8 -*-
|
||||||
|
|
||||||
|
__version_info__ = ("2", "3", "7")
|
||||||
|
__version__ = '.'.join(__version_info__)
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
# wget http://file.ofs.com/hv/script/umqtt/mqtt.py script/umqtt/mqtt.py
|
||||||
|
# mqtt_client.py 测试
|
||||||
|
|
||||||
|
from script.umqtt.simple import MQTTClient
|
||||||
|
from binascii import hexlify
|
||||||
|
import machine
|
||||||
|
import _thread
|
||||||
|
import time, sys
|
||||||
|
|
||||||
|
|
||||||
|
class MQTTClientThread:
|
||||||
|
def __init__(self, server, client_id):
|
||||||
|
self.server = server
|
||||||
|
self.client_id = client_id
|
||||||
|
self.running = False
|
||||||
|
self.send_list = []
|
||||||
|
self.receive_list = []
|
||||||
|
self.lock = _thread.allocate_lock()
|
||||||
|
self.client = MQTTClient(client_id, server)
|
||||||
|
|
||||||
|
def sub_cb(self, topic, msg):
|
||||||
|
with self.lock:
|
||||||
|
self.receive_list.append((topic, msg)) # 将接收到的消息添加到接收列表
|
||||||
|
print("Received: {}".format((topic, msg)))
|
||||||
|
|
||||||
|
def run(self):
|
||||||
|
try:
|
||||||
|
self.client.set_callback(self.sub_cb)
|
||||||
|
self.client.connect()
|
||||||
|
print("Connected to {}".format(self.server))
|
||||||
|
|
||||||
|
for topic in self.sub_list:
|
||||||
|
self.client.subscribe(topic)
|
||||||
|
|
||||||
|
self.running = True
|
||||||
|
|
||||||
|
while self.running:
|
||||||
|
self.client.check_msg()
|
||||||
|
self.process_messages()
|
||||||
|
|
||||||
|
print("mqtt exit")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
sys.print_exception(e)
|
||||||
|
finally:
|
||||||
|
_thread.exit()
|
||||||
|
self.client.disconnect()
|
||||||
|
print("mqtt stop")
|
||||||
|
|
||||||
|
def process_messages(self):
|
||||||
|
with self.lock:
|
||||||
|
while self.send_list:
|
||||||
|
topic, msg, qos = self.send_list.pop(0) # 从发送列表中取出第一个消息
|
||||||
|
self.client.publish(topic, msg, qos)
|
||||||
|
# print("Sent: {} to topic: {} with QoS: {}".format(msg, topic, qos))
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
if not self.running:
|
||||||
|
_thread.stack_size(18192)
|
||||||
|
_thread.start_new_thread(self.run, ())
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
self.running = False
|
||||||
|
|
||||||
|
def send_message(self, topic, message, qos=0):
|
||||||
|
with self.lock:
|
||||||
|
self.send_list.append((topic, message, qos)) # 将消息添加到发送列表
|
||||||
|
# print("Queued for sending: {}".format((topic, message, qos)))
|
||||||
|
|
||||||
|
def take_message(self):
|
||||||
|
with self.lock:
|
||||||
|
if self.receive_list:
|
||||||
|
return self.receive_list.pop(0) # 返回并移除接收列表的第一个消息
|
||||||
|
else:
|
||||||
|
return None # 如果没有消息,返回 None
|
||||||
|
|
||||||
|
|
||||||
|
def start_mqtt_client(params={}):
|
||||||
|
server = params['broker']['ip']
|
||||||
|
client_id = params['broker']['clientid'] + hexlify(machine.unique_id()).decode()[0:8]
|
||||||
|
mqtt_client = MQTTClientThread(server, client_id)
|
||||||
|
mqtt_client.client.port = params['broker']['port']
|
||||||
|
mqtt_client.client.user = params['broker']['user']
|
||||||
|
mqtt_client.client.pswd = params['broker']['passwd']
|
||||||
|
mqtt_client.sub_list = params['topic']['sub']
|
||||||
|
mqtt_client.start()
|
||||||
|
return mqtt_client
|
||||||
|
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
import socket
|
||||||
|
import struct
|
||||||
|
from binascii import hexlify
|
||||||
|
|
||||||
|
|
||||||
|
class MQTTException(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class MQTTClient:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
client_id,
|
||||||
|
server,
|
||||||
|
port=0,
|
||||||
|
user=None,
|
||||||
|
password=None,
|
||||||
|
keepalive=0,
|
||||||
|
ssl=None,
|
||||||
|
ssl_params={},
|
||||||
|
):
|
||||||
|
if port == 0:
|
||||||
|
port = 8883 if ssl else 1883
|
||||||
|
self.client_id = client_id
|
||||||
|
self.sock = None
|
||||||
|
self.server = server
|
||||||
|
self.port = port
|
||||||
|
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, timeout=None):
|
||||||
|
self.sock = socket.socket()
|
||||||
|
self.sock.settimeout(timeout)
|
||||||
|
addr = socket.getaddrinfo(self.server, self.port)[0][-1]
|
||||||
|
self.sock.connect(addr)
|
||||||
|
if self.ssl is True:
|
||||||
|
# Legacy support for ssl=True and ssl_params arguments.
|
||||||
|
import ssl
|
||||||
|
|
||||||
|
self.sock = ssl.wrap_socket(self.sock, **self.ssl_params)
|
||||||
|
elif self.ssl:
|
||||||
|
self.sock = self.ssl.wrap_socket(self.sock, server_hostname=self.server)
|
||||||
|
premsg = bytearray(b"\x10\0\0\0\0\0")
|
||||||
|
msg = bytearray(b"\x04MQTT\x04\x02\0\0")
|
||||||
|
|
||||||
|
sz = 10 + 2 + len(self.client_id)
|
||||||
|
msg[6] = clean_session << 1
|
||||||
|
if self.user:
|
||||||
|
sz += 2 + len(self.user) + 2 + len(self.pswd)
|
||||||
|
msg[6] |= 0xC0
|
||||||
|
if self.keepalive:
|
||||||
|
assert self.keepalive < 65536
|
||||||
|
msg[7] |= self.keepalive >> 8
|
||||||
|
msg[8] |= self.keepalive & 0x00FF
|
||||||
|
if self.lw_topic:
|
||||||
|
sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
|
||||||
|
msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
|
||||||
|
msg[6] |= self.lw_retain << 5
|
||||||
|
|
||||||
|
i = 1
|
||||||
|
while sz > 0x7F:
|
||||||
|
premsg[i] = (sz & 0x7F) | 0x80
|
||||||
|
sz >>= 7
|
||||||
|
i += 1
|
||||||
|
premsg[i] = sz
|
||||||
|
|
||||||
|
self.sock.write(premsg, i + 2)
|
||||||
|
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:
|
||||||
|
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
|
||||||
|
return op
|
||||||
|
|
||||||
|
# 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()
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
wget http://file.ofs.com/hv/main.py main.py
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import binascii
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# 测试不同类型的字符串
|
||||||
|
# 1. 纯ASCII字符串
|
||||||
|
ascii_str = "a" * 4096
|
||||||
|
ascii_b64 = binascii.b2a_base64(ascii_str.encode('utf-8')).decode('ascii').rstrip('\n')
|
||||||
|
ascii_decoded = binascii.a2b_base64(ascii_b64)
|
||||||
|
print(f"纯ASCII字符串:")
|
||||||
|
print(f" 原始字符串长度: {len(ascii_str)}")
|
||||||
|
print(f" Base64编码后长度: {len(ascii_b64)}")
|
||||||
|
print(f" Base64解码后字节数: {len(ascii_decoded)}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
# 2. 包含中文字符的字符串
|
||||||
|
# 假设每2个ASCII字符后面跟着1个中文字符
|
||||||
|
chinese_str = """
|
||||||
|
测试中文编码对Base64长度的影响
|
||||||
|
这是一个包含中文的测试字符串,用于验证UTF-8编码的字节数计算
|
||||||
|
""" * 100 # 重复多次以达到足够长度
|
||||||
|
chinese_str = chinese_str[:4096] # 截取4096个字符
|
||||||
|
chinese_b64 = binascii.b2a_base64(chinese_str.encode('utf-8')).decode('ascii').rstrip('\n')
|
||||||
|
chinese_decoded = binascii.a2b_base64(chinese_b64)
|
||||||
|
print(f"包含中文字符的字符串:")
|
||||||
|
print(f" 原始字符串长度: {len(chinese_str)}")
|
||||||
|
print(f" UTF-8编码后字节数: {len(chinese_str.encode('utf-8'))}")
|
||||||
|
print(f" Base64编码后长度: {len(chinese_b64)}")
|
||||||
|
print(f" Base64解码后字节数: {len(chinese_decoded)}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
# 3. 混合字符串(更接近实际使用场景)
|
||||||
|
mixed_str = """
|
||||||
|
// 这是一个JavaScript文件的开头
|
||||||
|
// 包含中文注释和英文代码
|
||||||
|
function 测试函数() {
|
||||||
|
console.log("Hello, World!");
|
||||||
|
console.log("你好,世界!");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 重复内容以达到足够长度
|
||||||
|
""" * 50
|
||||||
|
mixed_str = mixed_str[:4096]
|
||||||
|
mixed_b64 = binascii.b2a_base64(mixed_str.encode('utf-8')).decode('ascii').rstrip('\n')
|
||||||
|
mixed_decoded = binascii.a2b_base64(mixed_b64)
|
||||||
|
print(f"混合字符串:")
|
||||||
|
print(f" 原始字符串长度: {len(mixed_str)}")
|
||||||
|
print(f" UTF-8编码后字节数: {len(mixed_str.encode('utf-8'))}")
|
||||||
|
print(f" Base64编码后长度: {len(mixed_b64)}")
|
||||||
|
print(f" Base64解码后字节数: {len(mixed_decoded)}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
print("结论:")
|
||||||
|
print(" - Base64解码后的字节数取决于原始字符串的UTF-8编码长度")
|
||||||
|
print(" - 对于包含非ASCII字符的字符串,解码后的字节数会大于原始字符串长度")
|
||||||
|
print(" - 这解释了为什么4096字符的字符串解码后可能有4160字节")
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
# µPing (MicroPing) for MicroPython
|
||||||
|
# copyright (c) 2018 Shawwwn <shawwwn1@gmail.com>
|
||||||
|
# License: MIT
|
||||||
|
#
|
||||||
|
# Internet Checksum Algorithm
|
||||||
|
# Author: Olav Morken
|
||||||
|
# https://github.com/olavmrk/python-ping/blob/master/ping.py
|
||||||
|
# @data: bytes
|
||||||
|
#
|
||||||
|
# source code from: https://forum.pycom.io/topic/4930/ping-command/15
|
||||||
|
#
|
||||||
|
def checksum(data):
|
||||||
|
if len(data) & 0x1: # Odd number of bytes
|
||||||
|
data += b'\0'
|
||||||
|
cs = 0
|
||||||
|
for pos in range(0, len(data), 2):
|
||||||
|
b1 = data[pos]
|
||||||
|
b2 = data[pos + 1]
|
||||||
|
cs += (b1 << 8) + b2
|
||||||
|
while cs >= 0x10000:
|
||||||
|
cs = (cs & 0xffff) + (cs >> 16)
|
||||||
|
cs = ~cs & 0xffff
|
||||||
|
return cs
|
||||||
|
|
||||||
|
def ping(host, count=4, timeout=5000, interval=10, quiet=False, size=64):
|
||||||
|
import utime
|
||||||
|
import uselect
|
||||||
|
import uctypes
|
||||||
|
import usocket
|
||||||
|
import ustruct
|
||||||
|
import uos
|
||||||
|
|
||||||
|
# prepare packet
|
||||||
|
assert size >= 16, "pkt size too small"
|
||||||
|
pkt = b'Q'*size
|
||||||
|
pkt_desc = {
|
||||||
|
"type": uctypes.UINT8 | 0,
|
||||||
|
"code": uctypes.UINT8 | 1,
|
||||||
|
"checksum": uctypes.UINT16 | 2,
|
||||||
|
"id": (uctypes.ARRAY | 4, 2 | uctypes.UINT8),
|
||||||
|
"seq": uctypes.INT16 | 6,
|
||||||
|
"timestamp": uctypes.UINT64 | 8,
|
||||||
|
} # packet header descriptor
|
||||||
|
h = uctypes.struct(uctypes.addressof(pkt), pkt_desc, uctypes.BIG_ENDIAN)
|
||||||
|
h.type = 8 # ICMP_ECHO_REQUEST
|
||||||
|
h.code = 0
|
||||||
|
h.checksum = 0
|
||||||
|
h.id[0:2] = uos.urandom(2)
|
||||||
|
h.seq = 1
|
||||||
|
|
||||||
|
# init socket
|
||||||
|
sock = usocket.socket(usocket.AF_INET, usocket.SOCK_RAW, 1)
|
||||||
|
sock.setblocking(0)
|
||||||
|
sock.settimeout(timeout/1000)
|
||||||
|
try:
|
||||||
|
addr = usocket.getaddrinfo(host, 1)[0][-1][0] # ip address
|
||||||
|
except IndexError:
|
||||||
|
not quiet and print("Could not determine the address of", host)
|
||||||
|
return None
|
||||||
|
sock.connect((addr, 1))
|
||||||
|
not quiet and print("PING %s (%s): %u data bytes" % (host, addr, len(pkt)))
|
||||||
|
|
||||||
|
seqs = list(range(1, count+1)) # [1,2,...,count]
|
||||||
|
c = 1
|
||||||
|
t = 0
|
||||||
|
n_trans = 0
|
||||||
|
n_recv = 0
|
||||||
|
finish = False
|
||||||
|
while t < timeout:
|
||||||
|
if t==interval and c<=count:
|
||||||
|
# send packet
|
||||||
|
h.checksum = 0
|
||||||
|
h.seq = c
|
||||||
|
h.timestamp = utime.ticks_us()
|
||||||
|
h.checksum = checksum(pkt)
|
||||||
|
if sock.send(pkt) == size:
|
||||||
|
n_trans += 1
|
||||||
|
t = 0 # reset timeout
|
||||||
|
else:
|
||||||
|
seqs.remove(c)
|
||||||
|
c += 1
|
||||||
|
|
||||||
|
# recv packet
|
||||||
|
while 1:
|
||||||
|
socks, _, _ = uselect.select([sock], [], [], 0)
|
||||||
|
if socks:
|
||||||
|
resp = socks[0].recv(4096)
|
||||||
|
resp_mv = memoryview(resp)
|
||||||
|
h2 = uctypes.struct(uctypes.addressof(resp_mv[20:]), pkt_desc, uctypes.BIG_ENDIAN)
|
||||||
|
# TODO: validate checksum (optional)
|
||||||
|
seq = h2.seq
|
||||||
|
if h2.type==0 and h2.id==h.id and (seq in seqs): # 0: ICMP_ECHO_REPLY
|
||||||
|
t_elasped = (utime.ticks_us()-h2.timestamp) / 1000
|
||||||
|
ttl = ustruct.unpack('!B', resp_mv[8:9])[0] # time-to-live
|
||||||
|
n_recv += 1
|
||||||
|
not quiet and print("%u bytes from %s: icmp_seq=%u, ttl=%u, time=%f ms" % (len(resp), addr, seq, ttl, t_elasped))
|
||||||
|
seqs.remove(seq)
|
||||||
|
if len(seqs) == 0:
|
||||||
|
finish = True
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
if finish:
|
||||||
|
break
|
||||||
|
|
||||||
|
utime.sleep_ms(1)
|
||||||
|
t += 1
|
||||||
|
|
||||||
|
# close
|
||||||
|
sock.close()
|
||||||
|
ret = (n_trans, n_recv)
|
||||||
|
not quiet and print("%u packets transmitted, %u packets received" % (n_trans, n_recv))
|
||||||
|
return (n_trans, n_recv)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
ping('192.168.100.10')
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 5.4 KiB |
+2018
File diff suppressed because it is too large
Load Diff
Binary file not shown.
+6
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
Binary file not shown.
+1
@@ -0,0 +1 @@
|
|||||||
|
.cm-s-monokai.CodeMirror{background:#272822;color:#f8f8f2}.cm-s-monokai div.CodeMirror-selected{background:#49483e}.cm-s-monokai .CodeMirror-line::selection,.cm-s-monokai .CodeMirror-line>span::selection,.cm-s-monokai .CodeMirror-line>span>span::selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-line::-moz-selection,.cm-s-monokai .CodeMirror-line>span::-moz-selection,.cm-s-monokai .CodeMirror-line>span>span::-moz-selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-gutters{background:#272822;border-right:0}.cm-s-monokai .CodeMirror-guttermarker{color:#fff}.cm-s-monokai .CodeMirror-guttermarker-subtle{color:#d0d0d0}.cm-s-monokai .CodeMirror-linenumber{color:#d0d0d0}.cm-s-monokai .CodeMirror-cursor{border-left:1px solid #f8f8f0}.cm-s-monokai span.cm-comment{color:#75715e}.cm-s-monokai span.cm-atom{color:#ae81ff}.cm-s-monokai span.cm-number{color:#ae81ff}.cm-s-monokai span.cm-comment.cm-attribute{color:#97b757}.cm-s-monokai span.cm-comment.cm-def{color:#bc9262}.cm-s-monokai span.cm-comment.cm-tag{color:#bc6283}.cm-s-monokai span.cm-comment.cm-type{color:#5998a6}.cm-s-monokai span.cm-attribute,.cm-s-monokai span.cm-property{color:#a6e22e}.cm-s-monokai span.cm-keyword{color:#f92672}.cm-s-monokai span.cm-builtin{color:#66d9ef}.cm-s-monokai span.cm-string{color:#e6db74}.cm-s-monokai span.cm-variable{color:#f8f8f2}.cm-s-monokai span.cm-variable-2{color:#9effff}.cm-s-monokai span.cm-type,.cm-s-monokai span.cm-variable-3{color:#66d9ef}.cm-s-monokai span.cm-def{color:#fd971f}.cm-s-monokai span.cm-bracket{color:#f8f8f2}.cm-s-monokai span.cm-tag{color:#f92672}.cm-s-monokai span.cm-header{color:#ae81ff}.cm-s-monokai span.cm-link{color:#ae81ff}.cm-s-monokai span.cm-error{background:#f92672;color:#f8f8f0}.cm-s-monokai .CodeMirror-activeline-background{background:#373831}.cm-s-monokai .CodeMirror-matchingbracket{text-decoration:underline;color:#fff!important}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
.card {
|
||||||
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-header {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-control {
|
||||||
|
font-size: 1.1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feedbackVoltage,
|
||||||
|
#feedbackCurrent,
|
||||||
|
#filamentVoltage,
|
||||||
|
#filamentCurrent {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #0d6efd;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* 导航栏样式 */
|
||||||
|
.navbar {
|
||||||
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar-brand {
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link {
|
||||||
|
font-size: 1.1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link i {
|
||||||
|
margin-right: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 编辑器相关样式 */
|
||||||
|
.CodeMirror {
|
||||||
|
height: calc(100vh - 200px);
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#fileTree {
|
||||||
|
height: calc(100vh - 200px);
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jstree-default .jstree-icon {
|
||||||
|
color: #0d6efd;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jstree-default .jstree-themeicon {
|
||||||
|
color: #6c757d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jstree-default .jstree-themeicon-custom {
|
||||||
|
color: #0d6efd;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 文件类型图标颜色 */
|
||||||
|
.bi-filetype-py {
|
||||||
|
color: #306998;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bi-filetype-json {
|
||||||
|
color: #f7df1e;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bi-filetype-sh {
|
||||||
|
color: #4eaa25;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bi-folder {
|
||||||
|
color: #ffc107;
|
||||||
|
}
|
||||||
Vendored
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,325 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>测偏仪DAQ测试台</title>
|
||||||
|
<link href="css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<link href="css/bootstrap-icons.css" rel="stylesheet">
|
||||||
|
<link href="css/style.min.css" rel="stylesheet">
|
||||||
|
<link href="css/codemirror.min.css" rel="stylesheet">
|
||||||
|
<link href="css/monokai.min.css" rel="stylesheet">
|
||||||
|
|
||||||
|
<link href="css/style.css" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<!-- 导航栏 -->
|
||||||
|
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
|
||||||
|
<div class="container">
|
||||||
|
<a class="navbar-brand" href="/">测偏仪DAQ测试台</a>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="container-fluid mt-4">
|
||||||
|
<!-- Toast提示组件 -->
|
||||||
|
<div class="position-fixed top-0 start-50 translate-middle-x p-3" style="z-index: 11">
|
||||||
|
<div id="toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
|
||||||
|
<div class="toast-header">
|
||||||
|
<strong class="me-auto">系统提示</strong>
|
||||||
|
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
|
||||||
|
</div>
|
||||||
|
<div class="toast-body"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 选项卡 -->
|
||||||
|
<ul class="nav nav-tabs mb-3" id="mainTab" role="tablist">
|
||||||
|
<li class="nav-item" role="presentation">
|
||||||
|
<button class="nav-link active" id="panel-tab" data-bs-toggle="tab" data-bs-target="#panel"
|
||||||
|
type="button" role="tab" aria-controls="panel" aria-selected="true">控制面板</button>
|
||||||
|
</li>
|
||||||
|
<li class="nav-item" role="presentation">
|
||||||
|
<button class="nav-link" id="script-tab" data-bs-toggle="tab" data-bs-target="#script" type="button"
|
||||||
|
role="tab" aria-controls="script" aria-selected="false"><i class="bi bi-code-square"></i>
|
||||||
|
脚本编辑器</button>
|
||||||
|
</li>
|
||||||
|
<li class="nav-item" role="presentation">
|
||||||
|
<button class="nav-link" id="firmware-tab" data-bs-toggle="tab" data-bs-target="#firmware" type="button"
|
||||||
|
role="tab" aria-controls="firmware" aria-selected="false"><i class="bi bi-pc-display"></i>
|
||||||
|
固件升级</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div class="tab-content" id="mainTabContent">
|
||||||
|
<!-- 固件升级 -->
|
||||||
|
<div class="tab-pane fade" id="firmware" role="tabpanel" aria-labelledby="firmware-tab">
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-6">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">固件升级</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<!-- 显示当前版本 -->
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label">当前固件版本:</label>
|
||||||
|
<span id="currentVersion">--------</span>
|
||||||
|
</div>
|
||||||
|
<!-- 选择固件文件 -->
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="firmwareFile" class="form-label">选择固件文件 (.bin)</label>
|
||||||
|
<input type="file" class="form-control" id="firmwareFile" accept=".bin">
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label">文件信息</label>
|
||||||
|
<div class="form-control" id="fileInfo" style="height: auto;">
|
||||||
|
<div>文件名: <span id="fileName"></span></div>
|
||||||
|
<div>文件大小: <span id="fileSize"></span></div>
|
||||||
|
<div>校验值: <span id="fileChecksum"></span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label">上传进度</label>
|
||||||
|
<div class="progress" style="height: 30px;">
|
||||||
|
<div class="progress-bar progress-bar-striped progress-bar-animated"
|
||||||
|
id="uploadProgress" role="progressbar"
|
||||||
|
style="width: 0%;"
|
||||||
|
aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
|
||||||
|
0%
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="d-grid gap-2">
|
||||||
|
<button class="btn btn-primary" id="startUpload" disabled>
|
||||||
|
<i class="bi bi-upload"></i> 开始上传
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-danger" id="cancelUpload" disabled>
|
||||||
|
<i class="bi bi-x-circle"></i> 取消上传
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-success" id="upgradeFirmware" disabled>
|
||||||
|
<i class="bi bi-play-circle"></i> 执行升级
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="mt-3">
|
||||||
|
<label class="form-label">升级日志</label>
|
||||||
|
<div class="form-control" id="upgradeLog" style="height: 200px; overflow-y: auto;"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-6">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">升级说明</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<h5 class="card-title">注意事项</h5>
|
||||||
|
<ul class="list-unstyled">
|
||||||
|
<li><i class="bi bi-exclamation-triangle text-warning"></i> 固件升级过程中请勿断电</li>
|
||||||
|
<li><i class="bi bi-exclamation-triangle text-warning"></i> 升级完成后设备会自动重启</li>
|
||||||
|
<li><i class="bi bi-exclamation-triangle text-warning"></i> 请确保上传的是正确的固件文件</li>
|
||||||
|
<li><i class="bi bi-exclamation-triangle text-warning"></i> 升级过程可能需要几分钟时间</li>
|
||||||
|
</ul>
|
||||||
|
<h5 class="card-title mt-4">升级步骤</h5>
|
||||||
|
<ol>
|
||||||
|
<li>点击"选择固件文件"按钮选择.bin格式的固件文件</li>
|
||||||
|
<li>等待系统计算文件校验值</li>
|
||||||
|
<li>点击"开始上传"按钮上传固件文件</li>
|
||||||
|
<li>上传完成后点击"执行升级"按钮开始升级</li>
|
||||||
|
<li>等待升级完成,设备会自动重启</li>
|
||||||
|
</ol>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<!-- 控制面板 -->
|
||||||
|
<div class="tab-pane fade show active" id="panel" role="tabpanel" aria-labelledby="panel-tab">
|
||||||
|
<!-- DAQ数据采集控制 -->
|
||||||
|
<div class="row mb-4">
|
||||||
|
<div class="col-md-12">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">DAQ数据采集</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-1">
|
||||||
|
<button class="btn btn-warning" id="reboot">设备重启</button>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-1">
|
||||||
|
<button class="btn btn-success" id="start_daq">开始采集</button>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-1">
|
||||||
|
<button class="btn btn-danger" id="stop_daq">停止采集</button>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-2">
|
||||||
|
<div class="input-group">
|
||||||
|
<span class="input-group-text">采集时长</span>
|
||||||
|
<input type="number" class="form-control" id="daq_duration" value="1000" min="100" max="10000" step="100">
|
||||||
|
<span class="input-group-text">ms</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-2">
|
||||||
|
<div class="input-group">
|
||||||
|
<span class="input-group-text">序列号</span>
|
||||||
|
<div class="form-control" id="daq_info">--</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-md">
|
||||||
|
<div class="input-group">
|
||||||
|
<span class="input-group-text">DAQ状态</span>
|
||||||
|
<div class="form-control" id="daq_status">--</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 数据曲线图 -->
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-12">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">数据曲线</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<canvas id="daq_chart" width="800" height="400"></canvas>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 数据统计信息 -->
|
||||||
|
<div class="row mt-4">
|
||||||
|
<div class="col-md-12">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header d-flex justify-content-between align-items-center">
|
||||||
|
<span>数据统计信息</span>
|
||||||
|
<div class="btn-group" role="group" aria-label="数据操作按钮组">
|
||||||
|
<button id="save_data" class="btn btn-primary btn-sm px-2">
|
||||||
|
<i class="bi bi-save me-1"></i> 保存到设备
|
||||||
|
</button>
|
||||||
|
<button id="load_device" class="btn btn-info btn-sm px-2">
|
||||||
|
<i class="bi bi-hdd me-1"></i> 从设备载入
|
||||||
|
</button>
|
||||||
|
<button id="export_csv" class="btn btn-secondary btn-sm px-2">
|
||||||
|
<i class="bi bi-download me-1"></i> 导出CSV
|
||||||
|
</button>
|
||||||
|
<button id="load_local" class="btn btn-success btn-sm px-2">
|
||||||
|
<i class="bi bi-upload me-1"></i> 从本地载入
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped table-bordered">
|
||||||
|
<thead class="table-dark">
|
||||||
|
<tr>
|
||||||
|
<th>采集时间</th>
|
||||||
|
<th>数据长度</th>
|
||||||
|
<th>CH1平均值</th>
|
||||||
|
<th>CH1峰峰值</th>
|
||||||
|
<th>CH1波动水平</th>
|
||||||
|
<th>CH2平均值</th>
|
||||||
|
<th>CH2峰峰值</th>
|
||||||
|
<th>CH2波动水平</th>
|
||||||
|
<th>通道间差异</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="stats_table_body">
|
||||||
|
<!-- 统计数据将通过JavaScript动态添加 -->
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<!-- 脚本编辑器 -->
|
||||||
|
<div class="tab-pane fade" id="script" role="tabpanel" aria-labelledby="script-tab">
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-3">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header d-flex justify-content-between align-items-center">
|
||||||
|
<span>文件目录</span>
|
||||||
|
<div>
|
||||||
|
<button class="btn btn-sm btn-primary" id="refreshTree">
|
||||||
|
<i class="bi bi-arrow-clockwise"></i> 刷新
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div id="fileTree"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-9">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header d-flex justify-content-between align-items-center">
|
||||||
|
<span id="currentFile">未选择文件</span>
|
||||||
|
<div>
|
||||||
|
<button class="btn btn-sm btn-success" id="saveFile" disabled>
|
||||||
|
<i class="bi bi-save"></i> 保存
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-sm btn-danger" id="deleteFile" disabled>
|
||||||
|
<i class="bi bi-trash"></i> 删除
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<textarea id="editor"></textarea>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script src="js/lib/jquery.min.js"></script>
|
||||||
|
<script src="js/lib/bootstrap.bundle.min.js"></script>
|
||||||
|
<script src="js/lib/jstree.min.js"></script>
|
||||||
|
<script src="js/lib/codemirror.min.js"></script>
|
||||||
|
<script src="js/lib/python.min.js"></script>
|
||||||
|
<script src="js/lib/javascript.min.js"></script>
|
||||||
|
<script src="js/lib/shell.min.js"></script>
|
||||||
|
<script src="js/lib/htmlmixed.min.js"></script>
|
||||||
|
<script src="js/lib/xml.min.js"></script>
|
||||||
|
<script src="js/lib/css.min.js"></script>
|
||||||
|
<script src="js/lib/base64.min.js"></script>
|
||||||
|
<script src="js/lib/hammer.min.js"></script>
|
||||||
|
<script src="js/lib/chart.min.js"></script>
|
||||||
|
<script src="js/lib/chartjs-plugin-zoom.min.js"></script>
|
||||||
|
|
||||||
|
<!-- 模块化脚本文件 -->
|
||||||
|
<script src="js/ui-utils.js"></script>
|
||||||
|
<script src="js/websocket.js"></script>
|
||||||
|
<script src="js/firmware-upgrade.js"></script>
|
||||||
|
<script src="js/script-editor.js"></script>
|
||||||
|
<script src="js/chart.js"></script>
|
||||||
|
|
||||||
|
<script src="js/main.js"></script>
|
||||||
|
|
||||||
|
<!-- 序列号设置模态对话框 -->
|
||||||
|
<div class="modal fade" id="snModal" tabindex="-1" aria-labelledby="snModalLabel" aria-hidden="true">
|
||||||
|
<div class="modal-dialog">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h5 class="modal-title" id="snModalLabel">设置序列号</h5>
|
||||||
|
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="snInput" class="form-label">新序列号</label>
|
||||||
|
<input type="text" class="form-control" id="snInput" placeholder="请输入新的序列号">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
|
||||||
|
<button type="button" class="btn btn-primary" id="saveSnBtn">确定</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,573 @@
|
|||||||
|
// chart.js - 图表功能模块
|
||||||
|
|
||||||
|
const ChartModule = (function() {
|
||||||
|
let daqChart = null;
|
||||||
|
let chartData = {
|
||||||
|
ch1: [],
|
||||||
|
ch2: []
|
||||||
|
};
|
||||||
|
|
||||||
|
function getCurrentSn() {
|
||||||
|
// 从设备信息中获取SN并移除所有空格和所有斜杠
|
||||||
|
return $('#daq_info').text().replace(/\s+/g, '').replace(/\//g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化图表模块
|
||||||
|
function init() {
|
||||||
|
// 初始化图表
|
||||||
|
initChart();
|
||||||
|
|
||||||
|
// 设置拖动和缩放模式切换
|
||||||
|
initZoomControls();
|
||||||
|
|
||||||
|
// 将处理DAQ数据的函数暴露到全局
|
||||||
|
window.handleDaqData = handleDaqData;
|
||||||
|
|
||||||
|
// 添加删除行按钮的事件委托
|
||||||
|
const tbody = document.getElementById('stats_table_body');
|
||||||
|
tbody.addEventListener('click', function(event) {
|
||||||
|
if (event.target.closest('.delete-row')) {
|
||||||
|
const row = event.target.closest('tr');
|
||||||
|
row.remove();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 绑定功能按钮事件
|
||||||
|
bindFunctionButtons();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 绑定功能按钮事件
|
||||||
|
function bindFunctionButtons() {
|
||||||
|
// 导出CSV
|
||||||
|
document.getElementById('export_csv').addEventListener('click', exportToCSV);
|
||||||
|
|
||||||
|
// 保存到设备
|
||||||
|
document.getElementById('save_data').addEventListener('click', saveDataToDevice);
|
||||||
|
|
||||||
|
// 从本地载入
|
||||||
|
document.getElementById('load_local').addEventListener('click', loadDataFromLocal);
|
||||||
|
|
||||||
|
// 从设备载入
|
||||||
|
document.getElementById('load_device').addEventListener('click', loadDataFromDevice);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 导出数据到CSV文件
|
||||||
|
function exportToCSV() {
|
||||||
|
const table = document.querySelector('#stats_table_body');
|
||||||
|
const rows = table.querySelectorAll('tr');
|
||||||
|
|
||||||
|
// 获取表头
|
||||||
|
const headerRow = document.querySelector('#stats_table_body').previousElementSibling.querySelector('tr');
|
||||||
|
const headers = Array.from(headerRow.querySelectorAll('th')).map(th => {
|
||||||
|
// 移除操作列
|
||||||
|
if (th.textContent.trim() === '操作') return '';
|
||||||
|
return th.textContent.trim();
|
||||||
|
}).filter(h => h);
|
||||||
|
|
||||||
|
// 构建CSV内容
|
||||||
|
let csvContent = 'data:text/csv;charset=utf-8,';
|
||||||
|
csvContent += headers.join(',') + '\n';
|
||||||
|
|
||||||
|
// 添加行数据
|
||||||
|
rows.forEach(row => {
|
||||||
|
const cells = Array.from(row.querySelectorAll('td'));
|
||||||
|
const rowData = cells.map((cell, index) => {
|
||||||
|
// 跳过操作列
|
||||||
|
if (index === cells.length - 1) return '';
|
||||||
|
return cell.textContent.trim();
|
||||||
|
}).filter(d => d);
|
||||||
|
csvContent += rowData.join(',') + '\n';
|
||||||
|
});
|
||||||
|
|
||||||
|
// 创建下载链接
|
||||||
|
const sn = getCurrentSn();
|
||||||
|
const encodedUri = encodeURI(csvContent);
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.setAttribute('href', encodedUri);
|
||||||
|
link.setAttribute('download', `daq_stats_${sn}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.csv`);
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
document.body.removeChild(link);
|
||||||
|
|
||||||
|
// 显示提示
|
||||||
|
UIUtils.showToast('数据已导出为CSV文件');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存数据到设备
|
||||||
|
function saveDataToDevice() {
|
||||||
|
const table = document.querySelector('#stats_table_body');
|
||||||
|
const rows = table.querySelectorAll('tr');
|
||||||
|
|
||||||
|
// 收集所有统计数据
|
||||||
|
const statsData = Array.from(rows).map(row => {
|
||||||
|
const cells = Array.from(row.querySelectorAll('td'));
|
||||||
|
return {
|
||||||
|
time: cells[0].textContent.trim(),
|
||||||
|
dataLength: parseInt(cells[1].textContent.trim()),
|
||||||
|
ch1: {
|
||||||
|
average: parseFloat(cells[2].textContent.trim()),
|
||||||
|
peakToPeak: parseFloat(cells[3].textContent.trim()),
|
||||||
|
snr: parseFloat(cells[4].textContent.trim())
|
||||||
|
},
|
||||||
|
ch2: {
|
||||||
|
average: parseFloat(cells[5].textContent.trim()),
|
||||||
|
peakToPeak: parseFloat(cells[6].textContent.trim()),
|
||||||
|
snr: parseFloat(cells[7].textContent.trim())
|
||||||
|
},
|
||||||
|
channelDiff: parseFloat(cells[8].textContent.trim())
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(statsData);
|
||||||
|
// 从设备信息中获取SN并移除空格和/
|
||||||
|
const sn = getCurrentSn();
|
||||||
|
// 生成文件名
|
||||||
|
const filename = `stats_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.json`;
|
||||||
|
|
||||||
|
// 通过HTTP POST发送数据到设备
|
||||||
|
fetch('/api/stats/save', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
sn: sn,
|
||||||
|
filename: filename,
|
||||||
|
stats: statsData
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
if (data.success) {
|
||||||
|
UIUtils.showToast('统计数据已保存到设备');
|
||||||
|
} else {
|
||||||
|
UIUtils.showToast(`保存失败: ${data.message}`, 'error');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
UIUtils.showToast(`保存失败: ${error.message}`, 'error');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 显示提示
|
||||||
|
UIUtils.showToast('正在保存数据到设备...');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从本地载入数据
|
||||||
|
function loadDataFromLocal() {
|
||||||
|
const input = document.createElement('input');
|
||||||
|
input.type = 'file';
|
||||||
|
input.accept = '.csv';
|
||||||
|
|
||||||
|
input.onchange = function(e) {
|
||||||
|
const file = e.target.files[0];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = function(event) {
|
||||||
|
const csvContent = event.target.result;
|
||||||
|
parseCSVAndLoadData(csvContent);
|
||||||
|
};
|
||||||
|
|
||||||
|
reader.readAsText(file);
|
||||||
|
};
|
||||||
|
|
||||||
|
input.click();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析CSV并加载数据
|
||||||
|
function parseCSVAndLoadData(csvContent) {
|
||||||
|
const lines = csvContent.split('\n');
|
||||||
|
if (lines.length < 2) {
|
||||||
|
UIUtils.showToast('CSV文件格式错误');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清空现有表格
|
||||||
|
const tbody = document.getElementById('stats_table_body');
|
||||||
|
tbody.innerHTML = '';
|
||||||
|
|
||||||
|
// 收集所有数据行到数组
|
||||||
|
const dataRows = [];
|
||||||
|
|
||||||
|
// 跳过表头行,从数据行开始处理
|
||||||
|
for (let i = 1; i < lines.length; i++) {
|
||||||
|
const line = lines[i].trim();
|
||||||
|
if (!line) continue;
|
||||||
|
|
||||||
|
const cells = line.split(',');
|
||||||
|
if (cells.length < 9) continue;
|
||||||
|
|
||||||
|
// 收集数据行,包含时间和所有单元格
|
||||||
|
dataRows.push({ time: cells[0], cells: cells });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 按时间字符串倒序排列,确保最新数据在前
|
||||||
|
dataRows.sort((a, b) => {
|
||||||
|
if (a.time > b.time) return -1;
|
||||||
|
if (a.time < b.time) return 1;
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
// 将排序后的数据行添加到表格
|
||||||
|
dataRows.forEach(row => {
|
||||||
|
const cells = row.cells;
|
||||||
|
|
||||||
|
// 创建新的表格行
|
||||||
|
const newRow = `
|
||||||
|
<tr>
|
||||||
|
<td>${cells[0]}</td>
|
||||||
|
<td>${cells[1]}</td>
|
||||||
|
<td>${cells[2]}</td>
|
||||||
|
<td>${cells[3]}</td>
|
||||||
|
<td>${cells[4]}</td>
|
||||||
|
<td>${cells[5]}</td>
|
||||||
|
<td>${cells[6]}</td>
|
||||||
|
<td>${cells[7]}</td>
|
||||||
|
<td>${cells[8]}</td>
|
||||||
|
<td>
|
||||||
|
<button class="btn btn-danger btn-sm delete-row">
|
||||||
|
<i class="bi bi-trash"></i> 删除
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
`;
|
||||||
|
|
||||||
|
// 添加到表格
|
||||||
|
tbody.insertAdjacentHTML('beforeend', newRow);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 显示提示
|
||||||
|
UIUtils.showToast('数据已从本地CSV文件加载');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从设备载入数据
|
||||||
|
function loadDataFromDevice() {
|
||||||
|
// 通过HTTP GET从设备获取数据
|
||||||
|
const sn = getCurrentSn();
|
||||||
|
fetch('/api/stats/load?sn=' + sn)
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
if (data.success) {
|
||||||
|
// 清空现有表格
|
||||||
|
const tbody = document.getElementById('stats_table_body');
|
||||||
|
tbody.innerHTML = '';
|
||||||
|
|
||||||
|
// 检查是否有数据,
|
||||||
|
if (!data.data.stats || data.data.stats.length === 0) {
|
||||||
|
UIUtils.showToast('设备上没有统计数据');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 按时间字符串倒序排列,确保最新数据在前
|
||||||
|
const sortedStats = data.data.stats.sort((a, b) => {
|
||||||
|
// 比较时间字符串,倒序排列
|
||||||
|
if (a.time > b.time) return -1;
|
||||||
|
if (a.time < b.time) return 1;
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
sortedStats.forEach(stat => {
|
||||||
|
const newRow = `
|
||||||
|
<tr>
|
||||||
|
<td>${stat.time}</td>
|
||||||
|
<td>${stat.dataLength}</td>
|
||||||
|
<td>${stat.ch1.average}</td>
|
||||||
|
<td>${stat.ch1.peakToPeak}</td>
|
||||||
|
<td>${stat.ch1.snr}%</td>
|
||||||
|
<td>${stat.ch2.average}</td>
|
||||||
|
<td>${stat.ch2.peakToPeak}</td>
|
||||||
|
<td>${stat.ch2.snr}%</td>
|
||||||
|
<td>${stat.channelDiff}%</td>
|
||||||
|
<td>
|
||||||
|
<button class="btn btn-danger btn-sm delete-row">
|
||||||
|
<i class="bi bi-trash"></i> 删除
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
`;
|
||||||
|
tbody.insertAdjacentHTML('beforeend', newRow);
|
||||||
|
});
|
||||||
|
|
||||||
|
UIUtils.showToast('统计数据已从设备加载');
|
||||||
|
} else {
|
||||||
|
UIUtils.showToast(`加载失败: ${data.message}`, 'error');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
UIUtils.showToast(`加载失败: ${error.message}`, 'error');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 显示提示
|
||||||
|
UIUtils.showToast('正在从设备加载数据...');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化图表
|
||||||
|
function initChart() {
|
||||||
|
const ctx = document.getElementById('daq_chart').getContext('2d');
|
||||||
|
daqChart = new Chart(ctx, {
|
||||||
|
type: 'line',
|
||||||
|
data: {
|
||||||
|
labels: [],
|
||||||
|
datasets: [
|
||||||
|
{
|
||||||
|
label: 'CH1',
|
||||||
|
data: [],
|
||||||
|
borderColor: 'rgba(219, 24, 67, 1)',
|
||||||
|
backgroundColor: 'rgba(219, 24, 67, 1)',
|
||||||
|
borderWidth: 1,
|
||||||
|
fill: false,
|
||||||
|
tension: 0,
|
||||||
|
pointRadius: 3,
|
||||||
|
pointBackgroundColor: 'rgba(219, 24, 67, 1)',
|
||||||
|
pointBorderColor: 'rgba(219, 24, 67, 1)',
|
||||||
|
pointHoverRadius: 5,
|
||||||
|
pointHoverBackgroundColor: 'rgba(219, 24, 67, 0.8)',
|
||||||
|
pointHoverBorderColor: 'rgba(219, 24, 67, 1)'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'CH2',
|
||||||
|
data: [],
|
||||||
|
borderColor: 'rgba(10, 49, 223, 1)',
|
||||||
|
backgroundColor: 'rgba(10, 49, 223, 1)',
|
||||||
|
borderWidth: 1,
|
||||||
|
fill: false,
|
||||||
|
tension: 0,
|
||||||
|
pointRadius: 3,
|
||||||
|
pointBackgroundColor: 'rgba(10, 49, 223, 1)',
|
||||||
|
pointBorderColor: 'rgba(10, 49, 223, 1)',
|
||||||
|
pointHoverRadius: 5,
|
||||||
|
pointHoverBackgroundColor: 'rgba(10, 49, 223, 0.8)',
|
||||||
|
pointHoverBorderColor: 'rgba(10, 49, 223, 1)'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
scales: {
|
||||||
|
x: {
|
||||||
|
title: {
|
||||||
|
display: true,
|
||||||
|
text: '样本点'
|
||||||
|
},
|
||||||
|
grid: {
|
||||||
|
color: 'rgba(0, 0, 0, 0.1)'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
y: {
|
||||||
|
title: {
|
||||||
|
display: true,
|
||||||
|
text: '数值 (uint16)'
|
||||||
|
},
|
||||||
|
min: 0,
|
||||||
|
max: 65535,
|
||||||
|
grid: {
|
||||||
|
color: 'rgba(0, 0, 0, 0.1)'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
animation: false,
|
||||||
|
plugins: {
|
||||||
|
zoom: {
|
||||||
|
pan: {
|
||||||
|
enabled: true,
|
||||||
|
mode: 'xy',
|
||||||
|
speed: 10,
|
||||||
|
threshold: 10,
|
||||||
|
scaleMode: 'xy'
|
||||||
|
},
|
||||||
|
zoom: {
|
||||||
|
wheel: {
|
||||||
|
enabled: true,
|
||||||
|
speed: 0.1
|
||||||
|
},
|
||||||
|
drag: {
|
||||||
|
enabled: false,
|
||||||
|
borderColor: 'rgba(255, 255, 255, 0.5)',
|
||||||
|
borderWidth: 1,
|
||||||
|
backgroundColor: 'rgba(225, 225, 225, 0.3)',
|
||||||
|
drawTime: 'beforeDatasetsDraw'
|
||||||
|
},
|
||||||
|
pinch: {
|
||||||
|
enabled: true
|
||||||
|
},
|
||||||
|
mode: 'xy',
|
||||||
|
speed: 0.1,
|
||||||
|
scaleMode: 'xy'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化缩放控制
|
||||||
|
function initZoomControls() {
|
||||||
|
// 重置缩放按钮
|
||||||
|
$('#reset_zoom').on('click', function() {
|
||||||
|
if (daqChart) {
|
||||||
|
daqChart.resetZoom();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 缩放模式切换按钮
|
||||||
|
$('.zoom-mode-btn').on('click', function() {
|
||||||
|
const mode = $(this).data('mode');
|
||||||
|
|
||||||
|
// 更新按钮状态
|
||||||
|
$('.zoom-mode-btn').removeClass('active');
|
||||||
|
$(this).addClass('active');
|
||||||
|
|
||||||
|
// 更新图表缩放模式
|
||||||
|
if (daqChart) {
|
||||||
|
daqChart.options.plugins.zoom.pan.mode = mode;
|
||||||
|
daqChart.options.plugins.zoom.zoom.mode = mode;
|
||||||
|
daqChart.update('none');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理DAQ数据
|
||||||
|
function handleDaqData(daqData) {
|
||||||
|
if (!daqData || !daqData.data) {
|
||||||
|
console.error('无效的DAQ数据格式');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 解析数据
|
||||||
|
const parsedData = parseDaqData(daqData.data);
|
||||||
|
|
||||||
|
// 更新图表数据
|
||||||
|
chartData.ch1 = parsedData.ch1;
|
||||||
|
chartData.ch2 = parsedData.ch2;
|
||||||
|
|
||||||
|
// 更新图表
|
||||||
|
updateChart();
|
||||||
|
|
||||||
|
// 计算并显示统计信息
|
||||||
|
calculateAndDisplayStats(parsedData.ch1, parsedData.ch2);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('解析DAQ数据失败:', error);
|
||||||
|
showToast('解析DAQ数据失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算并显示统计信息
|
||||||
|
function calculateAndDisplayStats(ch1Data, ch2Data) {
|
||||||
|
// 计算各通道统计值
|
||||||
|
const ch1Stats = calculateStats(ch1Data);
|
||||||
|
const ch2Stats = calculateStats(ch2Data);
|
||||||
|
|
||||||
|
// 获取当前时间
|
||||||
|
const currentTime = new Date().toLocaleString();
|
||||||
|
|
||||||
|
const diff = Math.abs(ch1Stats.average - ch2Stats.average) / (Math.max(ch1Stats.average, ch2Stats.average) || 1) * 100;
|
||||||
|
|
||||||
|
// 创建新的表格行
|
||||||
|
const newRow = `
|
||||||
|
<tr>
|
||||||
|
<td>${currentTime}</td>
|
||||||
|
<td>${ch1Data.length}</td>
|
||||||
|
<td>${ch1Stats.average.toFixed(0)}</td>
|
||||||
|
<td>${ch1Stats.peakToPeak.toFixed(0)}</td>
|
||||||
|
<td>${ch1Stats.snr.toFixed(0)}%</td>
|
||||||
|
<td>${ch2Stats.average.toFixed(0)}</td>
|
||||||
|
<td>${ch2Stats.peakToPeak.toFixed(0)}</td>
|
||||||
|
<td>${ch2Stats.snr.toFixed(0)}%</td>
|
||||||
|
<td>${diff.toFixed(0)}%</td>
|
||||||
|
<td>
|
||||||
|
<button class="btn btn-danger btn-sm delete-row">
|
||||||
|
<i class="bi bi-trash"></i> 删除
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
`;
|
||||||
|
|
||||||
|
// 添加到表格顶部
|
||||||
|
const tbody = document.getElementById('stats_table_body');
|
||||||
|
tbody.insertAdjacentHTML('afterbegin', newRow);
|
||||||
|
|
||||||
|
// 限制表格行数(最多保留100条记录)
|
||||||
|
const maxRows = 100;
|
||||||
|
while (tbody.rows.length > maxRows) {
|
||||||
|
tbody.deleteRow(tbody.rows.length - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算单通道统计值
|
||||||
|
function calculateStats(data) {
|
||||||
|
if (!data || data.length === 0) {
|
||||||
|
return { average: 0, peakToPeak: 0, snr: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算平均值
|
||||||
|
const sum = data.reduce((acc, val) => acc + val, 0);
|
||||||
|
const average = sum / data.length;
|
||||||
|
|
||||||
|
// 计算峰峰值
|
||||||
|
const max = Math.max(...data);
|
||||||
|
const min = Math.min(...data);
|
||||||
|
const peakToPeak = max - min;
|
||||||
|
|
||||||
|
// 计算信噪比 (SNR)
|
||||||
|
// 简单实现:假设噪声是信号的标准差
|
||||||
|
|
||||||
|
const snr = average === 0 ? 0 : peakToPeak / average * 100;
|
||||||
|
|
||||||
|
return { average, peakToPeak, snr };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== DAQ数据处理相关 ==========
|
||||||
|
// 解析base64编码的uint16小端数据
|
||||||
|
function parseDaqData(base64Data) {
|
||||||
|
// 解码base64数据
|
||||||
|
const binaryData = atob(base64Data);
|
||||||
|
const dataView = new DataView(new ArrayBuffer(binaryData.length));
|
||||||
|
|
||||||
|
// 将二进制数据写入DataView
|
||||||
|
for (let i = 0; i < binaryData.length; i++) {
|
||||||
|
dataView.setUint8(i, binaryData.charCodeAt(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析uint16小端数据
|
||||||
|
const data = [];
|
||||||
|
for (let i = 4; i < binaryData.length; i += 2) { // 跳过前4字节头
|
||||||
|
data.push(dataView.getUint16(i, true)); // true表示小端
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分离CH1和CH2数据
|
||||||
|
const ch1 = [];
|
||||||
|
const ch2 = [];
|
||||||
|
for (let i = 0; i < data.length; i += 2) {
|
||||||
|
ch1.push(data[i]);
|
||||||
|
if (i + 1 < data.length) {
|
||||||
|
ch2.push(data[i + 1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ch1, ch2 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新图表
|
||||||
|
function updateChart() {
|
||||||
|
if (!daqChart) {
|
||||||
|
initChart();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新标签和数据
|
||||||
|
const labels = chartData.ch1.map((_, index) => index);
|
||||||
|
|
||||||
|
daqChart.data.labels = labels;
|
||||||
|
daqChart.data.datasets[0].data = chartData.ch1;
|
||||||
|
daqChart.data.datasets[1].data = chartData.ch2;
|
||||||
|
|
||||||
|
daqChart.update('none');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 暴露公共方法
|
||||||
|
return {
|
||||||
|
init: init,
|
||||||
|
updateChart: updateChart
|
||||||
|
};
|
||||||
|
})();
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
// firmware-upgrade.js - 固件升级模块
|
||||||
|
|
||||||
|
const FirmwareUpgrade = (function() {
|
||||||
|
const CHUNK_SIZE = 4096; // 4KB 分段大小
|
||||||
|
let uploadInProgress = false;
|
||||||
|
let uploadOffset = 0;
|
||||||
|
let uploadFile = null;
|
||||||
|
let fileChecksum = '';
|
||||||
|
|
||||||
|
// 初始化固件升级功能
|
||||||
|
function init() {
|
||||||
|
// 文件选择事件
|
||||||
|
$('#firmwareFile').on('change', handleFileSelect);
|
||||||
|
|
||||||
|
// 开始上传按钮点击事件
|
||||||
|
$('#startUpload').on('click', handleStartUpload);
|
||||||
|
|
||||||
|
// 取消上传按钮点击事件
|
||||||
|
$('#cancelUpload').on('click', handleCancelUpload);
|
||||||
|
|
||||||
|
// 执行升级按钮点击事件
|
||||||
|
$('#upgradeFirmware').on('click', handleUpgradeFirmware);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理文件选择
|
||||||
|
function handleFileSelect(e) {
|
||||||
|
const file = e.target.files[0];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
// 验证文件类型
|
||||||
|
if (!file.name.endsWith('.bin')) {
|
||||||
|
showToast('请选择.bin格式的固件文件');
|
||||||
|
$(this).val('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示文件信息
|
||||||
|
$('#fileName').text(file.name);
|
||||||
|
$('#fileSize').text(formatFileSize(file.size));
|
||||||
|
|
||||||
|
// 计算校验和
|
||||||
|
calculateFileChecksum(file);
|
||||||
|
|
||||||
|
// 重置状态
|
||||||
|
uploadOffset = 0;
|
||||||
|
uploadFile = file;
|
||||||
|
$('#uploadProgress').css('width', '0%').text('0%').attr('aria-valuenow', 0);
|
||||||
|
$('#startUpload').prop('disabled', true);
|
||||||
|
$('#upgradeFirmware').prop('disabled', true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算文件校验和
|
||||||
|
function calculateFileChecksum(file) {
|
||||||
|
$('#fileChecksum').text('计算中...');
|
||||||
|
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = function(e) {
|
||||||
|
const arrayBuffer = e.target.result;
|
||||||
|
const checksum = calculateChecksum(arrayBuffer);
|
||||||
|
fileChecksum = checksum;
|
||||||
|
$('#fileChecksum').text(checksum);
|
||||||
|
|
||||||
|
// 启用上传按钮
|
||||||
|
$('#startUpload').prop('disabled', false);
|
||||||
|
};
|
||||||
|
reader.onerror = function() {
|
||||||
|
$('#fileChecksum').text('计算失败');
|
||||||
|
showToast('文件校验和计算失败');
|
||||||
|
};
|
||||||
|
|
||||||
|
reader.readAsArrayBuffer(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算校验和的函数
|
||||||
|
function calculateChecksum(arrayBuffer) {
|
||||||
|
let checksum = 0;
|
||||||
|
const dataView = new DataView(arrayBuffer);
|
||||||
|
|
||||||
|
// 对每个字节进行累加,32位
|
||||||
|
for (let i = 0; i < dataView.byteLength; i++) {
|
||||||
|
checksum = (checksum + dataView.getUint8(i)) & 0xFFFFFFFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 转换为十六进制字符串,确保8位
|
||||||
|
return checksum.toString(16).padStart(8, '0');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 格式化文件大小
|
||||||
|
function formatFileSize(bytes) {
|
||||||
|
if (bytes < 1024) return bytes + ' B';
|
||||||
|
else if (bytes < 1048576) return (bytes / 1024).toFixed(2) + ' KB';
|
||||||
|
else return (bytes / 1048576).toFixed(2) + ' MB';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理开始上传
|
||||||
|
function handleStartUpload() {
|
||||||
|
if (!uploadFile) return;
|
||||||
|
|
||||||
|
$('#startUpload').prop('disabled', true);
|
||||||
|
$('#cancelUpload').prop('disabled', false);
|
||||||
|
uploadInProgress = true;
|
||||||
|
|
||||||
|
// 清空日志
|
||||||
|
$('#upgradeLog').text('开始上传固件...\n');
|
||||||
|
|
||||||
|
// 开始分段上传
|
||||||
|
uploadOffset = 0;
|
||||||
|
uploadNextChunk();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理取消上传
|
||||||
|
function handleCancelUpload() {
|
||||||
|
uploadInProgress = false;
|
||||||
|
$(this).prop('disabled', true);
|
||||||
|
|
||||||
|
// 发送取消请求
|
||||||
|
$.ajax({
|
||||||
|
url: '/api/firmware/cancel',
|
||||||
|
type: 'POST',
|
||||||
|
success: function() {
|
||||||
|
showToast('固件上传已取消');
|
||||||
|
$('#upgradeLog').append('上传已取消\n');
|
||||||
|
},
|
||||||
|
error: function() {
|
||||||
|
showToast('取消上传失败');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理执行升级
|
||||||
|
function handleUpgradeFirmware() {
|
||||||
|
$(this).prop('disabled', true);
|
||||||
|
$('#upgradeLog').append('开始执行固件升级...\n');
|
||||||
|
|
||||||
|
$.ajax({
|
||||||
|
url: '/api/firmware/upgrade',
|
||||||
|
type: 'POST',
|
||||||
|
contentType: 'application/json',
|
||||||
|
success: function(response) {
|
||||||
|
if (response.success) {
|
||||||
|
$('#upgradeLog').append('固件升级成功!\n');
|
||||||
|
$('#upgradeLog').append('设备将在1秒后重启...\n');
|
||||||
|
showToast('固件升级成功,设备将在1秒后重启');
|
||||||
|
} else {
|
||||||
|
$('#upgradeLog').append('升级失败:' + response.message + '\n');
|
||||||
|
showToast('固件升级失败:' + response.message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: function(xhr) {
|
||||||
|
let message = '升级请求失败';
|
||||||
|
if (xhr.responseJSON && xhr.responseJSON.message) {
|
||||||
|
message = xhr.responseJSON.message;
|
||||||
|
}
|
||||||
|
$('#upgradeLog').append('升级失败:' + message + '\n');
|
||||||
|
showToast('固件升级失败:' + message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 上传下一个文件块
|
||||||
|
function uploadNextChunk() {
|
||||||
|
if (!uploadInProgress || !uploadFile) return;
|
||||||
|
|
||||||
|
// 计算当前块的开始和结束位置
|
||||||
|
const start = uploadOffset;
|
||||||
|
const end = Math.min(start + CHUNK_SIZE, uploadFile.size);
|
||||||
|
const chunk = uploadFile.slice(start, end);
|
||||||
|
|
||||||
|
// 读取块内容并转换为Base64
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = function(e) {
|
||||||
|
const chunkData = e.target.result;
|
||||||
|
const base64Data = btoa(chunkData);
|
||||||
|
|
||||||
|
// 发送上传请求
|
||||||
|
$.ajax({
|
||||||
|
url: '/api/firmware/upload',
|
||||||
|
type: 'POST',
|
||||||
|
contentType: 'application/json',
|
||||||
|
data: JSON.stringify({
|
||||||
|
content: base64Data,
|
||||||
|
offset: start,
|
||||||
|
final: end >= uploadFile.size
|
||||||
|
}),
|
||||||
|
success: function(response) {
|
||||||
|
if (response.success) {
|
||||||
|
uploadOffset = response.offset;
|
||||||
|
|
||||||
|
// 更新进度
|
||||||
|
const progress = Math.min(Math.round((uploadOffset / uploadFile.size) * 100), 100);
|
||||||
|
$('#uploadProgress').css('width', progress + '%').text(progress + '%').attr('aria-valuenow', progress);
|
||||||
|
|
||||||
|
// 检查是否完成
|
||||||
|
if (response.final || uploadOffset >= uploadFile.size) {
|
||||||
|
$('#upgradeLog').append('固件上传完成!\n');
|
||||||
|
$('#upgradeLog').append('正在验证固件...\n');
|
||||||
|
|
||||||
|
// 验证固件
|
||||||
|
verifyFirmware();
|
||||||
|
} else {
|
||||||
|
// 继续上传下一块
|
||||||
|
setTimeout(uploadNextChunk, 100); // 添加小延迟,避免请求过于频繁
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new Error(response.message || '上传失败');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: function(xhr) {
|
||||||
|
let message = '上传失败';
|
||||||
|
if (xhr.responseJSON && xhr.responseJSON.message) {
|
||||||
|
message = xhr.responseJSON.message;
|
||||||
|
}
|
||||||
|
$('#upgradeLog').append('上传失败:' + message + '\n');
|
||||||
|
showToast('固件上传失败:' + message);
|
||||||
|
uploadInProgress = false;
|
||||||
|
$('#cancelUpload').prop('disabled', true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
reader.readAsBinaryString(chunk);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证固件
|
||||||
|
function verifyFirmware() {
|
||||||
|
$.ajax({
|
||||||
|
url: '/api/firmware/verify',
|
||||||
|
type: 'POST',
|
||||||
|
contentType: 'application/json',
|
||||||
|
data: JSON.stringify({
|
||||||
|
checksum: fileChecksum,
|
||||||
|
size: uploadFile.size
|
||||||
|
}),
|
||||||
|
success: function(response) {
|
||||||
|
if (response.success) {
|
||||||
|
$('#upgradeLog').append('固件验证成功!\n');
|
||||||
|
$('#upgradeLog').append('可以点击"执行升级"按钮进行升级\n');
|
||||||
|
$('#upgradeFirmware').prop('disabled', false);
|
||||||
|
$('#cancelUpload').prop('disabled', true);
|
||||||
|
showToast('固件上传完成并通过验证');
|
||||||
|
} else {
|
||||||
|
throw new Error(response.message || '验证失败');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: function(xhr) {
|
||||||
|
let message = '验证失败';
|
||||||
|
if (xhr.responseJSON && xhr.responseJSON.message) {
|
||||||
|
message = xhr.responseJSON.message;
|
||||||
|
}
|
||||||
|
$('#upgradeLog').append('验证失败:' + message + '\n');
|
||||||
|
showToast('固件验证失败:' + message);
|
||||||
|
$('#cancelUpload').prop('disabled', true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 暴露公共方法
|
||||||
|
return {
|
||||||
|
init: init
|
||||||
|
};
|
||||||
|
})();
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* Minified by jsDelivr using Terser v5.15.1.
|
||||||
|
* Original file: /npm/js-base64@3.7.5/base64.js
|
||||||
|
*
|
||||||
|
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
||||||
|
*/
|
||||||
|
!function(t,n){var r,e;"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(r=t.Base64,(e=n()).noConflict=function(){return t.Base64=r,e},t.Meteor&&(Base64=e),t.Base64=e)}("undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:this,(function(){"use strict";var t,n="3.7.5",r="function"==typeof atob,e="function"==typeof btoa,o="function"==typeof Buffer,u="function"==typeof TextDecoder?new TextDecoder:void 0,i="function"==typeof TextEncoder?new TextEncoder:void 0,f=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),c=(t={},f.forEach((function(n,r){return t[n]=r})),t),a=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,d=String.fromCharCode.bind(String),s="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):function(t){return new Uint8Array(Array.prototype.slice.call(t,0))},l=function(t){return t.replace(/=/g,"").replace(/[+\/]/g,(function(t){return"+"==t?"-":"_"}))},h=function(t){return t.replace(/[^A-Za-z0-9\+\/]/g,"")},p=function(t){for(var n,r,e,o,u="",i=t.length%3,c=0;c<t.length;){if((r=t.charCodeAt(c++))>255||(e=t.charCodeAt(c++))>255||(o=t.charCodeAt(c++))>255)throw new TypeError("invalid character found");u+=f[(n=r<<16|e<<8|o)>>18&63]+f[n>>12&63]+f[n>>6&63]+f[63&n]}return i?u.slice(0,i-3)+"===".substring(i):u},y=e?function(t){return btoa(t)}:o?function(t){return Buffer.from(t,"binary").toString("base64")}:p,A=o?function(t){return Buffer.from(t).toString("base64")}:function(t){for(var n=[],r=0,e=t.length;r<e;r+=4096)n.push(d.apply(null,t.subarray(r,r+4096)));return y(n.join(""))},b=function(t,n){return void 0===n&&(n=!1),n?l(A(t)):A(t)},g=function(t){if(t.length<2)return(n=t.charCodeAt(0))<128?t:n<2048?d(192|n>>>6)+d(128|63&n):d(224|n>>>12&15)+d(128|n>>>6&63)+d(128|63&n);var n=65536+1024*(t.charCodeAt(0)-55296)+(t.charCodeAt(1)-56320);return d(240|n>>>18&7)+d(128|n>>>12&63)+d(128|n>>>6&63)+d(128|63&n)},B=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,x=function(t){return t.replace(B,g)},C=o?function(t){return Buffer.from(t,"utf8").toString("base64")}:i?function(t){return A(i.encode(t))}:function(t){return y(x(t))},m=function(t,n){return void 0===n&&(n=!1),n?l(C(t)):C(t)},v=function(t){return m(t,!0)},U=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,F=function(t){switch(t.length){case 4:var n=((7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3))-65536;return d(55296+(n>>>10))+d(56320+(1023&n));case 3:return d((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return d((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},w=function(t){return t.replace(U,F)},S=function(t){if(t=t.replace(/\s+/g,""),!a.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(3&t.length));for(var n,r,e,o="",u=0;u<t.length;)n=c[t.charAt(u++)]<<18|c[t.charAt(u++)]<<12|(r=c[t.charAt(u++)])<<6|(e=c[t.charAt(u++)]),o+=64===r?d(n>>16&255):64===e?d(n>>16&255,n>>8&255):d(n>>16&255,n>>8&255,255&n);return o},E=r?function(t){return atob(h(t))}:o?function(t){return Buffer.from(t,"base64").toString("binary")}:S,D=o?function(t){return s(Buffer.from(t,"base64"))}:function(t){return s(E(t).split("").map((function(t){return t.charCodeAt(0)})))},R=function(t){return D(T(t))},z=o?function(t){return Buffer.from(t,"base64").toString("utf8")}:u?function(t){return u.decode(D(t))}:function(t){return w(E(t))},T=function(t){return h(t.replace(/[-_]/g,(function(t){return"-"==t?"+":"/"})))},Z=function(t){return z(T(t))},j=function(t){return{value:t,enumerable:!1,writable:!0,configurable:!0}},I=function(){var t=function(t,n){return Object.defineProperty(String.prototype,t,j(n))};t("fromBase64",(function(){return Z(this)})),t("toBase64",(function(t){return m(this,t)})),t("toBase64URI",(function(){return m(this,!0)})),t("toBase64URL",(function(){return m(this,!0)})),t("toUint8Array",(function(){return R(this)}))},O=function(){var t=function(t,n){return Object.defineProperty(Uint8Array.prototype,t,j(n))};t("toBase64",(function(t){return b(this,t)})),t("toBase64URI",(function(){return b(this,!0)})),t("toBase64URL",(function(){return b(this,!0)}))},P={version:n,VERSION:"3.7.5",atob:E,atobPolyfill:S,btoa:y,btoaPolyfill:p,fromBase64:Z,toBase64:m,encode:m,encodeURI:v,encodeURL:v,utob:x,btou:w,decode:Z,isValid:function(t){if("string"!=typeof t)return!1;var n=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(n)||!/[^\s0-9a-zA-Z\-_]/.test(n)},fromUint8Array:b,toUint8Array:R,extendString:I,extendUint8Array:O,extendBuiltins:function(){I(),O()},Base64:{}};return Object.keys(P).forEach((function(t){return P.Base64[t]=P[t]})),P}));
|
||||||
|
//# sourceMappingURL=/sm/555281732ed54ee1693a772f485329378d8ea5052ffa4370e9c2e9947eb42d22.map
|
||||||
File diff suppressed because one or more lines are too long
+13
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
Vendored
+1
File diff suppressed because one or more lines are too long
+7
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
|||||||
|
!function(t){"object"==typeof exports&&"object"==typeof module?t(require("../../lib/codemirror"),require("../xml/xml"),require("../javascript/javascript"),require("../css/css")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../xml/xml","../javascript/javascript","../css/css"],t):t(CodeMirror)}(function(m){"use strict";var l={script:[["lang",/(javascript|babel)/i,"javascript"],["type",/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i,"javascript"],["type",/./,"text/plain"],[null,null,"javascript"]],style:[["lang",/^css$/i,"css"],["type",/^(text\/)?(x-)?(stylesheet|css)$/i,"css"],["type",/./,"text/plain"],[null,null,"css"]]};var a={};function d(t,e){e=t.match(a[e=e]||(a[e]=new RegExp("\\s+"+e+"\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*")));return e?/^\s*(.*?)\s*$/.exec(e[2])[1]:""}function g(t,e){return new RegExp((e?"^":"")+"</\\s*"+t+"\\s*>","i")}function o(t,e){for(var a in t)for(var n=e[a]||(e[a]=[]),l=t[a],o=l.length-1;0<=o;o--)n.unshift(l[o])}m.defineMode("htmlmixed",function(i,t){var c=m.getMode(i,{name:"xml",htmlMode:!0,multilineTagIndentFactor:t.multilineTagIndentFactor,multilineTagIndentPastTag:t.multilineTagIndentPastTag,allowMissingTagName:t.allowMissingTagName}),s={},e=t&&t.tags,a=t&&t.scriptTypes;if(o(l,s),e&&o(e,s),a)for(var n=a.length-1;0<=n;n--)s.script.unshift(["type",a[n].matches,a[n].mode]);function u(t,e){var a,o,r,n=c.token(t,e.htmlState),l=/\btag\b/.test(n);return l&&!/[<>\s\/]/.test(t.current())&&(a=e.htmlState.tagName&&e.htmlState.tagName.toLowerCase())&&s.hasOwnProperty(a)?e.inTag=a+" ":e.inTag&&l&&/>$/.test(t.current())?(a=/^([\S]+) (.*)/.exec(e.inTag),e.inTag=null,l=">"==t.current()&&function(t,e){for(var a=0;a<t.length;a++){var n=t[a];if(!n[0]||n[1].test(d(e,n[0])))return n[2]}}(s[a[1]],a[2]),l=m.getMode(i,l),o=g(a[1],!0),r=g(a[1],!1),e.token=function(t,e){return t.match(o,!1)?(e.token=u,e.localState=e.localMode=null):(a=t,n=r,l=e.localMode.token(t,e.localState),t=a.current(),-1<(e=t.search(n))?a.backUp(t.length-e):t.match(/<\/?$/)&&(a.backUp(t.length),a.match(n,!1)||a.match(t)),l);var a,n,l},e.localMode=l,e.localState=m.startState(l,c.indent(e.htmlState,"",""))):e.inTag&&(e.inTag+=t.current(),t.eol()&&(e.inTag+=" ")),n}return{startState:function(){return{token:u,inTag:null,localMode:null,localState:null,htmlState:m.startState(c)}},copyState:function(t){var e;return t.localState&&(e=m.copyState(t.localMode,t.localState)),{token:t.token,inTag:t.inTag,localMode:t.localMode,localState:e,htmlState:m.copyState(c,t.htmlState)}},token:function(t,e){return e.token(t,e)},indent:function(t,e,a){return!t.localMode||/^\s*<\//.test(e)?c.indent(t.htmlState,e,a):t.localMode.indent?t.localMode.indent(t.localState,e,a):m.Pass},innerMode:function(t){return{state:t.localState||t.htmlState,mode:t.localMode||c}}}},"xml","javascript","css"),m.defineMIME("text/html","htmlmixed")});
|
||||||
+1
File diff suppressed because one or more lines are too long
+2
File diff suppressed because one or more lines are too long
+6
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
|||||||
|
!function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(s){"use strict";s.defineMode("shell",function(){var o={};function e(e,t){for(var n=0;n<t.length;n++)o[t[n]]=e}var t=["true","false"],n=["if","then","do","else","elif","while","until","for","in","esac","fi","fin","fil","done","exit","set","unset","export","function"],r=["ab","awk","bash","beep","cat","cc","cd","chown","chmod","chroot","clear","cp","curl","cut","diff","echo","find","gawk","gcc","get","git","grep","hg","kill","killall","ln","ls","make","mkdir","openssl","mv","nc","nl","node","npm","ping","ps","restart","rm","rmdir","sed","service","sh","shopt","shred","source","sort","sleep","ssh","start","stop","su","sudo","svn","tee","telnet","top","touch","vi","vim","wall","wc","wget","who","write","yes","zsh"];function i(e,t){if(e.eatSpace())return null;var n,r=e.sol(),i=e.next();if("\\"===i)return e.next(),null;if("'"===i||'"'===i||"`"===i)return t.tokens.unshift(f(i,"`"===i?"quote":"string")),l(e,t);if("#"===i)return r&&e.eat("!")?(e.skipToEnd(),"meta"):(e.skipToEnd(),"comment");if("$"===i)return t.tokens.unshift(u),l(e,t);if("+"===i||"="===i)return"operator";if("-"===i)return e.eat("-"),e.eatWhile(/\w/),"attribute";if("<"==i){if(e.match("<<"))return"operator";r=e.match(/^<-?\s*['"]?([^'"]*)['"]?/);if(r)return t.tokens.unshift((n=r[1],function(e,t){return e.sol()&&e.string==n&&t.tokens.shift(),e.skipToEnd(),"string-2"})),"string-2"}if(/\d/.test(i)&&(e.eatWhile(/\d/),e.eol()||!/\w/.test(e.peek())))return"number";e.eatWhile(/[\w-]/);i=e.current();return"="===e.peek()&&/\w+/.test(i)?"def":o.hasOwnProperty(i)?o[i]:null}function f(i,o){var s="("==i?")":"{"==i?"}":i;return function(e,t){for(var n,r=!1;null!=(n=e.next());){if(n===s&&!r){t.tokens.shift();break}if("$"===n&&!r&&"'"!==i&&e.peek()!=s){r=!0,e.backUp(1),t.tokens.unshift(u);break}if(!r&&i!==s&&n===i)return t.tokens.unshift(f(i,o)),l(e,t);if(!r&&/['"]/.test(n)&&!/['"]/.test(i)){t.tokens.unshift(function(n,r){return function(e,t){return t.tokens[0]=f(n,r),e.next(),l(e,t)}}(n,"string")),e.backUp(1);break}r=!r&&"\\"===n}return o}}s.registerHelper("hintWords","shell",t.concat(n,r)),e("atom",t),e("keyword",n),e("builtin",r);var u=function(e,t){1<t.tokens.length&&e.eat("$");var n=e.next();return/['"({]/.test(n)?(t.tokens[0]=f(n,"("==n?"quote":"{"==n?"def":"string"),l(e,t)):(/\d/.test(n)||e.eatWhile(/\w/),t.tokens.shift(),"def")};function l(e,t){return(t.tokens[0]||i)(e,t)}return{startState:function(){return{tokens:[]}},token:l,closeBrackets:"()[]{}''\"\"``",lineComment:"#",fold:"brace"}}),s.defineMIME("text/x-sh","shell"),s.defineMIME("application/x-sh","shell")});
|
||||||
Vendored
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,8 @@
|
|||||||
|
$(document).ready(function() {
|
||||||
|
// 初始化所有模块
|
||||||
|
UIUtils.init();
|
||||||
|
WebSocketManager.init();
|
||||||
|
FirmwareUpgrade.init();
|
||||||
|
ScriptEditor.init();
|
||||||
|
ChartModule.init();
|
||||||
|
});
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
// script-editor.js - 脚本编辑器模块
|
||||||
|
|
||||||
|
const ScriptEditor = (function() {
|
||||||
|
let scriptTabInited = false;
|
||||||
|
let editor = null;
|
||||||
|
|
||||||
|
// 初始化脚本编辑器功能
|
||||||
|
function init() {
|
||||||
|
// 监听标签页切换事件
|
||||||
|
$('button[data-bs-toggle="tab"]').on('shown.bs.tab', handleTabShown);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理标签页显示事件
|
||||||
|
function handleTabShown(e) {
|
||||||
|
console.log('tab shown', e);
|
||||||
|
const target = $(e.target).attr('data-bs-target');
|
||||||
|
|
||||||
|
// 初始化脚本编辑器
|
||||||
|
if (target === '#script' && !scriptTabInited) {
|
||||||
|
initCodeMirror();
|
||||||
|
initFileTree();
|
||||||
|
|
||||||
|
// 保存文件 - 分段写入
|
||||||
|
$('#saveFile').click(function() {
|
||||||
|
const path = $('#currentFile').text();
|
||||||
|
const fullContent = editor.getValue();
|
||||||
|
const chunkSize = 4096; // 4K 分段
|
||||||
|
const totalSize = fullContent.length;
|
||||||
|
const totalChunks = Math.ceil(totalSize / chunkSize);
|
||||||
|
let currentChunk = 0;
|
||||||
|
let currentOffset = 0;
|
||||||
|
|
||||||
|
showToast('正在保存文件...');
|
||||||
|
|
||||||
|
// 分段写入函数
|
||||||
|
function writeChunk(offset) {
|
||||||
|
if (offset >= totalSize) {
|
||||||
|
// 所有分块写入完成,请求服务器进行最终校验和重命名
|
||||||
|
$.ajax({
|
||||||
|
url: '/api/script/write/finalize',
|
||||||
|
type: 'POST',
|
||||||
|
contentType: 'application/json',
|
||||||
|
data: JSON.stringify({
|
||||||
|
path: path,
|
||||||
|
total_size: totalSize
|
||||||
|
}),
|
||||||
|
success: function(response) {
|
||||||
|
if (response.success) {
|
||||||
|
showToast('文件保存成功');
|
||||||
|
} else {
|
||||||
|
showToast('文件保存成功,但最终校验失败:' + response.message);
|
||||||
|
console.warn('文件校验失败,但内容可能已保存:', response.message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: function() {
|
||||||
|
// 即使最终校验请求失败,我们仍然告知用户文件已保存
|
||||||
|
// 因为分块已经写入,只是可能没有进行最后的重命名和校验
|
||||||
|
showToast('文件内容已保存,但最终处理请求失败');
|
||||||
|
console.warn('最终处理请求失败');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取当前分块内容
|
||||||
|
const chunkContent = fullContent.substring(offset, offset + chunkSize);
|
||||||
|
// 使用js-base64库编码
|
||||||
|
const encodedContent = Base64.encode(chunkContent);
|
||||||
|
const isFinal = offset + chunkSize >= totalSize;
|
||||||
|
|
||||||
|
// 更新进度
|
||||||
|
currentChunk++;
|
||||||
|
const progress = Math.min(100, Math.round((currentChunk / totalChunks) * 100));
|
||||||
|
showToast('正在保存文件... (' + progress + '%)');
|
||||||
|
|
||||||
|
$.ajax({
|
||||||
|
url: '/api/script/write',
|
||||||
|
type: 'POST',
|
||||||
|
contentType: 'application/json',
|
||||||
|
data: JSON.stringify({
|
||||||
|
path: path,
|
||||||
|
content: encodedContent,
|
||||||
|
offset: offset,
|
||||||
|
final: isFinal
|
||||||
|
}),
|
||||||
|
success: function(response) {
|
||||||
|
if (response.success) {
|
||||||
|
// 继续写入下一个分块
|
||||||
|
setTimeout(function() {
|
||||||
|
writeChunk(response.offset);
|
||||||
|
}, 10); // 短暂延迟,避免请求过于密集
|
||||||
|
} else {
|
||||||
|
showToast('保存文件失败:' + response.message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: function(jqXHR, textStatus, errorThrown) {
|
||||||
|
console.log('分段写入失败:', textStatus, errorThrown);
|
||||||
|
// 如果分段写入失败,尝试使用旧的一次性写入方式作为降级方案
|
||||||
|
console.log('分段写入失败,尝试一次性写入');
|
||||||
|
const fullEncodedContent = Base64.encode(fullContent);
|
||||||
|
$.ajax({
|
||||||
|
url: '/api/script/write',
|
||||||
|
type: 'POST',
|
||||||
|
contentType: 'application/json',
|
||||||
|
data: JSON.stringify({
|
||||||
|
path: path,
|
||||||
|
content: fullEncodedContent
|
||||||
|
}),
|
||||||
|
success: function(backupResponse) {
|
||||||
|
if (backupResponse.success) {
|
||||||
|
showToast('文件保存成功');
|
||||||
|
} else {
|
||||||
|
showToast('保存文件失败:' + backupResponse.message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: function() {
|
||||||
|
showToast('保存文件失败:服务器错误');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 开始写入第一个分块
|
||||||
|
writeChunk(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 删除文件
|
||||||
|
$('#deleteFile').click(function() {
|
||||||
|
if (confirm('确定要删除这个文件吗?')) {
|
||||||
|
const path = $('#currentFile').text();
|
||||||
|
$.ajax({
|
||||||
|
url: '/api/script/delete',
|
||||||
|
type: 'POST',
|
||||||
|
contentType: 'application/json',
|
||||||
|
data: JSON.stringify({
|
||||||
|
path: path
|
||||||
|
}),
|
||||||
|
success: function(response) {
|
||||||
|
if (response.success) {
|
||||||
|
showToast('文件删除成功');
|
||||||
|
$('#currentFile').text('未选择文件');
|
||||||
|
editor.setValue('');
|
||||||
|
$('#saveFile, #deleteFile').prop('disabled', true);
|
||||||
|
$('#fileTree').jstree('refresh');
|
||||||
|
} else {
|
||||||
|
showToast('删除文件失败:' + response.message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: function(jqXHR, textStatus, errorThrown) {
|
||||||
|
showToast('删除文件失败:服务器错误');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 刷新文件树
|
||||||
|
$('#refreshTree').click(function() {
|
||||||
|
console.log('刷新文件树');
|
||||||
|
$('#fileTree').jstree('refresh');
|
||||||
|
});
|
||||||
|
|
||||||
|
scriptTabInited = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化CodeMirror编辑器
|
||||||
|
function initCodeMirror() {
|
||||||
|
// 初始化CodeMirror
|
||||||
|
editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
|
||||||
|
mode: 'text/x-python',
|
||||||
|
theme: 'monokai',
|
||||||
|
lineNumbers: true,
|
||||||
|
indentUnit: 4,
|
||||||
|
lineWrapping: true,
|
||||||
|
matchBrackets: true,
|
||||||
|
autoCloseBrackets: true
|
||||||
|
});
|
||||||
|
|
||||||
|
editor.setValue("请选择一个文件");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化文件树
|
||||||
|
function initFileTree() {
|
||||||
|
// 初始化文件树
|
||||||
|
$('#fileTree').jstree({
|
||||||
|
'core': {
|
||||||
|
'data': {
|
||||||
|
'url': function(node) {
|
||||||
|
const url = node.id === '#' ? '/api/script/list' : '/api/script/list?path=' + node.id;
|
||||||
|
return url;
|
||||||
|
},
|
||||||
|
'data': function(node) {
|
||||||
|
return { 'id': node.id };
|
||||||
|
},
|
||||||
|
'dataFilter': function(data) {
|
||||||
|
var json = {};
|
||||||
|
try {
|
||||||
|
json = JSON.parse(data);
|
||||||
|
} catch (e) {
|
||||||
|
return "[]";
|
||||||
|
}
|
||||||
|
if (json.success && Array.isArray(json.data)) {
|
||||||
|
return JSON.stringify(json.data);
|
||||||
|
}
|
||||||
|
return "[]";
|
||||||
|
},
|
||||||
|
'error': function(jqXHR, textStatus, errorThrown) {
|
||||||
|
showToast('加载文件列表失败:' + textStatus);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'themes': {
|
||||||
|
'name': 'default',
|
||||||
|
'responsive': true
|
||||||
|
},
|
||||||
|
'check_callback': true,
|
||||||
|
'multiple': false
|
||||||
|
},
|
||||||
|
'types': {
|
||||||
|
'default': {
|
||||||
|
'icon': 'bi bi-file-text'
|
||||||
|
},
|
||||||
|
'folder': {
|
||||||
|
'icon': 'bi bi-folder'
|
||||||
|
},
|
||||||
|
'python': {
|
||||||
|
'icon': 'bi bi-filetype-py'
|
||||||
|
},
|
||||||
|
'json': {
|
||||||
|
'icon': 'bi bi-filetype-json'
|
||||||
|
},
|
||||||
|
'shell': {
|
||||||
|
'icon': 'bi bi-filetype-sh'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'plugins': ['types']
|
||||||
|
}).on('ready.jstree', function() {
|
||||||
|
// 文件树初始化完成
|
||||||
|
});
|
||||||
|
|
||||||
|
// 文件树节点点击事件
|
||||||
|
$('#fileTree').on('select_node.jstree', function(e, data) {
|
||||||
|
const node = data.node;
|
||||||
|
if (node.original.type != 'folder') {
|
||||||
|
loadFile(node.id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 加载文件内容 - 分段读取
|
||||||
|
function loadFile(path) {
|
||||||
|
// 先清空编辑器
|
||||||
|
editor.setValue("");
|
||||||
|
$('#currentFile').text(path);
|
||||||
|
showToast('正在加载文件...');
|
||||||
|
|
||||||
|
// 首先获取文件信息
|
||||||
|
$.get('/api/script/info?path=' + encodeURIComponent(path), function(infoResponse) {
|
||||||
|
if (infoResponse.success) {
|
||||||
|
const fileSize = infoResponse.size;
|
||||||
|
const chunkSize = 4096; // 4K 分段
|
||||||
|
let totalChunks = Math.ceil(fileSize / chunkSize);
|
||||||
|
let loadedChunks = 0;
|
||||||
|
let fileContent = '';
|
||||||
|
|
||||||
|
// 显示加载进度
|
||||||
|
showToast('正在加载文件... (0%)');
|
||||||
|
|
||||||
|
// 分段读取函数
|
||||||
|
function readChunk(offset) {
|
||||||
|
if (offset >= fileSize) {
|
||||||
|
// 所有分块读取完成
|
||||||
|
const ext = path.split('.').pop().toLowerCase();
|
||||||
|
switch(ext) {
|
||||||
|
case 'py':
|
||||||
|
editor.setOption('mode', 'text/x-python');
|
||||||
|
break;
|
||||||
|
case 'json':
|
||||||
|
editor.setOption('mode', 'application/json');
|
||||||
|
break;
|
||||||
|
case 'sh':
|
||||||
|
editor.setOption('mode', 'text/x-sh');
|
||||||
|
break;
|
||||||
|
case 'html':
|
||||||
|
editor.setOption('mode', 'text/html');
|
||||||
|
break;
|
||||||
|
case 'js':
|
||||||
|
editor.setOption('mode', 'javascript');
|
||||||
|
break;
|
||||||
|
case 'css':
|
||||||
|
editor.setOption('mode', 'css');
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
editor.setOption('mode', 'text/plain');
|
||||||
|
}
|
||||||
|
// 设置编辑器内容
|
||||||
|
editor.setValue(fileContent);
|
||||||
|
$('#saveFile, #deleteFile').prop('disabled', false);
|
||||||
|
showToast('文件加载完成');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 读取当前分块
|
||||||
|
$.get('/api/script/read?path=' + encodeURIComponent(path) + '&offset=' + offset + '&size=' + chunkSize, function(chunkResponse) {
|
||||||
|
if (chunkResponse.success) {
|
||||||
|
// 使用js-base64库解码
|
||||||
|
const chunkContent = Base64.decode(chunkResponse.data);
|
||||||
|
fileContent += chunkContent;
|
||||||
|
loadedChunks++;
|
||||||
|
|
||||||
|
// 更新进度
|
||||||
|
const progress = Math.round((loadedChunks / totalChunks) * 100);
|
||||||
|
if (progress % 20 === 0 || progress === 100) {
|
||||||
|
showToast('正在加载文件... (' + progress + '%)');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 读取下一个分块
|
||||||
|
readChunk(offset + chunkSize);
|
||||||
|
} else {
|
||||||
|
showToast('加载文件失败:' + chunkResponse.message);
|
||||||
|
}
|
||||||
|
}).fail(function() {
|
||||||
|
showToast('加载文件失败:网络错误');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 开始读取第一个分块
|
||||||
|
readChunk(0);
|
||||||
|
} else {
|
||||||
|
showToast('获取文件信息失败:' + infoResponse.message);
|
||||||
|
}
|
||||||
|
}).fail(function() {
|
||||||
|
showToast('获取文件信息失败:网络错误');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 暴露公共方法
|
||||||
|
return {
|
||||||
|
init: init
|
||||||
|
};
|
||||||
|
})();
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
// ui-utils.js - UI工具函数模块
|
||||||
|
|
||||||
|
const UIUtils = (function() {
|
||||||
|
let toast;
|
||||||
|
|
||||||
|
// 初始化UI工具
|
||||||
|
function init() {
|
||||||
|
// 初始化Toast
|
||||||
|
initToast();
|
||||||
|
|
||||||
|
// 初始化设备控制按钮
|
||||||
|
initDeviceControls();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化Toast通知
|
||||||
|
function initToast() {
|
||||||
|
const toastEl = document.getElementById('toast');
|
||||||
|
toast = new bootstrap.Toast(toastEl, {
|
||||||
|
autohide: true,
|
||||||
|
delay: 3000
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示Toast通知
|
||||||
|
function showToast(message) {
|
||||||
|
$('.toast-body').text(message);
|
||||||
|
toast.show();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化设备控制按钮
|
||||||
|
function initDeviceControls() {
|
||||||
|
// 设备重启按钮
|
||||||
|
$('#reboot').click(function() {
|
||||||
|
$.ajax({
|
||||||
|
url: '/api/device/reboot',
|
||||||
|
type: 'GET',
|
||||||
|
success: function(response) {
|
||||||
|
if (response.success) {
|
||||||
|
showToast('请求已发送');
|
||||||
|
} else {
|
||||||
|
showToast('请求失败:' + response.message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: function(jqXHR, textStatus, errorThrown) {
|
||||||
|
showToast('请求失败:服务器错误');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// DAQ控制按钮
|
||||||
|
$('#start_daq').click(function() {
|
||||||
|
WebSocketManager.publish(WebSocketManager.topic_daq_control, {
|
||||||
|
cmd: 'start',
|
||||||
|
len: parseInt($('#daq_duration').val())
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
$('#stop_daq').click(function() {
|
||||||
|
WebSocketManager.publish(WebSocketManager.topic_daq_control, {
|
||||||
|
cmd: 'stop'
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 序列号设置功能
|
||||||
|
$('#daq_info').dblclick(function() {
|
||||||
|
// 获取当前序列号
|
||||||
|
const currentSn = $(this).text().trim() || '';
|
||||||
|
// 设置输入框的值
|
||||||
|
$('#snInput').val(currentSn);
|
||||||
|
// 显示模态对话框
|
||||||
|
const snModal = new bootstrap.Modal(document.getElementById('snModal'));
|
||||||
|
snModal.show();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 保存序列号按钮点击事件
|
||||||
|
$('#saveSnBtn').click(function() {
|
||||||
|
// 获取输入的序列号
|
||||||
|
const newSn = $('#snInput').val().trim();
|
||||||
|
if (newSn === '') {
|
||||||
|
showToast('序列号不能为空');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 通过WebSocket发送设置序列号命令
|
||||||
|
WebSocketManager.publish(WebSocketManager.topic_daq_control, {
|
||||||
|
cmd: 'daq_set_sn',
|
||||||
|
sn: newSn
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关闭模态对话框
|
||||||
|
const snModal = bootstrap.Modal.getInstance(document.getElementById('snModal'));
|
||||||
|
snModal.hide();
|
||||||
|
|
||||||
|
// 显示保存成功提示
|
||||||
|
showToast('序列号设置命令已发送');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 暴露公共方法
|
||||||
|
return {
|
||||||
|
init: init,
|
||||||
|
showToast: showToast
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
|
||||||
|
// 为了兼容旧代码,将showToast函数添加到全局作用域
|
||||||
|
window.showToast = function(message) {
|
||||||
|
UIUtils.showToast(message);
|
||||||
|
};
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
// websocket.js - WebSocket通信模块
|
||||||
|
|
||||||
|
const WebSocketManager = (function() {
|
||||||
|
// DAQ相关的topic
|
||||||
|
const topic_daq_control = '/dev/daq/control';
|
||||||
|
const topic_daq_data = '/dev/daq/data';
|
||||||
|
const topic_daq_status = '/dev/daq/status';
|
||||||
|
|
||||||
|
// WebSocket客户端配置
|
||||||
|
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||||
|
const wsHost = location.hostname + (location.port ? ':' + location.port : '');
|
||||||
|
const wsuri = wsProtocol + '//' + wsHost + '/ws';
|
||||||
|
console.log('WebSocket连接URL:', wsuri);
|
||||||
|
|
||||||
|
let ws;
|
||||||
|
let reconnectTimer;
|
||||||
|
let status_str = '';
|
||||||
|
|
||||||
|
// 初始化WebSocket连接
|
||||||
|
function init() {
|
||||||
|
connectWebSocket();
|
||||||
|
|
||||||
|
// 定期检查连接状态(每10秒)
|
||||||
|
setInterval(monitorConnection, 10000);
|
||||||
|
|
||||||
|
// 页面关闭前关闭WebSocket连接
|
||||||
|
$(window).on('beforeunload', function() {
|
||||||
|
if (ws) {
|
||||||
|
ws.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 建立WebSocket连接
|
||||||
|
function connectWebSocket() {
|
||||||
|
console.log('WebSocket URI:', wsuri);
|
||||||
|
ws = new WebSocket(wsuri);
|
||||||
|
|
||||||
|
ws.onopen = function() {
|
||||||
|
showToast('已连接到WebSocket服务器');
|
||||||
|
// 订阅DAQ相关的主题
|
||||||
|
ws.send(JSON.stringify({ action: 'subscribe', topic: topic_daq_status }));
|
||||||
|
ws.send(JSON.stringify({ action: 'subscribe', topic: topic_daq_data }));
|
||||||
|
// 清除重连定时器
|
||||||
|
if (reconnectTimer) {
|
||||||
|
clearTimeout(reconnectTimer);
|
||||||
|
reconnectTimer = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onmessage = function(event) {
|
||||||
|
handleMessage(event);
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onerror = function(error) {
|
||||||
|
console.error('WebSocket错误:', error);
|
||||||
|
showToast('WebSocket连接错误: ' + (error.message || '未知错误'));
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onclose = function(event) {
|
||||||
|
console.log('WebSocket关闭原因:', event.code, event.reason);
|
||||||
|
showToast('WebSocket连接已关闭,正在尝试重连... 代码: ' + event.code + ', 原因: ' + event.reason);
|
||||||
|
// 仅在没有活跃定时器时创建新的重连定时器
|
||||||
|
if (!reconnectTimer) {
|
||||||
|
reconnectTimer = setTimeout(connectWebSocket, 5000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return ws;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理WebSocket消息
|
||||||
|
function handleMessage(event) {
|
||||||
|
let data;
|
||||||
|
|
||||||
|
try {
|
||||||
|
data = JSON.parse(event.data);
|
||||||
|
} catch (e) {
|
||||||
|
showToast('解析消息失败: ' + e.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const topic = data.topic;
|
||||||
|
const message = data.message;
|
||||||
|
|
||||||
|
if (topic && message) {
|
||||||
|
if (topic.startsWith(topic_daq_data)) {
|
||||||
|
try {
|
||||||
|
const daqData = typeof message === 'string' ? JSON.parse(message) : message;
|
||||||
|
// 处理DAQ数据
|
||||||
|
if (window.handleDaqData) {
|
||||||
|
window.handleDaqData(daqData);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showToast('解析DAQ数据失败: ' + e.message);
|
||||||
|
}
|
||||||
|
} else if (topic.startsWith(topic_daq_status)) {
|
||||||
|
try {
|
||||||
|
const daqStatus = typeof message === 'string' ? JSON.parse(message) : message;
|
||||||
|
// 更新DAQ状态
|
||||||
|
updateDaqStatus(daqStatus);
|
||||||
|
} catch (e) {
|
||||||
|
showToast('解析DAQ状态消息失败: ' + e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新DAQ状态
|
||||||
|
function updateDaqStatus(daqStatus) {
|
||||||
|
status_str = '';
|
||||||
|
if (!daqStatus.online) {
|
||||||
|
status_str += '采集板通讯异常';
|
||||||
|
} else {
|
||||||
|
if (daqStatus.run) {
|
||||||
|
status_str += '采集中 ';
|
||||||
|
} else {
|
||||||
|
status_str += '停止采集 ';
|
||||||
|
}
|
||||||
|
if (daqStatus.temp) {
|
||||||
|
daqStatus.temp = daqStatus.temp / 10.0;
|
||||||
|
status_str += '温度:' + daqStatus.temp.toFixed(1) + '℃ ';
|
||||||
|
}
|
||||||
|
if (daqStatus.info) {
|
||||||
|
$('#daq_info').text(daqStatus.info.date + '-' + daqStatus.info.sn);
|
||||||
|
if (daqStatus.info.version) {
|
||||||
|
$('#currentVersion').text(daqStatus.info.version);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$('#daq_status').text(status_str || '--');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 监控连接状态
|
||||||
|
function monitorConnection() {
|
||||||
|
if (!ws || ws.readyState === WebSocket.CLOSED) {
|
||||||
|
showToast('定期检查发现连接已关闭,尝试重连...');
|
||||||
|
if (!reconnectTimer) {
|
||||||
|
reconnectTimer = setTimeout(connectWebSocket, 5000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发布消息到WebSocket
|
||||||
|
function wsPublish(topic, msg) {
|
||||||
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||||
|
ws.send(JSON.stringify({
|
||||||
|
action: 'publish',
|
||||||
|
topic: topic,
|
||||||
|
message: msg
|
||||||
|
}));
|
||||||
|
} else {
|
||||||
|
showToast('WebSocket连接未建立,无法发送消息');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取当前WebSocket连接
|
||||||
|
function getWebSocket() {
|
||||||
|
return ws;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 暴露公共方法
|
||||||
|
return {
|
||||||
|
init: init,
|
||||||
|
publish: wsPublish,
|
||||||
|
getWebSocket: getWebSocket,
|
||||||
|
topic_daq_control: topic_daq_control,
|
||||||
|
topic_daq_data: topic_daq_data,
|
||||||
|
topic_daq_status: topic_daq_status
|
||||||
|
};
|
||||||
|
})();
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 5.4 KiB |
+2018
File diff suppressed because it is too large
Load Diff
Binary file not shown.
+6
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
Binary file not shown.
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
.cm-s-monokai.CodeMirror{background:#272822;color:#f8f8f2}.cm-s-monokai div.CodeMirror-selected{background:#49483e}.cm-s-monokai .CodeMirror-line::selection,.cm-s-monokai .CodeMirror-line>span::selection,.cm-s-monokai .CodeMirror-line>span>span::selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-line::-moz-selection,.cm-s-monokai .CodeMirror-line>span::-moz-selection,.cm-s-monokai .CodeMirror-line>span>span::-moz-selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-gutters{background:#272822;border-right:0}.cm-s-monokai .CodeMirror-guttermarker{color:#fff}.cm-s-monokai .CodeMirror-guttermarker-subtle{color:#d0d0d0}.cm-s-monokai .CodeMirror-linenumber{color:#d0d0d0}.cm-s-monokai .CodeMirror-cursor{border-left:1px solid #f8f8f0}.cm-s-monokai span.cm-comment{color:#75715e}.cm-s-monokai span.cm-atom{color:#ae81ff}.cm-s-monokai span.cm-number{color:#ae81ff}.cm-s-monokai span.cm-comment.cm-attribute{color:#97b757}.cm-s-monokai span.cm-comment.cm-def{color:#bc9262}.cm-s-monokai span.cm-comment.cm-tag{color:#bc6283}.cm-s-monokai span.cm-comment.cm-type{color:#5998a6}.cm-s-monokai span.cm-attribute,.cm-s-monokai span.cm-property{color:#a6e22e}.cm-s-monokai span.cm-keyword{color:#f92672}.cm-s-monokai span.cm-builtin{color:#66d9ef}.cm-s-monokai span.cm-string{color:#e6db74}.cm-s-monokai span.cm-variable{color:#f8f8f2}.cm-s-monokai span.cm-variable-2{color:#9effff}.cm-s-monokai span.cm-type,.cm-s-monokai span.cm-variable-3{color:#66d9ef}.cm-s-monokai span.cm-def{color:#fd971f}.cm-s-monokai span.cm-bracket{color:#f8f8f2}.cm-s-monokai span.cm-tag{color:#f92672}.cm-s-monokai span.cm-header{color:#ae81ff}.cm-s-monokai span.cm-link{color:#ae81ff}.cm-s-monokai span.cm-error{background:#f92672;color:#f8f8f0}.cm-s-monokai .CodeMirror-activeline-background{background:#373831}.cm-s-monokai .CodeMirror-matchingbracket{text-decoration:underline;color:#fff!important}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
.card {
|
||||||
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-header {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-control {
|
||||||
|
font-size: 1.1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
#feedbackVoltage,
|
||||||
|
#feedbackCurrent,
|
||||||
|
#filamentVoltage,
|
||||||
|
#filamentCurrent {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #0d6efd;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
width: 100%;
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 导航栏样式 */
|
||||||
|
.navbar {
|
||||||
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar-brand {
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link {
|
||||||
|
font-size: 1.1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link i {
|
||||||
|
margin-right: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 编辑器相关样式 */
|
||||||
|
.CodeMirror {
|
||||||
|
height: calc(100vh - 200px);
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#fileTree {
|
||||||
|
height: calc(100vh - 200px);
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jstree-default .jstree-icon {
|
||||||
|
color: #0d6efd;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jstree-default .jstree-themeicon {
|
||||||
|
color: #6c757d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jstree-default .jstree-themeicon-custom {
|
||||||
|
color: #0d6efd;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 文件类型图标颜色 */
|
||||||
|
.bi-filetype-py {
|
||||||
|
color: #306998;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bi-filetype-json {
|
||||||
|
color: #f7df1e;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bi-filetype-sh {
|
||||||
|
color: #4eaa25;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bi-folder {
|
||||||
|
color: #ffc107;
|
||||||
|
}
|
||||||
Vendored
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,259 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>扫描臂管理系统</title>
|
||||||
|
<link href="css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<link href="css/bootstrap-icons.css" rel="stylesheet">
|
||||||
|
<link href="css/style.min.css" rel="stylesheet">
|
||||||
|
<link href="css/codemirror.min.css" rel="stylesheet">
|
||||||
|
<link href="css/monokai.min.css" rel="stylesheet">
|
||||||
|
<link href="css/style.css" rel="stylesheet">
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<!-- 导航栏 -->
|
||||||
|
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
|
||||||
|
<div class="container">
|
||||||
|
<a class="navbar-brand" href="/">扫描臂管理系统</a>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="container-fluid mt-4">
|
||||||
|
<!-- Toast提示组件 -->
|
||||||
|
<div class="position-fixed top-0 start-50 translate-middle-x p-3" style="z-index: 11">
|
||||||
|
<div id="toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
|
||||||
|
<div class="toast-header">
|
||||||
|
<strong class="me-auto">系统提示</strong>
|
||||||
|
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
|
||||||
|
</div>
|
||||||
|
<div class="toast-body"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 选项卡 -->
|
||||||
|
<ul class="nav nav-tabs mb-3" id="mainTab" role="tablist">
|
||||||
|
<li class="nav-item" role="presentation">
|
||||||
|
<button class="nav-link active" id="panel-tab" data-bs-toggle="tab" data-bs-target="#panel"
|
||||||
|
type="button" role="tab" aria-controls="panel" aria-selected="true">控制面板</button>
|
||||||
|
</li>
|
||||||
|
<li class="nav-item" role="presentation">
|
||||||
|
<button class="nav-link" id="script-tab" data-bs-toggle="tab" data-bs-target="#script" type="button"
|
||||||
|
role="tab" aria-controls="script" aria-selected="false"><i class="bi bi-code-square"></i>
|
||||||
|
脚本编辑器</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div class="tab-content" id="mainTabContent">
|
||||||
|
<!-- 控制面板 -->
|
||||||
|
<div class="tab-pane fade show active" id="panel" role="tabpanel" aria-labelledby="panel-tab">
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-4">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">设备控制</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-3">
|
||||||
|
<button class="btn btn-primary" id="reboot">重启设备</button>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<button class="btn btn-primary" id="start_scan">开始扫描</button>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<button class="btn btn-primary" id="stop_scan">停止扫描</button>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<button class="btn btn-primary" id="reset_scan">扫描复位</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="row mt-3">
|
||||||
|
<div class="col-md-12">
|
||||||
|
<button class="btn btn-danger w-100" id="emer_stop">紧急停止</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="col-md">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">实时状态</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-3">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label">扫描器ID</label>
|
||||||
|
<div class="form-control" id="scannerId">--</div>
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label">上电时间</label>
|
||||||
|
<div class="form-control" id="runTime">--</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label">扫描器状态</label>
|
||||||
|
<div class="form-control" id="scannerState">--</div>
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label">当前位置 (mm)</label>
|
||||||
|
<div class="form-control" id="scannerPos">--</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label">速度</label>
|
||||||
|
<div class="form-control" id="scannerSpeed">--</div>
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label">上下部位置 (mm)</label>
|
||||||
|
<div class="form-control" id="scannerUpperAndLowerPos">--</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label">扫描范围 (mm)</label>
|
||||||
|
<div class="form-control" id="scannerScanRange">--</div>
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label">DAQ状态</label>
|
||||||
|
<div class="form-control" id="daqState">--</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 数据曲线图 -->
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-12">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">数据曲线</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<canvas id="daq_chart" width="800" height="400"></canvas>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 数据统计信息 -->
|
||||||
|
<div class="row mt-4">
|
||||||
|
<div class="col-md-12">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header d-flex justify-content-between align-items-center">
|
||||||
|
<span>数据统计信息</span>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped table-bordered">
|
||||||
|
<thead class="table-dark">
|
||||||
|
<tr>
|
||||||
|
<th>采集时间</th>
|
||||||
|
<th>数据长度</th>
|
||||||
|
<th>CH1平均值</th>
|
||||||
|
<th>CH1峰峰值</th>
|
||||||
|
<th>CH1波动水平</th>
|
||||||
|
<th>CH2平均值</th>
|
||||||
|
<th>CH2峰峰值</th>
|
||||||
|
<th>CH2波动水平</th>
|
||||||
|
<th>通道间差异</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="stats_table_body">
|
||||||
|
<!-- 统计数据将通过JavaScript动态添加 -->
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 脚本编辑器 -->
|
||||||
|
<div class="tab-pane fade" id="script" role="tabpanel" aria-labelledby="script-tab">
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-3">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header d-flex justify-content-between align-items-center">
|
||||||
|
<span>文件目录</span>
|
||||||
|
<div>
|
||||||
|
<button class="btn btn-sm btn-primary" id="refreshTree">
|
||||||
|
<i class="bi bi-arrow-clockwise"></i> 刷新
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div id="fileTree"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-9">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header d-flex justify-content-between align-items-center">
|
||||||
|
<span id="currentFile">未选择文件</span>
|
||||||
|
<div>
|
||||||
|
<button class="btn btn-sm btn-success" id="saveFile" disabled>
|
||||||
|
<i class="bi bi-save"></i> 保存
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-sm btn-danger" id="deleteFile" disabled>
|
||||||
|
<i class="bi bi-trash"></i> 删除
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<textarea id="editor"></textarea>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- <script src="http://192.168.8.150:8000/js/lib/jquery.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/lib/bootstrap.bundle.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/lib/jstree.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/lib/codemirror.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/lib/python.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/lib/javascript.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/lib/shell.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/lib/htmlmixed.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/lib/xml.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/lib/css.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/lib/base64.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/lib/hammer.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/lib/chart.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/lib/chartjs-plugin-zoom.min.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/chart.js"></script>
|
||||||
|
<script src="http://192.168.8.150:8000/js/utils.js"></script>
|
||||||
|
|
||||||
|
<script type="module" src="js/main.js"></script> -->
|
||||||
|
|
||||||
|
<script src="js/lib/jquery.min.js"></script>
|
||||||
|
<script src="js/lib/bootstrap.bundle.min.js"></script>
|
||||||
|
<script src="js/lib/jstree.min.js"></script>
|
||||||
|
<script src="js/lib/codemirror.min.js"></script>
|
||||||
|
<script src="js/lib/python.min.js"></script>
|
||||||
|
<script src="js/lib/javascript.min.js"></script>
|
||||||
|
<script src="js/lib/shell.min.js"></script>
|
||||||
|
<script src="js/lib/htmlmixed.min.js"></script>
|
||||||
|
<script src="js/lib/xml.min.js"></script>
|
||||||
|
<script src="js/lib/css.min.js"></script>
|
||||||
|
<script src="js/lib/base64.min.js"></script>
|
||||||
|
<script src="js/lib/hammer.min.js"></script>
|
||||||
|
<script src="js/lib/chart.min.js"></script>
|
||||||
|
<script src="js/lib/chartjs-plugin-zoom.min.js"></script>
|
||||||
|
<script src="js/chart.js"></script>
|
||||||
|
|
||||||
|
<script type="module" src="js/utils.js"></script>
|
||||||
|
<script type="module" src="js/main.js"></script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,297 @@
|
|||||||
|
// chart.js - 图表功能模块
|
||||||
|
|
||||||
|
const ChartModule = (function() {
|
||||||
|
let daqChart = null;
|
||||||
|
let chartData = {
|
||||||
|
ch1: [],
|
||||||
|
ch2: []
|
||||||
|
};
|
||||||
|
|
||||||
|
function getCurrentSn() {
|
||||||
|
// 从设备信息中获取SN并移除所有空格和所有斜杠
|
||||||
|
return $('#daq_info').text().replace(/\s+/g, '').replace(/\//g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化图表模块
|
||||||
|
function init() {
|
||||||
|
// 初始化图表
|
||||||
|
initChart();
|
||||||
|
|
||||||
|
// 设置拖动和缩放模式切换
|
||||||
|
initZoomControls();
|
||||||
|
|
||||||
|
// 将处理DAQ数据的函数暴露到全局
|
||||||
|
window.handleDaqData = handleDaqData;
|
||||||
|
|
||||||
|
// 添加删除行按钮的事件委托
|
||||||
|
const tbody = document.getElementById('stats_table_body');
|
||||||
|
tbody.addEventListener('click', function(event) {
|
||||||
|
if (event.target.closest('.delete-row')) {
|
||||||
|
const row = event.target.closest('tr');
|
||||||
|
row.remove();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// 初始化图表
|
||||||
|
function initChart() {
|
||||||
|
const ctx = document.getElementById('daq_chart').getContext('2d');
|
||||||
|
daqChart = new Chart(ctx, {
|
||||||
|
type: 'line',
|
||||||
|
data: {
|
||||||
|
labels: [],
|
||||||
|
datasets: [
|
||||||
|
{
|
||||||
|
label: 'CH1',
|
||||||
|
data: [],
|
||||||
|
borderColor: 'rgba(219, 24, 67, 1)',
|
||||||
|
backgroundColor: 'rgba(219, 24, 67, 1)',
|
||||||
|
borderWidth: 1,
|
||||||
|
fill: false,
|
||||||
|
tension: 0,
|
||||||
|
pointRadius: 3,
|
||||||
|
pointBackgroundColor: 'rgba(219, 24, 67, 1)',
|
||||||
|
pointBorderColor: 'rgba(219, 24, 67, 1)',
|
||||||
|
pointHoverRadius: 5,
|
||||||
|
pointHoverBackgroundColor: 'rgba(219, 24, 67, 0.8)',
|
||||||
|
pointHoverBorderColor: 'rgba(219, 24, 67, 1)'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'CH2',
|
||||||
|
data: [],
|
||||||
|
borderColor: 'rgba(10, 49, 223, 1)',
|
||||||
|
backgroundColor: 'rgba(10, 49, 223, 1)',
|
||||||
|
borderWidth: 1,
|
||||||
|
fill: false,
|
||||||
|
tension: 0,
|
||||||
|
pointRadius: 3,
|
||||||
|
pointBackgroundColor: 'rgba(10, 49, 223, 1)',
|
||||||
|
pointBorderColor: 'rgba(10, 49, 223, 1)',
|
||||||
|
pointHoverRadius: 5,
|
||||||
|
pointHoverBackgroundColor: 'rgba(10, 49, 223, 0.8)',
|
||||||
|
pointHoverBorderColor: 'rgba(10, 49, 223, 1)'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
scales: {
|
||||||
|
x: {
|
||||||
|
title: {
|
||||||
|
display: true,
|
||||||
|
text: '样本点'
|
||||||
|
},
|
||||||
|
grid: {
|
||||||
|
color: 'rgba(0, 0, 0, 0.1)'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
y: {
|
||||||
|
title: {
|
||||||
|
display: true,
|
||||||
|
text: '数值 (uint16)'
|
||||||
|
},
|
||||||
|
min: 0,
|
||||||
|
max: 65535,
|
||||||
|
grid: {
|
||||||
|
color: 'rgba(0, 0, 0, 0.1)'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
animation: false,
|
||||||
|
plugins: {
|
||||||
|
zoom: {
|
||||||
|
pan: {
|
||||||
|
enabled: true,
|
||||||
|
mode: 'xy',
|
||||||
|
speed: 10,
|
||||||
|
threshold: 10,
|
||||||
|
scaleMode: 'xy'
|
||||||
|
},
|
||||||
|
zoom: {
|
||||||
|
wheel: {
|
||||||
|
enabled: true,
|
||||||
|
speed: 0.1
|
||||||
|
},
|
||||||
|
drag: {
|
||||||
|
enabled: false,
|
||||||
|
borderColor: 'rgba(255, 255, 255, 0.5)',
|
||||||
|
borderWidth: 1,
|
||||||
|
backgroundColor: 'rgba(225, 225, 225, 0.3)',
|
||||||
|
drawTime: 'beforeDatasetsDraw'
|
||||||
|
},
|
||||||
|
pinch: {
|
||||||
|
enabled: true
|
||||||
|
},
|
||||||
|
mode: 'xy',
|
||||||
|
speed: 0.1,
|
||||||
|
scaleMode: 'xy'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化缩放控制
|
||||||
|
function initZoomControls() {
|
||||||
|
// 重置缩放按钮
|
||||||
|
$('#reset_zoom').on('click', function() {
|
||||||
|
if (daqChart) {
|
||||||
|
daqChart.resetZoom();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 缩放模式切换按钮
|
||||||
|
$('.zoom-mode-btn').on('click', function() {
|
||||||
|
const mode = $(this).data('mode');
|
||||||
|
|
||||||
|
// 更新按钮状态
|
||||||
|
$('.zoom-mode-btn').removeClass('active');
|
||||||
|
$(this).addClass('active');
|
||||||
|
|
||||||
|
// 更新图表缩放模式
|
||||||
|
if (daqChart) {
|
||||||
|
daqChart.options.plugins.zoom.pan.mode = mode;
|
||||||
|
daqChart.options.plugins.zoom.zoom.mode = mode;
|
||||||
|
daqChart.update('none');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理DAQ数据
|
||||||
|
function handleDaqData(daqData) {
|
||||||
|
try {
|
||||||
|
// 解析数据
|
||||||
|
const parsedData = parseDaqData(daqData);
|
||||||
|
|
||||||
|
// 更新图表数据
|
||||||
|
chartData.ch1 = parsedData.ch1;
|
||||||
|
chartData.ch2 = parsedData.ch2;
|
||||||
|
|
||||||
|
// 更新图表
|
||||||
|
updateChart();
|
||||||
|
|
||||||
|
// 计算并显示统计信息
|
||||||
|
calculateAndDisplayStats(parsedData.ch1, parsedData.ch2);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('解析DAQ数据失败:', error);
|
||||||
|
showToast('解析DAQ数据失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算并显示统计信息
|
||||||
|
function calculateAndDisplayStats(ch1Data, ch2Data) {
|
||||||
|
// 计算各通道统计值
|
||||||
|
const ch1Stats = calculateStats(ch1Data);
|
||||||
|
const ch2Stats = calculateStats(ch2Data);
|
||||||
|
|
||||||
|
// 获取当前时间
|
||||||
|
const currentTime = new Date().toLocaleString();
|
||||||
|
|
||||||
|
const diff = Math.abs(ch1Stats.average - ch2Stats.average) / (Math.max(ch1Stats.average, ch2Stats.average) || 1) * 100;
|
||||||
|
|
||||||
|
// 创建新的表格行
|
||||||
|
const newRow = `
|
||||||
|
<tr>
|
||||||
|
<td>${currentTime}</td>
|
||||||
|
<td>${ch1Data.length}</td>
|
||||||
|
<td>${ch1Stats.average.toFixed(0)}</td>
|
||||||
|
<td>${ch1Stats.peakToPeak.toFixed(0)}</td>
|
||||||
|
<td>${ch1Stats.snr.toFixed(0)}%</td>
|
||||||
|
<td>${ch2Stats.average.toFixed(0)}</td>
|
||||||
|
<td>${ch2Stats.peakToPeak.toFixed(0)}</td>
|
||||||
|
<td>${ch2Stats.snr.toFixed(0)}%</td>
|
||||||
|
<td>${diff.toFixed(0)}%</td>
|
||||||
|
<td>
|
||||||
|
<button class="btn btn-danger btn-sm delete-row">
|
||||||
|
<i class="bi bi-trash"></i> 删除
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
`;
|
||||||
|
|
||||||
|
// 添加到表格顶部
|
||||||
|
const tbody = document.getElementById('stats_table_body');
|
||||||
|
tbody.insertAdjacentHTML('afterbegin', newRow);
|
||||||
|
|
||||||
|
// 限制表格行数(最多保留100条记录)
|
||||||
|
const maxRows = 100;
|
||||||
|
while (tbody.rows.length > maxRows) {
|
||||||
|
tbody.deleteRow(tbody.rows.length - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算单通道统计值
|
||||||
|
function calculateStats(data) {
|
||||||
|
if (!data || data.length === 0) {
|
||||||
|
return { average: 0, peakToPeak: 0, snr: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算平均值
|
||||||
|
const sum = data.reduce((acc, val) => acc + val, 0);
|
||||||
|
const average = sum / data.length;
|
||||||
|
|
||||||
|
// 计算峰峰值
|
||||||
|
const max = Math.max(...data);
|
||||||
|
const min = Math.min(...data);
|
||||||
|
const peakToPeak = max - min;
|
||||||
|
|
||||||
|
// 计算信噪比 (SNR)
|
||||||
|
// 简单实现:假设噪声是信号的标准差
|
||||||
|
|
||||||
|
const snr = average === 0 ? 0 : peakToPeak / average * 100;
|
||||||
|
|
||||||
|
return { average, peakToPeak, snr };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== DAQ数据处理相关 ==========
|
||||||
|
// 解析uint16小端数据
|
||||||
|
function parseDaqData(arrayBuffer) {
|
||||||
|
// 将ArrayBuffer转换为DataView
|
||||||
|
const dataView = new DataView(arrayBuffer);
|
||||||
|
|
||||||
|
// 解析uint16小端数据
|
||||||
|
const data = [];
|
||||||
|
for (let i = 4; i < arrayBuffer.byteLength; i += 2) { // 跳过前4字节头
|
||||||
|
data.push(dataView.getUint16(i, true)); // true表示小端
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分离CH1和CH2数据
|
||||||
|
const ch1 = [];
|
||||||
|
const ch2 = [];
|
||||||
|
for (let i = 0; i < data.length; i += 2) {
|
||||||
|
ch1.push(data[i]);
|
||||||
|
if (i + 1 < data.length) {
|
||||||
|
ch2.push(data[i + 1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ch1, ch2 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新图表
|
||||||
|
function updateChart() {
|
||||||
|
if (!daqChart) {
|
||||||
|
initChart();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新标签和数据
|
||||||
|
const labels = chartData.ch1.map((_, index) => index);
|
||||||
|
|
||||||
|
daqChart.data.labels = labels;
|
||||||
|
daqChart.data.datasets[0].data = chartData.ch1;
|
||||||
|
daqChart.data.datasets[1].data = chartData.ch2;
|
||||||
|
|
||||||
|
daqChart.update('none');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 暴露公共方法
|
||||||
|
return {
|
||||||
|
init: init,
|
||||||
|
updateChart: updateChart
|
||||||
|
};
|
||||||
|
})();
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
// 文件树和文件操作模块
|
||||||
|
|
||||||
|
let fileTree = null;
|
||||||
|
|
||||||
|
// 初始化文件树
|
||||||
|
function initFileTree(onFileSelect) {
|
||||||
|
if (!fileTree) {
|
||||||
|
fileTree = $('#fileTree').jstree({
|
||||||
|
'core': {
|
||||||
|
'data': {
|
||||||
|
'url': function(node) {
|
||||||
|
const url = node.id === '#' ? '/api/script/list' : '/api/script/list?path=' + node.id;
|
||||||
|
return url;
|
||||||
|
},
|
||||||
|
'data': function(node) {
|
||||||
|
return { 'id': node.id };
|
||||||
|
},
|
||||||
|
'dataFilter': function(data) {
|
||||||
|
var json = {};
|
||||||
|
try {
|
||||||
|
json = JSON.parse(data);
|
||||||
|
} catch (e) {
|
||||||
|
return "[]";
|
||||||
|
}
|
||||||
|
if (json.success && Array.isArray(json.data)) {
|
||||||
|
return JSON.stringify(json.data);
|
||||||
|
}
|
||||||
|
return "[]";
|
||||||
|
},
|
||||||
|
'error': function(jqXHR, textStatus, errorThrown) {
|
||||||
|
showToast('加载文件列表失败:' + textStatus);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'themes': {
|
||||||
|
'name': 'default',
|
||||||
|
'responsive': true
|
||||||
|
},
|
||||||
|
'check_callback': true,
|
||||||
|
'multiple': false
|
||||||
|
},
|
||||||
|
'types': {
|
||||||
|
'default': {
|
||||||
|
'icon': 'bi bi-file-text'
|
||||||
|
},
|
||||||
|
'folder': {
|
||||||
|
'icon': 'bi bi-folder'
|
||||||
|
},
|
||||||
|
'python': {
|
||||||
|
'icon': 'bi bi-filetype-py'
|
||||||
|
},
|
||||||
|
'json': {
|
||||||
|
'icon': 'bi bi-filetype-json'
|
||||||
|
},
|
||||||
|
'shell': {
|
||||||
|
'icon': 'bi bi-filetype-sh'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'plugins': ['types']
|
||||||
|
}).on('ready.jstree', function() {
|
||||||
|
// 文件树初始化完成
|
||||||
|
});
|
||||||
|
|
||||||
|
// 文件树节点点击事件
|
||||||
|
$('#fileTree').on('select_node.jstree', function(e, data) {
|
||||||
|
const node = data.node;
|
||||||
|
if (node.original.type != 'folder') {
|
||||||
|
if (onFileSelect) {
|
||||||
|
onFileSelect(node.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return fileTree;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 刷新文件树
|
||||||
|
function refreshFileTree() {
|
||||||
|
if (fileTree) {
|
||||||
|
console.log('刷新文件树');
|
||||||
|
$('#fileTree').jstree('refresh');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化文件操作按钮事件
|
||||||
|
function initFileOperations(saveFileCallback, deleteFileCallback) {
|
||||||
|
// 保存文件
|
||||||
|
$('#saveFile').click(function() {
|
||||||
|
if (saveFileCallback) {
|
||||||
|
saveFileCallback();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 删除文件
|
||||||
|
$('#deleteFile').click(function() {
|
||||||
|
if (deleteFileCallback) {
|
||||||
|
deleteFileCallback();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 刷新文件树
|
||||||
|
$('#refreshTree').click(function() {
|
||||||
|
refreshFileTree();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取文件树实例
|
||||||
|
function getFileTree() {
|
||||||
|
return fileTree;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 导出模块
|
||||||
|
export {
|
||||||
|
initFileTree,
|
||||||
|
refreshFileTree,
|
||||||
|
initFileOperations,
|
||||||
|
getFileTree
|
||||||
|
};
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* Minified by jsDelivr using Terser v5.15.1.
|
||||||
|
* Original file: /npm/js-base64@3.7.5/base64.js
|
||||||
|
*
|
||||||
|
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
||||||
|
*/
|
||||||
|
!function(t,n){var r,e;"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(r=t.Base64,(e=n()).noConflict=function(){return t.Base64=r,e},t.Meteor&&(Base64=e),t.Base64=e)}("undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:this,(function(){"use strict";var t,n="3.7.5",r="function"==typeof atob,e="function"==typeof btoa,o="function"==typeof Buffer,u="function"==typeof TextDecoder?new TextDecoder:void 0,i="function"==typeof TextEncoder?new TextEncoder:void 0,f=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),c=(t={},f.forEach((function(n,r){return t[n]=r})),t),a=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,d=String.fromCharCode.bind(String),s="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):function(t){return new Uint8Array(Array.prototype.slice.call(t,0))},l=function(t){return t.replace(/=/g,"").replace(/[+\/]/g,(function(t){return"+"==t?"-":"_"}))},h=function(t){return t.replace(/[^A-Za-z0-9\+\/]/g,"")},p=function(t){for(var n,r,e,o,u="",i=t.length%3,c=0;c<t.length;){if((r=t.charCodeAt(c++))>255||(e=t.charCodeAt(c++))>255||(o=t.charCodeAt(c++))>255)throw new TypeError("invalid character found");u+=f[(n=r<<16|e<<8|o)>>18&63]+f[n>>12&63]+f[n>>6&63]+f[63&n]}return i?u.slice(0,i-3)+"===".substring(i):u},y=e?function(t){return btoa(t)}:o?function(t){return Buffer.from(t,"binary").toString("base64")}:p,A=o?function(t){return Buffer.from(t).toString("base64")}:function(t){for(var n=[],r=0,e=t.length;r<e;r+=4096)n.push(d.apply(null,t.subarray(r,r+4096)));return y(n.join(""))},b=function(t,n){return void 0===n&&(n=!1),n?l(A(t)):A(t)},g=function(t){if(t.length<2)return(n=t.charCodeAt(0))<128?t:n<2048?d(192|n>>>6)+d(128|63&n):d(224|n>>>12&15)+d(128|n>>>6&63)+d(128|63&n);var n=65536+1024*(t.charCodeAt(0)-55296)+(t.charCodeAt(1)-56320);return d(240|n>>>18&7)+d(128|n>>>12&63)+d(128|n>>>6&63)+d(128|63&n)},B=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,x=function(t){return t.replace(B,g)},C=o?function(t){return Buffer.from(t,"utf8").toString("base64")}:i?function(t){return A(i.encode(t))}:function(t){return y(x(t))},m=function(t,n){return void 0===n&&(n=!1),n?l(C(t)):C(t)},v=function(t){return m(t,!0)},U=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,F=function(t){switch(t.length){case 4:var n=((7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3))-65536;return d(55296+(n>>>10))+d(56320+(1023&n));case 3:return d((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return d((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},w=function(t){return t.replace(U,F)},S=function(t){if(t=t.replace(/\s+/g,""),!a.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(3&t.length));for(var n,r,e,o="",u=0;u<t.length;)n=c[t.charAt(u++)]<<18|c[t.charAt(u++)]<<12|(r=c[t.charAt(u++)])<<6|(e=c[t.charAt(u++)]),o+=64===r?d(n>>16&255):64===e?d(n>>16&255,n>>8&255):d(n>>16&255,n>>8&255,255&n);return o},E=r?function(t){return atob(h(t))}:o?function(t){return Buffer.from(t,"base64").toString("binary")}:S,D=o?function(t){return s(Buffer.from(t,"base64"))}:function(t){return s(E(t).split("").map((function(t){return t.charCodeAt(0)})))},R=function(t){return D(T(t))},z=o?function(t){return Buffer.from(t,"base64").toString("utf8")}:u?function(t){return u.decode(D(t))}:function(t){return w(E(t))},T=function(t){return h(t.replace(/[-_]/g,(function(t){return"-"==t?"+":"/"})))},Z=function(t){return z(T(t))},j=function(t){return{value:t,enumerable:!1,writable:!0,configurable:!0}},I=function(){var t=function(t,n){return Object.defineProperty(String.prototype,t,j(n))};t("fromBase64",(function(){return Z(this)})),t("toBase64",(function(t){return m(this,t)})),t("toBase64URI",(function(){return m(this,!0)})),t("toBase64URL",(function(){return m(this,!0)})),t("toUint8Array",(function(){return R(this)}))},O=function(){var t=function(t,n){return Object.defineProperty(Uint8Array.prototype,t,j(n))};t("toBase64",(function(t){return b(this,t)})),t("toBase64URI",(function(){return b(this,!0)})),t("toBase64URL",(function(){return b(this,!0)}))},P={version:n,VERSION:"3.7.5",atob:E,atobPolyfill:S,btoa:y,btoaPolyfill:p,fromBase64:Z,toBase64:m,encode:m,encodeURI:v,encodeURL:v,utob:x,btou:w,decode:Z,isValid:function(t){if("string"!=typeof t)return!1;var n=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(n)||!/[^\s0-9a-zA-Z\-_]/.test(n)},fromUint8Array:b,toUint8Array:R,extendString:I,extendUint8Array:O,extendBuiltins:function(){I(),O()},Base64:{}};return Object.keys(P).forEach((function(t){return P.Base64[t]=P[t]})),P}));
|
||||||
|
//# sourceMappingURL=/sm/555281732ed54ee1693a772f485329378d8ea5052ffa4370e9c2e9947eb42d22.map
|
||||||
File diff suppressed because one or more lines are too long
Vendored
+13
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
Vendored
+1
File diff suppressed because one or more lines are too long
+7
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
|||||||
|
!function(t){"object"==typeof exports&&"object"==typeof module?t(require("../../lib/codemirror"),require("../xml/xml"),require("../javascript/javascript"),require("../css/css")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../xml/xml","../javascript/javascript","../css/css"],t):t(CodeMirror)}(function(m){"use strict";var l={script:[["lang",/(javascript|babel)/i,"javascript"],["type",/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i,"javascript"],["type",/./,"text/plain"],[null,null,"javascript"]],style:[["lang",/^css$/i,"css"],["type",/^(text\/)?(x-)?(stylesheet|css)$/i,"css"],["type",/./,"text/plain"],[null,null,"css"]]};var a={};function d(t,e){e=t.match(a[e=e]||(a[e]=new RegExp("\\s+"+e+"\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*")));return e?/^\s*(.*?)\s*$/.exec(e[2])[1]:""}function g(t,e){return new RegExp((e?"^":"")+"</\\s*"+t+"\\s*>","i")}function o(t,e){for(var a in t)for(var n=e[a]||(e[a]=[]),l=t[a],o=l.length-1;0<=o;o--)n.unshift(l[o])}m.defineMode("htmlmixed",function(i,t){var c=m.getMode(i,{name:"xml",htmlMode:!0,multilineTagIndentFactor:t.multilineTagIndentFactor,multilineTagIndentPastTag:t.multilineTagIndentPastTag,allowMissingTagName:t.allowMissingTagName}),s={},e=t&&t.tags,a=t&&t.scriptTypes;if(o(l,s),e&&o(e,s),a)for(var n=a.length-1;0<=n;n--)s.script.unshift(["type",a[n].matches,a[n].mode]);function u(t,e){var a,o,r,n=c.token(t,e.htmlState),l=/\btag\b/.test(n);return l&&!/[<>\s\/]/.test(t.current())&&(a=e.htmlState.tagName&&e.htmlState.tagName.toLowerCase())&&s.hasOwnProperty(a)?e.inTag=a+" ":e.inTag&&l&&/>$/.test(t.current())?(a=/^([\S]+) (.*)/.exec(e.inTag),e.inTag=null,l=">"==t.current()&&function(t,e){for(var a=0;a<t.length;a++){var n=t[a];if(!n[0]||n[1].test(d(e,n[0])))return n[2]}}(s[a[1]],a[2]),l=m.getMode(i,l),o=g(a[1],!0),r=g(a[1],!1),e.token=function(t,e){return t.match(o,!1)?(e.token=u,e.localState=e.localMode=null):(a=t,n=r,l=e.localMode.token(t,e.localState),t=a.current(),-1<(e=t.search(n))?a.backUp(t.length-e):t.match(/<\/?$/)&&(a.backUp(t.length),a.match(n,!1)||a.match(t)),l);var a,n,l},e.localMode=l,e.localState=m.startState(l,c.indent(e.htmlState,"",""))):e.inTag&&(e.inTag+=t.current(),t.eol()&&(e.inTag+=" ")),n}return{startState:function(){return{token:u,inTag:null,localMode:null,localState:null,htmlState:m.startState(c)}},copyState:function(t){var e;return t.localState&&(e=m.copyState(t.localMode,t.localState)),{token:t.token,inTag:t.inTag,localMode:t.localMode,localState:e,htmlState:m.copyState(c,t.htmlState)}},token:function(t,e){return e.token(t,e)},indent:function(t,e,a){return!t.localMode||/^\s*<\//.test(e)?c.indent(t.htmlState,e,a):t.localMode.indent?t.localMode.indent(t.localState,e,a):m.Pass},innerMode:function(t){return{state:t.localState||t.htmlState,mode:t.localMode||c}}}},"xml","javascript","css"),m.defineMIME("text/html","htmlmixed")});
|
||||||
+1
File diff suppressed because one or more lines are too long
+2
File diff suppressed because one or more lines are too long
+6
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
!function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(s){"use strict";s.defineMode("shell",function(){var o={};function e(e,t){for(var n=0;n<t.length;n++)o[t[n]]=e}var t=["true","false"],n=["if","then","do","else","elif","while","until","for","in","esac","fi","fin","fil","done","exit","set","unset","export","function"],r=["ab","awk","bash","beep","cat","cc","cd","chown","chmod","chroot","clear","cp","curl","cut","diff","echo","find","gawk","gcc","get","git","grep","hg","kill","killall","ln","ls","make","mkdir","openssl","mv","nc","nl","node","npm","ping","ps","restart","rm","rmdir","sed","service","sh","shopt","shred","source","sort","sleep","ssh","start","stop","su","sudo","svn","tee","telnet","top","touch","vi","vim","wall","wc","wget","who","write","yes","zsh"];function i(e,t){if(e.eatSpace())return null;var n,r=e.sol(),i=e.next();if("\\"===i)return e.next(),null;if("'"===i||'"'===i||"`"===i)return t.tokens.unshift(f(i,"`"===i?"quote":"string")),l(e,t);if("#"===i)return r&&e.eat("!")?(e.skipToEnd(),"meta"):(e.skipToEnd(),"comment");if("$"===i)return t.tokens.unshift(u),l(e,t);if("+"===i||"="===i)return"operator";if("-"===i)return e.eat("-"),e.eatWhile(/\w/),"attribute";if("<"==i){if(e.match("<<"))return"operator";r=e.match(/^<-?\s*['"]?([^'"]*)['"]?/);if(r)return t.tokens.unshift((n=r[1],function(e,t){return e.sol()&&e.string==n&&t.tokens.shift(),e.skipToEnd(),"string-2"})),"string-2"}if(/\d/.test(i)&&(e.eatWhile(/\d/),e.eol()||!/\w/.test(e.peek())))return"number";e.eatWhile(/[\w-]/);i=e.current();return"="===e.peek()&&/\w+/.test(i)?"def":o.hasOwnProperty(i)?o[i]:null}function f(i,o){var s="("==i?")":"{"==i?"}":i;return function(e,t){for(var n,r=!1;null!=(n=e.next());){if(n===s&&!r){t.tokens.shift();break}if("$"===n&&!r&&"'"!==i&&e.peek()!=s){r=!0,e.backUp(1),t.tokens.unshift(u);break}if(!r&&i!==s&&n===i)return t.tokens.unshift(f(i,o)),l(e,t);if(!r&&/['"]/.test(n)&&!/['"]/.test(i)){t.tokens.unshift(function(n,r){return function(e,t){return t.tokens[0]=f(n,r),e.next(),l(e,t)}}(n,"string")),e.backUp(1);break}r=!r&&"\\"===n}return o}}s.registerHelper("hintWords","shell",t.concat(n,r)),e("atom",t),e("keyword",n),e("builtin",r);var u=function(e,t){1<t.tokens.length&&e.eat("$");var n=e.next();return/['"({]/.test(n)?(t.tokens[0]=f(n,"("==n?"quote":"{"==n?"def":"string"),l(e,t)):(/\d/.test(n)||e.eatWhile(/\w/),t.tokens.shift(),"def")};function l(e,t){return(t.tokens[0]||i)(e,t)}return{startState:function(){return{tokens:[]}},token:l,closeBrackets:"()[]{}''\"\"``",lineComment:"#",fold:"brace"}}),s.defineMIME("text/x-sh","shell"),s.defineMIME("application/x-sh","shell")});
|
||||||
Vendored
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,98 @@
|
|||||||
|
// 主入口文件 - 整合所有模块
|
||||||
|
|
||||||
|
// 导入WebSocket模块
|
||||||
|
import {
|
||||||
|
wsPublish,
|
||||||
|
initWebSocket,
|
||||||
|
setScannerStateHandler,
|
||||||
|
setScannerDataHandler,
|
||||||
|
setResponseHandler,
|
||||||
|
getWebSocket,
|
||||||
|
topic_control
|
||||||
|
} from './websocket.js';
|
||||||
|
|
||||||
|
// 导入扫描器状态模块
|
||||||
|
import {
|
||||||
|
updateScannerStatus,
|
||||||
|
initScannerControls
|
||||||
|
} from './scanner-status.js';
|
||||||
|
|
||||||
|
// 导入脚本编辑器模块
|
||||||
|
import {
|
||||||
|
initEditor,
|
||||||
|
loadFile,
|
||||||
|
saveFile,
|
||||||
|
deleteCurrentFile
|
||||||
|
} from './script-editor.js';
|
||||||
|
|
||||||
|
// 导入文件树模块
|
||||||
|
import {
|
||||||
|
initFileTree,
|
||||||
|
refreshFileTree
|
||||||
|
} from './file-tree.js';
|
||||||
|
|
||||||
|
// 将刷新文件树函数暴露到全局
|
||||||
|
window.refreshFileTree = refreshFileTree;
|
||||||
|
|
||||||
|
// 文档加载完成后初始化
|
||||||
|
$(document).ready(function() {
|
||||||
|
// 初始化WebSocket连接
|
||||||
|
initWebSocket();
|
||||||
|
|
||||||
|
ChartModule.init();
|
||||||
|
|
||||||
|
// 设置扫描器状态处理函数
|
||||||
|
setScannerStateHandler(function(topic, message) {
|
||||||
|
try {
|
||||||
|
const scannerData = typeof message === 'string' ? JSON.parse(message) : message;
|
||||||
|
updateScannerStatus(scannerData);
|
||||||
|
} catch (e) {
|
||||||
|
showToast('解析扫描器状态消息失败: ' + e.message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 设置扫描器数据处理函数
|
||||||
|
setScannerDataHandler(function(topic, message) {
|
||||||
|
try {
|
||||||
|
// 处理扫描器数据,例如更新显示
|
||||||
|
// console.log('扫描器数据:', scannerData);
|
||||||
|
handleDaqData(message);
|
||||||
|
} catch (e) {
|
||||||
|
showToast('解析扫描器数据消息失败: ' + e.message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 初始化扫描器控制按钮
|
||||||
|
initScannerControls(wsPublish, topic_control);
|
||||||
|
|
||||||
|
// 初始化脚本编辑器标签页事件
|
||||||
|
$('button[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
|
||||||
|
// 初始化文件树
|
||||||
|
initFileTree(function(filePath) {
|
||||||
|
loadFile(filePath);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 窗口关闭前关闭WebSocket连接
|
||||||
|
$(window).on('beforeunload', function() {
|
||||||
|
const ws = getWebSocket();
|
||||||
|
if (ws) {
|
||||||
|
ws.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 保存文件按钮点击事件
|
||||||
|
$('#saveFile').click(function() {
|
||||||
|
saveFile();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 删除文件按钮点击事件
|
||||||
|
$('#deleteFile').click(function() {
|
||||||
|
deleteCurrentFile();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 刷新文件树按钮点击事件
|
||||||
|
$('#refreshTree').click(function() {
|
||||||
|
refreshFileTree();
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user