Flightmatrixbridge

Latest version: v1.7.0

Safety actively analyzes 685670 Python packages for vulnerabilities to keep your Python projects secure.

Scan your dependencies

Page 3 of 3

0.0

Example 3: Fetching Sensor Data

python
from flightmatrix.bridge import FlightMatrixBridge

Initialize the bridge
bridge = FlightMatrixBridge()

Fetch sensor data
sensor_data = bridge.get_sensor_data()

Check for errors
if sensor_data.get('error'):
print("Error fetching sensor data:", sensor_data['error'])
else:
Extract sensor readings
location = sensor_data['location']
orientation = sensor_data['orientation']
angular_velocity = sensor_data['angular_velocity']
acceleration = sensor_data['acceleration']
magnetometer = sensor_data['magnetometer']
lidar = sensor_data['lidar']
collision = sensor_data['collision']
timestamp = sensor_data['timestamp']

Display sensor data in a readable format
print("Sensor Data:")
print("-----------------------")
print(f"Timestamp: {timestamp} ms")
print(f"Location (cm): X={location[0]:.2f}, Y={location[1]:.2f}, Z={location[2]:.2f}")
print(f"Orientation (degrees): Roll={orientation[0]:.2f}, Pitch={orientation[1]:.2f}, Yaw={orientation[2]:.2f}")
print(f"Angular Velocity (deg/s): X={angular_velocity[0]:.2f}, Y={angular_velocity[1]:.2f}, Z={angular_velocity[2]:.2f}")
print(f"Acceleration (cm/s²): X={acceleration[0]:.2f}, Y={acceleration[1]:.2f}, Z={acceleration[2]:.2f}")
print(f"Magnetometer (unit vector): X={magnetometer[0]:.2f}, Y={magnetometer[1]:.2f}, Z={magnetometer[2]:.2f}")
print(f"LiDAR Data (cm): Forward={lidar[0]:.2f}, Backward={lidar[1]:.2f}, Left={lidar[2]:.2f}, Right={lidar[3]:.2f}, Bottom={lidar[4]:.2f}")
print(f"Collision Detection: Status={collision[0]}, Location (cm): X={collision[1]:.2f}, Y={collision[2]:.2f}, Z={collision[3]:.2f}")



Documentation

Class: `FlightMatrixBridge`
This class interfaces with the Flight Matrix system using shared memory for inter-process communication. It manages frames, timestamps, and movement commands, enabling seamless data sharing between processes.

---

**Attributes:**

- `width (int)`: The width of the frame, initialized by the resolution provided.

- `height (int)`: The height of the frame, initialized by the resolution provided.

- `frame_shape (tuple)`: Tuple representing the shape of the frame as `(height, width)`.

- `frame_shape_3ch (tuple)`: Tuple representing the shape of the frame with 3 channels as `(height, width, 3)`.

- `noise_level (float)`: Specifies the level of noise to be applied. Defaults to `0.01`.

- `apply_noise (bool)`: Boolean flag that determines whether noise should be applied. Defaults to `False`.

- `memory_names (dict)`: Dictionary mapping keys to shared memory block names. Used for storing frame, depth, segmentation, and movement command data.

- `log (Logger)`: A logger instance used for logging events and debugging messages.

- `shm (dict)`: Dictionary storing the shared memory objects for frame data.

- `shm_timestamps (dict)`: Dictionary storing the shared memory objects for timestamps.

- `num_floats (int)`: Number of float values stored in shared memory for movement commands. Defaults to `6`.

---

**Methods:**

---

**`__init__(self, resolution=(1226, 370))`**

**Description:**
Initializes the `FlightMatrixBridge` class by setting up shared memory and logging.

**Args:**
- `resolution (tuple, optional)`: A tuple specifying the frame's width and height. Defaults to `(1226, 370)`.

**Example:**
python
bridge = FlightMatrixBridge(resolution=(800, 600))


---

**`set_log_level(self, log_level='INFO')`**

**Description:**
Sets the logging level for the logger instance to control the verbosity of log output.

**Args:**
- `log_level (str)`: Desired log level (`'DEBUG'`, `'INFO'`, `'WARNING'`, `'ERROR'`). Default is `'INFO'`.

