import kv
|
from driver import UART
|
import _thread
|
import tool
|
import app_aliyunIot
|
import utime # 延时函数在utime库中
|
uart = UART()
|
|
|
|
#电量
|
g_dianlaing = 0
|
g_dianya=0
|
g_dianlaingbaojing=0
|
|
#打开串口通讯
|
def uart_init():
|
uart.open("serial3")
|
print('open -----------serial3')
|
utime.sleep_ms(1000)
|
_thread.start_new_thread(uart_read, ())
|
|
#发送K到串口 读取返回数据
|
def uart_read():
|
print('开启串口读取')
|
while True:
|
# 定义16进制数据列表 电量%分比
|
hex_dataSos = [0x01, 0x04, 0x00,0X00,0X00,0X01,0X31,0XCA]
|
# 报警的命令
|
hex_dataAlert = [0x01,0x04,0x00,0x02,0x00,0x01,0x90,0x0A]
|
# 发送电压的命令
|
hex_dataV = [0x01, 0x04, 0x00,0X01,0X00,0X01,0X60,0X0A]
|
sundSos(hex_dataSos,'sos')
|
sundSos(hex_dataAlert,'alert')
|
sundSos(hex_dataV,'dianya')
|
|
utime.sleep_ms(10000)
|
def crc16(data, poly=0xA001, init_crc=0xFFFF):
|
crc = init_crc
|
for byte in data:
|
crc ^= byte
|
for _ in range(8):
|
if crc & 0x0001:
|
crc = (crc >> 1) ^ poly
|
else:
|
crc >>= 1
|
return crc
|
|
#发送指令到串口
|
def sundSos(hex_data,type):
|
global g_dianlaing,g_dianya,g_dianlaingbaojing
|
# 将16进制数据列表转换为字节串
|
byte_data = bytes(hex_data)
|
uart.write(byte_data)
|
#发送3秒后就读数据
|
utime.sleep_ms(1000)
|
readBuf = bytearray(570)
|
recvSize = uart.read(readBuf)
|
rData= bytearray(5)
|
for num in range(0,5): # 迭代 10 到 20 之间的数字
|
rData[num]=readBuf[num]
|
print("接收到数据:")
|
print(rData)
|
# 计算 CRC
|
calculated_crc = crc16(rData)
|
# 提取低位和高位字节
|
crc_low_byte = calculated_crc & 0xFF
|
crc_high_byte = (calculated_crc >> 8) & 0xFF
|
# 输出计算得到的 CRC
|
print("输出计算得到的 CRC: {} {}".format(crc_low_byte, crc_high_byte))
|
|
# 检查与给定的 CRC 校验码是否匹配
|
expected_crc_low_byte = readBuf[5]
|
expected_crc_high_byte = readBuf[6]
|
|
if crc_low_byte == expected_crc_low_byte and crc_high_byte == expected_crc_high_byte:
|
print("CRC 校验正确")
|
if type=='sos':
|
print("输出计算得到的电量: {}".format(readBuf[4]))
|
# app_aliyunIot.sudDataPostProps({"Dsos":readBuf[4]})
|
g_dianlaing=readBuf[4]
|
elif type=='alert':
|
print("输出计算得到的电池报警: {}".format(readBuf[4]))
|
g_dianlaingbaojing=readBuf[4]
|
# app_aliyunIot.sudDataPostProps({"Dalert":readBuf[4]})
|
elif type=='dianya':
|
print(readBuf[3],readBuf[4])
|
dianyasun=hex_to_decimal_divide(readBuf[3],readBuf[4])
|
print("输出计算得到的电压: {}".format(dianyasun))
|
g_dianya=dianyasun
|
# app_aliyunIot.sudDataPostProps({"Dv":dianyasun})
|
|
else:
|
print("CRC 校验不正确")
|
if type=='sos':
|
g_dianlaing=0
|
elif type=='alert':
|
g_dianlaingbaojing=0
|
elif type=='dianya':
|
g_dianya=0
|
# app_aliyunIot.sudDataPostProps({"Dv":dianyasun})
|
|
def hex_to_decimal_divide(dec1, dec2):
|
hex1 = '{:02X}'.format(dec1)
|
hex2 = '{:02X}'.format(dec2)
|
# 将十六进制字符串转换为整数
|
decimal_value = int(hex1 + hex2, 16)
|
# 除以 100 并保留一位小数
|
result = round(decimal_value / 100, 1)
|
return result
|
def getG_dian():
|
global g_dianlaing,g_dianya,g_dianlaingbaojing
|
return [g_dianlaing,g_dianya,g_dianlaingbaojing]
|