api module
The api module provides classes to connect and communicate with nanoOCM devices.
The main class in the module is OCM. It represents the connection with a nanoOCM and provides functions to send read/write commands.
The OCM class is a direct expansion of the serial_api.SerialModule class defined in the serial_api module.
It inherits all the functions and properties from serial_api.SerialModule and adds specific read/write commands for the nanoOCM registers.
- Device connection:
Use
OCM.get_serial_ports()to get a list of the available serial communication ports on the PC.Create an OCM object by instantiating the class:
ocm = OCM(com_port="COM1", baud_rate=SerialBaudRates.Baud_115200).Use
OCM.connect()to open the serial connection with the device andOCM.disconnect()to close it.
- Register-specific read/write command functions:
Use functions
OCM.read_reg_<REG NAME>()andOCM.write_reg_<REG NAME>()to read and write data from/to the device internal registers, as defined in the nanoOCM firmware user guide.These functions provide a customized interface for every register, with specific data types, error handling, automatic multibyte transfers when necessary, and additional features like waiting for pending commands to complete or waiting for one-shot scans to complete.
- Low-level register read/write commands:
Use
OCM.read_register()andOCM.write_register()to read and write raw data from/to individual device internal registers.Use
OCM.read_bytes()andOCM.write_bytes()to read and write raw data from/to device registers that require multibyte data transfers (AEA).Use
OCM.read_string()andOCM.write_string()to read and write raw strings from/to device registers that require multibyte data transfers (AEA).
The api module also defines some enumerations, custom exceptions, and helper classes. Some of them are imported directly from serial_api for convenience.
- Registers Enumerations:
- Exceptions:
- Helper Enumerations:
- Helper classes:
- class api.SerialRegistersStatus(value)
Bases:
SerialRegistersRegister codes for firmware commands in the “Status” category.
- StatusF = 32
Fatal Status
- StatusW = 33
Warning Status
- CaseTemp = 35
Case Temperature
- FCaseTemp = 36
Fatal Case Temperature configuration
- WCaseTemp = 37
Warning Case Temperature configuration
- ALMT = 42
Alarm Triggers
- static get_composed_enum(*enum_classes: Type[SerialRegisters]) Type[SerialRegisters]
Return an Enum for the combined list of all the register codes supported by a specific device.
- Parameters:
*enum_classes (Type[SerialRegisters]) – Enum classes to combine.
- Returns:
A new Enum class combining all the provided Enum classes.
- Return type:
Type[SerialRegisters]
- conjugate()
Returns self, the complex conjugate of any int.
- bit_length()
Number of bits necessary to represent self in binary.
>>> bin(37) '0b100101' >>> (37).bit_length() 6
- bit_count()
Number of ones in the binary representation of the absolute value of self.
Also known as the population count.
>>> bin(13) '0b1101' >>> (13).bit_count() 3
- to_bytes(length, byteorder, *, signed=False)
Return an array of bytes representing an integer.
- length
Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
- signed
Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
- from_bytes(byteorder, *, signed=False)
Return the integer represented by the given array of bytes.
- bytes
Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
- signed
Indicates whether two’s complement is used to represent the integer.
- as_integer_ratio()
Return integer ratio.
Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.
>>> (10).as_integer_ratio() (10, 1) >>> (-10).as_integer_ratio() (-10, 1) >>> (0).as_integer_ratio() (0, 1)
- real
the real part of a complex number
- imag
the imaginary part of a complex number
- numerator
the numerator of a rational number in lowest terms
- denominator
the denominator of a rational number in lowest terms
- class api.SerialRegistersOptical(value)
Bases:
SerialRegistersRegister codes for firmware commands in the “Optical” category.
- ScanMode = 48
Scan Mode
- BootScanMode = 49
Boot Scan Mode
- GridMemIdx = 50
Grid Memory Index
- GridMem = 51
Grid Memory
- ActiveGridIdx = 52
Active Grid Index
- BootGridIdx = 53
Boot Grid Index
- ScanData = 54
Scan Data
- ScanInterval = 55
Scan Interval
- InputLosses = 56
Input Losses
- CrosstalkSuppression = 57
Crosstalk Suppression
- ScanFrequencies = 58
Scan Frequencies
- Reboot = 63
Reboot module
- static get_composed_enum(*enum_classes: Type[SerialRegisters]) Type[SerialRegisters]
Return an Enum for the combined list of all the register codes supported by a specific device.
- Parameters:
*enum_classes (Type[SerialRegisters]) – Enum classes to combine.
- Returns:
A new Enum class combining all the provided Enum classes.
- Return type:
Type[SerialRegisters]
- conjugate()
Returns self, the complex conjugate of any int.
- bit_length()
Number of bits necessary to represent self in binary.
>>> bin(37) '0b100101' >>> (37).bit_length() 6
- bit_count()
Number of ones in the binary representation of the absolute value of self.
Also known as the population count.
>>> bin(13) '0b1101' >>> (13).bit_count() 3
- to_bytes(length, byteorder, *, signed=False)
Return an array of bytes representing an integer.
- length
Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
- signed
Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
- from_bytes(byteorder, *, signed=False)
Return the integer represented by the given array of bytes.
- bytes
Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
- signed
Indicates whether two’s complement is used to represent the integer.
- as_integer_ratio()
Return integer ratio.
Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.
>>> (10).as_integer_ratio() (10, 1) >>> (-10).as_integer_ratio() (-10, 1) >>> (0).as_integer_ratio() (0, 1)
- real
the real part of a complex number
- imag
the imaginary part of a complex number
- numerator
the numerator of a rational number in lowest terms
- denominator
the denominator of a rational number in lowest terms
- class api.ScanModes(value)
Bases:
IntEnumEnumeration for the possible ScanModes accepted by the ScanMode and BootScanMode registers.
- Standby = 0
Standby mode - The module responds to serial commands, but it is in low-power mode, it is not scanning, and it is not ready to scan.
- Idle = 1
Idle mode - The module is ready to scan, but it is not scanning.
- OneShot = 2
OneShot mode - The module scans once and returns to Idle mode.
- Continuous = 3
Continuous mode - The module scans continuously.
- conjugate()
Returns self, the complex conjugate of any int.
- bit_length()
Number of bits necessary to represent self in binary.
>>> bin(37) '0b100101' >>> (37).bit_length() 6
- bit_count()
Number of ones in the binary representation of the absolute value of self.
Also known as the population count.
>>> bin(13) '0b1101' >>> (13).bit_count() 3
- to_bytes(length, byteorder, *, signed=False)
Return an array of bytes representing an integer.
- length
Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
- signed
Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
- from_bytes(byteorder, *, signed=False)
Return the integer represented by the given array of bytes.
- bytes
Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value.
- signed
Indicates whether two’s complement is used to represent the integer.
- as_integer_ratio()
Return integer ratio.
Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.
>>> (10).as_integer_ratio() (10, 1) >>> (-10).as_integer_ratio() (-10, 1) >>> (0).as_integer_ratio() (0, 1)
- real
the real part of a complex number
- imag
the imaginary part of a complex number
- numerator
the numerator of a rational number in lowest terms
- denominator
the denominator of a rational number in lowest terms
- namedtuple api.StatusFlags(CaseTempL: bool = False, ChipThermL: bool = False, LoSL: bool = False, Reserved_03: bool = False, CRL: bool = False, MRL: bool = False, CEL: bool = False, XEL: bool = False, CaseTemp: bool = False, ChipTherm: bool = False, LoS: bool = False, Reserved_11: bool = False, Reserved_12: bool = False, Reserved_13: bool = False, ALARM: bool = False, Reserved_15: bool = False)
Bases:
NamedTupleClass that represents the status flags returned by the module in the StatusF and StatusW registers.
Latched flags are set when a fatal/warning condition occurs and are cleared by writing 0x00FF to the corresponding StatusF or StatusW register. Non-latched flags are set only when the condition is present and are cleared when the condition is no longer present.
- Fields:
CaseTempL (
bool) – Latched Case Temperature flag: True if the case temperature has exceeded the fatal/warning threshold.ChipThermL (
bool) – Latched Chip Thermal flag: True if the chip thermal stabilization signaled a fatal/warning condition.LoSL (
bool) – Latched Loss of Signal flag: True if the module detected a LoS condition in the optical input.Reserved_03 (
bool) – ReservedCRL (
bool) – Latched Communication Reset flag: True if the communication interface has been reset.MRL (
bool) – Latched Module Reset flag: True if the module has been reset.CEL (
bool) – Latched Communication Error flag: True if a communication error has occurred.XEL (
bool) – Latched Execution Error flag: True if an execution error has occurred.CaseTemp (
bool) – Case Temperature flag: True if the case temperature is exceeding the fatal/warning threshold.ChipTherm (
bool) – Chip Thermal flag: True if the chip thermal stabilization is signaling a fatal/warning condition.LoS (
bool) – Loss of Signal flag: True if the module is detecting a LoS condition in the optical input.Reserved_11 (
bool) – ReservedReserved_12 (
bool) – ReservedReserved_13 (
bool) – ReservedALARM (
bool) – Alarm flag: True if any of status flags selected by the ALMT register are set and the ALARM pin is asserted.Reserved_15 (
bool) – Reserved
- classmethod from_flags(status_flags: int)
Initializes a StatusFlags object with the status flags returned by the module in the StatusF and StatusW registers.
- Parameters:
status_flags (int) – Status flags in 16-bits binary format as returned by the module in response to a StatusF or StatusW register read command.
- to_flags() int
Converts the StatusFlags object to a 16-bits int in binary format, as expected by the module in the StatusF and StatusW registers.
- Returns:
Status flags in 16-bits binary format.
- Return type:
int
- namedtuple api.AlarmTriggers(FCaseTemp: bool = False, FChipTherm: bool = False, Reserved_02: bool = False, Reserved_03: bool = False, Reserved_04: bool = False, Reserved_05: bool = False, Reserved_06: bool = False, Reserved_07: bool = False, WCaseTemp: bool = False, WChipTherm: bool = False, WLoS: bool = False, Reserved_11: bool = False, Reserved_12: bool = False, Reserved_13: bool = False, CEL: bool = False, XEL: bool = False)
Bases:
NamedTupleClass that represents the alarm triggers configuration returned by the module in the ALMT register.
The ALMT register is used to select which status flags will trigger the ALARM pin when asserted.
- Fields:
FCaseTemp (
bool) – Alias for field number 0FChipTherm (
bool) – Alias for field number 1Reserved_02 (
bool) – Alias for field number 2Reserved_03 (
bool) – Alias for field number 3Reserved_04 (
bool) – Alias for field number 4Reserved_05 (
bool) – Alias for field number 5Reserved_06 (
bool) – Alias for field number 6Reserved_07 (
bool) – Alias for field number 7WCaseTemp (
bool) – Alias for field number 8WChipTherm (
bool) – Alias for field number 9WLoS (
bool) – Alias for field number 10Reserved_11 (
bool) – Alias for field number 11Reserved_12 (
bool) – Alias for field number 12Reserved_13 (
bool) – Alias for field number 13CEL (
bool) – Alias for field number 14XEL (
bool) – Alias for field number 15
- classmethod from_flags(alarm_triggers: int)
Initializes an AlarmTriggers object with the alarm triggers configuration returned by the module in the ALMT register.
- Parameters:
alarm_triggers (int) – Alarm triggers in 16-bits binary format as returned by the module in response to a ALMT register read command.
- to_flags() int
Converts the AlarmTriggers object to a 16-bits int in binary format, as expected by the module in the ALMT register.
- Returns:
Alarm triggers in 16-bits binary format.
- Return type:
int
- class api.OCM(com_port: str = '', baud_rate: SerialBaudRates = SerialBaudRates.Baud_9600, serial_timeout: float = 0.2, cmd_retry: int = 5, pending_timeout: float = 20, auto_nop_on_cmd_error: bool = True)
Bases:
SerialModuleThe
OCMclass represents the connection with a nanoOCM and provides functions to send read/write commands.The
OCMclass is a direct expansion of theserial_api.SerialModuleclass defined in theserial_apimodule. It inherits all the functions and properties fromserial_api.SerialModuleand adds specific read/write commands for the nanoOCM registers.- Device connection:
Use
OCM.get_serial_ports()to get a list of the available serial communication ports on the PC.Create an OCM object by instantiating the class:
ocm = OCM(com_port="COM1", baud_rate=SerialBaudRates.Baud_115200).Use
OCM.connect()to open the serial connection with the device andOCM.disconnect()to close it.
- Register-specific read/write command functions:
Use functions
OCM.read_reg_<REG NAME>()andOCM.write_reg_<REG NAME>()to read and write data from/to the device internal registers, as defined in the nanoOCM firmware user guide.These functions provide a customized interface for every register, with specific data types, error handling, automatic multibyte transfers when necessary, and additional features like waiting for pending commands to complete or waiting for one-shot scans to complete.
- Low-level register read/write commands:
Use
OCM.read_register()andOCM.write_register()to read and write raw data from/to individual device internal registers.Use
OCM.read_bytes()andOCM.write_bytes()to read and write raw data from/to device registers that require multibyte data transfers (AEA).Use
OCM.read_string()andOCM.write_string()to read and write raw strings from/to device registers that require multibyte data transfers (AEA).
- static get_device_serial_registers() Type[SerialRegisters]
Returns the Enum class representing the combined list of all the register codes supported by the device.
- verify_device_type() bool
Checks if the connected device is a nanoOCM.
- read_reg_status_f() StatusFlags
Reads the StatusF register and returns the fatal status flags.
- Returns:
Fatal status flags.
- Return type:
- write_reg_status_f()
Writes 0x00FF to the StatusF register, clearing the latched flags of the fatal status register.
- read_reg_status_w() StatusFlags
Reads the StatusW register and returns the warning status flags.
- Returns:
Warning status flags.
- Return type:
- write_reg_status_w()
Writes 0x00FF to the StatusW register, clearing the latched flags of the warning status register.
- read_reg_case_temp() float
Reads the CaseTemp register and returns the case temperature in °C.
- Returns:
Case temperature in °C.
- Return type:
float
- read_reg_f_case_temp() Tuple[int, int]
Reads the FCaseTemp register and returns the fatal case temperature thresholds.
- Returns:
Low and high fatal case temperature thresholds. Values are in °C.
- Return type:
Tuple(int, int)
- write_reg_f_case_temp(low_threshold: int, high_threshold: int)
Writes the FCaseTemp register, setting the fatal case temperature thresholds.
- Parameters:
low_threshold (int) – New low fatal case temperature threshold. Value is in °C.
high_threshold (int) – New high fatal case temperature threshold. Value is in °C.
- read_reg_w_case_temp() Tuple[int, int]
Reads the WCaseTemp register and returns the warning case temperature thresholds.
- Returns:
Low and high warning case temperature thresholds. Values are in °C.
- Return type:
Tuple(int, int)
- write_reg_w_case_temp(low_threshold: int, high_threshold: int)
Writes the WCaseTemp register, setting the warning case temperature thresholds.
- Parameters:
low_threshold (int) – New low warning case temperature threshold. Value is in °C.
high_threshold (int) – New high warning case temperature threshold. Value is in °C.
- read_reg_almt() AlarmTriggers
Reads the ALMT register and returns the current alarm triggers configuration.
- Returns:
Alarm triggers configuration.
- Return type:
- write_reg_almt(alarm_triggers: AlarmTriggers)
Writes the ALMT register, setting the alarm triggers configuration.
- Parameters:
alarm_triggers (AlarmTriggers) – New alarm triggers configuration. It can be initialized directly in place. Example: ocm.write_reg_almt(AlarmTriggers(FCaseTemp=True, WCaseTemp=True))
- read_reg_scan_mode() ScanModes
Reads the ScanMode register and returns the current scan mode.
- Returns:
Current scan mode.
- Return type:
- write_reg_scan_mode(scan_mode: ScanModes, wait_one_shot: bool = True, wait_pending: bool = True) int
Writes the ScanMode register, setting the new scan mode for the nanoOCM.
- Parameters:
scan_mode (ScanModes) – New scan mode.
wait_one_shot (bool) – If True and scan_mode is OneShot, the function will wait for the one-shot scan to complete.
wait_pending (bool) – If True and response status is CP, the function will wait for the command to complete.
- Returns:
The pending flags returned by the device. 0 if operation already completed.
- Return type:
int
- read_reg_boot_scan_mode() ScanModes
Reads the BootScanMode register and returns the boot scan mode. The boot scan mode is the scan mode that the module will automatically enter after reboot.
- Returns:
Boot scan mode.
- Return type:
- write_reg_boot_scan_mode(boot_scan_mode: ScanModes)
Writes the BootScanMode register, setting the boot scan mode for the nanoOCM. The boot scan mode is the scan mode that the module will automatically enter after reboot.
- Parameters:
boot_scan_mode (ScanModes) – New boot scan mode.
- read_reg_grid_mem_idx() int
Reads the GridMemIdx register and returns the index of the currently selected location in the acquisition grid memory.
- Returns:
Index of the currently selected location in the acquisition grid memory.
- Return type:
int
- write_reg_grid_mem_idx(grid_mem_idx: int)
Writes the GridMemIdx register, changing the selected location in the acquisition grid memory.
- Parameters:
grid_mem_idx (int) – The index of the location in the acquisition grid memory to select.
- read_reg_grid_mem() Tuple[List[int], List[int], List[float]]
Reads the GridMem register and returns the n, m, and LOS values for the acquisition grid configuration that is stored at the index selected by the GridMemIdx register. See write_reg_grid_mem_idx() to change the selected grid index.
- Returns:
n, m, and LOS values for the selected acquisition grid configuration. LOS values are in dBm.
- Return type:
Tuple[List[int], List[int], List[float]]
- write_reg_grid_mem(n: List[int], m: List[int], los: List[float], wait_pending: bool = True)
Writes the GridMem register, setting the n, m, and LOS values for the acquisition grid configuration that is stored at the index selected by the GridMemIdx register. See write_reg_grid_mem_idx() to change the selected grid index.
- Parameters:
n (List[int]) – List of n values for each grid channel.
m (List[int]) – List of m values for each grid channel.
los (List[float]) – List of LOS values for each grid channel. LOS values must be in dBm.
wait_pending (bool) – If True, the function will wait for the device to finish writing the configuration into flash memory.
- Returns:
The pending flags returned by the device. 0 if operation already completed.
- Return type:
int
- read_reg_active_grid_idx() int
Reads the ActiveGridIdx register and returns the index of the acquisition grid configuration that is currently in use by the module.
- Returns:
Index of the acquisition grid configuration that is currently in use by the module.
- Return type:
int
- write_reg_active_grid_idx(active_grid_idx: int)
Writes the ActiveGridIdx register, setting the index of the acquisition grid configuration that will be used by the module to perform scans.
- Parameters:
active_grid_idx (int) – Index of the acquisition grid configuration to use.
- read_reg_boot_grid_idx() int
Reads the BootGridIdx register and returns the index of the acquisition grid configuration that will be used by the module after reboot.
- Returns:
Index of the acquisition grid configuration that will be used by the module after reboot.
- Return type:
int
- write_reg_boot_grid_idx(boot_grid_idx: int)
Writes the BootGridIdx register, setting the index of the acquisition grid configuration that will be used by the module after reboot.
- Parameters:
boot_grid_idx (int) – Index of the acquisition grid configuration to use after reboot.
- read_reg_scan_data() List[float]
Reads the ScanData register and returns the channel power values from the last scan performed by the module.
- Returns:
Channel power values from the last scan performed by the module. Values are in dBm. The list length is equal to the number of channels in the active grid configuration.
- Return type:
List[float]
- read_reg_scan_interval() int
Reads the ScanInterval register and returns the current scan interval in continuous mode.
- Returns:
Current scan interval. The value is in milliseconds and represents the time between scans in continuous mode.
- Return type:
int
- write_reg_scan_interval(scan_interval: int)
Writes the ScanInterval register, setting the scan interval for the module in continuous mode.
- Parameters:
scan_interval (int) – New scan interval. The value is in milliseconds and represents the time between scans in continuous mode.
- read_reg_input_losses() float
Reads the InputLosses register and returns the input losses value. This value can be used to adjust and calibrate the channel power values read from the ScanData register to account for the losses in the input optical path.
- Returns:
Input losses value in dB.
- Return type:
float
- write_reg_input_losses(input_losses: float)
Writes the InputLosses register, setting the input losses value. This value can be used to adjust and calibrate the channel power values read from the ScanData register to account for the losses in the input optical path.
- Parameters:
input_losses (float) – New input losses value in dB.
- read_reg_crosstalk_suppression() bool
Reads the CrosstalkSuppression register and returns the current crosstalk suppression status.
- Returns:
True if crosstalk suppression is enabled, False if it is disabled.
- Return type:
bool
- write_reg_crosstalk_suppression(enable: bool)
Writes the CrosstalkSuppression register, enabling or disabling crosstalk suppression.
- Parameters:
enable (bool) – If True, crosstalk suppression will be enabled. If False, it will be disabled.
- read_reg_scan_frequencies() List[float]
Reads the ScanFrequencies register and returns the channel center frequency values from the last scan performed by the module.
- Returns:
Channel center frequency values from the last scan performed by the module. Values are in GHz. The list length is equal to the number of channels in the active grid configuration.
- Return type:
List[float]
- write_reg_reboot(auto_reconnect: bool = True)
Writes the Reboot register, forcing the module to reboot. No response is expected from this command.
- Parameters:
auto_reconnect (bool, optional) – If True, the module will automatically reconnect after reboot. Defaults to True.
- connect(com_port: str | None = None, baud_rate: SerialBaudRates | None = None, serial_timeout: float | None = None, cmd_retry: int | None = None, auto_baud: bool = True)
Connects to the serial module.
- Parameters:
com_port (Optional[str]) – The serial port to connect to. If None, uses the com_port provided during initialization. Defaults to None.
baud_rate (Optional[SerialBaudRates]) – The baud rate for the serial communication. If None, uses the baud_rate provided during initialization. Defaults to None.
serial_timeout (Optional[float]) – The timeout for reading from the serial port in seconds. If None, uses the serial_timeout provided during initialization. Defaults to None.
cmd_retry (Optional[int]) – The number of times to retry to send a command when a communication error is detected. If None, uses the cmd_retry provided during initialization. Defaults to None.
auto_baud (bool) – Whether to automatically try with the default baud if the specified one doesn’t work. Defaults to True.
- Raises:
SerialModuleConnectionError – If there is an error in establishing the connection.
- disconnect()
Disconnects from the serial module.
- static get_serial_ports(filter_name: str = '', filter_manufacturer: str = '')
Get a list of available serial ports.
- is_connected(check_response: bool = True)
Checks if the module is connected correctly.
- Parameters:
check_response (bool) – Whether to check only for the status of the serial port (False) or to check also if the module responds to a NOP command (True). Defaults to True.
- Returns:
True if the module is connected, False otherwise.
- read_bytes(register: SerialRegisters, data: int = 0) bytearray
Read a register from the serial module, returning the data as a bytearray. If the register requires AEA multibyte reads, the function will automatically read the required amount of bytes.
- Parameters:
register (SerialRegisters) – The register to read.
data (int) – Optional data to include in the read command, if required to customize the module response.
- Returns:
The data read from the register as a bytearray.
- Return type:
bytearray
- read_reg_aea_ea() int
Reads the AEA_EA register.
- Returns:
The content of the AEA_EA register.
- Return type:
int
- read_reg_aea_eac() int
Reads the AEA_EAC register.
- Returns:
The content of the AEA_EAC register.
- Return type:
int
- read_reg_aea_ear() int
Reads the AEA_EAR register.
- Returns:
The content of the AEA_EAR register.
- Return type:
int
- read_reg_dev_typ() str
Reads the DevTyp register.
- Returns:
The device type string.
- Return type:
str
- read_reg_gen_cfg() int
Reads the GenCfg register.
- Returns:
The data returned by the device, always 0.
- Return type:
int
- read_reg_io_cap() Tuple[SerialBaudRates, SerialBaudRates]
Reads the IOCap register.
- Returns:
Current baud rate and maximum baud rate supported by the connected module.
- Return type:
Tuple[SerialBaudRates, SerialBaudRates]
- read_reg_lst_resp() Tuple[int, int, int]
Reads the LstResp register.
- Returns:
The status, register and data of the last response sent by the module.
- Return type:
Tuple[int, int, int]
- read_reg_mfg_date() str
Reads the MFGDate register.
- Returns:
The manufacturing date string.
- Return type:
str
- read_reg_mfgr() str
Reads the MFGR register.
- Returns:
The manufacturer string.
- Return type:
str
- read_reg_model() str
Reads the Model register.
- Returns:
The model string.
- Return type:
str
- read_reg_nop() Tuple[SerialErrorCodes, bool, int]
Reads the NOP register.
- Returns:
Last command execution error, module ready flag, pending flags.
- Return type:
Tuple[SerialErrorCodes, bool, int]
- read_reg_rel_back() str
Reads the RelBack register.
- Returns:
The release backwards compatibility string.
- Return type:
str
- read_reg_release() str
Reads the Release register.
- Returns:
The release string.
- Return type:
str
- read_reg_ser_no() str
Reads the SerNo register.
- Returns:
The serial number string.
- Return type:
str
- read_register(register: SerialRegisters, data: int = 0) int
Read a register from the serial module.
- Parameters:
register (SerialRegisters) – The register to read.
data (int) – Optional data to include in the read command, if required to customize the module response.
- Returns:
The data read from the register as a 16-bits int.
- Return type:
int
- read_string(register: SerialRegisters, remove_null_terminator=True) str
Reads a string from the specified register with AEA.
- Parameters:
register (SerialRegisters) – The register to read the string from.
remove_null_terminator (bool) – Whether to remove the null terminator character (’') from the end of the string. Defaults to True.
- Returns:
The string read from the register.
- Return type:
str
- send_command(register: SerialRegisters = SerialRegistersGeneral.NOP, data: int = 0, write: bool = False, allow_ok: bool = True, allow_aea: bool = False, allow_cp: bool = False, check_response_reg: bool = True, cmd_retry: int | None = None, wait_pending: bool = True, auto_nop_on_cmd_error: bool | None = None) Tuple[SerialPacketStatus, int]
Sends a command to the serial module and retrieves the response.
- Parameters:
register (SerialRegisters) – The register code. 8 bits.
data (int) – The data associated with the command. 16 bits.
write (bool) – Indicates if the command is a write command.
allow_ok (bool) – Indicates if the command is allowed to return OK status.
allow_aea (bool) – Indicates if the command is allowed to return AEA status.
allow_cp (bool) – Indicates if the command is allowed to return CP status.
check_response_reg (bool) – Indicates if the response register address should be checked against the sent one.
cmd_retry (int) – The number of retries to perform if the command fails. If not None, this value overrides the one provided at initialization or at connection.
wait_pending (bool) – Indicates if the function should poll the NOP register until the pending flags are cleared, when the command response status is SerialModulePacketStatus.CP.
auto_nop_on_cmd_error (bool) – If not None, this value overrides the one provided at initialization. If True, automatically sends a NOP read command to retrieve the error cause when the command returns XE status code.
- Returns:
A tuple containing the response status and response data as a 16-bits int.
- Return type:
tuple[SerialPacketStatus, int]
- Raises:
SerialModuleConnectionError – If there is an error in the serial connection.
SerialModuleCommunicationError – If there is a communication error with the serial module, in either direction.
SerialModuleResponseError – If there is an error in the response received from the serial module.
SerialCommandError – If the command response status is SerialModulePacketStatus.XE.
- wait_pending(pending_mask: int = 255, pending_timeout: float | None = None)
Waits for pending commands to complete.
- Parameters:
pending_mask (int) – The mask for the pending flags to wait for. Defaults to 0xFF, which waits for all pending flags to clear.
pending_timeout (Optional[float]) – The timeout for waiting for pending commands to complete in seconds. If None, uses the pending_timeout provided during initialization. Defaults to None.
- Raises:
SerialPendingTimeoutError – If the pending commands do not complete within the specified timeout.
- write_bytes(register: SerialRegisters, data: bytearray, not_aea: bool = False, allow_pending: bool = True, wait_pending: bool = True) Tuple[SerialPacketStatus, int]
Write multiple bytes to a register in the serial module that supports AEA multibyte writes. The function also supports writing to command registers that do not support AEA multibyte writes, by setting the not_aea parameter to True and by passing a data array with only 2 elements.
- Parameters:
register (SerialRegisters) – The register to write.
data (bytearray) – The data to write in the register as a bytearray.
not_aea (bool) – If True, forces the function to write the data as a single 16-bits int, without using AEA multibyte writes.
allow_pending (bool) – If True, allows the command to return CP status without raising an exception, indicating that the command is continuing execution after the response.
wait_pending (bool) – If True, automatically waits for the pending flags in the NOP register to clear before returning from the function.
- Returns:
The execution status and the pending flags if CP status is returned and wait_pending is False.
- Return type:
Tuple[SerialPacketStatus, int]
- write_reg_aea_ea(data: int, wait_pending: bool = True) int
Writes the AEA_EA register.
- Parameters:
data (int) – The data to write to the AEA_EA register.
wait_pending (bool) – If True and response status is CP, the function will wait for the command to complete.
- Returns:
The pending flags returned by the device. 0 if operation already completed.
- Return type:
int
- write_reg_aea_eac(data: int, wait_pending: bool = True) int
Writes the AEA_EAC register.
- Parameters:
data (int) – The data to write to the AEA_EAC register.
wait_pending (bool) – If True and response status is CP, the function will wait for the command to complete.
- Returns:
The pending flags returned by the device. 0 if operation already completed.
- Return type:
int
- write_reg_aea_ear(data: int, wait_pending: bool = True) int
Writes the AEA_EAR register.
- Parameters:
data (int) – The data to write to the AEA_EAR register.
wait_pending (bool) – If True and response status is CP, the function will wait for the command to complete.
- Returns:
The pending flags returned by the device. 0 if operation already completed.
- Return type:
int
- Raises:
SerialCommandError – If the device returns an error.
SerialPendingTimeoutError – If waiting for the device to finish the pending operation times out.
- write_reg_gen_cfg(wait_pending: bool = True) int
Writes the GenCfg register with the required value to force the device to store non-volatile configuration into flash memory.
- Parameters:
wait_pending (bool) – If True, the function will wait for the device to finish writing the configuration into flash memory.
- Returns:
The pending flags returned by the device. 0 if operation already completed.
- Return type:
int
- Raises:
SerialCommandError – If the device returns an error.
SerialPendingTimeoutError – If waiting for the device to finish writing the configuration into flash memory times out.
- write_reg_io_cap(baud_rate: SerialBaudRates, auto_switch_baud: bool = True)
Writes the IOCap register.
- Parameters:
baud_rate (SerialBaudRates) – The baud rate to set.
auto_switch_baud (bool) – If True and device response is positive, the connection will automatically switch to the new baud rate. If False, the connection will remain at the current baud.
- write_reg_nop(data: int) int
Writes the NOP register.
- Parameters:
data (int) – The data to write to the NOP register.
- Returns:
The data returned by the device. Should be the same as the data written, if the module is working correctly.
- Return type:
int
- write_register(register: SerialRegisters, data: int = 0, allow_pending: bool = True, wait_pending: bool = True) Tuple[SerialPacketStatus, int]
Write a register in the serial module.
- Parameters:
register (SerialRegisters) – The register to write.
data (int) – The data to write in the register.
allow_pending (bool) – If True, allows the command to return CP status without raising an exception, indicating that the command is continuing execution after the response.
wait_pending (bool) – If True, automatically waits for the pending flags in the NOP register to clear before returning from the function.
- Returns:
The execution status and the pending flags if CP status is returned and wait_pending is False.
- Return type:
Tuple[SerialPacketStatus, int]
- write_string(register: SerialRegisters, data_string: str, max_length: int = 80, allow_pending: bool = True, wait_pending: bool = True) Tuple[SerialPacketStatus, int]
Write a string to the specified register with AEA.
- Parameters:
register (SerialRegisters) – The register to write the string to.
data_string (str) – The string to write to the register.
max_length (int) – The maximum length of the string, including the null terminator character (’'). Defaults to 80.
allow_pending (bool) – Whether to allow the command to return a pending status. Defaults to True.
wait_pending (bool) – Whether to wait for pending commands to complete after writing the string. Defaults to True.
- Returns:
The execution status and the pending flags if CP status is returned and wait_pending is False.
- Return type:
Tuple[SerialPacketStatus, int]