import serial
from serial.tools import list_ports
import modules.util.const as const
class TouchSensor:
def __init__(self):
self.ser = None
self.inhale_start = None
self.exhale_start = None
self.exhale_end = None
self.serial_command = "0"
self.previous = 0
self.setup_sensor()
def setup_sensor(self):
"""センサーのセットアップを行う"""
self.ser = self.init_serial_communication()
def init_serial_communication(self):
"""シリアル通信の初期化を行う"""
com = ""
ports = list(list_ports.comports())
for p in ports:
if p.vid == const.VID and p.pid == const.PID:
com = p.device
break
if not com:
print("Sensor device not found!")
return None
return serial.Serial(com, const.BAUDRATE, timeout=3)
def read_sensor_value(self):
"""センサーの値を読み取る"""
if not self.ser:
return None
self.ser.write(self.serial_command.encode())
dlen = self.ser.inWaiting()
d = self.ser.read(dlen)
strword = d.decode("utf-8", errors="ignore")
if len(strword) != 0:
touchData = strword[-1:]
value = int(touchData[0])
self.previous = value
return value
else:
return 2
def calc_serial_value(self, current_pos):
"""シリアル値を計算する"""
bar = 0
if not self.ser:
return None
if int(current_pos) < self.inhale_start:
bar = current_pos * const.BAR_TOR / self.inhale_start
elif int(current_pos) < self.exhale_start:
bar = const.BAR_TOR
elif int(current_pos) < self.exhale_end:
bar = const.BAR_TOR - const.BAR_TOR * (current_pos - self.exhale_start) / (
self.exhale_end - self.exhale_start
)
self.serial_command = chr(int(bar) + const.ADJUST_VALUE)
def close_connection(self):
"""シリアル接続を解除する"""
if self.ser:
self.ser.close()
self.ser = None