########################################################################### # # Copyright (c) 2020-2024 Diality Inc. - All Rights Reserved. # # THIS CODE MAY NOT BE COPIED OR REPRODUCED IN ANY FORM, IN PART OR IN # WHOLE, WITHOUT THE EXPLICIT PERMISSION OF THE COPYRIGHT OWNER. # # @file treatment_delivery.py # # @author (last) Dara Navaei # @date (last) 26-Feb-2024 # @author (original) Peter Lucia # @date (original) 02-Apr-2020 # ############################################################################ import struct from .modules.alarms import DDAlarms from .modules.balancing_chamber import DDBalancingChamber from .modules.concentrate_pump import DDConcentratePumps from .modules.conductivity_sensors import DDConductivitySensors from .modules.constants import NO_RESET, RESET from .modules.dialysate_pump import DDDialysatePumps from .modules.gen_dialysate import DDGenDialysate from .modules.heaters import DDHeaters from .modules.levels import DDLevels from .modules.piston_pump import DDPistonPumps from .modules.post_gen_dialysate import DDPostGenDialysate from .modules.pressure_sensors import DDPressureSensors from .modules.pre_gen_dialysate import DDPreGenDialysate from .modules.temperature_sensors import DDTemperatureSensors from .modules.ultrafiltration import DDUltrafiltration from .modules.valves import DDValves from .proxies.ro_proxy import ROProxy from .proxies.td_proxy import TDProxy from ..common.msg_defs import MsgIds, MsgFieldPositions, MsgFieldPositionsFWVersions from ..common.dd_defs import DDOpModes from ..protocols.CAN import DenaliMessage, DenaliCanMessenger, DenaliChannels from ..utils.base import AbstractSubSystem, publish, LogManager from ..utils.checks import check_broadcast_interval_override_ms from ..utils.conversions import integer_to_bytearray, unsigned_short_to_bytearray, bytearray_to_integer, \ bytearray_to_byte class DD(AbstractSubSystem): """ Treatment Delivery (DD) Dialin object API. It provides the basic interface to communicate with the DD firmware. """ # DD debug event max count _DD_DEBUG_EVENT_LIST_COUNT = 10 _DD_DEBUG_EVENT_MSG_LEN_INDEX = 5 # DD login password DD_LOGIN_PASSWORD = '123' def __init__(self, can_interface="can0", log_level=None): """ DD object provides test/service commands for the DD sub-system. >> DD_object = DD('can0') >> DD_object = DD(can_interface='can0', log_level="DEBUG") Possible log levels: ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL", "CAN_ONLY", "PRINT_ONLY"] @param can_interface: (str) CANBus interface name, e.g. "can0" @param log_level: (str) Logging level, defaults to None """ super().__init__() self._log_manager = LogManager(log_level=log_level, log_filepath=self.__class__.__name__ + ".log") self.logger = self._log_manager.logger # Create listener self.can_interface = DenaliCanMessenger(can_interface=can_interface, logger=self.logger) self.can_interface.start() self.callback_id = None # register handler for DD operation mode broadcast messages if self.can_interface is not None: channel_id = DenaliChannels.dd_sync_broadcast_ch_id msg_id = MsgIds.MSG_ID_DD_OP_MODE_DATA.value self.can_interface.register_receiving_publication_function(channel_id, msg_id, self._handler_dd_op_mode_sync) self.can_interface.register_receiving_publication_function(channel_id, MsgIds.MSG_ID_DD_VERSION_RESPONSE.value, self._handler_dd_version_response_sync) self.can_interface.register_receiving_publication_function(channel_id, MsgIds.MSG_ID_DD_DEBUG_EVENT.value, self._handler_dd_debug_event_sync) # create properties self.dd_op_mode_timestamp = 0.0 self.dd_debug_events_timestamp = 0.0 self.dd_version_response_timestamp = 0.0 self.dd_operation_mode = DDOpModes.MODE_INIT.value self.dd_operation_sub_mode = 0 self.dd_logged_in = False self.dd_set_logged_in_status(False) self.dd_debug_events = [''] * self._DD_DEBUG_EVENT_LIST_COUNT self.dd_debug_event_index = 0 self.dd_last_debug_event = '' # Create command groups self.alarms = DDAlarms(self.can_interface, self.logger) self.balancing_chamber = DDBalancingChamber(self.can_interface, self.logger) self.concentrate_pumps = DDConcentratePumps(self.can_interface, self.logger) self.conductivity_sensors = DDConductivitySensors(self.can_interface, self.logger) self.dialysate_pumps = DDDialysatePumps(self.can_interface, self.logger) self.gen_dialysate = DDGenDialysate(self.can_interface, self.logger) self.heaters = DDHeaters(self.can_interface, self.logger) self.levels = DDLevels(self.can_interface, self.logger) self.piston_pumps = DDPistonPumps(self.can_interface, self.logger) self.post_gen_dialysate = DDPostGenDialysate(self.can_interface, self.logger) self.pressure_sensors = DDPressureSensors(self.can_interface, self.logger) self.pre_gen_dialysate = DDPreGenDialysate(self.can_interface, self.logger) self.temperature_sensors = DDTemperatureSensors(self.can_interface, self.logger) self.ultrafiltration = DDUltrafiltration(self.can_interface, self.logger) self.valves = DDValves(self.can_interface, self.logger) self.ro_proxy = ROProxy(self.can_interface, self.logger) self.td_proxy = TDProxy(self.can_interface, self.logger) @publish(["dd_debug_events_timestamp","dd_debug_events"]) def _handler_dd_debug_event_sync(self, message, timestamp = 0.0): payload = message['message'] message_length = payload[self._DD_DEBUG_EVENT_MSG_LEN_INDEX] temp_message = '' index = MsgFieldPositions.START_POS_FIELD_1 for i in range(0, message_length): # Loop through the length and get the char, char_index = bytearray_to_byte(payload, index + i, False) temp_message += chr(char) self.dd_debug_events_timestamp = timestamp self.dd_debug_events.insert(self.dd_debug_event_index, temp_message) self.dd_last_debug_event = temp_message self.dd_debug_event_index += 1 if self.dd_debug_event_index == self._DD_DEBUG_EVENT_LIST_COUNT: self.dd_debug_event_index = 0 @publish(["dd_logged_in"]) def dd_set_logged_in_status(self, logged_in: bool = False): """ Callback for dd logged in status change. @param logged_in boolean logged in status for DD @return: none """ self.dd_logged_in = logged_in @publish(["dd_op_mode_timestamp","dd_operation_mode", "dd_operation_sub_mode"]) def _handler_dd_op_mode_sync(self, message, timestamp = 0.0): """ Handles published DD operation mode messages. Current DD operation mode is captured for reference. @param message: published DD operation mode broadcast message @return: None """ mode = struct.unpack('i', bytearray( message['message'][MsgFieldPositions.START_POS_FIELD_1:MsgFieldPositions.END_POS_FIELD_1])) smode = struct.unpack('i', bytearray( message['message'][MsgFieldPositions.START_POS_FIELD_2:MsgFieldPositions.END_POS_FIELD_2])) self.dd_operation_mode = mode[0] self.dd_operation_sub_mode = smode[0] self.dd_op_mode_timestamp = timestamp @publish(["dd_version, dd_fpga_version"]) def _handler_dd_version_response_sync(self,message, timestamp = 0.0): """ Handler for response from DD regarding its version. @param message: version response message from DD.\n @return: None if not successful, the version string if unpacked successfully """ major = struct.unpack(' 0 for each in [major, minor, micro, build, compatibility]]): self.dd_version = f"v{major[0]}.{minor[0]}.{micro[0]}-{build[0]}.{compatibility[0]}" self.logger.debug(f"DD VERSION: {self.dd_version}") if all([len(each) > 0 for each in [fpga_id, fpga_major, fpga_minor, fpga_lab]]): self.dd_fpga_version = f"v{fpga_id[0]}.{fpga_major[0]}.{fpga_minor[0]}-{fpga_lab[0]}" self.logger.debug(f"DD FPGA VERSION: {self.dd_fpga_version}") self.dd_version_response_timestamp = timestamp def cmd_log_in_to_dd(self, resend: bool = False) -> int: """ Constructs and sends a login command via CAN bus. Login required before \n other commands can be sent to the DD. @param resend: (bool) if False (default), try to login once. Otherwise, tries to login indefinitely @return: 1 if logged in, 0 if log in failed """ message = DenaliMessage.build_message(channel_id=DenaliChannels.dialin_to_dd_ch_id, message_id=MsgIds.MSG_ID_DD_TESTER_LOGIN_REQUEST.value, payload=list(map(int, map(ord, self.DD_LOGIN_PASSWORD)))) self.logger.debug("Logging in...") # Send message received_message = self.can_interface.send(message, resend=resend) if received_message is not None: if received_message['message'][DenaliMessage.PAYLOAD_START_INDEX] == 1: self.logger.debug("Success: Logged In") self.dd_set_logged_in_status(True) #self._send_dd_checkin_message() # Timer starts interval first #self.can_interface.transmit_interval_dictionary[self.callback_id].start() else: self.logger.debug("Failure: Log In Failed.") return received_message['message'][DenaliMessage.PAYLOAD_START_INDEX] else: self.logger.debug("Login Timeout!!!!") return False def cmd_dd_set_operation_mode(self, new_mode: int = 0) -> int: """ Constructs and sends a set operation mode request command via CAN bus. Constraints: Must be logged into DD. Transition from current to requested op mode must be legal. NOTE: for POST the DD device shall be in Standby Mode @param new_mode: ID of operation mode to transition to @return: 1 if successful, zero otherwise """ payload = integer_to_bytearray(new_mode) message = DenaliMessage.build_message(channel_id=DenaliChannels.dialin_to_dd_ch_id, message_id=MsgIds.MSG_ID_DD_SET_OPERATION_MODE_OVERRIDE_REQUEST.value, payload=payload) self.logger.debug("Requesting DD mode change to " + str(new_mode)) # Send message received_message = self.can_interface.send(message) if received_message is not None: if received_message['message'][DenaliMessage.PAYLOAD_START_INDEX] == 1: self.logger.debug("Success: Mode change accepted") else: self.logger.debug("Failure: Mode change rejected.") return received_message['message'][DenaliMessage.PAYLOAD_START_INDEX] else: self.logger.debug("DD mode change request Timeout!!!!") return False def cmd_dd_software_reset_request(self) -> None: """ Constructs and sends an DD software reset request via CAN bus. Constraints: Must be logged into DD. @return: None """ message = DenaliMessage.build_message(channel_id=DenaliChannels.dialin_to_dd_ch_id, message_id=MsgIds.MSG_ID_DD_SOFTWARE_RESET_REQUEST.value) self.logger.debug("requesting DD software reset") # Send message self.can_interface.send(message, 0) self.logger.debug("Sent request to DD to reset...") self.dd_set_logged_in_status(False) def cmd_dd_safety_shutdown_override(self, active: int, reset: int = NO_RESET) -> int: """ Constructs and sends an DD safety shutdown override command via CAN bus. Constraints: Must be logged into DD. @param active: int - True to activate safety shutdown, False to deactivate @param reset: integer - 1 to reset a previous override, 0 to override @return: 1 if successful, zero otherwise """ rst = integer_to_bytearray(reset) saf = integer_to_bytearray(active) payload = rst + saf message = DenaliMessage.build_message(channel_id=DenaliChannels.dialin_to_dd_ch_id, message_id=MsgIds.MSG_ID_DD_SAFETY_SHUTDOWN_OVERRIDE_REQUEST.value, payload=payload) self.logger.debug("overriding FP safety shutdown") # Send message received_message = self.can_interface.send(message) if received_message is not None: if received_message['message'][DenaliMessage.PAYLOAD_START_INDEX] == 1: self.logger.debug("Safety shutdown signal overridden") else: self.logger.debug("Safety shutdown signal override failed.") return received_message['message'][DenaliMessage.PAYLOAD_START_INDEX] else: self.logger.debug("Timeout!!!!") return False