This README refers to the **serialbridge** module used for the Hardware In the Loop (HIL) simulation.

## How to Build

The following steps will generate a `mex` file that can be used in MATLAB.

### With Just

Just takes care of setting the correct extension.
```bash
just build-env <MATLAB_PATH>
```
Where `<MATLAB_PATH>` is the path to the MATLAB installation directory. This can be found by running `matlabroot` in the MATLAB command window as follows:

```matlab
fullfile(matlabroot(), 'bin', computer('arch'))
```

### Manually

```bash
export MATLAB_LIB_DIR="<MATLAB_PATH>"
cargo build --release
mv target/release/libserial_bridge.dylib serialbridge.<EXT>
```

`<EXT>` is the extension of the library file (e.g. `mexa64` for Linux, `mexw64` for Windows, `mexmaci64` for macOS).

## Usage

serialbridge can be used in matlab in the following way:
- `serialbridge("Open", string_serialPort, uint_baudrate)`:
  - **"Open"**: specifies we want to open the serial port
  - string_serialPort: is the serial port we want to open (eg: "COM6")
  - uint_baudrate: is the baudrate of the port (eg: 256000)
- `serialbridge("Write", singleArray_Data)`:
  - **"Write"**: specifies that we want to write to the serial port
  - singleArray_Data: is the array of singles we want to write on serial (eg: [1 2 3 4.5 5.4])
- `singleArray_Data = serialbridge("Read", uint_nData)`;
  - **"Read"**: specifies that we want to read from the serial port
  - uint_nData: How many floats to read from serial (eg: 1)
  - singleArray_Data: array of floats read from the serial (eg: actuatorData)
- `serialbridge("Close", string_serialPort, uint_baudrate)`:
  - **"Close"**: specifies we want to close the serial port

**Example** in Matlab:
```
serialbridge("Open", "COM6", 256000); % Opens the serial port
serialbridge("Write", [1 2 3 4]);     % Sends the array "[1 2 3 4]" to the serial device
data = serialbridge("Read", 2);       % Receives 2 floats and stores them in the variable "data"
serialbridge("Close");                % Closes the serial port
```

Procedure in order to use the **MatlabTransceiver** module: https://git.skywarder.eu/scs/hermes/r2a-obsw/-/blob/Serial4Simulations-dev/src/tests/hardware_in_the_loop/README.md

***WARNING***:
* It's possible to open just ONE serial port with this module

## Dev

Tho have rustanalyzer working properly, you need to add a `config.toml` in the `.cargo` directory at the root of this repository with the following content:
```toml
[env]
MATLAB_LIB_DIR = <MATLAB_PATH>
```

To get the `<MATLAB_PATH>` you can follow the instructions in the "How to Build" section.