This commit is contained in:
2025-03-10 18:37:53 +08:00
parent 5519a8595b
commit b86ffd9f5b
26 changed files with 2078 additions and 0 deletions

View File

@@ -0,0 +1,91 @@
import json
import serial
import serial.tools.list_ports
import time
data_table = dict()
class Motor(object):
angle = None
def __init__(self, code):
self.angle = 0
self.code = code
data_table[code] = self.angle
def get(self):
self.angle = data_table[self.code]
return self.angle
def set(self, angle):
self.angle = angle
commander("svo", self.code, "s", angle)
return self.angle
class Engine(object):
speed = None
def __init__(self, code):
self.speed = 0
self.code = code
data_table[code] = self.speed
def get(self):
self.speed = data_table[self.code]
return self.speed
def tune(self, new_speed):
self.speed = new_speed
commander("eng", self.code, "s", new_speed)
return self.speed
class Battery:
def get():
power_left = 0.9
return power_left
def stat():
status = "Unplugged"
return status
class Serial:
ino = serial.Serial("COM7", 9600, timeout=2)
if ino.is_open:
print("串口初始化成功")
def close():
Serial.ino.close()
def write(data):
n = Serial.ino.write(data.encode())
print(f"写入 {n} 字节", data.encode())
def readln():
data = Serial.ino.readline()
print(f"读入: {data.decode('utf-8', 'ignore')}\n")
return data.decode('utf-8', 'ignore')
def commander(type, device, option, num = -1):
d = f""""type":"{type}", "device":"{device}", "option":"{option}", "num":{num}"""
d = "{" + d + "}"
Serial.write(d)
if option == "q":
b = Serial.readln()
if b.strip() != "":
print("BIS", b)
b = json.loads(b)
for i in b.keys():
data_table[i] = b[i]
def debug():
ports_list = list(serial.tools.list_ports.comports())
if len(ports_list) <= 0:
print("无串口设备。")
else:
print("可用的串口设备如下:")
for comport in ports_list:
print(list(comport)[0], list(comport)[1])
#Serial.init()
#time.sleep(1)
#print("hi",a)
#Serial.readln()
Serial.close()
"""/*
data["t(ype)"]: svo/eng
data["d(evice)"]: al, ar, tl, tr
data["o(ption)"]: s(et)/q(uery)
data["n(um)"]: SHORT
*/"""
if __name__ == "__main__":
debug()

View File

@@ -0,0 +1,14 @@
# Host Config
model: "SU27" # J-11/J-16
name: "零号侧卫"
hardware: # 硬件
surfaces: # 控制面
- al: "左副翼"
- ar: "右副翼"
- tv: "垂直尾翼"
- tl: "左尾翼"
- tr: "右尾翼"
engines: # 引擎
- e1: "一号引擎"
bools: # 布尔式硬件
- l1: "航行灯"

View File

View File

@@ -0,0 +1,33 @@
class Motor(object):
angle = None
def __init__(self, id):
self.angle = 0 # mark
self.id = id
def get(self):
return self.angle
def turn(self, add_angle):
self.angle += add_angle
return self.angle
class Engine(object):
speed = None
def __init__(self, id):
self.speed = 0 # Mark
self.id = id
def get(self):
return self.speed
def tune(self, new_speed):
self.speed = new_speed
return self.speed
class Battery:
def get():
power_left = 0.9
return power_left
def stat():
status = "Unplugged"
return status
class Network:
def stat():
delay = 0.2 # ms
return delay # or -1 (unreachable)

View File

