lenz-flashtool 0.1.2__tar.gz → 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/PKG-INFO +1 -1
  2. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/flashtool/core.py +370 -105
  3. lenz_flashtool-0.1.3/lenz_flashtool/flashtool/ft_bl_connection.py +217 -0
  4. lenz_flashtool-0.1.3/lenz_flashtool/flashtool/hex_generator.py +227 -0
  5. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/flashtool/hex_utils.py +425 -1
  6. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/flashtool/uart.py +154 -6
  7. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/pyproject.toml +1 -1
  8. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/.gitignore +0 -0
  9. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/LICENSE +0 -0
  10. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/README.md +0 -0
  11. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/__init__.py +0 -0
  12. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/biss/__init__.py +0 -0
  13. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/biss/cli.py +0 -0
  14. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/biss/commands.py +0 -0
  15. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/biss/crc.py +0 -0
  16. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/biss/registers.py +0 -0
  17. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/encproc/__init__.py +0 -0
  18. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/encproc/processing.py +0 -0
  19. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/flashtool/__init__.py +0 -0
  20. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/flashtool/errors.py +0 -0
  21. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/flashtool/logging.py +0 -0
  22. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/flashtool/operations.py +0 -0
  23. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/testing/__init__.py +0 -0
  24. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/testing/mock_flashtool.py +0 -0
  25. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/utils/__init__.py +0 -0
  26. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/utils/plot.py +0 -0
  27. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/utils/progress.py +0 -0
  28. {lenz_flashtool-0.1.2 → lenz_flashtool-0.1.3}/lenz_flashtool/utils/termcolors.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lenz-flashtool
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: FlashTool library for BiSS C Firmware Update and Calibration by LENZ Encoders
5
5
  Project-URL: Homepage, https://github.com/lenzencoders/lenz-flashtool-lib
6
6
  Project-URL: Source, https://github.com/lenzencoders/lenz-flashtool-lib
@@ -20,7 +20,7 @@ import os
20
20
  import sys
21
21
  import logging
22
22
  import signal
23
- from typing import Callable, Dict, Optional, List, Union, Any, Type, Tuple
23
+ from typing import Callable, Dict, Optional, List, Union, Any, Type, Tuple, Literal
24
24
  from types import TracebackType
25
25
  import serial
26
26
  import serial.tools.list_ports
@@ -29,7 +29,7 @@ from ..biss import (
29
29
  biss_commands, interpret_biss_commandstate, interpret_error_flags,
30
30
  BiSSBank,
31
31
  )
32
- from .uart import UartCmd
32
+ from .uart import UartCmd, UartBootloaderCmd, UartBootloaderMemoryStates
33
33
  from .errors import FlashToolError
