########################################################################### # # Copyright (c) 2022-2023 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 usage_info_record.py # # @author (last) Dara Navaei # @date (last) 19-Dec-2022 # @author (original) Dara Navaei # @date (original) 28-Apr-2022 # ############################################################################ import struct import time from collections import OrderedDict from logging import Logger from time import sleep from ..common.msg_defs import MsgIds, MsgFieldPositions from ..protocols.CAN import DenaliMessage, DenaliChannels from ..utils.base import AbstractSubSystem, publish from ..utils.nv_ops_utils import NVOpsUtils, NVUtilsObserver, NVRecords from ..utils.conversions import integer_to_bytearray class HDUsageNVRecord(AbstractSubSystem): """ @brief Hemodialysis Device (HD) Dialin API sub-class for setting and getting the usage information record. """ _DEFAULT_USAGE_INFO_VALUE = 0 _DEFAULT_CRC_VALUE = 0 _RECORD_SPECS_BYTES = 12 # Maximum allowed bytes to be written to RTC RAM _RTC_RAM_MAX_BYTES_TO_WRITE = 64 _PAYLOAD_TRANSFER_DELAY_S = 0.2 _FIRMWARE_STACK_NAME = 'HD' 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._current_message = 0 self._total_messages = 0 self._received_msg_length = 0 self._usage_info_data = 0 self._is_getting_usage_info_in_progress = False self._raw_usage_info_record = [] self._utilities = NVOpsUtils(logger=self.logger) self.hd_usage_info_record = self._prepare_hd_usage_info_record() if self.can_interface is not None: channel_id = DenaliChannels.hd_to_dialin_ch_id msg_id = MsgIds.MSG_ID_HD_SEND_USAGE_INFO_RECORD.value self.can_interface.register_receiving_publication_function(channel_id, msg_id, self._handler_hd_usage_info_sync) def _cmd_request_hd_usage_info_record(self) -> int: """ Handles getting HD usage information record from firmware. @return: 1 upon success, False otherwise """ if self._is_getting_usage_info_in_progress is not True: self._is_getting_usage_info_in_progress = True # Clear the list for the next call self._raw_usage_info_record.clear() # Run the firmware commands to get the record message = DenaliMessage.build_message(channel_id=DenaliChannels.dialin_to_hd_ch_id, message_id=MsgIds.MSG_ID_HD_GET_USAGE_INFO_RECORD.value) self.logger.debug('Getting HD usage information record') received_message = self.can_interface.send(message) # If there is content... if received_message is not None: self.logger.debug("Received FW ACK after requesting DG software configuration record.") # response payload is OK or not OK return received_message['message'][DenaliMessage.PAYLOAD_START_INDEX] else: self.logger.debug("Timeout!!!!") return False self.logger.debug("Request cancelled: an existing request is in progress.") return False def cmd_hd_usage_info_crc_override(self, crc: int) -> bool: """ Handles setting HD usage info record CRC override. @param crc: (int) the CRC override value @return: True if successful, False otherwise """ # This command does not have a reset but since the corresponding payload structure in firmware requires a reset # so the payload length is the same when it is received in the firmware. reset_byte_array = integer_to_bytearray(0) crc_value = integer_to_bytearray(crc) hd_record = integer_to_bytearray(NVRecords.NVDATAMGMT_USAGE_INFO_RECORD.value) payload = reset_byte_array + crc_value + hd_record message = DenaliMessage.build_message(channel_id=DenaliChannels.dialin_to_hd_ch_id, message_id=MsgIds.MSG_ID_HD_NV_RECORD_CRC_OVERRIDE.value, payload=payload) self.logger.debug("Overriding HD usage info CRC to: " + str(crc)) # 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 def _handler_hd_usage_info_sync(self, message): """ Handles published HD usage information record messages. @param message: published HD usage information record data message @return: None """ curr = struct.unpack('i', bytearray( message['message'][MsgFieldPositions.START_POS_FIELD_1:MsgFieldPositions.END_POS_FIELD_1]))[0] total = struct.unpack('i', bytearray( message['message'][MsgFieldPositions.START_POS_FIELD_2:MsgFieldPositions.END_POS_FIELD_2]))[0] length = struct.unpack('i', bytearray( message['message'][MsgFieldPositions.START_POS_FIELD_3:MsgFieldPositions.END_POS_FIELD_3]))[0] self._current_message = curr self._total_messages = total self._received_msg_length = length # The end of calibration_record record payload is from the start index + 12 bytes for the current message +total # messages + the length of calibration_record. The rest is the CAN messaging CRC that is not needed # to be kept end_of_data_index = MsgFieldPositions.START_POS_FIELD_1 + self._RECORD_SPECS_BYTES + self._received_msg_length # Get the data only and not specs of it (i.e current message number) self._usage_info_data = message['message'][MsgFieldPositions.START_POS_FIELD_1:end_of_data_index] # Continue getting calibration_record records until the all the calibration_record messages are received. # Concatenate the calibration_record records to each other if self._current_message <= self._total_messages: self._raw_usage_info_record += (message['message'][MsgFieldPositions.START_POS_FIELD_1 + self._RECORD_SPECS_BYTES:end_of_data_index]) if self._current_message == self._total_messages: # Done with receiving the messages self._is_getting_usage_info_in_progress = False # If all the messages have been received, call another function to process the raw data self._utilities.process_received_record_from_fw(self.hd_usage_info_record, self._raw_usage_info_record) self._handler_received_complete_hd_usage_info_record() @publish(["hd_usage_info_record"]) def _handler_received_complete_hd_usage_info_record(self): """ Publishes the received usage information record @return: None """ self.logger.debug("Received a complete HD usage information record.") def cmd_update_hd_usage_info_record(self, excel_report_path: str): """ Handles preparing the HD usage information from the provided excel report @param excel_report_path: (str) the directory in which the excel report of the information is located @return: none """ # Pass the software configuration record dictionary to be updated with the excel document self._utilities.write_excel_record_to_fw_record(self.hd_usage_info_record, excel_report_path, self._utilities.USAGE_INFO_RECORD_TAB_NAME) print(self.hd_usage_info_record) # TODO remove self._cmd_set_hd_usage_info_record(self.hd_usage_info_record) def _cmd_set_hd_usage_info_record(self, previous_record: OrderedDict) -> bool: """ Handles updating the HD usage information record and sends it to FW. @return: True upon success, False otherwise """ record_packets = self._utilities.prepare_record_to_send_to_fw(previous_record) self.logger.debug('Setting HD usage information record') # Update all the data packets with the last message count since is the number of messages that firmware # should receive for packet in record_packets: # Sleep to let the firmware receive and process the data time.sleep(self._PAYLOAD_TRANSFER_DELAY_S) # Convert the list packet to a bytearray payload = b''.join(packet) message = DenaliMessage.build_message(channel_id=DenaliChannels.dialin_to_hd_ch_id, message_id=MsgIds.MSG_ID_HD_SET_USAGE_INFO_RECORD.value, payload=payload) received_message = self.can_interface.send(message) # If there is no content... if received_message is None: self.logger.debug("Timeout!!!!") return False self.logger.debug("Finished sending HD usage information record.") return True def _prepare_hd_usage_info_record(self) -> OrderedDict: """ Handles assembling the sub dictionaries of HD usage information. @return: (OrderedDict) the assembled HD usage information """ record = OrderedDict() groups_byte_size = 0 # create a list of the functions of the sub dictionaries functions = [self._prepare_usage_info_record()] for function in functions: # Update the groups bytes size so far to be used to padding later groups_byte_size += function[1] # Update the calibration record record.update(function[0]) # Build the CRC of the main calibration_record record record_crc = OrderedDict({'crc': [' tuple: """ Handles creating the usage information record dictionary. @return: usage information record dictionary and the byte size of this group """ groups_byte_size = 0 usage_info_records = OrderedDict( {'usage_info_record': {'tx_total_time_hours': [' bool: """ Handles resetting HD usage info record. @return: True if successful, False otherwise """ self.hd_usage_info_record = self._prepare_hd_usage_info_record() self.hd_usage_info_record = self._utilities.reset_fw_record(self.hd_usage_info_record) status = self._cmd_set_hd_usage_info_record(self.hd_usage_info_record) return status def cmd_set_dg_usage_info_excel_to_fw(self, report_address: str): """ Handles setting the usage info data that is in an excel report to the firmware. @param report_address: (str) the address in which its data must be written from excel @return: none """ # Request the DG usage record and set and observer class to callback when the calibration record is read # back self._cmd_request_hd_usage_info_record() observer = NVUtilsObserver("hd_usage_info_record") # Attach the observer to the list self.attach(observer) while not observer.received: sleep(0.1) self._utilities.write_excel_record_to_fw_record(self.hd_usage_info_record, report_address, self._utilities.USAGE_INFO_RECORD_TAB_NAME) self._cmd_set_hd_usage_info_record(self.hd_usage_info_record)