**Returns:**
None.

**Example:**
python
bridge.set_log_level('DEBUG')


---

**`set_write_to_file(self, write_to_file)`**

**Description:**
Sets whether the logging should be written to a file or not.

**Args:**
- `write_to_file (bool)`: If `True`, log messages will be written to a file; otherwise, they won't.

**Returns:**
None.

**Example:**
python
bridge.set_write_to_file(True)


---

**`_initialize_shared_memory(self)`**

**Description:**
Initializes shared memory blocks for frames and timestamps based on the keys stored in `memory_names`. If the shared memory block for a specific key is not available, a warning will be logged.

**Raises:**
- `FileNotFoundError`: If the shared memory block for a key does not exist.

**Returns:**
None.

**Example:**
python
bridge._initialize_shared_memory()


---

**`_initialize_movement_command_memory(self)`**

**Description:**
Sets up shared memory for movement commands (`x, y, z, roll, pitch, yaw`) and an availability flag. If the shared memory block exists, it will attach to it; otherwise, it will create a new block.

**Raises:**
- `FileExistsError`: If the shared memory block already exists when trying to create it.

**Returns:**
None.

**Example:**
python
bridge._initialize_movement_command_memory()


---

**`_get_frame(self, key, channels=3)`**

**Description:**
Retrieves a frame from shared memory. Handles both 3-channel and single-channel frame retrieval.

**Args:**
- `key (str)`: Key identifying the shared memory segment.
- `channels (int, optional)`: Number of channels in the frame, default is `3`.

**Returns:**
- `dict`: A dictionary with:
- `'frame' (np.ndarray or None)`: The retrieved frame or `None` if an error occurred.
- `'timestamp' (any or None)`: The timestamp associated with the frame or `None` if an error occurred.
- `'error' (str or None)`: Error message, if any.

**Raises:**
- `Warning`: If shared memory is not available or if there is a resolution mismatch.

**Example:**
python
frame_data = bridge._get_frame('right_frame', channels=3)


---

**`_get_timestamp(self, key)`**

**Description:**
Retrieves the timestamp associated with the frame stored in shared memory.

**Args:**
- `key (str)`: Key identifying the shared memory segment for the timestamp.

**Returns:**
- `int or None`: The timestamp as an integer, or `None` if not available.

**Example:**
python
timestamp = bridge._get_timestamp('right_frame')


---

**`add_noise(self, data)`**

**Description:**
Adds Gaussian noise to the given data based on the configured noise level.

**Args:**
- `data (np.ndarray)`: The data (typically a frame) to which noise will be added.

**Returns:**
- `np.ndarray`: The noisy data.

**Example:**
python
noisy_frame = bridge.add_noise(frame_data)


---

**`get_sensor_data(self)`**

**Description:**
Retrieves sensor data from shared memory.

**Returns:**
- `np.ndarray or None`: The sensor data array, or `None` if the shared memory is not available.

**Example:**
python
sensor_data = bridge.get_sensor_data()


---

**`send_movement_command(self, x, y, z, roll, pitch, yaw)`**

**Description:**
Sends movement command values (`x, y, z, roll, pitch, yaw`) to the shared memory block.

**Args:**
- `x (float)`: Movement in the X-axis.
- `y (float)`: Movement in the Y-axis.
- `z (float)`: Movement in the Z-axis.
- `roll (float)`: Roll rotation.
- `pitch (float)`: Pitch rotation.
- `yaw (float)`: Yaw rotation.

**Returns:**
None.

**Example:**
python

000000.000

---

**`timestamp2datetime(timestamp)`**

**Description:**
Converts a timestamp in milliseconds (integer) to a `datetime` object.

**Args:**
- `timestamp (int)`: The timestamp in milliseconds to be converted.

**Returns:**
- `datetime`: The corresponding `datetime` object in UTC timezone.

**Example:**
python
dt_object = timestamp2datetime(1633036800000)
Output: datetime.datetime(2021, 10, 1, 0, 0, tzinfo=datetime.timezone.utc)

Page 3 of 3

© 2024 Safety CLI Cybersecurity Inc. All Rights Reserved.