34
34
  from .hex_utils import (
35
35
  calculate_checksum,
@@ -38,6 +38,8 @@ from .hex_utils import (
38
38
  reverse_endian, bytes_to_hex_str
39
39
  )
40
40
  from ..utils.progress import percent_complete
41
+ from ..utils.termcolors import TermColors
42
+ from .hex_utils import HexBlockExtractor
41
43
 
42
44
  logger = logging.getLogger(__name__)
43
45
 
@@ -478,7 +480,7 @@ class FlashTool:
478
480
  """
479
481
  # logger.debug(f'Uploading {hex_line} to the FlashTool.')
480
482
  tx_row = bytes.fromhex(hex_line[1:])
481
- logger.debug(tx_row.hex())
483
+ # logger.debug(tx_row.hex())
482
484
  self._write_to_port(tx_row)
483
485
  return tx_row
484
486
 
@@ -813,188 +815,451 @@ class FlashTool:
813
815
  self._write_to_port(tx_row)
814
816
  time.sleep(0.01)
815
817
 
816
- def select_spi_channel(self, channel: np.uint8) -> None:
818
+ def reboot_to_bl(self) -> None:
819
+ """
820
+ Reboot to BOOTLOADER FlashTool device.
821
+
822
+ Sends a Reboot to Bootloader command to the FlashTool.
823
+
824
+ Returns:
825
+ None
826
+
827
+ Example:
828
+ >>> ft = FlashTool()
829
+ >>> ft.reboot_to_bl()
830
+ """
831
+ logger.info('Sending REBOOT to BOOTLOADER command to FlashTool')
832
+ tx_row = bytes.fromhex(generate_hex_line(
833
+ address=0x0000,
834
+ command=UartCmd.CMD_REBOOT_TO_BL,
835
+ data=[0x00]
836
+ )[1:])
837
+ self._write_to_port(tx_row)
838
+ time.sleep(0.01)
839
+
840
+ def reboot_to_fw(self):
841
+ """
842
+ Reboot to FIRMWARE FlashTool device.
843
+
844
+ Sends a Reboot to Firmware command to the FlashTool.
845
+
846
+ Returns:
847
+ None
848
+
849
+ Example:
850
+ >>> ft = FlashTool()
851
+ >>> ft.reboot_to_fw()
852
+ """
853
+ logger.info('Sending REBOOT to FIRMWARE command to FlashTool')
854
+ tx_row = bytes.fromhex(generate_hex_line(
855
+ address=0x0000,
856
+ command=UartBootloaderCmd.UART_COMMAND_RUN_PROGRAM,
857
+ data=[0x00]
858
+ )[1:])
859
+ logger.debug(f"Sent BiSS Data: {tx_row.hex()}")
860
+ self._write_to_port(tx_row)
861
+ time.sleep(0.01)
862
+
863
+ def read_memory_state_bl(self) -> UartBootloaderMemoryStates:
864
+ """
865
+ Read Memory State of FlashTool bootloader.
866
+
867
+ Sends a Read Memory State command to FlashTool.
868
+
869
+ Returns:
870
+ UartBootloaderMemoryStates
871
+
872
+ Example:
873
+ >>> ft = FlashTool()
874
+ >>> ft.read_memory_state_bl()
875
+ """
876
+ tx_row = bytes.fromhex(generate_hex_line(
877
+ address=0x0000,
878
+ command=UartBootloaderCmd.UART_COMMAND_READ_MEMORYSTATE,
879
+ data=[0x00]
880
+ )[1:])
881
+ logger.debug(f"Sent BiSS Data: {tx_row.hex()}")
882
+ self._write_to_port(tx_row)
883
+ response = self.port_read(len(tx_row) - 1)
884
+ state = self._decode_memory_state_bl(response)
885
+ time.sleep(0.01)
886
+ return state
887
+
888
+ def _decode_memory_state_bl(self, response: np.ndarray) -> UartBootloaderMemoryStates:
889
+ """
890
+ Decode Memory State of FlashTool bootloader.
891
+
892
+ Input:
893
+ response: value from read_memory_state_bl
894
+
895
+ Returns:
896
+ UartBootloaderMemoryStates
897
+
898
+ Example:
899
+ >>> ft = FlashTool()
900
+ >>> ft._decode_memory_state_bl(response)
901
+ UartBootloaderMemoryStates
902
+ """
903
+ response = response[0]
904
+ if response in {state.value for state in UartBootloaderMemoryStates}:
905
+ matched_state = UartBootloaderMemoryStates(response)
906
+ print(f"{TermColors.Blue}Response: {matched_state.name} (0x{response:02x}{TermColors.Default})")
907
+ if matched_state == UartBootloaderMemoryStates.UART_MEMORYSTATE_FLASH_FW_CRC_OK:
908
+ logger.info('Firmware CRC check passed!')
909
+ elif matched_state == UartBootloaderMemoryStates.UART_MEMORYSTATE_FLASH_FW_CRC_FAULT:
910
+ logger.error('Firmware CRC check failed!')
911
+ elif matched_state == UartBootloaderMemoryStates.UART_MEMORYSTATE_IDLE:
912
+ logger.info('Uart state is IDLE!')
913
+ elif matched_state == UartBootloaderMemoryStates.UART_MEMORYSTATE_FW_CHECK_CRC32_FAULT:
914
+ logger.error('Firmware CRC check failed!')
915
+ elif matched_state == UartBootloaderMemoryStates.UART_MEMORYSTATE_FW_CHECK_CRC32_OK:
916
+ logger.info('Firmware CRC check passed!')
917
+ return matched_state
918
+
919
+ def check_main_fw_crc32(self) -> None:
920
+ """
921
+ Compare calculated main FlashTool firmware crc32 with ProgramCRC32 value in flash.
922
+
923
+ Input:
924
+ None
925
+
926
+ Returns:
927
+ None
928
+
929
+ Example:
930
+ >>> ft = FlashTool()
931
+ >>> ft.check_main_fw_crc32()
932
+ 'Response: UART_MEMORYSTATE_FW_CHECK_CRC32_OK (0x05)'
933
+ """
934
+ logger.info('Sending check main firmware CRC32 command to FlashTool')
935
+ tx_row = bytes.fromhex(generate_hex_line(
936
+ address=0x0000,
937
+ command=UartBootloaderCmd.UART_COMMAND_CHECK_PROGRAM_CRC32,
938
+ data=[0x00]
939
+ )[1:])
940
+ logger.debug(f"Sent BiSS Data: {tx_row.hex()}")
941
+ self._write_to_port(tx_row)
942
+ self.read_memory_state_bl()
943
+
944
+ def download_fw_to_ft(self, hex_file_path: str, max_retries: int = 3, pbar: Optional[Any] = None):
945
+ """
946
+ Download main firmware from HEX file to FlashTool device using bootloader protocol.
947
+
948
+ Implements a robust flash programming routine with:
949
+ - Automatic CRC verification
950
+ - Retry mechanism for failed pages
951
+ - Progress tracking
952
+ - Error recovery
953
+
954
+ Protocol Flow:
955
+ 1. For each 2KB block in HEX file:
956
+ 1.a. Send block's CRC32 checksum first
957
+ 1.b. Transfer data in 64-byte chunks
958
+ 1.c. Verify flash operation success
959
+ 1.d. Retry on failure (up to max_retries)
960
+ 2. Handle both successful and error cases gracefully
961
+
962
+ Args:
963
+ hex_file_path (str): Path to Intel HEX format firmware file
964
+ max_retries (int): Maximum retry attempts per page (default: 3)
965
+
966
+ Raises:
967
+ RuntimeError: When exceeding max retries for a page
968
+ IOError: For file access problems
969
+ ValueError: For invalid HEX file format
970
+ Exception: For communication errors with device
971
+
972
+ Returns:
973
+ None: Success is implied by normal completion
974
+
975
+ Side Effects:
976
+ - Programs firmware to target device flash
977
+ - Modifies device memory state
978
+ - May reset communication interface
979
+
980
+ Example:
981
+ >>> tool = FlashTool()
982
+ >>> tool.download_fw_to_ft("firmware_v1.2.hex")
983
+
984
+ Notes:
985
+ - Requires active bootloader connection
986
+ - Uses 2KB page size (device-specific)
987
+ - 64-byte chunk size optimized for UART throughput
988
+ - Includes mandatory 1s delay after programming
989
+ - CRC verification is mandatory for each page
990
+ """
991
+ extractor = HexBlockExtractor()
992
+ retry_count = 0
993
+ total_pages = 12 # Default value
994
+ metadata_total_pages = 1
995
+
996
+ try:
997
+ first_block_start, first_block_data, _ = next(extractor.process_hex_file(hex_file_path))
998
+ first_lower_addr = first_block_start & 0xFFFF
999
+ first_page_number = first_lower_addr // 2048
1000
+
1001
+ # Extract ProgramLen from metadata (offset 0x0C, 4 bytes)
1002
+ if len(first_block_data) >= 0x0C + 4:
1003
+ program_len_bytes = first_block_data[0x0C:0x0C+4]
1004
+ program_total_pages = int.from_bytes(program_len_bytes, byteorder='little')
1005
+ logger.info(f"Extracted program total pages from metadata: {program_total_pages}")
1006
+
1007
+ # Extract BootloaderLen from metadata (offset 0x1C, 4 bytes)
1008
+ if len(first_block_data) >= 0x1C + 4:
1009
+ program_len_bytes = first_block_data[0x1C:0x1C+4]
1010
+ bootloader_total_pages = int.from_bytes(program_len_bytes, byteorder='little')
1011
+ logger.info(f"Extracted bootloader total pages from metadata: {bootloader_total_pages}")
1012
+
1013
+ total_pages = program_total_pages + bootloader_total_pages + metadata_total_pages
1014
+ logger.info(f"Extracted total pages from metadata: {total_pages}")
1015
+
1016
+ for block_start, block_data, block_crc in extractor.process_hex_file(hex_file_path):
1017
+ lower_addr = block_start & 0xFFFF
1018
+ page_number = lower_addr // 2048
1019
+ count_pages = page_number - first_page_number + 1
1020
+ success = False
1021
+
1022
+ while not success and retry_count < max_retries:
1023
+ try:
1024
+ # 1. Send CRC Record
1025
+ crc_bytes = [
1026
+ (block_crc >> 24) & 0xFF,
1027
+ (block_crc >> 16) & 0xFF,
1028
+ (block_crc >> 8) & 0xFF,
1029
+ block_crc & 0xFF
1030
+ ]
1031
+ crc_line = generate_hex_line(
1032
+ address=0x0000,
1033
+ command=UartBootloaderCmd.UART_COMMAND_WRITE_CURRENT_PAGE_CRC32,
1034
+ data=crc_bytes
1035
+ )
1036
+ logger.info(f"Sent BiSS Data: {crc_line}")
1037
+ self.hex_line_send(crc_line)
1038
+
1039
+ # 2. Send Data Records in 64-byte chunks
1040
+ for offset in range(0, len(block_data), 64):
1041
+ chunk = block_data[offset:offset+64]
1042
+ chunk_addr = (0x01 << 8) | ((page_number) & 0xFF)
1043
+ data_line = generate_hex_line(
1044
+ address=chunk_addr,
1045
+ command=UartBootloaderCmd.UART_COMMAND_LOAD_2K,
1046
+ data=list(chunk)
1047
+ )
1048
+ self.hex_line_send(data_line)
1049
+
1050
+ if pbar:
1051
+ percent_complete(count_pages, total_pages, title=f"Sending Page {count_pages}")
1052
+ # 3. Wait for flash 2048 bytes operation to complete
1053
+ time.sleep(1)
1054
+
1055
+ # 4. Verify CRC32 check
1056
+ matched_state = self.read_memory_state_bl()
1057
+ if matched_state == UartBootloaderMemoryStates.UART_MEMORYSTATE_FLASH_FW_CRC_FAULT:
1058
+ retry_count += 1
1059
+ print(f"CRC Error on page {page_number}, retry {retry_count}/{max_retries}")
1060
+ if retry_count >= max_retries:
1061
+ raise RuntimeError(f"Max retries ({max_retries}) exceeded for page {page_number}")
1062
+ continue
1063
+ elif matched_state == UartBootloaderMemoryStates.UART_MEMORYSTATE_FLASH_FW_CRC_OK:
1064
+ success = True
1065
+ retry_count = 0
1066
+ else:
1067
+ raise RuntimeError(f"Unexpected memory state: {matched_state.name}")
1068
+
1069
+ except Exception as e:
1070
+ retry_count += 1
1071
+ print(f"Error on page {page_number}, retry {retry_count}/{max_retries}: {str(e)}")
1072
+ if retry_count >= max_retries:
1073
+ raise RuntimeError(f"Max retries ({max_retries}) exceeded for page {page_number}")
1074
+ time.sleep(1)
1075
+ continue
1076
+
1077
+ except Exception as e:
1078
+ print(f"Fatal error during firmware upload: {str(e)}")
1079
+ raise
1080
+ self.check_main_fw_crc32()
1081
+ time.sleep(0.05)
1082
+
1083
+ def select_spi_channel(self, channel: Literal["channel1", "channel2"]) -> None:
817
1084
  """
818
1085
  Select SPI communication channel.
819
1086
 
820
1087
  Sends a SELECT CHANNEL command to the FlashTool.
821
1088
 
822
1089
  There are two channels:
823
- 0 --> channel 1;
824
- 1 --> channel 2.
1090
+ channel1;
1091
+ channel2.
825
1092
 
826
1093
  Args:
827
- channel (uint8): The channel number (must be 0 or 1).
1094
+ channel: "channel1" or "channel2".
828
1095
 
829
1096
  Returns:
830
1097
  None
831
1098
 
832
1099
  Raises:
833
- ValueError: If the mode is not 0 or 1.
1100
+ ValueError: If the mode is not channel1 or channel2.
834
1101
 
835
1102
  Example:
836
1103
  >>> ft = FlashTool()
837
- >>> ft.select_SPI_channel(0)
1104
+ >>> ft.select_SPI_channel('channel1')
838
1105
  """
839
- channel = np.uint8(channel)
840
- valid_channels = {np.uint8(0), np.uint8(1)}
841
- if channel not in valid_channels:
842
- raise ValueError(f"Invalid mode: {channel}. Must be one of the {valid_channels} (0: channel 1, 1: \
843
- channel 2).")
844
-
845
- channel_descriptions = {
846
- 0: "CHANNEL 1",
847
- 1: "CHANNEL 2"
1106
+ channel_mapping = {
1107
+ "channel1": (0, "CHANNEL 1"),
1108
+ "channel2": (1, "CHANNEL 2")
848
1109
  }
849
- logger.info(f"Selected Channel: {channel} - {channel_descriptions[channel]}")
850
1110
 
851
- tx_row = bytes.fromhex(generate_hex_line(0, UartCmd.CMD_SELECT_SPI_CH, [channel])[1:])
852
- # logger.debug(tx_row)
1111
+ if channel not in channel_mapping:
1112
+ raise ValueError(f'Invalid channel: "{channel}". Must be "channel1" or "channel2".')
1113
+
1114
+ channel_num, channel_desc = channel_mapping[channel]
1115
+ logger.info(f"Selected Channel: {channel_num} - {channel_desc}")
1116
+
1117
+ tx_row = bytes.fromhex(generate_hex_line(0, UartCmd.CMD_SELECT_SPI_CH, [channel_num])[1:])
853
1118
  self.__port.reset_output_buffer()
854
1119
  self.__port.write(tx_row)
855
1120
  self.__port.flush()
856
1121
 
857
- def select_flashtool_mode(self, mode: np.uint8):
1122
+ def select_flashtool_mode(self, mode: Literal["spi_spi", "ab_uart", "spi_uart_irs", "ab_spi", "default_spi"]) -> None:
858
1123
  """
859
- Select FlashTool mode.
1124
+ Select FlashTool communication mode.
860
1125
 
861
1126
  Sends a SELECT FLASHTOOL MODE command to configure the communication protocol
862
1127
  for both channels of the FlashTool.
863
1128
 
864
1129
  Available modes:
865
- 0 (BISS_MODE_SPI_SPI):
866
- Channel 1: SPI, Channel 2: SPI
867
- 1 (BISS_MODE_AB_UART):
868
- Channel 1: AB signal, Channel 2: UART
869
- 2 (BISS_MODE_SPI_UART_IRS):
870
- Channel 1: SPI, Channel 2: UART for IRS encoders
871
- 3 (BISS_MODE_AB_SPI):
872
- Channel 1: AB signal, Channel 2: SPI
873
- 4 (BISS_MODE_DEFAULT_SPI):
874
- Default mode - Channel 1: Without communication, Channel 2: SPI
1130
+ "spi_spi" - Channel 1: SPI, Channel 2: SPI
1131
+ "ab_uart" - Channel 1: AB signal, Channel 2: UART
1132
+ "spi_uart_irs" - Channel 1: SPI, Channel 2: UART for IRS encoders
1133
+ "ab_spi" - Channel 1: AB signal, Channel 2: SPI
1134
+ "default_spi" - Default mode: Channel 1: None, Channel 2: SPI
875
1135
 
876
1136
  Args:
877
- mode (np.uint8): The communication mode number (0-4)
878
- - 0: SPI on both channels
879
- - 1: AB sginal + UART
880
- - 2: SPI + UART for IRS encoders
881
- - 3: AB signal + SPI
882
- - 4: Without communication + SPI
1137
+ mode: Communication mode as descriptive string:
1138
+ - "spi_spi" (0: BISS_MODE_SPI_SPI)
1139
+ - "ab_uart" (1: BISS_MODE_AB_UART)
1140
+ - "spi_uart_irs" (2: BISS_MODE_SPI_UART_IRS)
1141
+ - "ab_spi" (3: BISS_MODE_AB_SPI)
1142
+ - "default_spi" (4: BISS_MODE_DEFAULT_SPI)
883
1143
 
884
1144
  Returns:
885
1145
  None
886
1146
 
887
1147
  Raises:
888
- ValueError: If the mode is not in range 0-4
889
- TypeError: If the mode is not convertible to np.uint8
1148
+ ValueError: If invalid mode string provided
890
1149
 
891
1150
  Example:
892
1151
  >>> ft = FlashTool()
893
- >>> ft.select_flashtool_mode(0) # Sets SPI on both channels
894
- >>> ft.select_flashtool_mode(2) # Sets SPI + UART for IRS encoders
895
- """
896
- mode = np.uint8(mode)
897
- valid_modes = {np.uint8(0), np.uint8(1), np.uint8(2), np.uint8(3), np.uint8(4)}
898
- if mode not in valid_modes:
899
- raise ValueError(f"Invalid mode: {mode}. Must be one of the {valid_modes} (0: BISS_MODE_SPI_SPI, 1: \
900
- BISS_MODE_AB_UART, 2: BISS_MODE_SPI_UART_IRS, 3: BISS_MODE_AB_SPI, 4: BISS_MODE_DEFAULT_SPI).")
901
-
902
- mode_descriptions = {
903
- 0: "BISS_MODE_SPI_SPI",
904
- 1: "BISS_MODE_AB_UART",
905
- 2: "BISS_MODE_SPI_UART_IRS",
906
- 3: "BISS_MODE_AB_SPI",
907
- 4: "BISS_MODE_DEFAULT_SPI"
1152
+ >>> ft.select_flashtool_mode("spi_spi") # Sets SPI on both channels
1153
+ >>> ft.select_flashtool_mode("spi_uart_irs") # Sets SPI + UART for IRS
1154
+ """
1155
+ mode_mapping = {
1156
+ "spi_spi": (0, "BISS_MODE_SPI_SPI"),
1157
+ "ab_uart": (1, "BISS_MODE_AB_UART"),
1158
+ "spi_uart_irs": (2, "BISS_MODE_SPI_UART_IRS"),
1159
+ "ab_spi": (3, "BISS_MODE_AB_SPI"),
1160
+ "default_spi": (4, "BISS_MODE_DEFAULT_SPI")
908
1161
  }
909
- logger.info(f"Selected FlashTool mode: {mode} - {mode_descriptions[mode]}")
910
1162
 
911
- tx_row = bytes.fromhex(generate_hex_line(0, UartCmd.CMD_SELECT_FLASHTOOL_MODE, [mode])[1:])
912
- # logger.debug(tx_row)
1163
+ if mode not in mode_mapping:
1164
+ valid_modes = list(mode_mapping.keys())
1165
+ raise ValueError(f'Invalid mode: "{mode}". Must be one of: {valid_modes}')
1166
+
1167
+ mode_num, mode_desc = mode_mapping[mode]
1168
+ logger.info(f"Selected FlashTool mode: {mode_num} - {mode_desc}")
1169
+
1170
+ tx_row = bytes.fromhex(generate_hex_line(0, UartCmd.CMD_SELECT_FLASHTOOL_MODE, [mode_num])[1:])
913
1171
  self.__port.reset_output_buffer()
914
1172
  self.__port.write(tx_row)
915
1173
  self.__port.flush()
916
1174
  time.sleep(0.05)
917
1175
 
918
- def select_FlashTool_current_sensor_mode(self, mode: np.uint8):
1176
+ def select_FlashTool_current_sensor_mode(self, mode: Literal["disable", "enable"]) -> None:
919
1177
  """
920
1178
  Select FlashTool Current sensor mode.
921
1179
 
922
1180
  Sends a SELECT Current sensor mode command to the FlashTool.
923
1181
 
924
- There are two modes:
925
- 0 --> CURRENT_SENSOR_MODE_DISABLE.
926
- 1 --> CURRENT_SENSOR_MODE_ENABLE.
1182
+ Available modes:
1183
+ "disable" - CURRENT_SENSOR_MODE_DISABLE (0)
1184
+ "enable" - CURRENT_SENSOR_MODE_ENABLE (1)
927
1185
 
928
1186
  Args:
929
- mode (uint8): The mode number (must be 0, 1).
1187
+ mode: Current sensor mode as descriptive string:
1188
+ - "disable" (0: CURRENT_SENSOR_MODE_DISABLE)
1189
+ - "enable" (1: CURRENT_SENSOR_MODE_ENABLE)
930
1190
 
931
1191
  Returns:
932
1192
  None
933
1193
 
934
1194
  Raises:
935
- ValueError: If the mode is not 0, 1.
1195
+ ValueError: If invalid mode string provided
936
1196
 
937
1197
  Example:
938
1198
  >>> ft = FlashTool()
939
- >>> ft.select_FlashTool_current_sensor_mode(0)
1199
+ >>> ft.select_FlashTool_current_sensor_mode("disable")
1200
+ >>> ft.select_FlashTool_current_sensor_mode("enable")
940
1201
  """
941
- mode = np.uint8(mode)
942
- valid_modes = {np.uint8(0), np.uint8(1)}
943
- if mode not in valid_modes:
944
- raise ValueError(f"Invalid mode: {mode}. Must be one of the {valid_modes} (0: CURRENT_SENSOR_MODE_DISABLE, 1: \
945
- CURRENT_SENSOR_MODE_ENABLE).")
946
-
947
- mode_descriptions = {
948
- 0: "CURRENT_SENSOR_MODE_DISABLE",
949
- 1: "CURRENT_SENSOR_MODE_ENABLE"
1202
+ mode_mapping = {
1203
+ "disable": (0, "CURRENT_SENSOR_MODE_DISABLE"),
1204
+ "enable": (1, "CURRENT_SENSOR_MODE_ENABLE")
950
1205
  }
951
- logger.info(f"Selected current sensor mode: {mode} - {mode_descriptions[mode]}")
952
1206
 
953
- tx_row = bytes.fromhex(generate_hex_line(0, UartCmd.CMD_SELECT_FLASHTOOL_CURRENT_SENSOR_MODE, [mode])[1:])
954
- logger.debug(tx_row.hex())
1207
+ if mode not in mode_mapping:
1208
+ valid_modes = list(mode_mapping.keys())
1209
+ raise ValueError(f'Invalid mode: "{mode}". Must be one of: {valid_modes}')
1210
+
1211
+ mode_num, mode_desc = mode_mapping[mode]
1212
+ logger.info(f"Selected current sensor mode: {mode_num} - {mode_desc}")
1213
+
1214
+ tx_row = bytes.fromhex(generate_hex_line(0, UartCmd.CMD_SELECT_FLASHTOOL_CURRENT_SENSOR_MODE, [mode_num])[1:])
1215
+ logger.debug(f"Current sensor mode command: {tx_row.hex()}")
955
1216
  self.__port.reset_output_buffer()
956
1217
  self.__port.write(tx_row)
957
1218
  self.__port.flush()
958
1219
 
959
- def select_spi_ch1_mode(self, mode: np.uint8) -> None:
1220
+ def select_spi_ch1_mode(self, mode: Literal["lenz_biss", "lir_ssi", "lir_biss_21b"]) -> None:
960
1221
  """
961
1222
  Select SPI channel 1 mode.
962
1223
 
963
1224
  Sends a SELECT channel 1 SPI mode command to the FlashTool.
964
1225
 
965
- There are three modes:
966
- 0 --> CH1_LENZ_BISS;
967
- 1 --> CH1_LIR_SSI;
968
- 2 --> CH1_LIR_BISS_21B
1226
+ Available modes:
1227
+ "lenz_biss" - CH1_LENZ_BISS (0)
1228
+ "lir_ssi" - CH1_LIR_SSI (1)
1229
+ "lir_biss_21b" - CH1_LIR_BISS_21B (2)
969
1230
 
970
1231
  Args:
971
- mode (uint8): The mode number (must be 0 or 1 or 2).
1232
+ mode: SPI channel 1 mode as descriptive string:
1233
+ - "lenz_biss" (0: CH1_LENZ_BISS)
1234
+ - "lir_ssi" (1: CH1_LIR_SSI)
1235
+ - "lir_biss_21b" (2: CH1_LIR_BISS_21B)
972
1236
 
973
1237
  Returns:
974
1238
  None
975
1239
 
976
1240
  Raises:
977
- ValueError: If the mode is not 0 or 1 or 2.
1241
+ ValueError: If invalid mode string provided
978
1242
 
979
1243
  Example:
980
1244
  >>> ft = FlashTool()
981
- >>> ft.select_spi_ch1_mode(0)
982
- """
983
- mode = np.uint8(mode)
984
- valid_channels = {np.uint8(0), np.uint8(1), np.uint8(2)}
985
- if mode not in valid_channels:
986
- raise ValueError(f"Invalid mode: {mode}. Must be one of the {valid_channels} (0: CH1_LENZ_BISS, 1: \
987
- CH1_LIR_SSI, 2: CH1_LIR_BISS_21B).")
988
-
989
- channel_descriptions = {
990
- 0: "CH1_LENZ_BISS",
991
- 1: "CH1_LIR_SSI",
992
- 2: "CH1_LIR_BISS_21B"
1245
+ >>> ft.select_spi_ch1_mode("lenz_biss")
1246
+ >>> ft.select_spi_ch1_mode("lir_ssi")
1247
+ """
1248
+ mode_mapping = {
1249
+ "lenz_biss": (0, "CH1_LENZ_BISS"),
1250
+ "lir_ssi": (1, "CH1_LIR_SSI"),
1251
+ "lir_biss_21b": (2, "CH1_LIR_BISS_21B")
993
1252
  }
994
- logger.info(f"Selected SPI channel 1 Mode: {mode} - {channel_descriptions[mode]}")
995
1253
 
996
- tx_row = bytes.fromhex(generate_hex_line(0, UartCmd.CMD_SELECT_CH1_MODE, [mode])[1:])
997
- # logger.debug(tx_row)
1254
+ if mode not in mode_mapping:
1255
+ valid_modes = list(mode_mapping.keys())
1256
+ raise ValueError(f'Invalid mode: "{mode}". Must be one of: {valid_modes}')
1257
+
1258
+ mode_num, mode_desc = mode_mapping[mode]
1259
+ logger.info(f"Selected SPI channel 1 Mode: {mode_num} - {mode_desc}")
1260
+
1261
+ tx_row = bytes.fromhex(generate_hex_line(0, UartCmd.CMD_SELECT_CH1_MODE, [mode_num])[1:])
1262
+ # logger.debug(f"ch1 mode: {tx_row.hex()}")
998
1263
  self.__port.reset_output_buffer()
999
1264
  self.__port.write(tx_row)
1000
1265
  self.__port.flush()
@@ -1845,7 +2110,7 @@ class FlashTool:
1845
2110
  enc_data_np = np.array(list(enc_ans), dtype='uint8')
1846
2111
 
1847
2112
  if (enc_data_np[0] != enc_data_np.size - UartCmd.PKG_INFO_LENGTH) or \
1848
- (enc_data_np[3] != UartCmd.HEX_READ_ENC2_CURRENT + UartCmd.CMD_VAL_ADD):
2113
+ (enc_data_np[3] != UartCmd.HEX_READ_ENC2_CURRENT + UartCmd.CMD_VAL_ADD):
1849
2114
  logger.error("Invalid response structure from encoder!")
1850
2115
  return False
1851
2116
 
@@ -1868,9 +2133,9 @@ class FlashTool:
1868
2133
  logger.error(f"Error reading encoder current: {str(e)}", exc_info=True)
1869
2134
  return False
1870
2135
 
1871
- def read_current_angle_enc_SPI(self) -> tuple[str, list[int]] | bool:
2136
+ def read_instant_angle_enc_SPI(self) -> tuple[str, list[int]] | bool:
1872
2137
  """
1873
- Read current angle encoder via SPI over USB.
2138
+ Read instant angle encoder via SPI over USB.
1874
2139
 
1875
2140
  Returns:
1876
2141
  tuple[str, list[int]]: If successful, returns:
@@ -1886,7 +2151,7 @@ class FlashTool:
1886
2151
  try:
1887
2152
  self.__port.reset_output_buffer()
1888
2153
  self.__port.reset_input_buffer()
1889
- self.__port.write(generate_byte_line(0, UartCmd.HEX_READ_CURRENT_ANGLE_ENC_SPI, list(range(RX_DATA_LENGTH))))
2154
+ self.__port.write(generate_byte_line(0, UartCmd.HEX_READ_INSTANT_ANGLE_ENC_SPI, list(range(RX_DATA_LENGTH))))
1890
2155
  self.__port.flush()
1891
2156
 
1892
2157
  enc_ans = self.__port.read(RX_DATA_LENGTH + PKG_INFO_LENGTH)
@@ -1899,7 +2164,7 @@ class FlashTool:
1899
2164
  enc_data_np = np.array(list(enc_ans), dtype='uint8')
1900
2165
 
1901
2166
  if (enc_data_np[0] != enc_data_np.size - PKG_INFO_LENGTH) or \
1902
- (enc_data_np[3] != UartCmd.HEX_READ_CURRENT_ANGLE_ENC_SPI + CMD_VAL_ADD):
2167
+ (enc_data_np[3] != UartCmd.HEX_READ_INSTANT_ANGLE_ENC_SPI + CMD_VAL_ADD):
1903
2168
  logger.error("Invalid response structure from IRS encoder!")
1904
2169
  return False
1905
2170