lenz-flashtool 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,68 @@
1
+ """
2
+
3
+ FlashTool library for BiSS C Firmware Update and Calibration.
4
+
5
+ This library provides functions for interfacing with BiSS C encoders using LENZ FlashTool, performing firmware updates,
6
+ and executing calibration routines.
7
+
8
+ Author:
9
+ LENZ ENCODERS, 2020-2025
10
+ """
11
+
12
+ #
13
+ # r'''
14
+ # _ _____ _ _ _____ _____ _ _ ____ ___ ____ _____ ____ ____
15
+ # | | | ____| \ | |__ / | ____| \ | |/ ___/ _ \| _ \| ____| _ \/ ___|
16
+ # | | | _| | \| | / / | _| | \| | | | | | | | | | _| | |_) \___ \
17
+ # | |___| |___| |\ |/ /_ | |___| |\ | |__| |_| | |_| | |___| _ < ___) |
18
+ # |_____|_____|_| \_/____| |_____|_| \_|\____\___/|____/|_____|_| \_|____/
19
+ # '''
20
+
21
+ from .utils import plot, plot2, TermColors
22
+ from .biss import (
23
+ ERROR_FLAGS, BISS_COMMANDSTATE, biss_commands, BiSSBank
24
+ )
25
+ from .flashtool import (
26
+ UartCmd,
27
+ FlashTool,
28
+ FlashToolError,
29
+ generate_hex_line,
30
+ init_logging,
31
+ get_nonce,
32
+ _readhex,
33
+ biss_send_hex,
34
+ biss_send_dif
35
+ )
36
+ from .testing import MockFlashTool
37
+ from .encproc import LenzEncoderProcessor
38
+
39
+ __all__ = [
40
+ # Constants
41
+ 'ERROR_FLAGS',
42
+ 'BISS_COMMANDSTATE',
43
+ 'biss_commands',
44
+ 'BiSSBank',
45
+
46
+ # Command constants
47
+ 'UartCmd',
48
+
49
+ # Core classes
50
+ 'FlashTool',
51
+ 'FlashToolError',
52
+ 'MockFlashTool',
53
+ 'LenzEncoderProcessor',
54
+
55
+ # Utility functions and classes
56
+ 'generate_hex_line',
57
+ 'init_logging',
58
+ 'get_nonce',
59
+ '_readhex',
60
+ 'biss_send_dif',
61
+ 'biss_send_hex',
62
+ 'plot',
63
+ 'plot2',
64
+ 'TermColors'
65
+ ]
66
+
67
+ __version__ = "0.1.0"
68
+ __author__ = "LENZ ENCODERS"
@@ -0,0 +1,42 @@
1
+ """
2
+
3
+ LENZ BiSS Protocol Implementation
4
+
5
+ Provides BiSS encoder protocol standarts and utilities.
6
+
7
+ Author:
8
+ LENZ ENCODERS, 2020-2025
9
+ """
10
+
11
+ #
12
+ # r'''
13
+ # _ _____ _ _ _____ _____ _ _ ____ ___ ____ _____ ____ ____
14
+ # | | | ____| \ | |__ / | ____| \ | |/ ___/ _ \| _ \| ____| _ \/ ___|
15
+ # | | | _| | \| | / / | _| | \| | | | | | | | | | _| | |_) \___ \
16
+ # | |___| |___| |\ |/ /_ | |___| |\ | |__| |_| | |_| | |___| _ < ___) |
17
+ # |_____|_____|_| \_/____| |_____|_| \_|\____\___/|____/|_____|_| \_|____/
18
+ #
19
+
20
+ from .commands import (
21
+ BISS_COMMANDSTATE,
22
+ ERROR_FLAGS,
23
+ biss_commands,
24
+ interpret_biss_commandstate,
25
+ interpret_error_flags
26
+ )
27
+ from .crc import biss_crc6_calc
28
+ from .registers import (
29
+ BiSSBank,
30
+ )
31
+
32
+ __all__ = [
33
+ 'BISS_COMMANDSTATE',
34
+ 'ERROR_FLAGS',
35
+ 'biss_commands',
36
+ 'interpret_biss_commandstate',
37
+ 'interpret_error_flags',
38
+
39
+ 'biss_crc6_calc',
40
+
41
+ 'BiSSBank'
42
+ ]
@@ -0,0 +1,391 @@
1
+ """
2
+
3
+ LENZ BiSS Encoder Command Line Interface Module
4
+
5
+ Provides a command-line interface for interacting with LENZ BiSS encoders through
6
+ the FlashTool library. Supports all major device operations including register access,
7
+ command execution, and device information reading.
8
+
9
+ Features:
10
+
11
+ - Direct register reading (single/bank/range)
12
+ - Predefined command execution
13
+ - Raw hex command sending
14
+ - Serial number and device info reading
15
+ - Comprehensive error handling
16
+ - Sending hex files to the encoder
17
+
18
+ Usage:
19
+ >>> python -m lenz_flashtool.biss.cli <command> [arguments]
20
+
21
+ Example Commands:
22
+ >>> python -m lenz_flashtool.biss.cli run
23
+ >>> python -m lenz_flashtool.biss.cli registers 2
24
+ >>> python -m lenz_flashtool.biss.cli reg 0x02 0x10
25
+ >>> python -m lenz_flashtool.biss.cli hex 41 82 AA55FF
26
+ >>> python -m lenz_flashtool.biss.cli readserial
27
+ >>> python -m lenz_flashtool.biss.cli sendhexfile SAB039_1_1_4.hex
28
+ """
29
+ #
30
+ # r'''
31
+ # _ _____ _ _ _____ _____ _ _ ____ ___ ____ _____ ____ ____
32
+ # | | | ____| \ | |__ / | ____| \ | |/ ___/ _ \| _ \| ____| _ \/ ___|
33
+ # | | | _| | \| | / / | _| | \| | | | | | | | | | _| | |_) \___ \
34
+ # | |___| |___| |\ |/ /_ | |___| |\ | |__| |_| | |_| | |___| _ < ___) |
35
+ # |_____|_____|_| \_/____| |_____|_| \_|\____\___/|____/|_____|_| \_|____/
36
+ #
37
+
38
+ import sys
39
+ import logging
40
+ import time
41
+ from typing import List
42
+ from ..flashtool import FlashTool, biss_send_hex
43
+ from ..flashtool import generate_hex_line
44
+ from ..utils.termcolors import TermColors
45
+ from . import (
46
+ BiSSBank,
47
+ biss_commands
48
+ )
49
+ try:
50
+ import colorama
51
+ colorama.init()
52
+ except ImportError:
53
+ pass
54
+
55
+
56
+ class BiSSCommandLine:
57
+ """Command line interface for BiSS encoder operations"""
58
+
59
+ def __init__(self, flashtool: FlashTool):
60
+ """
61
+ Initialize with a FlashTool instance
62
+
63
+ Args:
64
+ flashtool: Initialized FlashTool object
65
+ """
66
+ self.ft = (flashtool
67
+ .register_cleanup(self._script_cleanup)
68
+ .enable_signal_handling())
69
+ self.logger = logging.getLogger(__name__)
70
+ self.exit_flag = False
71
+
72
+ def _script_cleanup(self):
73
+ """Cleanup function"""
74
+ # Get rid of logging level reset
75
+ logging.getLogger('lenz_flashtool.flashtool.core').setLevel(logging.WARNING)
76
+
77
+ logging.info('Performing script cleanup...')
78
+
79
+ print('', end="\n", flush=True)
80
+ # logging.info('Ctrl-c was pressed. Wrapping up...')
81
+ self.exit_flag = True # Set the flag to exit the loop
82
+
83
+ def _show_usage(self, script_name: str) -> None:
84
+ """Display command usage information"""
85
+ print("LENZ BiSS Encoder Command Line Interface\n")
86
+ print(f"Usage: {script_name} <command> [arguments]\n")
87
+ print("Available commands:")
88
+ for cmd, (_, desc) in biss_commands.items():
89
+ print(f" {cmd.ljust(14)} - {desc}")
90
+ print("\nRegister Access:")
91
+ print(" registers [bank] - Read all registers in specified bank (default: service bank 2)")
92
+ print(" reg <addr> <len> - Read specific register(s) at hex address with byte length")
93
+ print(" Example: reg 0x1A 2 - Reads 2 bytes from address 0x1A")
94
+ print(" regb <bank> <addr> <len> - Read registers in specified bank at hex address")
95
+ print(" Example: regb 1 0x10 4 - Reads 4 bytes from BiSS C bank")
96
+ print("\nDevice Information:")
97
+ print(" readserial - Read encoder serial number, manufacturing date, device ID, and firmware version")
98
+ print(" readhsi - Read hardware status indicator")
99
+ print("\nAdvanced Operation:")
100
+ print(" hex <addr> <cmd> <data> - Send custom hexadecimal FlashTool command sequence")
101
+ print(" Format: <target_addr> <command_byte> <data_bytes...>")
102
+ print(" Examples: hex 0x0 0x0B 0x10 - Turn off power of first channel")
103
+ print(" hex 0x40 0x82 0x11 - Read 0x40 register, any <data> defines lenght.")
104
+ print(" hex 0x40 0x82 0x1111 - Read 0x40 and 0x41 registers, ")
105
+ print(" <data> used only for length.")
106
+ print(" sendhexfile <filename> - Send a hex file to the encoder")
107
+ print(" Example: sendhexfile SAB039_1_1_4.hex")
108
+
109
+ def execute_command(self, args: List[str]) -> None:
110
+ """
111
+ Execute a command provided via command-line arguments.
112
+
113
+ Supports a wide range of operations with LENZ BiSS encoders through the FlashTool
114
+ backend. This function serves as the central dispatcher for interpreting CLI
115
+ arguments and executing the appropriate action.
116
+
117
+ Args:
118
+ args (List[str]): A list of command-line arguments (typically from sys.argv).
119
+
120
+ Supported Commands:
121
+ run
122
+ - Description: Runs the encoder or initiates default operational mode.
123
+ - Usage: run
124
+
125
+ registers [bank]
126
+ - Description: Reads all registers in a given bank.
127
+ - Default bank: 2 (service bank)
128
+ - Usage: registers # reads from bank 2
129
+ registers 1 # reads from bank 1
130
+
131
+ reg <addr> <len>
132
+ - Description: Reads a specific number of bytes from a register address.
133
+ - Address and length must be in hex or decimal format.
134
+ - Usage: reg 0x10 2 # reads 2 bytes from address 0x10
135
+
136
+ regb <bank> <addr> <len>
137
+ - Description: Reads registers from a specific bank and address.
138
+ - Usage: regb 1 0x10 4 # reads 4 bytes from address 0x10 in bank 1
139
+
140
+ hex <addr> <cmd> [data...]
141
+ - Description: Sends a raw command composed of address, command byte, and optional data bytes.
142
+ - The data is sent as-is and interpreted by the encoder.
143
+ - Usage:
144
+ hex 0x00 0x0B 0x10 # turns off power of first channel
145
+ hex 0x40 0x82 0x11 # reads one byte from register 0x40
146
+ hex 0x40 0x82 0x1122 # reads two bytes from 0x40 and 0x41
147
+ hex 0x80 0x91 # generic command with no data
148
+
149
+ readserial
150
+ - Description: Reads device serial number, date of manufacture, firmware version, and ID.
151
+ - Usage: readserial
152
+
153
+ readhsi
154
+ - Description: Reads the hardware status indicator.
155
+ - Usage: readhsi
156
+
157
+ sendhexfile <filename>
158
+ - Description: Sends a hex file to the encoder.
159
+ - Usage: sendhexfile <filename.hex>
160
+
161
+ <predefined command>
162
+ - Description: Executes a predefined command from the biss_commands registry.
163
+ - Examples:
164
+ run
165
+ ampcalibrate
166
+ reboot2bl
167
+ zeroing
168
+ - Use `_show_usage()` or run without arguments to list all predefined commands.
169
+
170
+ Raises:
171
+ ValueError: If arguments are missing or invalid.
172
+ FlashToolError: On communication or device interaction failure.
173
+
174
+ Notes:
175
+ - All addresses and data bytes can be in either hexadecimal (0xNN) or decimal (NN) format.
176
+ - The method logs each step and captures errors for user-friendly CLI output.
177
+ """
178
+
179
+ if len(args) < 2:
180
+ self._show_usage(args[0])
181
+ sys.exit(1)
182
+
183
+ command = args[1].lower()
184
+
185
+ try:
186
+ if command in biss_commands:
187
+ self._send_biss_command(command)
188
+ elif command == "registers":
189
+ self._read_registers(args)
190
+ elif command == "flags":
191
+ self._read_flags()
192
+ elif command == "ctv":
193
+ self._ctv()
194
+ elif command == "reg":
195
+ self._read_register(args)
196
+ elif command == "regb":
197
+ self._read_bank_register(args)
198
+ elif command == "hex":
199
+ self._send_hex(args)
200
+ elif command == "readserial":
201
+ self._read_serial()
202
+ elif command == "readhsi":
203
+ self._read_hsi()
204
+ elif command == "angle":
205
+ self._read_angle_once()
206
+ elif command == "angleloop":
207
+ self._read_angle_loop()
208
+ elif command == "sendhexfile":
209
+ self._send_hex_file(args)
210
+ else:
211
+ raise ValueError(f"Unknown command: {command}")
212
+ except ValueError as e:
213
+ self.logger.error("Invalid input: %s", e)
214
+ self._show_usage(args[0])
215
+ sys.exit(1)
216
+ except Exception as e:
217
+ self.logger.error("Operation failed: %s", e)
218
+ sys.exit(1)
219
+
220
+ def _send_biss_command(self, command: str) -> None:
221
+ """Send a predefined BiSS command"""
222
+ cmd_data = [
223
+ biss_commands[command][0] & 0xFF,
224
+ (biss_commands[command][0] >> 8) & 0xFF
225
+ ]
226
+ self.ft.biss_write_word(BiSSBank.CMD_REG_INDEX, 0, cmd_data)
227
+ time.sleep(0.3)
228
+ self.ft.biss_read_flags()
229
+
230
+ def _read_registers(self, args: List[str]) -> None:
231
+ """Read all registers in specified bank"""
232
+ bank = int(args[2]) if len(args) > 2 else 2 # Default to service bank
233
+ self.ft.biss_read_registers(bank)
234
+
235
+ def _read_flags(self) -> None:
236
+ """Read and display status flags"""
237
+ flags, cmd_state = self.ft.biss_read_flags()
238
+ print("\nDevice Status:")
239
+ print("-" * 40)
240
+ for flag in flags:
241
+ print(f" {flag}")
242
+ print(f"\nCommand State: {cmd_state[0]}")
243
+ print("-" * 40)
244
+
245
+ def _ctv(self) -> None:
246
+ """Read and display calibration, temperature and Vcc data"""
247
+ self.ft.biss_read_calibration_temp_vcc()
248
+
249
+ def _read_register(self, args: List[str]) -> None:
250
+ """Read specific register range"""
251
+ if len(args) < 3:
252
+ raise ValueError("Usage: reg <address> <length>")
253
+
254
+ address = self._parse_hex(args[2])
255
+ length = self._parse_hex(args[3]) if len(args) > 3 else 1 # default one register
256
+
257
+ print(f"\nReading registers {hex(address)}-{hex(address + length - 1)}:")
258
+ result = self.ft.biss_addr_read(address, length)
259
+ self._print_register_data(result)
260
+
261
+ def _read_bank_register(self, args: List[str]) -> None:
262
+ """Read registers in specific bank"""
263
+ if len(args) < 4:
264
+ raise ValueError("Usage: regb <bissbank> <address> <length>")
265
+
266
+ bank = self._parse_hex(args[2])
267
+ address = self._parse_hex(args[3])
268
+ length = self._parse_hex(args[4]) if len(args) > 4 else 1 # default one register
269
+
270
+ print(f"\nReading bank {bank}, registers {hex(address)}-{hex(address + length - 1)}:")
271
+ result = self.ft.biss_addr_readb(bank, address, length)
272
+ self._print_register_data(result)
273
+
274
+ def _send_hex(self, args: List[str]) -> None:
275
+ """Send raw hex command"""
276
+ if len(args) < 5:
277
+ raise ValueError("Usage: hex <address> <command> <data_hex_str>")
278
+
279
+ address = self._parse_hex(args[2])
280
+ command = self._parse_hex(args[3])
281
+ hex_str = args[4].replace('0x', '').replace(' ', '')
282
+
283
+ try:
284
+ data = bytes.fromhex(hex_str)
285
+ except ValueError:
286
+ raise ValueError("Invalid hex string format")
287
+
288
+ hex_line = generate_hex_line(address, command, data)
289
+ print("Sending hex line: %s", hex_line)
290
+ self.ft.hex_line_send(hex_line)
291
+
292
+ if len(data) > 0:
293
+ print("\nTrying to read response data...")
294
+ response = self.ft.port_read(len(data)) # +1 for checksum
295
+ self._print_register_data(response)
296
+
297
+ def _read_serial(self) -> None:
298
+ """Read device serial information"""
299
+ bootloader, serial, mfg_date, program = self.ft.biss_read_snum()
300
+
301
+ print("\nDevice Information:")
302
+ print("-" * 40)
303
+ print(f"Serial Number: \t {serial}")
304
+ print(f"Firmware Version:\t {program}")
305
+ print(f"Manufacture Date:\t {mfg_date}")
306
+ print(f"Bootloader: \t {bootloader}")
307
+ print("-" * 40)
308
+
309
+ def _read_hsi(self) -> None:
310
+ """Read hardware status indicator"""
311
+ hsi = self.ft.biss_read_HSI()
312
+ print(f"\n{TermColors.Green}HSI: {hsi}{TermColors.ENDC}")
313
+
314
+ def _read_angle_once(self) -> None:
315
+ """Read angle"""
316
+ self.ft.biss_read_angle_once()
317
+
318
+ def _read_angle_loop(self) -> None:
319
+ """Read angle in loop"""
320
+ degree_sign = "\N{DEGREE SIGN}"
321
+ res = 2**24
322
+ while not self.exit_flag:
323
+ _, ans = self.ft.read_data_enc1_enc2_SPI(0.01, False)
324
+ if self.exit_flag: # Check the flag immediately after reading
325
+ break
326
+ ang = int(ans[0]) * 360 / res
327
+ degrs = int(ang)
328
+ mins = int((ang - degrs) * 60)
329
+ secs = int((ang - degrs - (mins / 60)) * 3600)
330
+ self._std(ans[0], degrs, degree_sign, mins, secs)
331
+
332
+ def _send_hex_file(self, args: List[str]) -> None:
333
+ """Send a hex file to the encoder"""
334
+ if len(args) < 3:
335
+ raise ValueError("Usage: sendhexfile <filename> [pbar]")
336
+
337
+ filename = args[2]
338
+ pbar = len(args) > 3 and args[3].lower() in ('true', '1', 't', 'y', 'yes')
339
+
340
+ print(f"\nSending hex file: {filename} (Progress bar: {'enabled' if pbar else 'disabled'})")
341
+ biss_send_hex(filename, pbar=pbar)
342
+ print(f"Successfully sent hex file: {filename}")
343
+
344
+ @staticmethod
345
+ def _std(ans2, degrs, degree_sign, mins, secs):
346
+ """stdout format"""
347
+ sys.stdout.write("\r" + f'[{ans2}]: \t {str(degrs):>3}{degree_sign} {str(mins):2}\' {str(secs):2}\"' + '\t\t')
348
+ sys.stdout.flush()
349
+
350
+ def _parse_hex(self, value: str) -> int:
351
+ """Safely parse hex or decimal string"""
352
+ try:
353
+ return int(value, 16 if value.startswith('0x') else 10)
354
+ except ValueError:
355
+ raise ValueError(f"Invalid number format: {value}")
356
+
357
+ def _print_register_data(self, data) -> None:
358
+ """Format register data for display"""
359
+ print(f'{TermColors.Green}{data}{TermColors.ENDC}')
360
+ if hasattr(data, 'tolist'): # numpy array
361
+ data = data.tolist()
362
+
363
+ for i, byte in enumerate(data):
364
+ print(f"{TermColors.DarkGray}{i:04X}: {byte:02X} ({byte:3d}){TermColors.ENDC}")
365
+
366
+
367
+ def main():
368
+ """Command line entry point, making the library script executes directly:
369
+ >>> python -m lenz_flashtool.biss.cli <command>
370
+ """
371
+ import lenz_flashtool as lenz
372
+
373
+ # Configure logging
374
+ lenz.init_logging(
375
+ # TODO review each function's output and change stdout_level to .WARNING
376
+ logfilename='biss_cli.log',
377
+ stdout_level=logging.DEBUG,
378
+ file_level=logging.DEBUG
379
+ )
380
+
381
+ try:
382
+ with lenz.FlashTool() as ft:
383
+ cli = BiSSCommandLine(ft)
384
+ cli.execute_command(sys.argv)
385
+ except Exception as e:
386
+ logging.critical("Fatal error: %s", e)
387
+ sys.exit(1)
388
+
389
+
390
+ if __name__ == "__main__":
391
+ main()
@@ -0,0 +1,157 @@
1
+ r'''
2
+ _ _____ _ _ _____ _____ _ _ ____ ___ ____ _____ ____ ____
3
+ | | | ____| \ | |__ / | ____| \ | |/ ___/ _ \| _ \| ____| _ \/ ___|
4
+ | | | _| | \| | / / | _| | \| | | | | | | | | | _| | |_) \___ \
5
+ | |___| |___| |\ |/ /_ | |___| |\ | |__| |_| | |_| | |___| _ < ___) |
6
+ |_____|_____|_| \_/____| |_____|_| \_|\____\___/|____/|_____|_| \_|____/
7
+
8
+
9
+ BiSS Encoder Commands Interface Module
10
+
11
+ This module provides constants and functions for interacting with BiSS encoder devices,
12
+ specifically focused on command interpretation and error flag decoding.
13
+
14
+ Key Components:
15
+ - ERROR_FLAGS: Dictionary mapping bit positions to error flag descriptions
16
+ - BISS_COMMANDSTATE: Dictionary mapping state integers to command state descriptions
17
+ - biss_commands: Dictionary of supported BiSS commands with opcodes and descriptions
18
+
19
+ Functions:
20
+ - interpret_biss_commandstate(): Decodes integer state values into human-readable strings
21
+ - interpret_error_flags(): Converts bitmask error values into list of active error flags
22
+
23
+ Usage Examples:
24
+ >>> interpret_biss_commandstate(5)
25
+ ['BISS_COMMANDSTATE_OTP_SERDATE_CRC_OK']
26
+
27
+ >>> interpret_error_flags(0x105) # Bits 0 and 8 set
28
+ ['FLAGS_FW_CRC32_CHECK_FAIL', 'FLAGS_KEY_NULL']
29
+
30
+ Error Flag Notes:
31
+ - Error flags use bitmask representation where each bit corresponds to a specific error
32
+ - Multiple flags can be active simultaneously
33
+ - Flag descriptions indicate various hardware and firmware conditions
34
+
35
+ Command State Notes:
36
+ - Represents the current operational state of the BiSS encoder
37
+ - Includes states for firmware updates, CRC checks, and device initialization
38
+
39
+ Command Reference:
40
+ - The biss_commands dictionary provides complete command documentation including:
41
+ - Hexadecimal opcodes
42
+ - Detailed functional descriptions
43
+ - Permanent vs temporary operation indicators
44
+ - Configuration vs operational commands
45
+
46
+ Security Considerations:
47
+ - Several commands perform permanent OTP (One-Time Programmable) operations
48
+ - Flash memory operations require explicit unlock sequences
49
+ - Device contains secure elements for key storage and validation
50
+
51
+ Author:
52
+ LENZ ENCODERS, 2020-2025
53
+ '''
54
+ ERROR_FLAGS = {
55
+ 0: "FLAGS_FW_CRC32_CHECK_FAIL",
56
+ 1: "FLAGS_FLASH_FW_ERROR",
57
+ 2: "FLAGS_STARTUP_ERROR",
58
+ 3: "FLAGS_BL_CRC32_CHECK_FAIL",
59
+ 4: "FLAGS_STAY_IN_BL",
60
+ 5: "FLAGS_OTP_SERIAL_DATE_ERROR",
61
+ 6: "FLAGS_OTP_DEVID_ERROR",
62
+ 7: "FLAGS_DEVID_NULL",
63
+ 8: "FLAGS_FLASH_KEY_ERROR",
64
+ 9: "FLAGS_KEY_NULL",
65
+ 10: "FLAGS_RDP_AA",
66
+ 11: "FLAGS_BISS_ERR",
67
+ 12: "FLAGS_BISS_WARN",
68
+ }
69
+
70
+ BISS_COMMANDSTATE = {
71
+ 0: "BISS_COMMANDSTATE_IDLE",
72
+ 2: "BISS_COMMANDSTATE_FLASH_FW_CRC_OK",
73
+ 3: "BISS_COMMANDSTATE_FLASH_FW_CRC_FAULT",
74
+ 4: "BISS_COMMANDSTATE_FW_CHECK_CRC32_FAULT",
75
+ 5: "BISS_COMMANDSTATE_OTP_SERDATE_CRC_OK",
76
+ 6: "BISS_COMMANDSTATE_OTP_SERDATE_CRC_FAULT",
77
+ 7: "BISS_COMMANDSTATE_FLASH_KEY_CRC_OK",
78
+ 8: "BISS_COMMANDSTATE_FLASH_KEY_CRC_FAULT",
79
+ 9: "BISS_COMMANDSTATE_FLASH_KEY_NULL",
80
+ 10: "BISS_COMMANDSTATE_OTP_DEVID_CRC_OK",
81
+ 11: "BISS_COMMANDSTATE_OTP_DEVID_CRC_FAULT",
82
+ 12: "BISS_COMMANDSTATE_FLASH_FW_NULL",
83
+ 240: "BISS_COMMANDSTATE_BSY_START",
84
+ 255: "BISS_COMMANDSTATE_FLASH_BSY"
85
+ }
86
+
87
+ biss_commands = {
88
+ 'non': (0x0000, "No operation command. Device remains in current state with no action taken."),
89
+ 'load2k': (0x0107, "Load 2 KB of data from registers into device memory. Used for firmware updates."),
90
+ 'staybl': (0x020E, "Force device to stay in bootloader mode. Prevents automatic transition to application mode "
91
+ "for extended maintenance operations."),
92
+ 'run': (0x0309, "Exit bootloader mode and execute the main application program. Initiates normal encoder operation."),
93
+ 'zeroing': (0x041C, "Perform encoder zeroing procedure. Resets position counter to zero at current mechanical position."),
94
+ 'set_dir_cw': (0x051B, "Configure encoder direction sensing for clockwise rotation. "
95
+ "Position values will increase when rotating clockwise."),
96
+ 'set_dir_ccw': (0x0612, "Configure encoder direction sensing for counterclockwise rotation. Position values will increase "
97
+ "when rotating counterclockwise."),
98
+ 'saveflash': (0x0838, "Commit current configuration parameters to flash memory. All settings will persist after "
99
+ "power cycle."),
100
+ 'ampcalibrate': (0x0A36, "Initiate amplitude calibration routine. Automatically adjusts signal amplitudes."),
101
+ 'cleardiflut': (0x0B31, "Clear differential lookup table (DifLUT). Resets all offset compensation values to default state."),
102
+ 'setfastbiss': (0x0C24, "Enable high-speed BiSS communication mode. Increases data transmission rate at the cost of "
103
+ "potential reduced noise immunity."),
104
+ 'setdefbiss': (0x0D23, "Revert to standard BiSS communication mode. Provides robust communication with standard "
105
+ "timing parameters."),
106
+ 'reboot': (0x0F2D, "Perform device reboot."),
107
+ 'reboot2bl': (0x1070, "Reboot device directly into bootloader mode. Enables firmware update and configuration procedures "
108
+ "without external hardware intervention"),
109
+ 'loadseriald': (0x1177, "Write serial number and manufacturing date to OTP memory. This operation is permanent and "
110
+ "cannot be reversed."),
111
+ 'loaddevid': (0x146C, "Program DevID into OTP memory. This operation is permanent and cannot be reversed."),
112
+ 'loadkey': (0x1379, "Store key in secure flash memory. Used for secure communication and firmware validation."),
113
+ 'savediftable': (0x156B, "Save differential compensation table to memory. Preserves signal integrity calibration across "
114
+ "power cycles."),
115
+ 'unlockflash': (0x1662, "Enable write access to protected flash memory regions. Required before performing configuration "
116
+ "changes."),
117
+ 'unlocksetup': (0x1D53, 'Disable configuration write protection. Allows modification of sensitive device parameters.'),
118
+ 'enarccal': (0x1E5A, 'Enable arc-based calibration mode. Prepares device for angular position calibration procedures.'),
119
+ 'clearcalflash': (0x1F5D, 'Erase all high-speed oscillator (HSI) and differential calibration data from flash.'),
120
+ }
121
+
122
+
123
+ def interpret_biss_commandstate(state_int: int) -> list:
124
+ """
125
+ Interpret a given integer as a BiSS command state.
126
+
127
+ Args:
128
+ state_int (int): An integer representing the current command state.
129
+
130
+ Returns:
131
+ List[str]: A list containing the description of the current command state.
132
+ If the state is not recognized, returns ["Unknown state"].
133
+ """
134
+ state_description = BISS_COMMANDSTATE.get(state_int, "Unknown state")
135
+ return [state_description]
136
+
137
+
138
+ def interpret_error_flags(error_int: int) -> list:
139
+ """
140
+ Interpret a given integer as a set of error flags.
141
+
142
+ Args:
143
+ error_int (int): An integer where each bit represents a different error flag.
144
+
145
+ Returns:
146
+ List[str]: A list of active error flags based on the set bits in the input integer.
147
+ If no flags are set, returns ["No error flags set"].
148
+ """
149
+ active_flags = []
150
+
151
+ for bit_pos, flag_name in ERROR_FLAGS.items():
152
+ if error_int & (1 << bit_pos):
153
+ active_flags.append(flag_name)
154
+
155
+ if active_flags:
156
+ return active_flags
157
+ return ["No error flags set"]