Compare commits

..

34 Commits

Author SHA1 Message Date
Roy 9ad1f394be [update] update decode and data length = 40 byte 2022-02-18 13:16:49 +08:00
Roy d3af9e79bc update] print less and update decode 2022-02-17 10:58:05 +08:00
Roy 4aa6634f1e [update] print less 2022-02-16 10:52:48 +08:00
Roy 31b6a60046 [update] spi data length = 120 bytes 2022-02-14 14:41:54 +08:00
Roy 12e0ec7c69 Merge branch 'dev/1to8_process_0210' into main 2022-02-14 14:32:14 +08:00
Roy 7087ded6d4 [update] only use survive memory board to scan 2022-02-14 14:31:01 +08:00
Roy cdb4ddfe04 [update] check jump ram more rigorous 2022-02-14 14:29:52 +08:00
Roy 8d68d15023 [update] take away unused function 2022-02-11 14:56:30 +08:00
Roy 3ebf283c89 [update] take away unused function 2022-02-11 13:13:39 +08:00
Roy a70d20c4b8 [update] print delete content 2022-02-10 17:51:08 +08:00
Roy 8be3e1fa0e [update] fix spi routine 2022-02-10 17:47:35 +08:00
Roy e33b4d9a21 [update] fix spi reset 2022-02-10 17:46:36 +08:00
Roy a38fe5066f [update] remove redundant spi condition 2022-02-10 17:42:28 +08:00
Roy b6abf0885a [update] clear not used code in class ExtMemManager 2022-02-10 17:41:49 +08:00
Roy a3c0f1e4a3 [update] delete configuration[c] when stop sync 2022-02-10 17:40:23 +08:00
Roy 6446204013 [update] update uart read timeout: 0.01s 2022-02-10 17:39:45 +08:00
Roy 3b60d74c47 [update] remove available_device 2022-02-10 17:38:28 +08:00
Roy d1c4b0a29f [update] merge Spi & mitiSpi class 2022-02-10 17:32:36 +08:00
Roy 0034681e55 Merge branch 'rel/v1.2.2_eis1.0_v1' into main 2022-02-10 16:45:16 +08:00
peterlu14 6b3649c8a0 [update] change wifi name auto update 2022-01-20 15:48:46 +08:00
peterlu14 3f1ba0971c [update] change wifi name auto update 2022-01-20 15:29:20 +08:00
Roy 95d27aa6f2 mem data don't save in database 2022-01-19 15:53:22 +08:00
Roy 651e34d6e0 Merge branch 'rel/v1.0.1_data_len_20B' into main 2022-01-19 12:23:35 +08:00
peterlu14 d3621e0c9c [update] mac_address format fix 2022-01-19 12:12:49 +08:00
Roy 0d1b1f4825 Revert "[update] mac_address format fix"
This reverts commit 67b645dac6.
2022-01-19 12:01:08 +08:00
Roy ec0fe2ec9f mem data don't save in database 2022-01-19 12:00:26 +08:00
peterlu14 67b645dac6 [update] mac_address format fix 2022-01-14 01:15:55 +08:00
benny a3d794d9a1 change initial value of FREQ_STOP and DC_BIAS 2022-01-13 17:53:09 +08:00
benny 197a3a6f05 Merge branch 'dev/eis' into main 2022-01-12 17:53:21 +08:00
benny 0977e9bd87 modify equations 2022-01-12 17:44:17 +08:00
Roy b9dc607ac0 mem data don't save in database 2022-01-10 17:06:02 +08:00
benny 6203584a48 change DC_bias domain to 35001 2022-01-03 18:16:27 +08:00
peterlu14 ae2f8e7e70 [update] support get device by mac_address_str 2021-12-24 10:32:42 +08:00
peterlu14 a13dde3055 [update] add gitignore 2021-12-24 10:31:43 +08:00
20 changed files with 365 additions and 715 deletions
+7
View File
@@ -0,0 +1,7 @@
.DS_Store
*.cpython-37.opt-2.pyc
*.pyc
*/__pycache__
/.vscode
/media
python/biopro/sever/_identify.py
+116 -246
View File
@@ -315,14 +315,6 @@ class CC2650MasterDevice(MasterDevice, metaclass=abc.ABCMeta):
return cls.CC2650_RESET_PIN
@classmethod
def get_uart_irq_pin(cls) -> OutputPin:
if cls.CC2650_UART_IRQ is None:
cls.CC2650_UART_IRQ = OutputPin.get_used(P3Pin.MEM_RST, initial=True)
return cls.CC2650_UART_IRQ
class CC2650Device(Device):
def __init__(self,
@@ -955,9 +947,6 @@ class CC2650SingleMasterDevice(CC2650MasterDevice, Synchronized):
self._cc2650.recv_util(..., when=self._cond, timeout=timeout)
def available_device(self) -> List[int]:
return [0]
@synchronized
def scan_callback(self, callback: Callable[[DeviceResponseInfo], None], timeout=5, all_device=False) -> bool:
if self._scan_max_time != timeout:
@@ -1442,11 +1431,6 @@ class CC2650MultiMasterDevice(CC2650MasterDevice, Synchronized):
super().shutdown()
self._selector.close()
def available_device(self) -> List[int]:
return list(map(lambda it: it[0],
filter(lambda it: it[1] is not None,
enumerate(self._cc2650))))
def get_device(self, device: int) -> Optional[Device]:
return self._device[device]
@@ -1942,44 +1926,34 @@ class CC2650SingleMasterCentralDevice(CC2650MasterDevice, Synchronized):
self.log_verbose('reset (hardware)')
pin.output(False)
sleep(0.1)
# sleep(0.001)
pin.output(True)
sleep(0.1)
@synchronized
def reset_software(self):
"""software reset cc2650 (master)"""
# print('resettt---------14')
# print()
# self.log_verbose('reset (software)')
# try:
# #self._cc2650.send("3B", 1, 0, 0)
# pass
self.log_verbose('reset (software)')
# except SerialTimeoutException as e:
# raise RecvTimeout('device CC2650 reset fail') from e
try:
#self._cc2650.send("3B", 1, 0, 0)
pass
# finally:
# sleep(0.1)
print("pass")
print()
except SerialTimeoutException as e:
raise RecvTimeout('device CC2650 reset fail') from e
finally:
sleep(0.1)
@synchronized
def init_hardware(self, timeout=1):
"""initialize cc2650 (master)"""
pass
def available_device(self) -> List[int]:
return [0]
def scan_send_ins(self):
# send scan command
try:
print(':: scan_send_ins ::', self.CC2650_COMMAND_LEN, 3, 0, 0)
print()
self._cc2650.send(self.CC2650_COMMAND_LEN, 3, 0, 0)
except SerialTimeoutException as e:
@@ -1991,21 +1965,16 @@ class CC2650SingleMasterCentralDevice(CC2650MasterDevice, Synchronized):
clean_buf = self._cc2650.receive_timeout("20B", timeout=3)
print("clean_buf = ", clean_buf)
def cc2650_uart_irq(self):
uart_irq = self.get_uart_irq_pin()
uart_irq.output(False)
sleep(0.001)
uart_irq.output(True)
# def cc2650_uart_irq(self):
# uart_irq = self.get_uart_irq_pin()
# uart_irq.output(False)
# sleep(0.001)
# uart_irq.output(True)
@synchronized
def scan_callback(self, callback: Callable[[DeviceResponseInfo], None], timeout=5, all_device=False) -> bool:
# if self._scan_max_time != timeout:
# self.log_info('set max scan limit time', timeout)
# self._scan_max_time = timeout
self._found = found = []
self._found_with_id = []
number_of_device = 0
hdr_BPHS = [66, 80, 72, 83]
scan_response: Union[Optional[tuple], Any] = None
@@ -2015,42 +1984,16 @@ class CC2650SingleMasterCentralDevice(CC2650MasterDevice, Synchronized):
scan_ins.append(1) #length
scan_ins.append(0xF1)
print('send_scan', list(scan_ins))
# print('send_scan', bytes(scan_ins))
self._cc2650.send("bytes", bytes(scan_ins))
# for wait_scan_response in range(5):
# try:
# scan_response = self._cc2650.recv_uart(0.2)
# except RecvTimeout:
# if wait_scan_response == 4:
# self.reset_internal()
# self.reset_hardware()
# self._interface.flush()
# return True
# else:
# self.log_info("wait for scan response")
# continue
# # check if response is valid
# if scan_response is None:
# if wait_scan_response == 4:
# self.reset_internal()
# self.reset_hardware()
# self._interface.flush()
# else:
# self.log_info("wait for scan response")
# continue
# else:
# break
try:
scan_response = self._cc2650.recv_uart(0.2)
scan_response = self._cc2650.recv_uart(timeout)
except RecvTimeout:
self.reset_internal()
self.reset_hardware()
self._interface.flush()
return True
# self.reset_internal()
# self.reset_hardware()
# self._interface.flush()
return False
# instruction format:
# ins[0]: get_scan_response = 0x04
@@ -2145,6 +2088,35 @@ class CC2650SingleMasterCentralDevice(CC2650MasterDevice, Synchronized):
def found(self) -> List[DeviceResponseInfo]:
return self._found
def check_mem_survive(self) -> Optional[CC2650Device]:
ack = []
ins = bytearray()
ins.append(10)
ins.append(1) #length
ins.append(0xF1)
# print('ins', list(ins))
try:
self._cc2650.send("bytes", bytes(ins))
except SerialTimeoutException as e:
raise RecvTimeout('device CC2650 check_mem_survive timeout') from e
else:
try:
ack = self._cc2650.recv_uart(0.001)
except RecvTimeout:
self.log_info("no memory board")
# else:
# print('ack=', ack)
if ack == [3]:
return True
return False
@synchronized
def connect(self, response: DeviceResponseInfo, direct_connect: bool = False) -> Optional[CC2650Device]:
if self._handle is not None:
@@ -2175,7 +2147,6 @@ class CC2650SingleMasterCentralDevice(CC2650MasterDevice, Synchronized):
# send device mac and addrType
try:
print('send_connect..',list(connect_ins))
self._cc2650.send("bytes", bytes(connect_ins))
except SerialTimeoutException as e:
@@ -2208,26 +2179,39 @@ class CC2650SingleMasterCentralDevice(CC2650MasterDevice, Synchronized):
# send device mac and addrType
try:
print('send_connect',list(connect_ins))
# print('send_connect',bytes(connect_ins))
self._cc2650.send("bytes", bytes(connect_ins))
except SerialTimeoutException as e:
raise RecvTimeout('device CC2650 connect fail') from e
else:
sleep(1)
sleep(2)
# connection establish done?
for retry_recv_ack in range(5):
self._cc2650.send("bytes", bytes((0, 0, 0, 0)))
try:
con_done = self._cc2650.recv_uart(timeout = 0.1)
except RecvTimeout:
self.log_info("recv connection timeout, fail... ")
self.log_info("recv connection timeout, retry... ")
continue
if con_done[0] is 46 and \
# is the ack valid?
if con_done is None:
continue
elif con_done[0] is 46 and \
con_done[1] is 80 and \
con_done[2] is 48 and \
con_done[3] is 4:
connected = True
print('con_done=', con_done)
# print('con_done=', con_done)
break
else:
continue
# if select device is invalid or connect failed
self._interface.flush_input()
@@ -2248,36 +2232,6 @@ class CC2650SingleMasterCentralDevice(CC2650MasterDevice, Synchronized):
return ret
def check_mem_survive(self) -> Optional[CC2650Device]:
ack = []
ins = bytearray()
ins.append(10)
ins.append(1) #length
ins.append(0xF1)
try:
self._cc2650.send("bytes", bytes(ins))
except SerialTimeoutException as e:
raise RecvTimeout('device CC2650 check_mem_survive timeout') from e
else:
# sleep(1)
try:
ack = self._cc2650.recv_uart(timeout = 0.1)
except RecvTimeout:
self.log_info("no survive device")
else:
print('ack=', ack)
if ack == [3]:
return True
return False
@synchronized
def disconnect(self, device: int, force=False) -> bool:
self.log_info(DEVICE_DISCONNECTING, device)
@@ -2288,7 +2242,7 @@ class CC2650SingleMasterCentralDevice(CC2650MasterDevice, Synchronized):
ins.append(0xF1)
try:
print('send_disconnect',list(ins))
# print('send_disconnect',bytes(ins))
self._cc2650.send("bytes", bytes(ins))
except RecvTimeout:
@@ -2323,20 +2277,28 @@ class CC2650SingleMasterCentralDevice(CC2650MasterDevice, Synchronized):
ins.append(handle)
ins.append(0xF1)
try:
print('read_characteristic',list(ins))
self._cc2650.send("bytes", bytes(ins))
except SerialTimeoutException:
raise RecvTimeout('device CC2650 send read_characteristic fail')
for _ in range(2):
try:
# print('send_read',bytes(ins))
self._cc2650.send("bytes", bytes(ins))
except SerialTimeoutException:
raise RecvTimeout('device CC2650 send read_characteristic fail')
try:
ret = self._cc2650.recv_uart(timeout = 2)
except Exception as e2:
raise RecvTimeout()
else:
# print("======== read ret = ", ret)
self._interface.flush_input()
try:
ret = self._cc2650.recv_uart(timeout = 2)
except Exception as e2:
raise RecvTimeout()
else:
# print("======== read ret = ", ret)
self._interface.flush_input()
# try:
# ret = self._cc2650.recv_uart(timeout = 1)
# except Exception as e2:
# raise RecvTimeout()
# else:
# # print("read_characteristic ret = ", ret)
# pass
if ret is None:
return None
@@ -2364,21 +2326,23 @@ class CC2650SingleMasterCentralDevice(CC2650MasterDevice, Synchronized):
try:
self._cc2650.send("bytes", list(data_array))
print('send_write',list(data_array))
self._cc2650.send("bytes", bytes(data_array))
# print('send_write',bytes(data_array))
except SerialTimeoutException as e:
raise RecvTimeout('device CC2650 send instruction fail') from e
# read error code
try:
ret = self._cc2650.recv_uart(timeout = 0.1)
print('ret=', ret)
ret = self._cc2650.recv_uart()
# print("_______ write ack = ", ret)
except Exception as e2:
pass
else:
pass
self._interface.flush_input()
self._interface.flush_output()
@@ -2555,143 +2519,44 @@ class CC2650MultiMasterCentralDevice(CC2650MasterDevice, Synchronized):
else:
self.log_warn('cannot %s notify for device : %s' % (message, device.__class__.__name__))
# def reset(self, device: Optional[List[int]] = None, software_reset=True):
# print('resettt---------15')
# print()
# # self.log_verbose('reset')
# # reset hardware
# # print("reset device = ", device)
# print('device:', device, software_reset)
# print('self._device', list(self._device))
# print('self._cc2650_once:', list(self._cc2650))
# print('|')
# print('|')
# for i in range(len(self._cc2650)):
# print('i', i)
# if device is None or i in device:
# self._device[i] = None
# m = self._cc2650[i]
# if m is None:
# m = CC2650SingleMasterCentralDevice(self._master, self._interface, self._options)
# self._interface.flush()
# self._selector.select(i)
# try:
# self.log_info('reset device', i)
# with m:
# m.reset_internal()
# m.reset_hardware()
# if software_reset:
# check_mem_survive_flag = m.check_mem_survive()
# if check_mem_survive_flag:
# self._cc2650[i] = m
# except RecvTimeout:
# self.log_warn('reset device', i, 'fail')
# self._cc2650[i] = None
# print('self._cc2650::', list(self._cc2650))
# return
def reset(self, device: Optional[List[int]] = None, software_reset=True):
print('resettt---------15')
print()
# self.log_verbose('reset')
# reset hardware
# print("reset device = ", device)
print('device:', device, software_reset)
print('self._device', list(self._device))
print('self._cc2650_once:', list(self._cc2650))
print('|')
print('|')
for i in range(len(self._cc2650)):
if device is None:
if device is None or i in device:
self._device[i] = None
m = self._cc2650[i]
if m is None:
m = CC2650SingleMasterCentralDevice(self._master, self._interface, self._options)
self._cc2650[i] = m
self._interface.flush()
self._selector.select(i)
try:
self.log_info('reset device', i)
with m:
m.reset_internal()
m.reset_hardware()
if not software_reset:
check_mem_survive_flag = m.check_mem_survive()
if check_mem_survive_flag:
self._cc2650[i] = m
m.reset_software()
except RecvTimeout:
self.log_warn('reset device', i, 'fail')
self._cc2650[i] = None
print('self._cc2650::', list(self._cc2650))
return
def reset_empty_master(self, device: Optional[List[int]] = None, software_reset=True):
self.log_verbose('reset')
# reset hardware
# print("reset device = ", device)
for i in range(len(self._cc2650)):
# print(i)
m = self._cc2650[i]
d = self._device[i]
# print(m, d)
if m is not None and d is None:
m = CC2650SingleMasterCentralDevice(self._master, self._interface, self._options)
# m.set_log_level(self._cc2650_log_level)
self._interface.flush()
self._selector.select(i)
self._mem_selector.select(i)
try:
self.log_info('reset device', i)
with m:
m.reset_internal()
m.reset_hardware()
except RecvTimeout:
self.log_warn('reset device', i, 'fail')
self._cc2650[i] = None
def available_device(self) -> List[int]:
return list(map(lambda it: it[0],
filter(lambda it: it[1] is not None,
enumerate(self._cc2650))))
if not software_reset:
return
def _foreach_empty_master(self) -> Iterable[int]:
for i in range(len(self._cc2650)):
m = self._cc2650[i]
for i in range(len(self._device)):
d = self._device[i]
if m is not None and d is None:
if d is None:
yield i
def scan_callback(self, callback: Callable[[DeviceResponseInfo], None], timeout=5, all_device=False) -> bool:
@@ -2699,28 +2564,35 @@ class CC2650MultiMasterCentralDevice(CC2650MasterDevice, Synchronized):
all_result = False
for device in self._foreach_empty_master():
for device in range(len(self._cc2650)):
self.log_verbose('use', device)
m = self._cc2650[device]
d = self._device[device]
if m is not None and d is None:
if d is None:
error = None
with self:
self._interface.flush()
self._selector.select(device)
# self._mem_selector.select(device)
try:
sleep(0.0001)
result = m.scan_callback(callback, timeout=timeout)
if m.check_mem_survive() == False:
continue
result = m.scan_callback(callback, timeout=0.001)
except RuntimeError as e:
error = e
else:
if result == False:
result = True
all_result = all_result or result
continue
all_result = all_result or result
if result and not all_device:
@@ -2728,8 +2600,7 @@ class CC2650MultiMasterCentralDevice(CC2650MasterDevice, Synchronized):
if error is not None:
self.log_warn('suppressed error : ' + str(error))
# self.reset(device)
sleep(1)
return all_result
def found(self) -> List[DeviceResponseInfo]:
@@ -2782,7 +2653,6 @@ class CC2650MultiMasterCentralDevice(CC2650MasterDevice, Synchronized):
with self:
self._interface.flush()
self._selector.select(master)
# self._mem_selector.select(device)
sleep(0.0001)
d = m.connect(response, direct_connect)
+6 -10
View File
@@ -261,8 +261,7 @@ class DeviceManager(MasterDevice, Synchronized):
__slots__ = ('_handler', '_options',
'_library_path', '_library',
'_interface', '_master', '_found_history', '_found', '_device', '_master_log_level',
'_mem_survive_channel')
'_interface', '_master', '_found_history', '_found', '_device', '_master_log_level')
def __init__(self,
options: DeviceManagerOptions,
@@ -382,16 +381,8 @@ class DeviceManager(MasterDevice, Synchronized):
"""reset master device"""
self._device.clear()
self._demo.clear()
print('resettt---------21')
print()
self._centralMaster.reset(device, software_reset)
def get_mem_survive_channel(self):
return self._mem_survive_channel
def available_device(self) -> List[int]:
return self._centralMaster.available_device()
@logging_info
def shutdown(self, release_resource=True):
# shutdown reset memeryboard
@@ -581,6 +572,11 @@ class DeviceManager(MasterDevice, Synchronized):
if slave.device_id == device:
return slave
elif isinstance(device, str):
for slave in self._device:
if ':'.join('{:02x}'.format(b) for b in slave.mac_address) == device:
return slave
elif isinstance(device, DeviceInfo):
for slave in self._device:
if device.match(slave):
+43 -27
View File
@@ -889,12 +889,14 @@ class I4V4Z4T4DataDecoder(RecDataDecoder):
cycle_number = struct.unpack('>H', data[17:19])[0]
finish_mode_falg = data[19]
mem_wrong_information = struct.unpack('>i', data[40:40+4])[0]
# print('decode', list(data[20:]))
mem_wrong = data[120]
mem_retry_cnt = data[121]
mem_green_wrong = data[122]
mem_green_retry_cnt = data[123]
ram_num = data[124]
mem_wrong = data[40]
mem_retry_cnt = data[41]
mem_green_wrong = data[42]
mem_green_retry_cnt = data[43]
ram_num = data[44]
broken_flag = data[-1]
if (finish_mode_falg & 0b11110000 == 0b10100000):
@@ -930,6 +932,7 @@ class I4V4Z4T4DataDecoder(RecDataDecoder):
# '|', '{:5}'.format(mem_retry_cnt),
# '|', '{:5}'.format(mem_green_wrong),
# '|', '{:5}'.format(mem_green_retry_cnt),
# '|', '{:5}'.format(mem_wrong_information),
# '|', '{:5}'.format(ram_num),
# '|', '{:5}'.format(broken_flag),
# '@', str(self.device), '|')
@@ -948,12 +951,14 @@ class I4V4Z4T4DataDecoder(RecDataDecoder):
ret.append_data(3, cycle_number)
# memoryboard information
ret.append_data(4, mem_wrong)
ret.append_data(5, mem_retry_cnt)
ret.append_data(6, mem_green_wrong)
ret.append_data(7, mem_green_retry_cnt)
ret.append_data(8, ram_num)
ret.append_data(9, broken_flag)
# ret.append_data(4, mem_wrong)
# ret.append_data(5, mem_retry_cnt)
# ret.append_data(6, mem_green_wrong)
# ret.append_data(7, mem_green_retry_cnt)
ret.append_data(4, ram_num)
ret.append_data(5, broken_flag)
ret.append_data(6, mem_wrong_information)
# ret.append_data(4, ram_num)
if cycle_number != self._cycle_number:
# notify cycle_number change
@@ -1378,41 +1383,46 @@ class EISZeroOneDataDecoder(RecDataDecoder):
index = 20
for i in range(index, index+16, 8):
phase_para_a.append(struct.unpack('>I', cali_coeff[i+1:i+5])[0])
phase_para_a.append(struct.unpack('>i', cali_coeff[i+1:i+5])[0])
phase_para_b.append(struct.unpack('>i', cali_coeff[i+5:i+9])[0])
index = 40
for i in range(index, index+16, 8):
phase_para_a.append(struct.unpack('>I', cali_coeff[i+1:i+5])[0])
phase_para_a.append(struct.unpack('>i', cali_coeff[i+1:i+5])[0])
phase_para_b.append(struct.unpack('>i', cali_coeff[i+5:i+9])[0])
#Lv[0] 160k
index = 60
hsrtia_a.append(struct.unpack('>I', cali_coeff[index+1:index+5])[0]/1e8)
hsrtia_a.append(struct.unpack('>i', cali_coeff[index+1:index+5])[0]/1e8)
hsrtia_b.append(struct.unpack('>i', cali_coeff[index+5:index+9])[0]/1e8)
hsrtia_c.append(struct.unpack('>i', cali_coeff[index+9:index+13])[0]/1e4)
hsrtia_d.append(struct.unpack('>B', cali_coeff[index+13:index+14])[0])
#Lv[1] 20k
index = 80
hsrtia_a.append(struct.unpack('>I', cali_coeff[index+1:index+5])[0]/1e8)
hsrtia_a.append(struct.unpack('>i', cali_coeff[index+1:index+5])[0]/1e8)
hsrtia_b.append(struct.unpack('>i', cali_coeff[index+5:index+9])[0]/1e8)
hsrtia_c.append(struct.unpack('>I', cali_coeff[index+9:index+13])[0]/1e4)
hsrtia_c.append(struct.unpack('>i', cali_coeff[index+9:index+13])[0]/1e4)
hsrtia_d.append(struct.unpack('>B', cali_coeff[index+13:index+14])[0])
#Lv[2] 5k
index = 100
hsrtia_a.append(struct.unpack('>I', cali_coeff[index+1:index+5])[0]/1e8)
hsrtia_a.append(struct.unpack('>i', cali_coeff[index+1:index+5])[0]/1e8)
hsrtia_b.append(struct.unpack('>i', cali_coeff[index+5:index+9])[0]/1e8)
hsrtia_c.append(struct.unpack('>I', cali_coeff[index+9:index+13])[0]/1e4)
hsrtia_c.append(struct.unpack('>i', cali_coeff[index+9:index+13])[0]/1e4)
hsrtia_d.append(struct.unpack('>B', cali_coeff[index+13:index+14])[0])
#Lv[3] 200R
index = 120
hsrtia_a.append(struct.unpack('>I', cali_coeff[index+1:index+5])[0])
hsrtia_b.append(struct.unpack('>I', cali_coeff[index+5:index+9])[0]/1e6)
hsrtia_c.append(struct.unpack('>I', cali_coeff[index+9:index+13])[0]/1e5)
hsrtia_d.append(struct.unpack('>I', cali_coeff[index+13:index+17])[0]/1e6)
hsrtia_a.append(struct.unpack('>i', cali_coeff[index+1:index+5])[0]/1e8)
hsrtia_b.append(struct.unpack('>i', cali_coeff[index+5:index+9])[0]/1e8)
hsrtia_c.append(struct.unpack('>i', cali_coeff[index+9:index+13])[0]/1e4)
hsrtia_d.append(struct.unpack('>B', cali_coeff[index+13:index+14])[0])
# hsrtia_a.append(struct.unpack('>I', cali_coeff[index+1:index+5])[0])
# hsrtia_b.append(struct.unpack('>I', cali_coeff[index+5:index+9])[0]/1e6)
# hsrtia_c.append(struct.unpack('>I', cali_coeff[index+9:index+13])[0]/1e5)
# hsrtia_d.append(struct.unpack('>I', cali_coeff[index+13:index+17])[0]/1e6)
# print('cutoff_freq', cutoff_freq)
# print('hsrtia_a', hsrtia_a)
@@ -1492,13 +1502,19 @@ class EISZeroOneDataDecoder(RecDataDecoder):
voltage_mag = math.sqrt(img ** 2 + real ** 2) * (1 + freq ** 2 / cutoff_freq ** 2)
if (gain == 3):
current = hsrtia_a[gain] * math.exp(hsrtia_b[gain] * voltage_mag) + hsrtia_c[gain] * math.exp(hsrtia_d[gain] * voltage_mag)
else:
current = voltage_mag ** 2 * hsrtia_a[gain] + voltage_mag * hsrtia_b[gain] + hsrtia_c[gain]
# if (gain == 3):
# current = hsrtia_a[gain] * math.exp(hsrtia_b[gain] * voltage_mag) + hsrtia_c[gain] * math.exp(hsrtia_d[gain] * voltage_mag)
# else:
current = voltage_mag ** 2 * hsrtia_a[gain] + voltage_mag * hsrtia_b[gain] + hsrtia_c[gain]
# print(current)
# print(voltage_mag)
# print(hsrtia_a[gain])
# print(hsrtia_b[gain])
# print(hsrtia_c[gain])
if (current != 0):
impedance = voltage_amp * 1000000 / current
# impedance = voltage_amp * 1000_000 / 1.414213 / current
impedance = voltage_amp * 707106.78 / current
else:
impedance = 0
-7
View File
@@ -963,10 +963,6 @@ class MasterDevice(LoggerFlag, metaclass=abc.ABCMeta):
"""
pass
@abc.abstractmethod
def available_device(self) -> List[int]:
pass
def scan(self, timeout=5, all_device=False) -> List[DeviceResponseInfo]:
"""scan the nearby device.
@@ -1101,9 +1097,6 @@ class NullMasterDevice(MasterDevice):
def shutdown(self, release_resource=True):
pass
def available_device(self) -> List[int]:
return []
def scan(self, timeout=5, all_device=False) -> List[DeviceResponseInfo]:
return []
+1 -4
View File
@@ -3720,12 +3720,9 @@ class CC2650Central(LoggerFlag):
if ret is not None and len(ret) > 0:
return ret
elif _time() - start > 1:
elif _time() - start > 0.01: # read timeout
return None
else:
sleep(0.01)
def _recv_event(self, timeout: Optional[float] = 1) -> Optional[list]:
code = self._recv_byte()
# print("code = ", code)
+58 -77
View File
@@ -16,8 +16,6 @@ MEM_REG_READ = 0x05
DEFAULT_REGISTER_VALUE = 0b0100_0011 # 67
MEM_SIZE = 0x1000
_RUNTIME_COMPILE = False
_SLEEP_TIME_ = 0.001
@@ -29,9 +27,10 @@ class MultiExtMemSpiInterface(LowLevelHardwareInterface):
MEM_INS_MARKED = [MEM_INS_WRITE, 0, 2, 1, 1]
MEM_INS_RESET = [MEM_INS_WRITE, 0, 2, 1, 1, 0, 0xFF]
__slots__ = ('_selector', '_wait_for_first_data', '_spi', '_tx_buffer', '_tx_buffer_header', '_tx_buffer_data',
'pin_busy', 'pin_request', 'pin_reset', 'pin_sel',
__slots__ = ('_selector', '_wait_for_first_data', '_spi', '_tx_buffer_header', '_tx_buffer_data',
'pin_busy', 'pin_mem_req', 'pin_mem_sel', 'pin_ram_sel',
'_pin_sel_val',
'_pin_ram_sel_value', '_pin_mem_sel_value', '_pin_mem_req_value',
'_read_green_times','_read_red_times',
'_elite_data_len', '_mem_header_len', '_mem_tailer_len', '_single_data_len',
'_head_wrong_cnt')
@@ -41,24 +40,26 @@ class MultiExtMemSpiInterface(LowLevelHardwareInterface):
device: Tuple[int, int] = None):
self._spi = HardwareImplSpiInterface(device,
spi_speed=12_000_000 # XXX temp parameter
)
spi_speed=12_000_000)
self._elite_data_len = 120
self._elite_data_len = 40
self._mem_header_len = 3
self._mem_tailer_len = 8
self._single_data_len = self._elite_data_len + self._mem_header_len + self._mem_tailer_len
# buffer
self._tx_buffer = [0] * 512
self._tx_buffer_header = [0] * 11
self._tx_buffer_data = [0] * (self._single_data_len * 10 + 3)
# memory control pin
self.pin_busy = OutputPin.get_used(P3Pin.MEM_BZY, True)
self.pin_request = OutputPin.get_used(P3Pin.MEM_REQ, True)
self.pin_reset = OutputPin.get_used(P3Pin.MEM_RST, True)
self.pin_sel: Optional[InputPin] = InputPin.get_used(P3Pin.MEM_SEL)
self.pin_mem_req = OutputPin.get_used(P3Pin.MEM_REQ, False)
self.pin_mem_sel = OutputPin.get_used(P3Pin.MEM_RST, True) # MEM_RST -> actually which memory board is assign
self.pin_ram_sel: Optional[InputPin] = InputPin.get_used(P3Pin.MEM_SEL) # MEM_SEL -> actually is RAM_SEL, which RAM is assign
self._pin_ram_sel_value = [bool(self.pin_ram_sel) for _ in range(Selector.SIZE)]
self._pin_mem_sel_value = [bool(self.pin_mem_sel) for _ in range(Selector.SIZE)]
self._pin_mem_req_value = [bool(self.pin_mem_req) for _ in range(Selector.SIZE)]
self._read_green_times = 0
self._read_red_times = 0
@@ -71,6 +72,28 @@ class MultiExtMemSpiInterface(LowLevelHardwareInterface):
self._pin_sel_val = [False for _ in range(Selector.SIZE)]
self._wait_for_first_data = [True for _ in range(Selector.SIZE)]
def set_pin_mem_req(self, value: bool):
channel = self.select
self.pin_mem_req.output(value)
self._pin_mem_req_value[channel] = value
def set_pin_mem_sel(self, value: bool):
channel = self.select
self.pin_mem_sel.output(value)
self._pin_mem_sel_value[channel] = value
def get_pin_mem_req(self):
channel = self.select
return self._pin_mem_req_value[channel]
def get_pin_ram_sel(self):
channel = self.select
if self.pin_ram_sel.input() == 0:
self._pin_ram_sel_value[channel] = False
else:
self._pin_ram_sel_value[channel] = True
return self._pin_ram_sel_value[channel]
@property
def select(self) -> int:
return self._selector.channel
@@ -79,71 +102,35 @@ class MultiExtMemSpiInterface(LowLevelHardwareInterface):
def select(self, value: int):
self._selector.select(value)
def changed(self, flip=False) -> bool:
channel = self._selector.channel
old = self._pin_sel_val[channel]
value = bool(self.pin_sel)
if flip:
self._pin_sel_val[channel] = value
return value != old
def reset(self):
self._spi.reset()
def flush(self):
pass
def close(self):
self._selector.close()
self._spi.close()
def flush(self):
self.pin_reset.output(False)
self.pin_reset.output(True)
def send_byte(self, data: bytes):
raise RuntimeError()
def recv_byte(self, size: int) -> Optional[bytes]:
raise RuntimeError()
# def flush_all(self):
# for _ in self._selector.foreach():
# self.pin_reset.output(False)
# self.pin_reset.output(True)
def foreach(self) -> Iterable[int]:
for channel in self._selector.foreach():
yield channel
def set_wait_flag(self, spi_idx:int = None, value:bool = None):
self._wait_for_first_data[spi_idx] = value
def get_wait_flag(self, spi_idx:int = None) -> Optional[bool]:
if spi_idx < Selector.SIZE:
return self._wait_for_first_data[spi_idx]
else:
return None
def request_data(self):
self.pin_request.output(False)
sleep(0.001)
# count = 0
# for i in range(300):
# count = count + 1
self.pin_request.output(True)
# sleep(0.001) -> 1.2ms
# no sleep -> 5us ~ 12us (central can't receive)
# for i in range
# (1000) -> 500us ~ 1ms
# (500) -> 200us ~ 500us
# (300) -> 120us ~ 270us (seldom)
# (200) -> 70us ~ 160us (skip req about every 64 time) x
# (100) -> 40us ~ 100us (skip req sometimes) x
def compare_green_data(self, data_first: Union[bytes, List[int]], data_second: Union[bytes, List[int]], data_third: Union[bytes, List[int]], length: int):
data = []
data.append(255)
@@ -202,8 +189,8 @@ class MultiExtMemSpiInterface(LowLevelHardwareInterface):
if (data[0] != 255 or data[1] != 255 or data[2] != 255):
self._head_wrong_cnt[device] = self._head_wrong_cnt[device] + 1
if (self._head_wrong_cnt[device] < 6):
print('data_first[0:3] != [255, 255, 255]', device)
if (self._head_wrong_cnt[device] <= 5): # print 5 times
print('data_first[0:3] != [255, 255, 255], device:', device, ',', self._head_wrong_cnt[device], 'times')
print(list(data[0:7]))
data[0:3] = [255, 255, 255]
@@ -222,13 +209,13 @@ class MultiExtMemSpiInterface(LowLevelHardwareInterface):
# if (data_first[0] != 255 or data_first[1] != 255 or data_first[2] != 255):
# self._head_wrong_cnt[device] = self._head_wrong_cnt[device] + 1
# if (self._head_wrong_cnt[device] < 10):
# print('data_first[0:3] != [255, 255, 255]', device)
# print('data_first[0:3] != [255, 255, 255], device:', device, ',', self._head_wrong_cnt[device], 'times')
# print(list(data_first[0:7]))
# if (data_second[0] != 255 or data_second[1] != 255 or data_second[2] != 255):
# self._head_wrong_cnt[device] = self._head_wrong_cnt[device] + 1
# if (self._head_wrong_cnt[device] < 10):
# print('data_second[0:3] != [255, 255, 255]', device)
# print('data_second[0:3] != [255, 255, 255], device:', device, ',', self._head_wrong_cnt[device], 'times')
# print(list(data_second[0:7]))
# if (data_first[3:] == data_second[3:]):
@@ -382,39 +369,37 @@ class MultiExtMemSpiInterface(LowLevelHardwareInterface):
class ExtMemManager:
def __init__(self, ext_mem: MultiExtMemSpiInterface):
self._mem_sel = InputPin.get_used(P3Pin.MEM_SEL, pull_up_down=True)
self._mem_req = OutputPin.get_used(P3Pin.MEM_REQ, initial=True)
self._ext_mem = ext_mem
print('ExtMemManager.....')
print()
def mem_request(self):
self._mem_req.pulse()
sleep(_SLEEP_TIME_)
def get_ext_mem_register(self) -> List[Tuple[Optional[int], Optional[int]]]:
print('get_ext_mem_register......')
print()
ret = [(None, None) for _ in range(Selector.SIZE)]
for channel in self._ext_mem.foreach():
r = [None, None]
self.mem_request()
sleep(0.01)
m1 = int(self._mem_sel)
self._ext_mem.set_pin_mem_sel(False)
pin_value = self._ext_mem.get_pin_mem_req()
self._ext_mem.set_pin_mem_req(not pin_value)
m1 = int(self._ext_mem.get_pin_ram_sel())
# print("m1 = ", m1)
self._ext_mem.write_register(DEFAULT_REGISTER_VALUE)
r[m1] = self._ext_mem.read_register()
sleep(0.040)
self._ext_mem.set_pin_mem_sel(True)
sleep(0.200)
self.mem_request()
sleep(0.01)
m2 = int(self._mem_sel)
self._ext_mem.set_pin_mem_sel(False)
pin_value = self._ext_mem.get_pin_mem_req()
self._ext_mem.set_pin_mem_req(not pin_value)
m2 = int(self._ext_mem.get_pin_ram_sel())
# print("m2 = ", m2)
self._ext_mem.write_register(DEFAULT_REGISTER_VALUE)
r[m2] = self._ext_mem.read_register()
sleep(0.040)
self._ext_mem.set_pin_mem_sel(True)
sleep(0.200)
ret[channel] = tuple(r)
@@ -441,12 +426,9 @@ class ExtMemManager:
return 0
def get_available_channel(self, result: List[Tuple[Optional[int], Optional[int]]] = None) -> List[int]:
print('get_available_channel......')
print()
if result is None:
result = self.get_ext_mem_register()
ret = []
for channel, result in enumerate(result):
@@ -459,4 +441,3 @@ class ExtMemManager:
ret.append(channel)
return ret
+1 -1
View File
@@ -53,7 +53,7 @@ class HardwareImplSpiInterface(LowLevelHardwareInterface):
*MISO*, *SCLK*, *GE0_N*
"""
__slots__ = ('_device', '_spi', '_spi_mode', 'pin_request', '_spi_speed')
__slots__ = ('_device', '_spi', '_spi_mode', '_spi_speed')
def __init__(self,
device: Tuple[int, int] = None,
+1 -1
View File
@@ -28,7 +28,7 @@ class UARTInterface(LowLevelHardwareInterface):
self._serial = serial.Serial(self._port,
baudrate=self._baudrate,
timeout=0,
writeTimeout=1)
writeTimeout=0.01)
# deprecate function name which change at version 3.0
self._serial.flushInput()
self._serial.flushOutput()
+8 -8
View File
@@ -117,14 +117,14 @@ class Selector:
self._p1.output(p[1])
self._p2.output(p[2])
if (value == 4 and self._last_sel != 6):
print('mem_sel is not use gray code, value:', value, ', last value:', self._last_sel)
elif (value == 5 and self._last_sel != 4):
print('mem_sel is not use gray code, value:', value, ', last value:', self._last_sel)
elif (value == 7 and self._last_sel != 5):
print('mem_sel is not use gray code, value:', value, ', last value:', self._last_sel)
elif (value == 6 and self._last_sel != 7):
print('mem_sel is not use gray code, value:', value, ', last value:', self._last_sel)
# if (value == 4 and self._last_sel != 6):
# print('mem_sel is not use gray code, value:', value, ', last value:', self._last_sel)
# elif (value == 5 and self._last_sel != 4):
# print('mem_sel is not use gray code, value:', value, ', last value:', self._last_sel)
# elif (value == 7 and self._last_sel != 5):
# print('mem_sel is not use gray code, value:', value, ', last value:', self._last_sel)
# elif (value == 6 and self._last_sel != 7):
# print('mem_sel is not use gray code, value:', value, ', last value:', self._last_sel)
self._last_sel = value
+6 -17
View File
@@ -280,14 +280,11 @@ class Main(CliMain):
@cli_command('controller')
def _controller_server(self, command: str, argv: List[str]):
"""controller server"""
print(self, command, argv)
print('##_controller_server')
return _ControlServer
@cli_command('data')
def _data_server(self, command: str, argv: List[str]):
"""data server"""
print('##_data_server')
return _DataServer
@cli_command('export')
@@ -305,7 +302,6 @@ class Main(CliMain):
return LEDControlMain(command)
def run(self):
print('RUN!!!!!!!!!!!!!!!!!!!')
self.print_help()
@@ -339,16 +335,15 @@ class _ServerMain(CliSubCommandMain, metaclass=abc.ABCMeta):
def run(self):
exit_code = 1
print('create_server')
server = self.create_server()
exit_code = server.main()
print('....after create_server')
print('.. ..')
print()
if _RUNTIME_COMPILE:
exit_code = server.main()
else:
with self.profiling_options.generate_profile_context():
exit_code = server.main()
sys.exit(exit_code)
# noinspection PyUnusedLocal
@@ -360,7 +355,6 @@ class _ControlServer(_ServerMain):
from biopro.device.manager import DeviceManagerOptions
from biopro.server.data import DataServerOptions
from biopro.exp_pro.manager import ExpManagerOption
print('command', command)
super().__init__(command)
@@ -462,8 +456,6 @@ class _ControlServer(_ServerMain):
def create_server(self) -> SocketServer:
from biopro.server.main import ControlServer
print('..create_server')
return ControlServer(self.server_device_options,
self.server_data_options,
self.server_controller_options,
@@ -485,11 +477,8 @@ class _DataServer(_ServerMain):
def create_server(self) -> SocketServer:
from biopro.server.data import DataServer
print('.1.create_server')
return DataServer(self.server_data_options)
if __name__ == '__main__':
print('START!!!!!!!!!!!!!!!!!!!!!!!!')
Main().main()
+1 -1
View File
@@ -64,7 +64,7 @@ class RoutineConnectDeviceThread(ServerThread):
self._current_times = 0
self._time = time()
if len(self._manager._device) < len(self._manager.available_device()) and not self.check_device_status('update') and not self.check_device_status('running') and self._current_times < 3:
if not self.check_device_status('update') and not self.check_device_status('running') and self._current_times < 3:
self._current_times += 1
register_device = DeviceAPI.getAll()
if register_device is not None:
+53 -244
View File
@@ -131,9 +131,6 @@ class DataServer(SocketServer, DataAPI):
self._available_channel.clear()
if self._spi is not None:
self.log_verbose('spi flush')
# self._spi.flush_all()
self.reset_available_channel()
LEAK.reset()
@@ -199,10 +196,8 @@ class DataServer(SocketServer, DataAPI):
self.setup_spi(spi_mode)
print('self.setup()')
print()
# restart
self.setup()
# self.setup()
# data_server setup mqtt start
if self.mqtt_thread is not None:
@@ -227,8 +222,6 @@ class DataServer(SocketServer, DataAPI):
elif spi_mode == self.MODE_DISABLE:
spi = None
elif spi_mode == self.MODE_SELECTOR:
print('~~~~~')
print()
spi = MultiExtMemSpiInterface(Selector.get(Selector.MEM_SELECTOR))
else:
raise ValueError('illegal spi mode : ' + spi_mode)
@@ -306,8 +299,6 @@ class DataServer(SocketServer, DataAPI):
return self._spi_mode
def available_channel(self, reset=False) -> List[int]:
print('!!!!!!!!!!!!!!')
print()
if reset:
self.reset_available_channel()
@@ -515,8 +506,6 @@ class DataServer(SocketServer, DataAPI):
# start sync
for runtime in r:
if runtime is not None and not runtime.sync_started:
# if isinstance(runtime, DeviceDataRuntime):
# self.spi_flush(runtime.device)
# if client is not None:
# client.drop_data(runtime.device)
@@ -566,28 +555,11 @@ class DataServer(SocketServer, DataAPI):
# self.spi_reset_ram_header(c._device)
self._spi.set_wait_flag(c._device, True)
self._configurations[d] = None
del self._configurations[d]
self.log_info('stop_sync', c._device)
self.mqtt_thread.broadcast_command('stop:' + str(c._device))
# r.append(c)
# stop sync
# for runtime in r:
# if runtime is not None and runtime.sync_started:
# self.log_info('stop_sync', runtime.device)
# self.mqtt_thread.broadcast_command('stop:' + str(runtime.device))
# try:
# runtime.shutdown()
# except:
# print_exception(self)
# # finally:
# # # self.spi_flush(runtime.device)
# # if _FLAG_DATA_LOST_STATS_:
# # if isinstance(runtime, DeviceDataRuntime):
# # runtime.log_data_receive_statistics(self)
# # runtime.shutdown()
# stop runtime, none device working
if not self.sync_started:
@@ -667,52 +639,40 @@ class DataServer(SocketServer, DataAPI):
client.clear()
client.close_socket()
def recv_data_form_spi(self) -> bool:
"""
"""
current_time = time()
def get_spi_obj(self):
return self._spi
def whether_to_record(self, device):
# if user click "start", return True; if user click "stop", return False;
if device in self._configurations.keys() and self._configurations[device] is not None:
return True
else:
return False
def recv_data_form_spi_new(self, device) -> bool:
ret = False
sync = self.get_spi_obj()
devicelist = self._configurations.keys()
if sync.get_pin_mem_req() == sync.get_pin_ram_sel():
spi_data = sync.recv_memory(device)
signal = sync.get_pin_mem_req()
sync.set_pin_mem_req(not signal)
data = spi_data
devicelist = [4, 5, 7, 6]
else:
data = None
for c in devicelist:
sync = self._spi
sync.select = c
if data is not None:
if self._configurations[device].queue_flag:
self._configurations[device].queue_flag = False
print("q size= ", self._configurations[device]._queue_rec.qsize())
# delay 120us ~ 270us
count = 0
for i in range(300):
count = count + 1
if c in self._configurations.keys() and self._configurations[c] is not None:
data = self.spi_recv(c)
if time() - current_time > 0.1:
print('time, spi_recv', current_time, time() - current_time)
current_time = time()
if data is not None:
try:
if self._configurations[c].queue_flag:
self._configurations[c].queue_flag = False
print("q size= ", self._configurations[c]._queue_rec.qsize())
self._configurations[c].put_rec_queue(data)
if time() - current_time > 0.05:
print('time, queue', current_time, time() - current_time)
current_time = time()
# print('done put queue')
except:
return
else:
ret = True
# else:
# print('****1')
self._configurations[device].put_rec_queue(data)
ret = True
return ret
def rec_update(self) -> bool:
device_id = self._queue_db_error.get()
@@ -726,165 +686,6 @@ class DataServer(SocketServer, DataAPI):
return True
def recv_data_foreach_runtime(self, device_id: int) -> bool:
# """foreach data runtime to receive data. called by :class:`DataRuntimeThread`.
# :return: has runtime received data
# """
# q = None
# data = None
# try:
# q = self._queue_spi_dict[device_id].get()
# except:
# return False
# ret = False
# if self._queue_spi_dict[device_id].qsize() > 10:
# print('qsize: ', device_id, self._queue_spi_dict[device_id].qsize())
# for c in self._configurations:
# if self._configurations[c] is not None and self._configurations[c].sync_started:
# if self._configurations[c]._device == device_id:
# try:
# data = self._configurations[c].sync_data(q)
# except EODInterrupt:
# self._configurations[c].sync_started = False
# except:
# # catch any error and ignore it
# print_exception(self)
# self._configurations[c].sync_started = False
# else:
# if data is not None and len(data) > 0:
# ret = True
# # if self._configurations[c].sync_file_request:
# # self._configurations[c].sync_file()
# # for c in self._configurations:
# # # print('_configurations', c)
# # if c is not None and c.sync_started:
# # if q[0] == c._device:
# # try:
# # # print('c.time', c._prev_data, c._prev_time_stamp, c._prev_delta_time)
# # # c._timer_of_not_send = int(time())
# # data = c.sync_data(q[1])
# # except EODInterrupt:
# # c.sync_started = False
# # except:
# # # catch any error and ignore it
# # print_exception(self)
# # c.sync_started = False
# # else:
# # if data is not None and len(data) > 0:
# # ret = True
# # if c.sync_file_request:
# # c.sync_file()
# del q
# del data
return
def spi_flush(self, device: int):
"""clean spi buffer"""
if self._spi is not None:
self._spi.select = device
self._spi.flush()
return
def spi_reset_ram_header(self, device: int):
if self._spi is not None:
self._spi.select = device
self._spi.request_data()
sleep(0.01)
self._spi.reset()
self._spi.flush()
return
def spi_send(self, device: int, address: int, data: bytes):
sync = self._spi
if sync is None:
return
sync.select = device
sync.write_memory(address, data)
return
def spi_recv(self, device: int) -> Optional[bytes]:
sync = self._spi
if sync is None:
return None
if self._is_usb_port(device):
# if self._is_demo_usb_port(device):
# self._usb will be a list when suporting multi usb device
sync = self._usb
if sync is None:
return None
data = sync.recv_memory()
if data is None:
return None
data_length = len(data) + 1
header = 0xFF
data_counter = 0x00
data_header = [header, data_counter, data_length, device]
data_header.extend(data)
return bytes(data_header)
else:
sync = self._spi
if sync is None:
return None
# sync.select = device
# sleep(0.003)
if sync.changed(flip=True):
spi_data = sync.recv_memory(device)
return spi_data
# if sync.get_wait_flag(device) is False:
# return spi_data
# else:
# sync.set_wait_flag(device, False)
# print("discard first data")
# return None
# return sync.recv_memory()
else:
sync.request_data()
return None
def _is_usb_port(self, device: int) -> bool:
max_spi_port_number = 8
if device >= max_spi_port_number:
return True
else:
return False
sync.select = device
if sync.changed(flip=True):
# print('recv_memory~~~')
return sync.recv_memory()
else:
# print('request_data___')
return sync.request_data()
class DataRuntime(metaclass=abc.ABCMeta):
__slots__ = ('_server', '_device', '_meta_file', '_data_format',
'_sync_started', 'sync_file_request', '_writer')
@@ -1332,12 +1133,6 @@ class DataRuntimeThread(ServerThread):
return True
def routine(self, event = None) -> None:
# start = time()
# ret = self._server.recv_data_foreach_runtime(self._device_id)
# self._counter += 1
# if self._counter > 10000:
# gc.collect()
# self._counter = 0
del ret
return
@@ -1350,8 +1145,9 @@ class SpiRuntimeThread(ServerThread):
# routine period control
self._start_time = 0.0
self._time_stamp = 0.0
self._interval = 0.15
self._interval = 0.045
self._timer = time()
self._read_memory_board_idx = 0
def setup(self) -> None:
super().setup()
@@ -1364,27 +1160,40 @@ class SpiRuntimeThread(ServerThread):
# self._server.close_cache_client()
return True
def routine(self, event = None) -> None:
def routine(self, event = None) -> None: # routine 50 ms
server = self._server
self._timer = time()
ret = server.recv_data_form_spi()
sync = server.get_spi_obj()
# select channel
devicelist = [4, 5, 7, 6]
c = devicelist[self._read_memory_board_idx]
sync.select = c
if server.whether_to_record(c):
sync.set_pin_mem_sel(False)
ret = server.recv_data_form_spi_new(c) # read ram & put data into queue, if has data, ret = true
self._read_memory_board_idx = 0 if self._read_memory_board_idx == 3 else self._read_memory_board_idx + 1
run_time = time() - self._timer
if run_time > self._interval:
print('time, recv_data_form_spi_routine_time', time(), run_time)
if run_time > 0.15:
run_time = 0.15
if run_time > 0.045:
print('time, recv_data_form_spi_routine_time', time(), run_time)
run_time = 0.045
if server.sync_started:
event.wait((self._interval - run_time))
event.wait(self._interval - run_time)
sync.set_pin_mem_sel(True)
sleep(0.005)
return
else:
event.wait(self._interval - run_time)
sync.set_pin_mem_sel(True)
self.close()
return
self._start_time = time()
return
class RecRuntimeThread(ServerThread):
def __init__(self, server: DataServer):
super().__init__('RecRunTime', MAGENTA)
+16 -43
View File
@@ -84,9 +84,7 @@ class ControlServer(SocketServer, ControlServerAPI, CacheAPI, CacheNotifyHandler
# data server
data_options = DataServerOptions.get_options(*options)
data_options.repository = device_option.repository
print('self.data_server')
self.data_server = DataServerProcess(data_options)
print('self.data_server')
# experimental protocol
# exp_options = ExpManagerOption.get_options(*options)
@@ -200,8 +198,6 @@ class ControlServer(SocketServer, ControlServerAPI, CacheAPI, CacheNotifyHandler
def setup(self) -> None:
"""setup the control server
"""
print('ControlServer: setup')
print()
# print allow host
from biopro.util.inet import allow_host
@@ -217,11 +213,10 @@ class ControlServer(SocketServer, ControlServerAPI, CacheAPI, CacheNotifyHandler
self.led_thread.set_state(LED.POWER_ON)
# sha checking
if _RUNTIME_COMPILE or not self._controller_options.flag_disable_sha_check:
self.run_thread(_RandomCrashThread())
# if _RUNTIME_COMPILE or not self._controller_options.flag_disable_sha_check:
# self.run_thread(_RandomCrashThread())
# data server
print('start_process')
interface = self.device_manager.interface
options = self.data_server.options
if interface == DeviceHardwareInterface.INTERFACE_DUMMY:
@@ -232,7 +227,6 @@ class ControlServer(SocketServer, ControlServerAPI, CacheAPI, CacheNotifyHandler
options.storage_root = str(self.file_manager.storage_root)
self.data_server.start_process()
print('start_process___')
# file manager
self.log_verbose('setup file manager')
@@ -242,9 +236,7 @@ class ControlServer(SocketServer, ControlServerAPI, CacheAPI, CacheNotifyHandler
# device manager
self.log_verbose('setup device manager')
print('self.device_manager.setup()')
self.device_manager.setup()
print('self.device_manager.setup()____')
self.submit_thread(self._setup_library)
# device manager reset
@@ -277,9 +269,6 @@ class ControlServer(SocketServer, ControlServerAPI, CacheAPI, CacheNotifyHandler
self.mqtt_thread.start()
# self.run_thread(self.mqtt_thread)
print('ControlServer: setup______end')
print()
def _setup_file_manager(self):
self.log_verbose('setup file manager')
@@ -318,13 +307,19 @@ class ControlServer(SocketServer, ControlServerAPI, CacheAPI, CacheNotifyHandler
if len(controller) == 0:
ControllerAPI.create(hardware_info)
elif len(controller) > 0:
if hardware_info['mac_address'] != controller[0]['mac_address'] or hardware_info['software_version'] != controller[0]['software_version'] or hardware_info['mqtt_id'] != controller[0]['mqtt_id']:
ControllerAPI.updateByAttrs('mac_address', hardware_info['mac_address'], {'software_version': hardware_info['software_version'], 'mqtt_id': mqtt_id })
if hardware_info['mac_address'] != controller[0]['mac_address'] or hardware_info['software_version'] != controller[0]['software_version'] or hardware_info['mqtt_id'] != controller[0]['mqtt_id'] or hardware_info['wifi_name'] != controller[0]['wifi_name']:
ControllerAPI.updateByAttrs (
'mac_address', hardware_info['mac_address'], {
'software_version': hardware_info['software_version'],
'mqtt_id': mqtt_id,
'name': hardware_info['name'],
'wifi_name': hardware_info['wifi_name']
}
)
def _setup_device(self):
# wait data server
print('resettt---------30')
print()
self.log_verbose('device hardware reset')
self.device_manager.reset(software_reset=False)
@@ -340,7 +335,7 @@ class ControlServer(SocketServer, ControlServerAPI, CacheAPI, CacheNotifyHandler
if available_channel is None:
self.device_manager.setup(DeviceHardwareInterface.INTERFACE_DUMMY)
else:
self._setup_device_manager(available_channel)
self.broadcast_command('state:device_available')
except ServerShutdownException as e:
self.interrupt(e)
@@ -374,8 +369,6 @@ class ControlServer(SocketServer, ControlServerAPI, CacheAPI, CacheNotifyHandler
while retry < 10:
try:
with client:
print('resettt---------31')
print()
client.reset()
break
except RuntimeError:
@@ -414,26 +407,6 @@ class ControlServer(SocketServer, ControlServerAPI, CacheAPI, CacheNotifyHandler
self.log_verbose('available channel', available_channel)
return available_channel
def _setup_device_manager(self, available_channel: List[int]):
# device reset
# only reset those device has channel available
print('resettt---------33')
print()
self.log_verbose('reset device')
self.device_manager.reset(available_channel)
# device checking
available_device = self.device_manager.available_device()
self.log_verbose('available device', available_device)
self.broadcast_command('state:device_available')
if len(available_device) == 0:
raise RuntimeError('empty device')
elif available_device != available_channel:
raise RuntimeError('device/channel mismatch')
def _setup_restart_device_manager(self, interface: str):
self.log_info('shutdown device manager')
self.device_manager.shutdown()
@@ -672,9 +645,9 @@ class ControlServer(SocketServer, ControlServerAPI, CacheAPI, CacheNotifyHandler
if self.device_manager.scan_callback(callback, timeout=self._scan_max_timeout, all_device=True):
self.broadcast_command(DataMessage.scan('done'))
if device_not_found:
# no device found, longer the max scan time
self._scan_max_timeout = min(10, self._scan_max_timeout + 2)
# if device_not_found:
# # no device found, longer the max scan time
# self._scan_max_timeout = min(10, self._scan_max_timeout + 2)
@logging_info
def hardware_device(self) -> List[DeviceResponseInfo]:
-1
View File
@@ -121,7 +121,6 @@ class ControllerProcess(LoggerFlag, Generic[PO, PC], metaclass=abc.ABCMeta):
cmd = current_command_header()
cmd.extend(arg)
print('cmd', cmd, env)
self.__process = process = Popen(cmd, env=env)
self.log_info('process PID :', process.pid)
+43 -10
View File
@@ -324,19 +324,52 @@ class RecordingProcess(Process):
if (save == False):
self._wrong_cnt += 1
print('jump cnt', self._wrong_cnt, 'times', datetime.now())
print('jump cnt', self._wrong_cnt, 'times, device:', device, ',', datetime.now())
return save
def _check_jump_ram(self, raw_data: bytes, colum_now: int, colum_total: int, save: bool, device: int):
i = colum_now
if (raw_data[i][0] == 255 and raw_data[i][3] == device):
if (i <= colum_total - 3):
if(raw_data[i + 1][1] - raw_data[i][1] == 1 and raw_data[i + 2][1] - raw_data[i + 1][1] == 1):
if colum_total < 3:
print('this ram data < 3 records, need to fix, colum_total = ', colum_total)
if colum_total == 1:
print('raw_data[0]', raw_data[0])
elif colum_total == 2:
print('raw_data[0]', raw_data[0])
print('raw_data[1]', raw_data[1])
else:
if((raw_data[i + 1][1] - raw_data[i][1] == 1 and raw_data[i + 2][1] - raw_data[i + 1][1] == 1) or
(raw_data[i][1] == 255 and raw_data[i + 1][1] == 0 and raw_data[i + 2][1] == 1) or
(raw_data[i][1] == 254 and raw_data[i + 1][1] == 255 and raw_data[i + 2][1] == 0)):
if ((raw_data[i][1] == 255 and raw_data[i + 1][1] == 0 and raw_data[i + 2][1] == 1) or
(raw_data[i][1] == 254 and raw_data[i + 1][1] == 255 and raw_data[i + 2][1] == 0)):
print('cnt = [254, 255, 0] or [255, 0, 1]')
save = True
self._skip_ram_cnt += 1
last_data_cnt = raw_data[i][1]
print('skip RAM, but data is right, solve data', list(raw_data[i]), 'skip Ram', self._skip_ram_cnt, 'times')
if (device == 4):
print('self._last_cnt[4]:', self._last_cnt[4], ', last_data_cnt:', last_data_cnt)
if (device == 5):
print('self._last_cnt[5]:', self._last_cnt[5], ', last_data_cnt:', last_data_cnt)
if (device == 6):
print('self._last_cnt[6]:', self._last_cnt[6], ', last_data_cnt:', last_data_cnt)
if (device == 7):
print('self._last_cnt[7]:', self._last_cnt[7], ', last_data_cnt:', last_data_cnt)
print('skip RAM, but data is right, solve data', list(raw_data[i][0:3]), 'skip Ram', self._skip_ram_cnt, 'times')
# print('data:')
# print('|', list(raw_data[0]))
# print('|', list(raw_data[1]))
# print('| ... ... ...')
# print('| ... ... ...')
# print('|', list(raw_data[colum_total-1]))
print()
if (device == 4):
@@ -465,7 +498,7 @@ class RecordingProcess(Process):
"""
raw_data = []
index = 0
elite_data_len = 120
elite_data_len = 40
mem_header_len = 3
mem_tailer_len = 8
single_data_len = elite_data_len + mem_header_len + mem_tailer_len
@@ -509,11 +542,11 @@ class RecordingProcess(Process):
print_flag = True
print('delete data:', list(raw_data[i]))
if print_flag:
print('delete data context:')
for i in range(0, len(data), single_data_len):
print(list(data[i:i+single_data_len]))
print()
# if print_flag:
# print('delete data context:')
# for i in range(0, len(data), single_data_len):
# print(list(data[i:i+single_data_len]))
# print()
return
+2 -11
View File
@@ -621,20 +621,16 @@ class CliMain(AbstractCliMain, metaclass=abc.ABCMeta):
self.__cli_help_document[handle] = _resolve_doc(handle.help_doc)
def main(self, argv: List[str] = None):
print('main', argv)
if argv is None:
print('Main None', sys.argv[1:])
argv = sys.argv[1:]
try:
argv = self.parsing(argv)
print('1', argv)
if argv is None:
self.run()
else:
command, *argv = argv
print('2', command, argv)
self.invoke_subcommand(command, argv)
@@ -658,7 +654,6 @@ class CliMain(AbstractCliMain, metaclass=abc.ABCMeta):
while i < len(argv):
arg = argv[i]
print('arg', i, arg)
if not left_all and arg.startswith('-'):
@@ -681,7 +676,6 @@ class CliMain(AbstractCliMain, metaclass=abc.ABCMeta):
else:
# sub command
print('self._cli_commands', self._cli_commands)
if parsing_sub_command and j == 0:
if arg in self._cli_commands:
return argv[i:]
@@ -717,7 +711,7 @@ class CliMain(AbstractCliMain, metaclass=abc.ABCMeta):
# handle not found
return False
print('_handle_flags_', arg)
# print('_handle_flags_', arg)
handle.invoke(arg)
if handle.force_return:
@@ -734,7 +728,6 @@ class CliMain(AbstractCliMain, metaclass=abc.ABCMeta):
:return: number of arguments consumed, 0 if fail.
"""
arg, value = part_suffix(arg, '=')
print('_handle_options_', arg, value)
handle = self._cli_options.get(arg, None)
@@ -768,7 +761,6 @@ class CliMain(AbstractCliMain, metaclass=abc.ABCMeta):
:return: None if fail, true if left all.
"""
a = self._cli_arguments
print('cli_argument', arg, pos, a)
handle = a.get(pos, None)
if handle is None and pos == 0:
@@ -825,11 +817,10 @@ class CliMain(AbstractCliMain, metaclass=abc.ABCMeta):
:return:
"""
handle = self._cli_commands.get(command, None)
print('handle', handle)
if handle is None:
raise RuntimeError('sub-command not found : ' + command)
return handle.invoke(command, argv)
def print_help(self, print_usage=True, file: Optional[IO] = None) -> None:
-2
View File
@@ -529,7 +529,6 @@ class CliHandleCommand(CliHandle):
"""
try:
main = self.handle(self._target, command, argv)
print('3', main, self._target, command, argv)
except (MainForceReturn, SystemExit, KeyboardInterrupt):
raise
@@ -547,7 +546,6 @@ class CliHandleCommand(CliHandle):
elif isinstance(main, type):
# initialize CliSubCommandMain
main = main(command)
print('4', main)
if not isinstance(main, AbstractCliMain):
raise RuntimeError('not a CliSubCommandMain : ' + type(main).__class__)
-2
View File
@@ -64,10 +64,8 @@ class ProfileOptions(CliOptions):
self.profiling_sorting = fields
def generate_profile_context(self) -> 'ProfileContext':
print('self.profiling_method:', self.profiling_method)
if self.profiling_method is None:
ret = _NullProfileContext(self)
print('ret=', ret)
else:
try:
+3 -3
View File
@@ -67,7 +67,7 @@
"FREQ_STOP": {
"description": "End of Freq Scan",
"record_meta": true,
"initial": 1,
"initial": 7,
"domain": [
"FREQ_MAX"
],
@@ -100,9 +100,9 @@
"DC_BIAS": {
"description": "DC voltage bias in mV",
"record_meta": true,
"initial": 0,
"initial": 15000,
"domain": [
4096
35001
],
"value": {
"expression": "VALUE"