########################################################################### # # 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 valves.py # # @author (last) Micahel Garthwaite # @date (last) 17-Aug-2023 # @author (original) Peman Montazemi # @date (original) 19-May-2020 # ############################################################################ import struct from enum import unique from logging import Logger from collections import OrderedDict from .constants import NO_RESET from leahi_dialin.common.msg_defs import MsgIds from leahi_dialin.protocols.CAN import DenaliMessage, DenaliChannels from leahi_dialin.utils.base import AbstractSubSystem, publish, DialinEnum from leahi_dialin.utils.checks import check_broadcast_interval_override_ms from leahi_dialin.utils.conversions import integer_to_bytearray # Valve states ENERGIZED = True DEENERGIZED = False @unique class DDValveStates(DialinEnum): VALVE_STATE_CLOSED = 0 VALVE_STATE_OPEN = 1 @unique class DDValveNames(DialinEnum): VHO = 0 # Valve Hydraulics Outlet (D14) VTD = 1 # Valve Thermal Disinfect (D52) VHB = 2 # Valve Hydraulics Bypass (D8) VRP = 3 # Valve Rinse Port (D54) VDR = 4 # Valve Drain (D53) VDB2 = 5 # Valve DryBcarb Inlet (D65) VP1 = 6 # Valve Purge 1 (D64) VPT = 7 # Valve Pressure Test (D31) VDB1 = 8 # Valve Dialyzer Bypass (D34) VDI = 9 # Valve Dialyzer Inlet (D35) VDO = 10 # Valve Dialyzer Outlet (D40) VP2 = 11 # Valve Dialysate Out Purge 2 (D47) VHI = 12 # Valve Hydraulics Inlet (D3) VWI = 13 # Valve Water Inlet (M4) RSRVD_SPACE1 = 14 # This space has been reserved RSRVD_SPACE2 = 15 # This space has been reserved BCV1 = 16 # Balancing chamber Valve 1 (D23) BCV2 = 17 # Balancing chamber Valve 2 (D19) BCV3 = 18 # Balancing chamber Valve 3 (D25) BCV4 = 19 # Balancing chamber Valve 4 (D21) BCV5 = 20 # Balancing chamber Valve 5 (D24) BCV6 = 21 # Balancing chamber Valve 6 (D20) BCV7 = 22 # Balancing chamber Valve 7 (D26) BCV8 = 23 # Balancing chamber Valve 8 (D22) UFI1 = 24 # Ultrafiltration Valve 1 Inlet (D69) UFI2 = 25 # Ultrafiltration Valve 2 Inlet (D71) UFO1 = 26 # Ultrafiltration Valve 1 Outlet (D70) UFO2 = 27 # Ultrafiltration Valve 2 Outlet (D72) class DDValves(AbstractSubSystem): """ Dialysate Delivery (DG) interface for valve related commands. """ # Valves states publish message field positions START_POS_VALVES_STATES = DenaliMessage.PAYLOAD_START_INDEX END_POS_VALVES_STATES = START_POS_VALVES_STATES + 2 # Valves States come in as a U16 value (2 bytes) START_POS_BCV_VALVES_STATES = END_POS_VALVES_STATES END_POS_BCV_VALVES_STATES = START_POS_BCV_VALVES_STATES + 1 START_POS_UFI_VALVES_STATES = END_POS_BCV_VALVES_STATES END_POS_UFI_VALVES_STATES = START_POS_UFI_VALVES_STATES + 1 END_POS_ALL_VALVES = START_POS_VALVES_STATES + 4 def __init__(self, can_interface, logger: Logger): """ @param can_interface: Denali CAN Messenger object """ super().__init__() self.can_interface = can_interface self.logger = logger self.valves_sensed_states = OrderedDict() self.dg_valves_states_timestamp = 0.0 if self.can_interface is not None: channel_id = DenaliChannels.dd_sync_broadcast_ch_id msg_id = MsgIds.MSG_ID_DD_VALVES_STATES_DATA.value self.can_interface.register_receiving_publication_function(channel_id, msg_id, self._handler_valves_sync) self.valve_states_all = 0x00000000 self.valve_state_VDR = {"id": DDValveNames.VDR.value, "state": DEENERGIZED} self.valve_state_VTD = {"id": DDValveNames.VTD.value, "state": DEENERGIZED} self.valve_state_VHB = {"id": DDValveNames.VHB.value, "state": DEENERGIZED} self.valve_state_VRP = {"id": DDValveNames.VRP.value, "state": DEENERGIZED} self.valve_state_VHO = {"id": DDValveNames.VHO.value, "state": DEENERGIZED} self.valve_state_VDB1 = {"id": DDValveNames.VDB1.value, "state": DEENERGIZED} self.valve_state_VP1 = {"id": DDValveNames.VP1.value, "state": DEENERGIZED} self.valve_state_VPT = {"id": DDValveNames.VPT.value, "state": DEENERGIZED} self.valve_state_VDB2 = {"id": DDValveNames.VDB2.value, "state": DEENERGIZED} self.valve_state_VDI = {"id": DDValveNames.VDI.value, "state": DEENERGIZED} self.valve_state_VDO = {"id": DDValveNames.VDO.value, "state": DEENERGIZED} self.valve_state_VP2 = {"id": DDValveNames.VP2.value, "state": DEENERGIZED} self.valve_state_VHI = {"id": DDValveNames.VHI.value, "state": DEENERGIZED} self.valve_state_VWI = {"id": DDValveNames.VWI.value, "state": DEENERGIZED} self.valve_state_rsvrd1 = {"id": DDValveNames.RSRVD_SPACE1.value, "state": DEENERGIZED} self.valve_state_rsvrd2 = {"id": DDValveNames.RSRVD_SPACE2.value, "state": DEENERGIZED} self.valve_state_BCV1 = {"id": DDValveNames.BCV1.value, "state": DEENERGIZED} self.valve_state_BCV2 = {"id": DDValveNames.BCV2.value, "state": DEENERGIZED} self.valve_state_BCV3 = {"id": DDValveNames.BCV3.value, "state": DEENERGIZED} self.valve_state_BCV4 = {"id": DDValveNames.BCV4.value, "state": DEENERGIZED} self.valve_state_BCV5 = {"id": DDValveNames.BCV5.value, "state": DEENERGIZED} self.valve_state_BCV6 = {"id": DDValveNames.BCV6.value, "state": DEENERGIZED} self.valve_state_BCV7 = {"id": DDValveNames.BCV7.value, "state": DEENERGIZED} self.valve_state_BCV8 = {"id": DDValveNames.BCV8.value, "state": DEENERGIZED} self.valve_state_UFI1 = {"id": DDValveNames.BCV1.value, "state": DEENERGIZED} self.valve_state_UFI2 = {"id": DDValveNames.BCV1.value, "state": DEENERGIZED} self.valve_state_UFI3 = {"id": DDValveNames.BCV1.value, "state": DEENERGIZED} self.valve_state_UFI4 = {"id": DDValveNames.BCV1.value, "state": DEENERGIZED} # NOTE: The len function counts the enums with the same number only once. This is not the case in the DG valves # class because each valve must have a unique ID. self.valve_states_enum = [0 for _ in range(len(DDValveNames))] for valve in DDValveNames.__members__: self.valves_sensed_states[valve] = '' def get_valve_states(self): """ Gets the valve states @return: All valve states """ return [ self.valve_state_VDR.get("state", None), self.valve_state_VTD.get("state", None), self.valve_state_VHB.get("state", None), self.valve_state_VRP.get("state", None), self.valve_state_VHO.get("state", None), self.valve_state_VDB1.get("state", None), self.valve_state_VP1.get("state", None), self.valve_state_VPT.get("state", None), self.valve_state_VDB2.get("state", None), self.valve_state_VDI.get("state", None), self.valve_state_VDO.get("state", None), self.valve_state_VP2.get("state", None), self.valve_state_VHI.get("state", None), self.valve_state_VWI.get("state", None), self.valve_state_rsvrd1.get("state", None), self.valve_state_rsvrd2.get("state", None), self.valve_state_BCV1.get("state", None), self.valve_state_BCV2.get("state", None), self.valve_state_BCV3.get("state", None), self.valve_state_BCV4.get("state", None), self.valve_state_BCV5.get("state", None), self.valve_state_BCV6.get("state", None), self.valve_state_BCV7.get("state", None), self.valve_state_BCV8.get("state", None), self.valve_state_UFI1.get("state", None), self.valve_state_UFI2.get("state", None), self.valve_state_UFI3.get("state", None), self.valve_state_UFI4.get("state", None) ] @staticmethod def sort_by_id(observation): """ Converts a published dictionary of valve state information to an ordered list of tuples. @param observation: dictionary of the observed valve states @return: a list of tuples of the valve states """ result = [] for key, value in observation.items(): if isinstance(value, dict): result.append((key, value.get("id", None), value.get("state", None))) result = sorted(result, key=lambda each: each[1]) return result @staticmethod def _binary_to_valve_state(binary) -> bool: """ @param binary: binary value @return: 1 = energized, otherwise de-energized """ if binary != 0: return ENERGIZED else: return DEENERGIZED @publish([ "dg_valves_states_timestamp", "valve_states_all", "valve_state_VDR", "valve_state_VTD", "valve_state_VHB", "valve_state_VRP", "valve_state_VHO", "valve_state_VDB1", "valve_state_VP1", "valve_state_VPT", "valve_state_VDB2", "valve_state_VDI", "valve_state_VDO", "valve_state_VP2", "valve_state_VHI", "valve_state_VWI", "valve_state_rsvrd1", "valve_state_rsvrd2", "valve_state_BCV1", "valve_state_BCV2", "valve_state_BCV3", "valve_state_BCV4", "valve_state_BCV5", "valve_state_BCV6", "valve_state_BCV7", "valve_state_BCV8", "valve_state_UFI1", "valve_state_UFI2", "valve_state_UFI3", "valve_state_UFI4", "valve_states_enum" ]) def _handler_valves_sync(self, message, timestamp=0.0): """ Handles published valves states message. @param message: published valves states message @return: none """ vsa = struct.unpack('I', bytearray(message['message'][self.START_POS_VALVES_STATES:self.END_POS_ALL_VALVES])) self.valve_states_all = vsa[0] vst = struct.unpack('H', bytearray(message['message'][self.START_POS_VALVES_STATES:self.END_POS_VALVES_STATES])) # Extract each valve state from U16 valves states using bit-masking self.valve_state_VHO["state"] = self._binary_to_valve_state(vst[0] & 1) self.valve_state_VTD["state"] = self._binary_to_valve_state(vst[0] & 2) self.valve_state_VHB["state"] = self._binary_to_valve_state(vst[0] & 8) self.valve_state_VRP["state"] = self._binary_to_valve_state(vst[0] & 16) self.valve_state_VDR["state"] = self._binary_to_valve_state(vst[0] & 32) self.valve_state_VDB2["state"] = self._binary_to_valve_state(vst[0] & 64) self.valve_state_VP1["state"] = self._binary_to_valve_state(vst[0] & 128) self.valve_state_VPT["state"] = self._binary_to_valve_state(vst[0] & 256) self.valve_state_VDB1["state"] = self._binary_to_valve_state(vst[0] & 512) self.valve_state_VDI["state"] = self._binary_to_valve_state(vst[0] & 1024) self.valve_state_VDO["state"] = self._binary_to_valve_state(vst[0] & 2048) self.valve_state_VP2["state"] = self._binary_to_valve_state(vst[0] & 4096) self.valve_state_VHI["state"] = self._binary_to_valve_state(vst[0] & 8192) self.valve_state_VWI["state"] = self._binary_to_valve_state(vst[0] & 16384) self.valve_state_rsvrd1["state"] = self._binary_to_valve_state(vst[0] & 32768) self.valve_state_rsvrd2["state"] = self._binary_to_valve_state(vst[0] & 65536) bcv = struct.unpack('B', bytearray(message['message'][self.START_POS_BCV_VALVES_STATES:self.END_POS_BCV_VALVES_STATES])) self.valve_state_BCV1["state"] = self._binary_to_valve_state(bcv[0] & 1) self.valve_state_BCV2["state"] = self._binary_to_valve_state(bcv[0] & 2) self.valve_state_BCV3["state"] = self._binary_to_valve_state(bcv[0] & 8) self.valve_state_BCV4["state"] = self._binary_to_valve_state(bcv[0] & 16) self.valve_state_BCV5["state"] = self._binary_to_valve_state(bcv[0] & 32) self.valve_state_BCV6["state"] = self._binary_to_valve_state(bcv[0] & 64) self.valve_state_BCV7["state"] = self._binary_to_valve_state(bcv[0] & 128) self.valve_state_BCV8["state"] = self._binary_to_valve_state(bcv[0] & 256) ufi = struct.unpack('B', bytearray(message['message'][self.START_POS_UFI_VALVES_STATES:self.END_POS_UFI_VALVES_STATES])) self.valve_state_UFI1["state"] = self._binary_to_valve_state(ufi[0] & 1) self.valve_state_UFI2["state"] = self._binary_to_valve_state(ufi[0] & 2) self.valve_state_UFI3["state"] = self._binary_to_valve_state(ufi[0] & 8) self.valve_state_UFI4["state"] = self._binary_to_valve_state(ufi[0] & 16) start = self.END_POS_UFI_VALVES_STATES end = start + 1 for valve_id in self.valves_sensed_states: valve_state_number = struct.unpack('B', bytearray(message['message'][start:end]))[0] self.valves_sensed_states[valve_id] = DDValveNames(valve_state_number).name start = end end += 1 self.dg_valves_states_timestamp = timestamp def cmd_valve_sensed_state_override(self, valve: int, state: bool, reset: int = NO_RESET) -> int: """ Constructs and sends the valve sensed state override command. Constraints: Must be logged into DG. Given valve ID must be one of the valve IDs listed below. @param valve: unsigned int - valve ID @param state: bool - valve state @param reset: integer - 1 to reset a previous override, 0 to override @return: 1 if successful, zero otherwise """ rst = integer_to_bytearray(reset) ste = integer_to_bytearray(int(state)) vlv = integer_to_bytearray(valve) payload = rst + ste + vlv message = DenaliMessage.build_message(channel_id=DenaliChannels.dialin_to_dd_ch_id, message_id=MsgIds.MSG_ID_DD_VALVE_SENSED_STATE_OVERRIDE_REQUEST.value, payload=payload) self.logger.debug("Override valve sensed state") # Send message received_message = self.can_interface.send(message) # If there is content... if received_message is not None: # response payload is OK or not OK return received_message['message'][DenaliMessage.PAYLOAD_START_INDEX] else: self.logger.debug("Timeout!!!!") return False def cmd_valve_override(self, valve: int, state: bool, reset: int = NO_RESET) -> int: """ Constructs and sends the valve state override command. Constraints: Must be logged into DG. Given valve ID must be one of the valve IDs listed below. @param valve: unsigned int - valve ID @param state: bool - valve state @param reset: integer - 1 to reset a previous override, 0 to override @return: 1 if successful, zero otherwise """ rst = integer_to_bytearray(reset) ste = integer_to_bytearray(int(state)) vlv = integer_to_bytearray(valve) payload = rst + ste + vlv message = DenaliMessage.build_message(channel_id=DenaliChannels.dialin_to_dd_ch_id, message_id=MsgIds.MSG_ID_DD_VALVE_STATE_OVERRIDE_REQUEST.value, payload=payload) self.logger.debug("Override valve state") # Send message received_message = self.can_interface.send(message) # If there is content... if received_message is not None: # response payload is OK or not OK return received_message['message'][DenaliMessage.PAYLOAD_START_INDEX] else: self.logger.debug("Timeout!!!!") return False def cmd_valve_broadcast_interval_override(self, ms: int, reset: int = NO_RESET) -> int: """ Constructs and sends the valve state override command. Constraints: Must be logged into DG. Given interval must be non-zero and a multiple of the DG general task interval (50 ms). @param ms: unsigned int - broadcast interval (in ms) @param reset: integer - 1 to reset a previous override, 0 to override @return: 1 if successful, zero otherwise """ if not check_broadcast_interval_override_ms(ms): return False rst = integer_to_bytearray(reset) ivl = integer_to_bytearray(ms) payload = rst + ivl message = DenaliMessage.build_message(channel_id=DenaliChannels.dialin_to_dd_ch_id, message_id=MsgIds.MSG_ID_DD_VALVE_PUBLISH_INTERVAL_OVERRIDE_REQUEST.value, payload=payload) self.logger.debug("override valves states publish interval") # Send message received_message = self.can_interface.send(message) # If there is content in message if received_message is not None: # Response payload is OK or not return received_message['message'][DenaliMessage.PAYLOAD_START_INDEX] else: self.logger.debug("Timeout!!!!") return False def cmd_valve_set_open_close(self, valve: int, state: int) -> int: """ Constructs and sends the valve open close command @param valve: unsigned int - dialysate pump ID @param command: int - value to command the dialysate pump @param speed: integer - rpm to set the speed to @return: 1 if successful, zero otherwise """ vlv = integer_to_bytearray(valve) sts = integer_to_bytearray(state) payload = vlv + sts message = DenaliMessage.build_message(channel_id=DenaliChannels.dialin_to_dd_ch_id, message_id=MsgIds.MSG_ID_DD_VALVES_OPEN_CLOSE_STATE_OVERRIDE_REQUEST.value, payload=payload) self.logger.debug("setting " + str(state) + " - for valve: " + str(valve)) # Send message received_message = self.can_interface.send(message) # If there is content... if received_message is not None: # response payload is OK or not OK return received_message['message'][DenaliMessage.PAYLOAD_START_INDEX] else: self.logger.error("Timeout!!!!") return False