@@ -0,0 +1,201 @@
import dummy_api as ctrl
import time
import os
import threading
class Surface(object):
motor = None
name = None
curr_angle = None
id = None
type_ = "surface"
def __init__(self, name, id):
self.motor = ctrl.Motor(id)
self.curr_angle = self.motor.get()
self.name = name
self.id = id
print("初始化操纵面 {}, 硬件代号绑定为 {}".format(name, id))
def add_angle(self, angle):
self.motor.turn(angle)
self.curr_angle = self.motor.get();
#print("将 {} 的角度加成 {} 度".format(self.name, angle))
def set_angle(self, angle):
angle_turn = angle - self.motor.get()
self.motor.turn(angle_turn)
self.curr_angle = self.motor.get()
#print("将 {} 的角度设置为 {} 度".format(self.name, angle))
def get_angle(self):
self.curr_angle = self.motor.get()
#print("{} 当前角度为 {} 度".format(self.name, self.curr_angle))
return self.curr_angle
def status(self):
return {"type":"Surface", "name":self.name, "angle":self.curr_angle}
def selfchk(self):
print("开始自检操纵面 {}".format(self.name))
self.add_angle(30)
self.add_angle(-60)
self.set_angle(0)
class Engine(object):
engine = None
curr_speed = None
id = None
name = None
type_ = "engine"
def __init__(self, name, id):
self.id = id
self.name = name
self.engine = ctrl.Engine(id)
self.curr_speed = self.engine.get()
print("初始化引擎 {}, 硬件代号绑定为 {}".format(name, id))
def set_speed(self, new_speed):
self.engine.tune(new_speed)
self.curr_speed = self.engine.get()
##print("将 {} 的转速调谐为 {} RPM".format(self.name, new_speed))
def add_speed(self, add_speed):
self.engine.tune(self.curr_speed + add_speed)
self.curr_speed = self.engine.get()
##print("将 {} 的转速加成 {} RPM".format(self.name, add_speed))
def get_speed(self):
##print("{} 当前转速为 {} RPM".format(self.name, self.curr_speed))
self.curr_speed = self.engine.get()
return self.curr_speed
def status(self):
##print(self.curr_speed)
return {"type":"Engine", "name":self.name, "speed":self.get_speed()}
def selfchk(self):
print("开始自检引擎 {}".format(self.name))
self.add_speed(3)
self.add_speed(-6)
self.set_speed(0)
self.curr_speed = self.engine.get()
class Sensor:
data = dict()
data["speed"] = 0
data["battery"] = 0
data["xangle"] = 0
data["yangle"] = 0
data["zangle"] = 0
data["sign"] = 0
data["cpuload"] = 0
data["memload"] = 0
data["memsum"] = 0
data["torch"] = 0
data["acc"] = 0
is_torch_on = 0
@staticmethod
def speed():
Sensor.data["speed"] = 99
return Sensor.data["speed"]
@staticmethod
def battery():
Sensor.data["battery"] = 0.8
return Sensor.data["battery"]
@staticmethod
def xangle():
Sensor.data["xangle"] = 201
return Sensor.data["xangle"]
@staticmethod
def yangle():
Sensor.data["yangle"] = 108
return Sensor.data["yangle"]
@staticmethod
def zangle():
Sensor.data["zangle"] = 0
return Sensor.data["zangle"]
@staticmethod
def sign():
Sensor.data["sign"] = 322
return Sensor.data["sign"]
@staticmethod
def cpuload():
Sensor.data["cpuload"] = 0.12
return Sensor.data["cpuload"]
@staticmethod
def memload():
Sensor.data["memload"] = 0.88
return Sensor.data["memload"]
@staticmethod
def memsum():
Sensor.data["memsum"] = 2048
return Sensor.data["memsum"]
@staticmethod
def torch():
Sensor.data["torch"] = Sensor.is_torch_on
return Sensor.data["torch"]
@staticmethod
def torchon():
Sensor.is_torch_on = 1
@staticmethod
def acc():
Sensor.data["acc"] = 3
return Sensor.data["acc"]
@staticmethod
def net_delay():
Sensor.data["net_delay"] = 300
return Sensor.data["net_delay"]
@staticmethod
def refresh():
Sensor.speed()
Sensor.battery()
Sensor.xangle()
Sensor.yangle()
Sensor.zangle()
Sensor.sign()
Sensor.cpuload()
Sensor.memload()
Sensor.memsum()
Sensor.torch()
Sensor.acc()
Sensor.net_delay()
@staticmethod
def stat():
#Sensor.refresh()
return Sensor.data
def pseudo_gui():
import tkinter as tk
def update_label(key, value):
labels[key].config(text=f"{key}: {value}")
def update():
while 1:
for key in Sensor.data.keys():
Sensor.data[key] = sliders[key].get()
root = tk.Tk()
root.title("DEBUGGING CONSOLE")
labels = {}
sliders = {}
# 自动布局
for key in Sensor.data.keys():
# 创建标签
label = tk.Label(root, text=f"{key}: {Sensor.data[key]}")
label.pack()
labels[key] = label
# 创建滑块
slider = tk.Scale(root, from_=0, to=100, orient=tk.HORIZONTAL, command=lambda value, k=key: update_label(k, value))
slider.pack()
sliders[key] = slider
up = threading.Thread(target=update, name='Update')
up.start()
root.mainloop()
up.join()

