Files
car_stm32f103vet6/物流小车/web/checksum.py

73 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
物流小车控制指令 - 校验和算法工具(交互式)
用法:
python checksum.py # 启动交互模式,手动输入指令计算校验和
"""
import sys
import io
if sys.platform == 'win32':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
def calc_checksum(data: str) -> str:
"""计算校验和ASCII码求和 % 256 → 2位十六进制"""
total = sum(ord(c) for c in data)
return format(total % 256, '02X')
def print_ascii_detail(data: str):
"""打印每个字符的 ASCII 码值"""
print(f"\n 原始字符串: {data}")
print(f" ASCII 码分解:")
total = 0
parts = []
for c in data:
val = ord(c)
total += val
parts.append(f"'{c}'({val})")
print(" " + " + ".join(parts))
print(f" 总和 = {total}")
print(f" 取余 = {total} % 256 = {total % 256}")
print(f" 十六进制 = {calc_checksum(data)}")
def main():
print("\n" + "=" * 55)
print(" 物流小车指令校验和工具(交互式)")
print(" 输入原始字符串,自动计算校验和并生成完整指令")
print(" 输入 q 退出")
print("=" * 55)
while True:
print(f"\n{'' * 55}")
raw = input("\n 请输入指令内容(如 LOGI:GS:001: ").strip()
if raw.lower() in ('q', 'quit', 'exit'):
print("\n 再见!\n")
break
if not raw:
continue
# 如果用户输入的不是以 LOGI: 开头,自动拼接
if not raw.upper().startswith('LOGI:'):
print(f"\n [提示] 检测到未包含帧头,已自动添加 LOGI:")
raw = 'LOGI:' + raw
cs = calc_checksum(raw)
full_cmd = f"{raw}:{cs}#"
# 显示计算过程
print_ascii_detail(raw)
print(f"\n >>> 完整指令: {full_cmd}")
if __name__ == '__main__':
main()