2024-09-02 17:57:24 +08:00
|
|
|
import types
|
2024-03-15 17:14:22 +08:00
|
|
|
import socket
|
|
|
|
import json
|
2024-04-19 15:39:29 +08:00
|
|
|
import logging
|
2024-08-02 17:44:51 +08:00
|
|
|
import time
|
|
|
|
from threading import Thread
|
2024-06-21 11:01:20 +08:00
|
|
|
from aenum import StrEnum, NoAlias
|
2024-08-02 17:44:51 +08:00
|
|
|
import queue
|
|
|
|
import asyncio
|
2024-06-21 11:01:20 +08:00
|
|
|
|
|
|
|
class _dt(StrEnum):
|
|
|
|
ip_settings = "ip_settings"
|
|
|
|
temp_adc_filter = "temp_adc_filter"
|
|
|
|
f32 = "data_f32"
|
|
|
|
bool = "data_bool"
|
|
|
|
none = "None"
|
|
|
|
|
2024-08-02 17:44:51 +08:00
|
|
|
class State(StrEnum):
|
|
|
|
disconnected = "disconnected"
|
|
|
|
connected = "connected"
|
|
|
|
|
2024-06-21 11:01:20 +08:00
|
|
|
class CmdList:
|
|
|
|
class device(StrEnum, settings=NoAlias):
|
|
|
|
_target = "device_cmd"
|
|
|
|
SetIPSettings = _dt.ip_settings
|
|
|
|
SetPdFinGain = _dt.f32
|
|
|
|
SetPdTransconductance = _dt.f32
|
|
|
|
SetActiveReportMode = _dt.bool
|
2024-09-03 16:33:40 +08:00
|
|
|
GetHwRev = _dt.none
|
2024-06-21 11:01:20 +08:00
|
|
|
GetStatusReport = _dt.none
|
|
|
|
GetSettingsSummary = _dt.none
|
|
|
|
Dfu = _dt.none
|
|
|
|
SaveFlashSettings = _dt.none
|
|
|
|
LoadFlashSettings = _dt.none
|
|
|
|
HardReset = _dt.none
|
|
|
|
|
|
|
|
class ld(StrEnum, settings=NoAlias):
|
|
|
|
_target = "laser_diode_cmd"
|
|
|
|
SetDefaultPowerOn = _dt.bool
|
|
|
|
PowerUp = _dt.none
|
|
|
|
PowerDown = _dt.none
|
|
|
|
LdTermsShort = _dt.none
|
|
|
|
LdTermsOpen = _dt.none
|
|
|
|
SetI = _dt.f32
|
|
|
|
SetPdResponsitivity = _dt.f32
|
|
|
|
SetPdDarkCurrent = _dt.f32
|
|
|
|
SetLdPwrLimit = _dt.f32
|
|
|
|
ClearAlarm = _dt.none
|
|
|
|
|
|
|
|
class thermostat(StrEnum, settings=NoAlias):
|
|
|
|
_target = "thermostat_cmd"
|
|
|
|
SetDefaultPowerOn = _dt.bool,
|
|
|
|
PowerUp = _dt.f32,
|
|
|
|
PowerDown = _dt.f32,
|
|
|
|
SetTecMaxV = _dt.f32,
|
|
|
|
SetTecMaxIPos = _dt.f32,
|
|
|
|
SetTecMaxINeg = _dt.f32,
|
|
|
|
SetTecIOut = _dt.f32,
|
|
|
|
SetTemperatureSetpoint = _dt.f32,
|
|
|
|
SetPidEngage = _dt.none,
|
|
|
|
SetPidDisEngage = _dt.none,
|
|
|
|
SetPidKp = _dt.f32,
|
|
|
|
SetPidKi = _dt.f32,
|
|
|
|
SetPidKd = _dt.f32,
|
|
|
|
SetPidOutMin = _dt.f32,
|
|
|
|
SetPidOutMax = _dt.f32,
|
|
|
|
ConfigTempAdcFilter = _dt.temp_adc_filter,
|
|
|
|
SetTempMonUpperLimit = _dt.f32,
|
|
|
|
SetTempMonLowerLimit = _dt.f32,
|
|
|
|
ClearAlarm = _dt.none,
|
|
|
|
SetShT0 = _dt.f32,
|
|
|
|
SetShR0 = _dt.f32,
|
|
|
|
SetShBeta = _dt.f32,
|
|
|
|
|
|
|
|
class FilterConfig:
|
|
|
|
class Sinc5Sinc1With50hz60HzRejection(StrEnum):
|
|
|
|
f27sps = "F27SPS"
|
|
|
|
f21sps = "F21SPS"
|
|
|
|
f20sps = "F20SPS"
|
|
|
|
f16sps = "F16SPS"
|
|
|
|
|
|
|
|
def _odr_type(self):
|
|
|
|
return "sinc5sinc1postfilter"
|
|
|
|
|
|
|
|
def _filter_type(self):
|
|
|
|
return "Sinc5Sinc1With50hz60HzRejection"
|
|
|
|
|
|
|
|
class Sinc5Sinc1(StrEnum):
|
|
|
|
f31250_0sps = "F31250_0SPS"
|
|
|
|
f15625_0sps = "F15625_0SPS"
|
|
|
|
f10417_0sps = "F10417_0SPS"
|
|
|
|
f5208_0sps = "F5208_0SPS"
|
|
|
|
f2597_0sps = "F2597_0SPS"
|
|
|
|
f1007_0sps = "F1007_0SPS"
|
|
|
|
f503_8sps = "F503_8SPS"
|
|
|
|
f381_0sps = "F381_0SPS"
|
|
|
|
f200_3sps = "F200_3SPS"
|
|
|
|
f100_2sps = "F100_2SPS"
|
|
|
|
f59_52sps = "F59_52SPS"
|
|
|
|
f49_68sps = "F49_68SPS"
|
|
|
|
f20_01sps = "F20_01SPS"
|
|
|
|
f16_63sps = "F16_63SPS"
|
|
|
|
f10_0sps = "F10_0SPS"
|
|
|
|
f5_0sps = "F5_0SPS"
|
|
|
|
f2_5sps = "F2_5SPS"
|
|
|
|
f1_25sps = "F1_25SPS"
|
|
|
|
|
|
|
|
def _odr_type(self):
|
|
|
|
return "sinc5sinc1odr"
|
|
|
|
|
|
|
|
def _filter_type(self):
|
|
|
|
return "Sinc5Sinc1"
|
|
|
|
|
|
|
|
class Sinc3(StrEnum):
|
|
|
|
f31250_0sps = "F31250_0SPS"
|
|
|
|
f15625_0sps = "F15625_0SPS"
|
|
|
|
f10417_0sps = "F10417_0SPS"
|
|
|
|
f5208_0sps = "F5208_0SPS"
|
|
|
|
f2597_0sps = "F2597_0SPS"
|
|
|
|
f1007_0sps = "F1007_0SPS"
|
|
|
|
f503_8sps = "F503_8SPS"
|
|
|
|
f381_0sps = "F381_0SPS"
|
|
|
|
f200_3sps = "F200_3SPS"
|
|
|
|
f100_2sps = "F100_2SPS"
|
|
|
|
f59_52sps = "F59_52SPS"
|
|
|
|
f49_68sps = "F49_68SPS"
|
|
|
|
f20_01sps = "F20_01SPS"
|
|
|
|
f16_63sps = "F16_63SPS"
|
|
|
|
f10_0sps = "F10_0SPS"
|
|
|
|
f5_0sps = "F5_0SPS"
|
|
|
|
f2_5sps = "F2_5SPS"
|
|
|
|
f1_25sps = "F1_25SPS"
|
|
|
|
|
|
|
|
def _odr_type(self):
|
|
|
|
return "sinc3odr"
|
|
|
|
|
|
|
|
def _filter_type(self):
|
|
|
|
return "Sinc3"
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-06-21 11:01:20 +08:00
|
|
|
class Sinc3WithFineODR():
|
|
|
|
def __init__(self, rate):
|
|
|
|
assert rate >= 1.907465 and rate <= 31250
|
|
|
|
self.rate = float(rate)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-06-21 11:01:20 +08:00
|
|
|
def _odr_type(self):
|
|
|
|
return "sinc3fineodr"
|
|
|
|
|
|
|
|
def _filter_type(self):
|
|
|
|
return "Sinc3WithFineODR"
|
2024-03-15 17:14:22 +08:00
|
|
|
|
|
|
|
class InvalidDataType(Exception):
|
|
|
|
pass
|
|
|
|
|
2024-04-19 15:39:29 +08:00
|
|
|
class InvalidCmd(Exception):
|
|
|
|
pass
|
|
|
|
|
2024-03-15 17:14:22 +08:00
|
|
|
class Device:
|
2024-09-02 17:57:24 +08:00
|
|
|
def __init__(self, send_cmd_handler, send_raw_cmd_handler):
|
2024-06-21 11:01:20 +08:00
|
|
|
self._cmd = CmdList.device
|
2024-03-15 17:14:22 +08:00
|
|
|
self._send_cmd = send_cmd_handler
|
|
|
|
self._send_raw_cmd = send_raw_cmd_handler
|
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_ip_settings(self, addr="192.168.1.128", port=1337, prefix_len=24, gateway="192.168.1.1"):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Upon command execution, the ip settings are saved into flash and are effective upon next reboot.
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-04-19 15:36:27 +08:00
|
|
|
try:
|
|
|
|
socket.inet_aton(addr)
|
|
|
|
socket.inet_aton(gateway)
|
|
|
|
except OSError:
|
2024-03-15 17:14:22 +08:00
|
|
|
raise InvalidDataType
|
2024-04-19 15:36:27 +08:00
|
|
|
|
|
|
|
addr = addr.split(".")
|
|
|
|
gateway = gateway.split(".")
|
2024-03-15 17:14:22 +08:00
|
|
|
|
|
|
|
if not(isinstance(port, int) and isinstance(prefix_len, int)):
|
|
|
|
raise InvalidDataType
|
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_raw_cmd(
|
2024-03-15 17:14:22 +08:00
|
|
|
{
|
|
|
|
"device_cmd": "SetIPSettings",
|
|
|
|
"ip_settings": {
|
2024-06-13 16:25:52 +08:00
|
|
|
"addr": [int(x) for x in addr],
|
2024-03-15 17:14:22 +08:00
|
|
|
"port": port,
|
|
|
|
"prefix_len": prefix_len,
|
2024-06-13 16:25:52 +08:00
|
|
|
"gateway": [int(x) for x in gateway],
|
2024-03-15 17:14:22 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_active_report_mode(self, on):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Set active report to be on. If it is on, Kirdy will send status report
|
2024-09-02 17:57:24 +08:00
|
|
|
to the client socket according to the temperature polling rate set.
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetActiveReportMode, on)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_pd_mon_fin_gain(self, gain):
|
2024-06-13 11:10:40 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Configure the photodiode monitor final analog front-end stage gain.
|
2024-06-13 11:10:40 +08:00
|
|
|
- gain: unitless
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetPdFinGain, gain)
|
2024-06-13 11:10:40 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_pd_mon_transconductance(self, transconductance):
|
2024-06-13 11:10:40 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Configure the photodiode monitor transconductance value.
|
2024-06-13 11:10:40 +08:00
|
|
|
- transconductance: 1/Ohm
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetPdTransconductance, transconductance)
|
2024-06-13 11:10:40 +08:00
|
|
|
|
2024-09-03 16:33:40 +08:00
|
|
|
async def get_hw_rev(self):
|
|
|
|
"""
|
|
|
|
Get hardware revision of the connected Kirdy
|
|
|
|
|
|
|
|
{
|
|
|
|
'msg_type': 'HwRev',
|
|
|
|
'hw_rev': {
|
|
|
|
'major': 0,
|
|
|
|
'minor': 3
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"""
|
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.GetHwRev, msg_type="HwRev")
|
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def get_status_report(self, sig=None):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Get status of all peripherals in a json object.
|
2024-03-18 15:38:08 +08:00
|
|
|
|
|
|
|
{
|
|
|
|
'ts': 227657, # Relative Timestamp (ms)
|
2024-04-10 16:48:04 +08:00
|
|
|
'msg_type': 'Report' # Indicate it is a 'Report' json object
|
2024-03-18 15:38:08 +08:00
|
|
|
'laser': {
|
|
|
|
'pwr_on': False, # Laser Power is On (True/False)
|
|
|
|
'pwr_excursion': False, # Was Laser experienced an Overpowered Condition? (True/False)
|
|
|
|
'ld_i_set': 0.0, # Laser Diode Output Current (A)
|
|
|
|
'pd_i': 2.0000002e-06, # Internal Photodiode Monitor current (A)
|
|
|
|
'pd_pwr': None, # Power Readings from Internal Photodiode (W). Return None if pd_mon parameter(s) are not defined.
|
2024-09-02 17:57:24 +08:00
|
|
|
'term_50ohm': 'On' # Is the Low Frequency Modulation Input's Impedance 50 Ohm? ("On"/"Off")
|
2024-03-18 15:38:08 +08:00
|
|
|
},
|
|
|
|
'thermostat': {
|
|
|
|
'pwr_on': False, # Tec Power is On (True/False)
|
|
|
|
'pid_engaged': False, # Is Pid_Engaged. If False, it is in Constant Current Mode (True/False)
|
|
|
|
'temp_mon_status': { # Temperature Monitor:
|
2024-09-02 17:57:24 +08:00
|
|
|
'status': 'Off', # "Off": Power is Off
|
|
|
|
# "ConstantCurrentMode": Thermostat is regulated in CC mode
|
|
|
|
# "PidStartUp": PID Regulation is not stable
|
|
|
|
# "PidStable": PID Regulation is stable and the temperature is within +-1mK to the setpoint
|
|
|
|
# "OverTempAlarm": Overtemperature Alarm is triggered
|
2024-03-18 15:38:08 +08:00
|
|
|
'over_temp_alarm': False # Was Laser Diode experienced an Overtemperature condition (True/False)
|
|
|
|
},
|
2024-04-02 15:22:52 +08:00
|
|
|
'temperature': 25.03344, # Temperature Readings (Degree Celsius)
|
2024-03-18 15:38:08 +08:00
|
|
|
'i_set': 0.0, # Tec Current Set by User/PID Controller(A)
|
|
|
|
'tec_i': 0.0024998188, # Tec Current Readings (A)
|
|
|
|
'tec_v': -0.00399971 # Tec Voltage Readings (V)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.GetStatusReport, msg_type="Report", sig=sig)
|
2024-03-18 15:38:08 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def get_settings_summary(self, sig=None):
|
2024-03-18 15:38:08 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Get the current settings of laser and thermostat in a json object.
|
2024-03-18 15:38:08 +08:00
|
|
|
|
2024-03-15 17:14:22 +08:00
|
|
|
{
|
2024-04-10 16:48:04 +08:00
|
|
|
'msg_type': 'Settings', # Indicate it is a 'Settings' json object
|
2024-03-15 17:14:22 +08:00
|
|
|
'laser': {
|
2024-04-10 16:48:04 +08:00
|
|
|
'default_pwr_on': False, # Power On Laser Diode at Startup
|
|
|
|
'ld_drive_current': { # Laser Diode Output Current(A)
|
2024-03-15 17:14:22 +08:00
|
|
|
'value': 0.0, # Value Set
|
|
|
|
'max': 0.3 # Max Value Settable
|
2024-09-02 17:57:24 +08:00
|
|
|
},
|
2024-04-10 16:48:04 +08:00
|
|
|
'pd_mon_params': { # Laser Diode Software Current Limit(A)
|
2024-03-15 17:14:22 +08:00
|
|
|
'responsitivity': None, # Value Set
|
|
|
|
'i_dark': 0.0 # Max Value Settable
|
2024-09-02 17:57:24 +08:00
|
|
|
},
|
|
|
|
'ld_pwr_limit': 0.0, # Laser Diode Power Limit(W)
|
|
|
|
'ld_terms_short: False, # Is Laser Diode Terminals short? (True/False)
|
2024-03-15 17:14:22 +08:00
|
|
|
},
|
|
|
|
'thermostat': {
|
|
|
|
'default_pwr_on': True, # Power on Thermostat at Startup
|
|
|
|
'pid_engaged': True, # True: PID Control Mode | False Constant Current Mode
|
2024-04-02 15:22:52 +08:00
|
|
|
'temperature_setpoint': 25.0, # Temperature Setpoint (Degree Celsius)
|
2024-03-15 17:14:22 +08:00
|
|
|
'tec_settings': {
|
|
|
|
'i_set': { # Current TEC Current Set by PID Controller/User
|
|
|
|
'value': 0.04330516, # Value Set
|
|
|
|
'max': 1.0 # Max Value Settable
|
|
|
|
},
|
|
|
|
'max_v': { # Max Voltage Across Tec Terminals
|
|
|
|
'value': 4.990857, # Value Set
|
|
|
|
'max': 5.0 # Max Value Settable
|
|
|
|
},
|
|
|
|
'max_i_pos': { # Max Cooling Current Across Tec Terminals
|
|
|
|
'value': 0.99628574, # Value Set
|
|
|
|
'max': 1.0 # Max Value Settable
|
|
|
|
},
|
|
|
|
'max_i_neg': { # Max Heating Current Across Tec Terminals
|
|
|
|
'value': 0.99628574, # Value Set
|
|
|
|
'max': 1.0 # Max Value Settable
|
|
|
|
}
|
|
|
|
},
|
|
|
|
'pid_params': { # PID Controller Parameters
|
|
|
|
'kp': 0.15668282, # Proportional Gain
|
|
|
|
'ki': 0.0021359625, # Integral Gain
|
|
|
|
'kd': 0.8292545, # Derivative Gain
|
|
|
|
'output_min': -1.0, # Minimum Current Output (A)
|
|
|
|
'output_max': 1.0 # Maximum Current Output (A)
|
|
|
|
},
|
|
|
|
'temp_adc_settings': { # Temperature ADC Settings (Please read AD7172-2 Documentation)
|
|
|
|
'filter_type': 'Sinc5Sinc1With50hz60HzRejection', # Filter Types
|
|
|
|
'sinc5sinc1odr': None, # (Unused)
|
|
|
|
'sinc3odr': None, # (Unused)
|
|
|
|
'sinc5sinc1postfilter': None, # (Unused)
|
|
|
|
'sinc3fineodr': None, # (Unused)
|
|
|
|
'rate': 16.67 # ADC Sampling Rate (Hz)
|
|
|
|
},
|
|
|
|
'temp_mon_settings': { # Temperature Monitor Settings
|
|
|
|
'upper_limit': 40.0, # Temperature Upper Limit (Degree Celsius)
|
|
|
|
'lower_limit': 10.0 # Temperature Lower Limit (Degree Celsius)
|
|
|
|
},
|
|
|
|
'thermistor_params': { # Thermistor Steinhart-Hart equation parameters
|
|
|
|
't0': 25.0, # t0: Degree Celsius
|
|
|
|
'r0': 10000.0, # r0: Ohm
|
|
|
|
'b': 3900.0 # b: (unitless)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.GetSettingsSummary, msg_type="Settings", sig=sig)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def dfu(self):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Hard reset and put the connected Kirdy into the Dfu mode for firmware update.
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.Dfu)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def save_current_settings_to_flash(self):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-04-10 16:24:18 +08:00
|
|
|
Save the current laser diode and thermostat configurations into flash.
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SaveFlashSettings)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def restore_settings_from_flash(self):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Restore the laser diode and thermostat settings from flash.
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.LoadFlashSettings)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def hard_reset(self):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Hard Reset Kirdy. The socket connection will be closed by Kirdy.
|
|
|
|
Laser diode power and Tec power will be turned off.
|
2024-09-02 17:57:24 +08:00
|
|
|
Kirdy will send out a json({'msg_type': 'HardReset'}) to all sockets before hard reset take place.
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.HardReset)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
|
|
|
class Laser:
|
2024-08-02 17:44:51 +08:00
|
|
|
def __init__(self, send_cmd_handler):
|
2024-06-21 11:01:20 +08:00
|
|
|
self._cmd = CmdList.ld
|
2024-03-15 17:14:22 +08:00
|
|
|
self._send_cmd = send_cmd_handler
|
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_power_on(self, on):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Power Up or Power Down laser diode. Powering up the Laser Diode resets the pwr_excursion status
|
|
|
|
- on (True/False)
|
|
|
|
"""
|
|
|
|
if on:
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.PowerUp, None)
|
2024-03-15 17:14:22 +08:00
|
|
|
else:
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.PowerDown, None)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_default_pwr_on(self, on):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Set whether laser diode is powered up at Startup.
|
2024-03-15 17:14:22 +08:00
|
|
|
- on (True/False)
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetDefaultPowerOn, on)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_ld_terms_short(self, short):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Open/Short laser diode terminals.
|
|
|
|
- on (True/False)
|
|
|
|
"""
|
|
|
|
if short:
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.LdTermsShort, None)
|
2024-03-15 17:14:22 +08:00
|
|
|
else:
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.LdTermsOpen, None)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_i(self, i):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Set laser diode output current: Max(0, Min(i_set, 300mA)).
|
2024-03-18 15:41:31 +08:00
|
|
|
- i: A
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetI, i)
|
2024-04-10 16:25:17 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_pd_mon_responsitivity(self, responsitivity):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Configure the photodiode monitor responsitivity parameter.
|
2024-03-15 17:14:22 +08:00
|
|
|
- responsitivity: A/W
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetPdResponsitivity, responsitivity)
|
2024-04-10 16:25:17 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_pd_mon_dark_current(self, dark_current):
|
2024-04-10 16:25:17 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Configure the photodiode monitor dark current parameter.
|
2024-08-02 17:44:51 +08:00
|
|
|
- dark_current: A
|
2024-04-10 16:25:17 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetPdDarkCurrent, dark_current)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_ld_pwr_limit(self, pwr_limit):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Set the power limit for the power excursion monitor.
|
2024-03-15 17:14:22 +08:00
|
|
|
If the calculated power with the params of pd_mon > pwr_limit,
|
|
|
|
overpower protection is triggered.
|
2024-04-03 10:52:31 +08:00
|
|
|
- pwr_limit: W
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetLdPwrLimit, pwr_limit)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def clear_alarm(self):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Clear the power excursion monitor alarm.
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.ClearAlarm)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
|
|
|
class Thermostat:
|
2024-08-02 17:44:51 +08:00
|
|
|
def __init__(self, send_cmd_handler, send_raw_cmd_handler):
|
2024-06-21 11:01:20 +08:00
|
|
|
self._cmd = CmdList.thermostat
|
2024-03-15 17:14:22 +08:00
|
|
|
self._send_cmd = send_cmd_handler
|
|
|
|
self._send_raw_cmd = send_raw_cmd_handler
|
2024-08-02 17:44:51 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_power_on(self, on):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Power up or power down thermostat.
|
2024-03-15 17:14:22 +08:00
|
|
|
- Powering up the thermostat resets the pwr_excursion status
|
|
|
|
"""
|
|
|
|
if on:
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.PowerUp, None)
|
2024-03-15 17:14:22 +08:00
|
|
|
else:
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.PowerDown, None)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_default_pwr_on(self, on):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Set whether thermostat is powered up at Startup.
|
2024-08-02 17:44:51 +08:00
|
|
|
- on: (True/False)
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetDefaultPowerOn, on)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_tec_max_v(self, max_v):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Set Tec Maximum Voltage Across the TEC Terminals.
|
2024-03-15 17:14:22 +08:00
|
|
|
- max_v: V
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetTecMaxV, max_v)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_tec_max_cooling_i(self, max_i_pos):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-03-18 17:50:37 +08:00
|
|
|
Set Tec maximum cooling current (Settable Range: 0.0 - 1.0)
|
2024-03-15 17:14:22 +08:00
|
|
|
- max_i_pos: A
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetTecMaxIPos, max_i_pos)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_tec_max_heating_i(self, max_i_neg):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-03-18 17:50:37 +08:00
|
|
|
Set Tec maximum heating current (Settable Range: 0.0 - 1.0)
|
2024-03-15 17:14:22 +08:00
|
|
|
- max_i_neg: A
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetTecMaxINeg, max_i_neg)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_tec_i_out(self, i_out):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Set Tec Output Current (Settable Range: 0.0 - 1.0)
|
2024-03-15 17:14:22 +08:00
|
|
|
This cmd is only effective in constant current control mode
|
|
|
|
or your newly set value will be overwritten by PID Controller Output
|
|
|
|
- i_out: A
|
|
|
|
"""
|
|
|
|
if isinstance(i_out, float):
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_raw_cmd({"tec_set_i": i_out})
|
2024-03-15 17:14:22 +08:00
|
|
|
elif isinstance(i_out, int):
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_raw_cmd({"tec_set_i": float(i_out)})
|
2024-03-15 17:14:22 +08:00
|
|
|
else:
|
|
|
|
raise InvalidDataType
|
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_constant_current_control_mode(self):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Disable PID Controller and output current can be controlled with set_tec_i_out() cmd.
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetPidDisEngage, None)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_temperature_setpoint(self, temperature):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Set Temperature Setpoint for PID Controller. This parameter is not active in constant current control mode
|
|
|
|
- temperature: Degree Celsius
|
|
|
|
"""
|
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetTemperatureSetpoint, temperature)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_pid_control_mode(self):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Enable PID Controller. Its PID Update Interval is controlled by the Temperature ADC polling rate.
|
|
|
|
Please refer to config_temp_adc_filter for the possible polling rate options
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetPidEngage, None)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_pid_kp(self, kp):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Set Kp parameter for PID Controller
|
|
|
|
kp: (unitless)
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetPidKp, kp)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_pid_ki(self, ki):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Set Ki parameter for PID Controller
|
|
|
|
ki: (unitless)
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetPidKi, ki)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_pid_kd(self, kd):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Set Kd parameter for PID Controller
|
|
|
|
kd: (unitless)
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetPidKd, kd)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_pid_output_max(self, out_max):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Set max output limit at the PID Output
|
|
|
|
- out_max: A
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetPidOutMax, out_max)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_pid_output_min(self, out_min):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Set min output limit at the PID Output
|
|
|
|
- out_min: A
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetPidOutMin, out_min)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_temp_mon_upper_limit(self, upper_limit):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Set Temperature Monitor Upper Limit Threshold. Exceeding the limit for too long
|
|
|
|
will force the TEC Controller, PID Controller and Laser Diode Power to Shutdown
|
|
|
|
- upper_limit: Degree Celsius
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetTempMonUpperLimit, upper_limit)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_temp_mon_lower_limit(self, lower_limit):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Set Temperature Monitor Lower Limit Threshold. Exceeding the limit for too long
|
|
|
|
will force the TEC Controller, PID Controller and Laser Diode Power to Shutdown
|
|
|
|
- lower_limit: Degree Celsius
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetTempMonLowerLimit, lower_limit)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def clear_alarm(self):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Clear the temperature monitor alarm
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.ClearAlarm)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_sh_t0(self, t0):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Set t0 Steinhart-Hart parameter for the laser diode NTC
|
|
|
|
- t0: Degree Celsius
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetShT0, t0)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_sh_r0(self, r0):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Set r0 Steinhart-Hart parameter for the laser diode NTC
|
|
|
|
- r0: Ohm
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetShR0, r0)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def set_sh_beta(self, beta):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Set beta Steinhart-Hart parameter for the laser diode NTC
|
|
|
|
- beta: (unitless)
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_cmd(self._cmd._target, self._cmd.SetShBeta, beta)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def config_temp_adc_filter(self, filter_config):
|
2024-03-15 17:14:22 +08:00
|
|
|
"""
|
|
|
|
Configure the temperature adc filter type and sampling rate.
|
|
|
|
Please refer to AD7172 datasheet for the usage of various types of filter.
|
|
|
|
The actual temperature polling rate is bottlenecked by the processing speed of the MCU and
|
|
|
|
performs differently under different kinds of workload. Please verify the polling rate with
|
|
|
|
the timestamp.
|
|
|
|
"""
|
|
|
|
cmd = {}
|
2024-06-21 11:01:20 +08:00
|
|
|
cmd[self._cmd._target] = self._cmd.ConfigTempAdcFilter.name
|
|
|
|
if hasattr(filter_config, 'rate'):
|
|
|
|
cmd[self._cmd.ConfigTempAdcFilter] = {
|
|
|
|
"filter_type": filter_config._filter_type(),
|
|
|
|
filter_config._odr_type(): filter_config.rate,
|
|
|
|
}
|
|
|
|
else:
|
|
|
|
cmd[self._cmd.ConfigTempAdcFilter] = {
|
|
|
|
"filter_type": filter_config._filter_type(),
|
|
|
|
filter_config._odr_type(): filter_config,
|
|
|
|
}
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
return await self._send_raw_cmd(cmd)
|
2024-03-15 17:14:22 +08:00
|
|
|
class Kirdy:
|
|
|
|
def __init__(self):
|
2024-09-02 17:57:24 +08:00
|
|
|
self.device = Device(self._send_cmd, self._send_raw_cmd)
|
|
|
|
self.laser = Laser(self._send_cmd)
|
|
|
|
self.thermostat = Thermostat(self._send_cmd, self._send_raw_cmd)
|
2024-09-03 16:40:59 +08:00
|
|
|
self.hw_rev = None
|
2024-08-02 17:44:51 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
self._task_queue, self._int_msg_queue, self._report_queue = None, None, None
|
|
|
|
self._timeout = 5.0
|
2024-08-02 17:44:51 +08:00
|
|
|
self._writer, self._reader = None, None
|
|
|
|
self._event_loop = None
|
2024-06-21 11:01:20 +08:00
|
|
|
|
2024-08-02 17:44:51 +08:00
|
|
|
self._msg_queue_get_report = False
|
|
|
|
self._report_mode_on = False
|
2024-09-02 17:57:24 +08:00
|
|
|
self._state = State.disconnected
|
|
|
|
|
|
|
|
self.read_response_task, self.handler_task = None, None
|
|
|
|
self._lock = asyncio.Lock()
|
2024-08-02 17:44:51 +08:00
|
|
|
|
|
|
|
# PyQt Signal
|
|
|
|
self._report_sig = None # Dict
|
|
|
|
self._connected_sig = None # Bool
|
2024-09-02 17:57:24 +08:00
|
|
|
|
|
|
|
self.connected_event = None
|
|
|
|
|
2024-09-03 16:40:59 +08:00
|
|
|
def get_hw_rev(self):
|
|
|
|
return self.hw_rev
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-08-02 17:44:51 +08:00
|
|
|
def set_report_sig(self, sig):
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Connect a PyQt Signal to the active report output(dict). This should be configured before the session is started.
|
2024-08-02 17:44:51 +08:00
|
|
|
"""
|
|
|
|
self._report_sig = sig
|
|
|
|
|
|
|
|
def set_connected_sig(self, sig):
|
|
|
|
"""
|
|
|
|
Connect a PyQt Signal to connection status(bool)
|
|
|
|
- True: Connection is established
|
|
|
|
- False: Connection is dropped
|
|
|
|
"""
|
|
|
|
self._connected_sig = sig
|
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
def start_session(self, host='192.168.1.128', port=1337):
|
2024-08-02 17:44:51 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Start Kirdy Connection Session.
|
|
|
|
In case of disconnection, all the queued tasks are cleared and the handler task retries TCP connection indefinitely.
|
2024-08-02 17:44:51 +08:00
|
|
|
- host: Kirdy's IP Address
|
2024-09-02 17:57:24 +08:00
|
|
|
- port: Kirdy's Port Number
|
2024-08-02 17:44:51 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
self._host, self._ctrl_port = host, port
|
2024-08-02 17:44:51 +08:00
|
|
|
if self._event_loop is None:
|
2024-09-02 17:57:24 +08:00
|
|
|
try:
|
|
|
|
self._event_loop = asyncio.get_running_loop()
|
|
|
|
except:
|
|
|
|
self._event_loop = asyncio.new_event_loop()
|
|
|
|
self._event_loop.run_forever()
|
|
|
|
self.connected_event = asyncio.Event()
|
|
|
|
self.handler_task = asyncio.create_task(self._handler())
|
2024-08-02 17:44:51 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def end_session(self, block=False):
|
2024-08-02 17:44:51 +08:00
|
|
|
"""
|
|
|
|
Stop Kirdy's TCP connection and its associated thread.
|
|
|
|
"""
|
|
|
|
if self._event_loop is not None:
|
|
|
|
if block:
|
2024-09-02 17:57:24 +08:00
|
|
|
await self._task_queue.join()
|
|
|
|
|
|
|
|
if self.read_response_task is not None:
|
|
|
|
self.read_response_task.cancel()
|
|
|
|
await self.read_response_task
|
|
|
|
self.read_response_task = None
|
|
|
|
|
|
|
|
if self.handler_task is not None:
|
|
|
|
self.handler_task.cancel()
|
|
|
|
await self.handler_task
|
|
|
|
self.handler_task = None
|
|
|
|
|
2024-08-02 17:44:51 +08:00
|
|
|
self._writer = None
|
|
|
|
|
|
|
|
if self._connected_sig is not None:
|
|
|
|
self._connected_sig.emit(False)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
|
|
|
def connecting(self):
|
2024-08-02 17:44:51 +08:00
|
|
|
"""
|
|
|
|
Return True if client is connecting
|
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
return self._state == State.disconnected and self.read_response_task is not None
|
2024-03-15 17:14:22 +08:00
|
|
|
|
|
|
|
def connected(self):
|
2024-08-02 17:44:51 +08:00
|
|
|
"""
|
|
|
|
Returns True if client is connected.
|
|
|
|
"""
|
2024-03-15 17:14:22 +08:00
|
|
|
return self._writer is not None
|
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def wait_until_connected(self):
|
|
|
|
if not(self.connected()):
|
|
|
|
await self.connected_event.wait()
|
|
|
|
|
|
|
|
async def report_mode(self):
|
2024-08-02 17:44:51 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
Enable and retrieve active report from Kirdy
|
2024-08-02 17:44:51 +08:00
|
|
|
"""
|
2024-09-02 17:57:24 +08:00
|
|
|
if self.connected():
|
2024-08-02 17:44:51 +08:00
|
|
|
self._report_mode_on = True
|
2024-09-02 17:57:24 +08:00
|
|
|
await self.device.set_active_report_mode(True)
|
|
|
|
report = None
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-08-02 17:44:51 +08:00
|
|
|
while self._report_mode_on:
|
2024-09-02 17:57:24 +08:00
|
|
|
report = await self._report_queue.get()
|
|
|
|
if not(isinstance(report, dict)):
|
|
|
|
self.stop_active_report()
|
|
|
|
else:
|
|
|
|
yield report
|
|
|
|
|
|
|
|
if isinstance(report, dict):
|
|
|
|
await self.device.set_active_report_mode(False)
|
2024-08-02 17:44:51 +08:00
|
|
|
else:
|
|
|
|
raise ConnectionError
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-08-02 17:44:51 +08:00
|
|
|
def stop_report_mode(self):
|
|
|
|
self._report_mode_on = False
|
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
def task_dispatcher(self, awaitable_fn):
|
|
|
|
"""
|
|
|
|
Enqueue a task to be handled by the handler.
|
|
|
|
"""
|
|
|
|
if self.connected():
|
|
|
|
self._task_queue.put_nowait(lambda: awaitable_fn)
|
|
|
|
else:
|
|
|
|
raise ConnectionError
|
|
|
|
|
2024-08-02 17:44:51 +08:00
|
|
|
async def _sock_disconnection_handling(self):
|
2024-03-15 17:14:22 +08:00
|
|
|
# Reader needn't be closed
|
2024-06-17 12:46:42 +08:00
|
|
|
try:
|
2024-08-02 17:44:51 +08:00
|
|
|
self._writer.close()
|
2024-06-17 12:46:42 +08:00
|
|
|
await self._writer.wait_closed()
|
2024-08-02 17:44:51 +08:00
|
|
|
except:
|
2024-06-17 12:46:42 +08:00
|
|
|
# In Hard Reset/DFU cmd, Kirdy may close its socket first
|
|
|
|
pass
|
2024-03-15 17:14:22 +08:00
|
|
|
self._reader = None
|
|
|
|
self._writer = None
|
|
|
|
|
2024-08-02 17:44:51 +08:00
|
|
|
for i in range(self._report_queue.maxsize):
|
|
|
|
if self._report_queue.full():
|
|
|
|
self._report_queue.get_nowait()
|
|
|
|
self._report_queue.put_nowait(None)
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-08-02 17:44:51 +08:00
|
|
|
if self._connected_sig is not None:
|
|
|
|
self._connected_sig.emit(False)
|
|
|
|
|
|
|
|
async def _handler(self):
|
|
|
|
try:
|
2024-09-02 17:57:24 +08:00
|
|
|
self._state = State.disconnected
|
2024-08-02 17:44:51 +08:00
|
|
|
first_con = True
|
|
|
|
task = None
|
|
|
|
while True:
|
2024-09-02 17:57:24 +08:00
|
|
|
if self._state == State.disconnected:
|
2024-08-02 17:44:51 +08:00
|
|
|
try:
|
2024-09-03 16:40:59 +08:00
|
|
|
self.hw_rev = None
|
2024-08-02 17:44:51 +08:00
|
|
|
await self.__coninit(self._timeout)
|
2024-09-02 17:57:24 +08:00
|
|
|
self.read_response_task = asyncio.create_task(self._read_response_handler())
|
2024-08-02 17:44:51 +08:00
|
|
|
task = None
|
2024-09-02 17:57:24 +08:00
|
|
|
logging.info("Connected to %s:%d", self._host, self._ctrl_port)
|
2024-09-03 16:40:59 +08:00
|
|
|
|
|
|
|
hw_rev = await self.device.get_hw_rev()
|
|
|
|
self.hw_rev = hw_rev["hw_rev"]
|
|
|
|
|
|
|
|
if self._connected_sig is not None:
|
|
|
|
self._connected_sig.emit(True)
|
2024-09-02 17:57:24 +08:00
|
|
|
self.connected_event.set()
|
2024-08-02 17:44:51 +08:00
|
|
|
|
|
|
|
# State Transition
|
2024-09-02 17:57:24 +08:00
|
|
|
self._state = State.connected
|
2024-08-02 17:44:51 +08:00
|
|
|
except (OSError, TimeoutError):
|
|
|
|
if first_con:
|
|
|
|
first_con = False
|
2024-09-02 17:57:24 +08:00
|
|
|
logging.warning("Cannot connect to %s:%d. Retrying in the background.", self._host, self._ctrl_port)
|
|
|
|
await asyncio.sleep(5.0)
|
2024-08-02 17:44:51 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
elif self._state == State.connected:
|
2024-08-02 17:44:51 +08:00
|
|
|
try:
|
|
|
|
task = await self._task_queue.get()
|
|
|
|
if isinstance(task, Exception):
|
|
|
|
raise task
|
2024-09-02 17:57:24 +08:00
|
|
|
await task()
|
|
|
|
self._task_queue.task_done()
|
|
|
|
|
|
|
|
except (TimeoutError, ConnectionResetError, ConnectionError):
|
|
|
|
logging.warning("Connection to Kirdy is dropped.")
|
2024-08-02 17:44:51 +08:00
|
|
|
first_con = True
|
2024-09-02 17:57:24 +08:00
|
|
|
self.read_response_task.cancel()
|
2024-08-02 17:44:51 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
# State Transition
|
|
|
|
self._state = State.disconnected
|
|
|
|
await self._sock_disconnection_handling()
|
2024-08-02 17:44:51 +08:00
|
|
|
except asyncio.exceptions.CancelledError:
|
2024-09-02 17:57:24 +08:00
|
|
|
pass
|
2024-08-02 17:44:51 +08:00
|
|
|
except:
|
2024-09-02 17:57:24 +08:00
|
|
|
logging.warning("Handler experienced an error.", exc_info=True)
|
2024-08-02 17:44:51 +08:00
|
|
|
await self._sock_disconnection_handling()
|
|
|
|
|
|
|
|
async def _read_response_handler(self):
|
|
|
|
try:
|
|
|
|
while True:
|
|
|
|
if self._report_mode_on:
|
2024-09-02 17:57:24 +08:00
|
|
|
responses = await asyncio.wait_for(self._read_response(), self._timeout)
|
2024-08-02 17:44:51 +08:00
|
|
|
else:
|
|
|
|
responses = await self._read_response()
|
|
|
|
for response in responses:
|
2024-09-02 17:57:24 +08:00
|
|
|
if response["msg_type"] == 'HardReset':
|
|
|
|
raise asyncio.exceptions.CancelledError
|
2024-08-02 17:44:51 +08:00
|
|
|
if response["msg_type"] == 'Report' and not self._msg_queue_get_report:
|
|
|
|
if self._report_sig is None:
|
2024-09-02 17:57:24 +08:00
|
|
|
self._report_queue.put_nowait_overwrite(response)
|
2024-08-02 17:44:51 +08:00
|
|
|
else:
|
|
|
|
self._report_sig.emit(response)
|
|
|
|
else:
|
|
|
|
if self._msg_queue_get_report:
|
2024-09-02 17:57:24 +08:00
|
|
|
self._msg_queue_get_report = False
|
|
|
|
self._int_msg_queue.put_nowait_overwrite(response)
|
2024-08-02 17:44:51 +08:00
|
|
|
except asyncio.exceptions.CancelledError:
|
2024-09-02 17:57:24 +08:00
|
|
|
pass
|
|
|
|
except (TimeoutError, ConnectionResetError, ConnectionError) as exec:
|
|
|
|
self._task_queue.put_nowait_overwrite(exec)
|
|
|
|
self._int_msg_queue.put_nowait_overwrite(exec)
|
|
|
|
except Exception as exec:
|
2024-08-02 17:44:51 +08:00
|
|
|
logging.warn("Read Response Handler experienced an error. Exiting.", exc_info=True)
|
2024-09-02 17:57:24 +08:00
|
|
|
self._task_queue.put_nowait_overwrite(exec)
|
|
|
|
self._int_msg_queue.put_nowait_overwrite(exec)
|
2024-08-02 17:44:51 +08:00
|
|
|
if self._report_mode_on:
|
|
|
|
self._report_mode_on = False
|
2024-09-02 17:57:24 +08:00
|
|
|
self._report_queue.put_nowait_overwrite(TimeoutError)
|
2024-08-02 17:44:51 +08:00
|
|
|
|
|
|
|
async def _stop_handler(self):
|
|
|
|
for task in asyncio.all_tasks():
|
|
|
|
task.cancel()
|
|
|
|
await asyncio.gather(*asyncio.all_tasks(), loop=self._event_loop)
|
|
|
|
|
|
|
|
async def __coninit(self, timeout):
|
2024-09-02 17:57:24 +08:00
|
|
|
def _put_nowait_overwrite(self, item):
|
|
|
|
if self.full():
|
|
|
|
self.get_nowait()
|
|
|
|
self.put_nowait(item)
|
|
|
|
asyncio.Queue.put_nowait_overwrite = _put_nowait_overwrite
|
|
|
|
|
|
|
|
if self._task_queue is not None:
|
|
|
|
while not(self._task_queue.empty()):
|
|
|
|
task = self._task_queue.get_nowait()
|
|
|
|
if isinstance(task, types.FunctionType):
|
|
|
|
task().close()
|
|
|
|
else:
|
|
|
|
self._task_queue = asyncio.Queue(maxsize=16)
|
2024-08-02 17:44:51 +08:00
|
|
|
self._int_msg_queue = asyncio.Queue(maxsize=4)
|
2024-09-02 17:57:24 +08:00
|
|
|
self._report_queue = asyncio.Queue(maxsize=16)
|
2024-08-02 17:44:51 +08:00
|
|
|
|
|
|
|
self._reader, self._writer = await asyncio.wait_for(asyncio.open_connection(self._host, self._ctrl_port), timeout)
|
|
|
|
writer_sock = self._writer.get_extra_info("socket")
|
|
|
|
writer_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
|
|
|
|
|
|
async def _read_response(self, buffer_size=16384):
|
2024-08-26 11:33:48 +08:00
|
|
|
raw_response = b''
|
|
|
|
while len(raw_response) == 0:
|
|
|
|
# Ignore 0 size packet
|
|
|
|
raw_response = await self._reader.read(buffer_size)
|
2024-08-02 17:44:51 +08:00
|
|
|
response = raw_response.decode('utf-8', errors='ignore').split("\n")
|
2024-08-26 11:33:48 +08:00
|
|
|
response = response[:-1]
|
|
|
|
|
2024-08-02 17:44:51 +08:00
|
|
|
items = []
|
2024-08-26 11:33:48 +08:00
|
|
|
for item in response:
|
2024-08-02 17:44:51 +08:00
|
|
|
items.append(json.loads(item))
|
|
|
|
return items
|
2024-04-02 13:19:40 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def _send_raw_cmd(self, cmd, msg_type="Acknowledge", sig=None):
|
2024-08-02 17:44:51 +08:00
|
|
|
if self.connected():
|
2024-09-02 17:57:24 +08:00
|
|
|
async with self._lock:
|
|
|
|
self._writer.write(bytes(json.dumps(cmd), "UTF-8"))
|
|
|
|
await self._writer.drain()
|
|
|
|
msg = await asyncio.wait_for(self._int_msg_queue.get(), self._timeout)
|
|
|
|
|
|
|
|
if msg["msg_type"] == msg_type:
|
2024-08-02 17:44:51 +08:00
|
|
|
if sig is not None:
|
2024-09-02 17:57:24 +08:00
|
|
|
sig.emit(msg)
|
2024-08-02 17:44:51 +08:00
|
|
|
return {"msg_type": "Acknowledge"}
|
2024-09-02 17:57:24 +08:00
|
|
|
return msg
|
2024-08-02 17:44:51 +08:00
|
|
|
else:
|
|
|
|
raise InvalidCmd
|
|
|
|
else:
|
|
|
|
raise ConnectionError
|
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async def _send_cmd(self, target, cmd, data=None, msg_type="Acknowledge", sig=None):
|
2024-03-15 17:14:22 +08:00
|
|
|
cmd_dict = {}
|
2024-06-21 11:01:20 +08:00
|
|
|
cmd_dict[target] = cmd.name
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-06-21 11:01:20 +08:00
|
|
|
if cmd == _dt.f32:
|
2024-03-15 17:14:22 +08:00
|
|
|
if isinstance(data, float):
|
2024-06-21 11:01:20 +08:00
|
|
|
cmd_dict[cmd] = data
|
2024-03-15 17:14:22 +08:00
|
|
|
elif isinstance(data, int):
|
2024-06-21 11:01:20 +08:00
|
|
|
cmd_dict[cmd] = float(data)
|
|
|
|
elif cmd == _dt.bool:
|
2024-03-15 17:14:22 +08:00
|
|
|
if isinstance(data, bool):
|
2024-06-21 11:01:20 +08:00
|
|
|
cmd_dict[cmd] = data
|
2024-03-15 17:14:22 +08:00
|
|
|
else:
|
|
|
|
raise InvalidDataType
|
2024-06-21 11:01:20 +08:00
|
|
|
elif cmd == "None":
|
2024-03-15 17:14:22 +08:00
|
|
|
pass
|
|
|
|
|
2024-08-02 17:44:51 +08:00
|
|
|
if msg_type == 'Report':
|
2024-09-02 17:57:24 +08:00
|
|
|
self._msg_queue_get_report = True
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-09-02 17:57:24 +08:00
|
|
|
async with self._lock:
|
|
|
|
self._writer.write(bytes(json.dumps(cmd_dict), "UTF-8"))
|
|
|
|
await self._writer.drain()
|
|
|
|
|
|
|
|
msg = await asyncio.wait_for(self._int_msg_queue.get(), self._timeout)
|
|
|
|
if isinstance(msg, Exception):
|
|
|
|
raise msg
|
2024-03-15 17:14:22 +08:00
|
|
|
|
2024-08-02 17:44:51 +08:00
|
|
|
if msg['msg_type'] == msg_type:
|
|
|
|
if sig is not None:
|
|
|
|
sig.emit(msg)
|
|
|
|
return {"msg_type": "Acknowledge"}
|
2024-09-02 17:57:24 +08:00
|
|
|
else:
|
|
|
|
return msg
|
2024-08-02 17:44:51 +08:00
|
|
|
else:
|
|
|
|
raise InvalidCmd
|