View File

@@ -0,0 +1,163 @@
import yaml
__dummy_mode__ = 1
cfg = None
if not __dummy_mode__:
import sys, os
sys.path.append("arduino_api")
sys.path.append("termux_lib")
import termux_lib as lib
import socket
import json
import os
import time
import threading
else:
import sys
sys.path.append("dummy_all")
import dummy_lib as lib
import socket
import json
import os
import time
import threading
def hwinit():
global hw
hw = dict()
hw["aile_left"] = lib.Flank("左副翼", "al")
hw["aile_right"] = lib.Flank("右副翼", "ar")
#hw["tail_vert"] = lib.Flank("垂直尾翼", "tv")
hw["tail_left"] = lib.Flank("左尾翼", "tl")
hw["tail_right"] = lib.Flank("右尾翼", "tr")
hw["engine_main"] = lib.Engine("一号引擎", "e1")
def check():
for i in hw.values():
i.selfchk()
print("操纵面与引擎自检完成, 等待远程指令")
def proc(data):
global hw
#print(data)
inf = json.loads(data.replace('\n', ';'))
print("DT"+data + "DT")
if inf["type"] == "cmd":
#print(f"执行命令")
exec(inf["cmd"])
elif inf["type"] == "syscmd":
#print(f"执行系统级命令")
os.system(inf["cmd"])
elif inf["type"] == "reset":
pass
#print(f"系统重置")
elif inf["type"] == "stop":
#print(f"退出系统")
return 1
else:
pass
#print(f"未知命令")
return 0
global isx
isx = 0
def stat():
global isx
status = dict()
status["devices"] = dict()
for i in hw.items():
status["devices"][i[0]] = i[1].status()
status["name"] = name
status["sensors"] = lib.Sensor.stat()
status["time"] = time.asctime()
isx+=1
return status
def debug_shell():
lib.Sensor.pseudo_gui()
def init_hardware():
global hwobj
hwobj = dict()
print("注册传感器")
for i in hw["surfaces"]:
hwobj[i.key] = lib.Surface(i.value, i.key)
print("注册操纵面")
for i in hw["surfaces"]:
hwobj[i.key] = lib.Surface(i.value, i.key)
print("注册引擎")
for i in hw["engines"]:
hwobj[i.key] = lib.Engine(i.value, i.key)
print("注册机炮")
for i in hw["cannons"]:
hwobj[i.key] = lib.Engine(i.value, i.key)
print("注册供能系统")
for i in hw["powersys"]:
hwobj[i.key] = lib.Engine(i.value, i.key)
print("注册机轮制动")
for i in hw["powersys"]:
hwobj[i.key] = lib.Engine(i.value, i.key)
print("注册雷达")
for i in hw["powersys"]:
hwobj[i.key] = lib.Engine(i.value, i.key)
print("注册挂架")
for i in hw[""]:
hwobj[i.key] = lib.Engine(i.value, i.key)
print("注册布尔元件")
for i in hw["bools"]:
hwobj[i.key] = lib.Surface(i.value, i.key)
def selfchk():
print("开始自检")
for i in hw:
print(f"{i}")
for i in hw["engines"]:
print(f"{j} ", end="")
if __name__ == "__main__":
name = "零号侧卫"
global hw
hw = dict()
port = 40808
print(f"Commdore 飞行控制系统 服务端")
print("正在加载配置文件")
with open("config.yaml") as cfg_file:
cfg = yaml.safe_load(cfg_file)
name = cfg["name"]
model = cfg["model"]
hw = cfg["hardware"]
print(f"型号: {model}")
print(f"名称: {name}")
print("正在初始化硬件")
print("启动 socket 网络通信")
print("启动备用 socket 网络通信")
dummy = socket.socket()
dummy.bind(("localhost", port)) # 端口监听
dummy.listen(1)
print(f"监听端口 " + str(port))
conn, address = dummy.accept()
print(f"来自 {address} 的连接已接收")
msg = json.dumps(stat()) # 状态回传
size = len(msg.encode())
conn.send(msg.encode("UTF-8").ljust(2048))
np = threading.Thread(target=debug_shell, name='Debugging')
np.start()
while True:
# 接收消息
print(lib.Sensor.data)
data: str = conn.recv(2048).decode("UTF-8")
if data == "" or data == None:
continue
print(f"命令接收: {data}")
ret = proc(data)
if ret == 1:
break
msg = json.dumps(stat()) # 状态回传
size = len(msg.encode())
conn.send(msg.encode("UTF-8").ljust(2048 - size)) # encode将字符串编码为字节数组对象
#print(msg.encode("UTF-8").decode('unicode_escape'))
#print(f"当前状态已回传")
# 关闭连接
conn.close()
dummy.close()
np.join()

View File

@@ -0,0 +1,232 @@
import sys
import os
sys.path.append("../arduino_api")
import arduino_api as ctrl
import time
import os
import threading
import json
import subprocess
import psutil
import threading
class Flank(object):
motor = None
name = None
curr_angle = None
code = None
type = "flank"
def __init__(self, name, code):
self.motor = ctrl.Motor(code)
self.curr_angle = self.motor.get()
self.name = name
self.code = code
print("初始化操纵面 {}, 硬件代号绑定为 {}".format(name, code))
def set_angle(self, angle):
self.motor.set(angle)
self.curr_angle = self.motor.get()
#print("将 {} 的角度设置为 {} 度".format(self.name, angle))
def add_angle(self, add_angle):
self.motor.set(self.curr_angle + add_angle)
self.curr_angle = self.motor.get()
def status(self):
return {"type":"Flank", "name":self.name, "angle":self.curr_angle}
def selfchk(self):
print("开始自检操纵面 {}".format(self.name))
self.add_angle(30)
self.add_angle(-60)
self.set_angle(0)
class Engine(object):
engine = None
curr_speed = None
code = None
name = None
type = "engine"
def __init__(self, name, code):
self.code = code
self.name = name
self.engine = ctrl.Engine(code)
self.curr_speed = self.engine.get()
print("初始化引擎 {}, 硬件代号绑定为 {}".format(name, code))
def set_speed(self, new_speed):
self.engine.tune(new_speed)
self.curr_speed = self.engine.get()
##print("将 {} 的转速调谐为 {} RPM".format(self.name, new_speed))
def add_speed(self, add_speed):
self.engine.tune(self.curr_speed + add_speed)
self.curr_speed = self.engine.get()
##print("将 {} 的转速加成 {} RPM".format(self.name, add_speed))
def get_speed(self):
##print("{} 当前转速为 {} RPM".format(self.name, self.curr_speed))
self.curr_speed = self.engine.get()
return self.curr_speed
def status(self):
##print(self.curr_speed)
return {"type":"Engine", "name":self.name, "speed":self.get_speed()}
def selfchk(self):
print("开始自检引擎 {}".format(self.name))
self.add_speed(3)
self.add_speed(-6)
self.set_speed(0)
self.curr_speed = self.engine.get()
"""
@liteon-proximity: 光学接近传感器,用于检测物体的接近
!yas537-mag: 磁力计传感器,用于测量磁场强度和方向
@liteon-light: 光传感器,用于测量环境光强度
@MPU6050-gyro: 陀螺仪传感器,用于测量角速度
@MPU6050-accel: 加速度计传感器,用于测量线性加速度
!liteon-pocket: 可能是特定用途的传感器,具体功能需参考设备文档
*yas537-orientation: 方向传感器,结合磁力计和加速度计数据来确定设备的方向
@Game Rotation Vector Sensor: 用于测量设备的旋转向量,常用于游戏和增强现实应用
@GeoMag Rotation Vector Sensor: 结合地磁和加速度数据来测量设备的旋转向量
@Gravity Sensor: 测量重力加速度,用于确定设备的姿态
*Linear Acceleration Sensor: 测量去除重力影响后的线性加速度
@Rotation Vector Sensor: 综合陀螺仪和加速度计数据来测量设备的旋转向量
"""
class Sensor:
data = {
"speed": 0,
"battery": 0,
"xangle": 0,
"yangle": 0,
"zangle": 0,
"sign": 0,
"cpuload": 0,
"memload": 0,
"memsum": 0,
"torch": 0,
"acc": 0
}
is_torch_on = 0
@staticmethod
def speed(): #TODO
Sensor.data["speed"] = -1
return Sensor.data["speed"]
@staticmethod
def battery(): # 电池剩余
return Sensor.data["sysbattery"]
def battery(): # TODO: 电机电池剩余
return Sensor.data["battery"]
@staticmethod
def xangle(): # X迎角
return Sensor.data["xangle"]
@staticmethod
def yangle():
return Sensor.data["yangle"]
@staticmethod
def zangle():
return Sensor.data["zangle"]
@staticmethod
def sign(): # 信号强度
Sensor.data["sign"] = -1
return Sensor.data["sign"]
@staticmethod
def cpuload(): # CPU占用(百分比)
Sensor.data["cpuload"] = psutil.cpu_percent(interval=1) / 100
return Sensor.data["cpuload"]
@staticmethod
def memload(): # 内存占用(百分比)
Sensor.data["memload"] = psutil.virtual_memory().percent / 100
return Sensor.data["memload"]
@staticmethod
def memsum(): # 内存总量(MB)
return Sensor.data["memsum"]
@staticmethod
def torch():
return Sensor.data["torch"]
@staticmethod
def torchon(): # 打开电筒
Sensor.is_torch_on = not Sensor.is_torch_on
to = {0:"off", 1:"on"}
os.system(f"torch {to[Sensor.is_torch_on]} &")
@staticmethod
def refresh():
Sensor.speed()
Sensor.battery()
Sensor.xangle()
Sensor.yangle()
Sensor.zangle()
Sensor.sign()
Sensor.cpuload()
Sensor.memload()
Sensor.memsum()
Sensor.torch()
@staticmethod
def stat():
#Sensor.refresh()
return Sensor.data
def update_battery():
while True:
result = subprocess.run(['termux-battery-status'], capture_output=True, text=True)
data = json.loads(result.stdout)
Sensor.data["sysbattery"] = data["percentage"]
def update_orientation():
while True:
# TODO: 优化
result = subprocess.run(['termux-sensor', '-s', 'yas537-orientation', '-n', '1'], capture_output=True, text=True)
data = json.loads(result.stdout)
Sensor.data["xangle"] = data["yas537-orientation"]["values"][0]
Sensor.data["yangle"] = data["yas537-orientation"]["values"][1]
Sensor.data["zangle"] = data["yas537-orientation"]["values"][2]
def update_acceleration():
while True:
result = subprocess.run(['termux-sensor', '-s', 'Linear Acceleration Sensor', '-n', '1'], capture_output=True, text=True)
data = json.loads(result.stdout)
Sensor.data["acc"] = data["Linear Acceleration Sensor"]["values"]
def update_func(cmd):
while True:
exec(cmd)
time.sleep(0.1)
def init():
Sensor.data = {
"speed": 0,
"battery": 0,
"xangle": 0,
"yangle": 0,
"zangle": 0,
"sign": 0,
"cpuload": 0,
"memload": 0,
"memsum": 0,
"torch": 0,
"acc": 0
}
os.system("termux-torch off &")
Sensor.is_torch_on = 0
Sensor.data["memsum"] = psutil.virtual_memory().total / (1024 * 1024)
def deamon():
# 启动线程
Sensor.battery_thread = threading.Thread(target=Sensor.update_battery)
Sensor.orientation_thread = threading.Thread(target=Sensor.update_orientation)
Sensor.acceleration_thread = threading.Thread(target=Sensor.update_acceleration)
Sensor.other_thread = threading.Thread(target=Sensor.update_func, args=("""Sensor.sign()\nSensor.cpuload()\nSensor.memload()\nSensor.torch()"""))
Sensor.battery_thread.start()
Sensor.orientation_thread.start()
Sensor.acceleration_thread.start()
def stop():
Sensor.orientation_thread.join()
Sensor.battery_thread.join()
Sensor.acceleration_thread.join()
Sensor.other_thread.join()