シリアルポート通信 (RS-232C) を行う

Recipe ID: hw-001

IoT デバイスや産業機器との通信によく使われるシリアルポート(RS-232C/UART)を Rust 側で制御する方法です。標準的な serialport クレートを使用します。

1. 依存関係の追加

src-tauri ディレクトリで以下のコマンドを実行し、Cargo.tomlserialport クレートを追加します。

cd src-tauri
cargo add serialport

2. シリアルポートを開く

ポート名(COMポートやデバイスファイルパス)とボーレートを指定して接続します。

use serialport::{DataBits, FlowControl, Parity, StopBits};
use std::time::Duration;

#[tauri::command]
fn open_serial_port(port_name: String, baud_rate: u32) -> Result<String, String> {
    let port = serialport::new(&port_name, baud_rate)
        .timeout(Duration::from_millis(100))
        .data_bits(DataBits::Eight)
        .flow_control(FlowControl::None)
        .parity(Parity::None)
        .stop_bits(StopBits::One)
        .open();

    match port {
        Ok(_) => Ok(format!("{} を開きました", port_name)),
        Err(e) => Err(format!("エラー: {}", e)),
    }
}

※ 実際に読み書きを行う場合は、open() が返す Box<dyn SerialPort> オブジェクトを State などで保持(管理)する必要があります(hw-003 参照)。

3. 権限とプラットフォーム固有の設定

  • Linux: ユーザーが dialout グループなどに所属している必要があります。
  • macOS: 特に追加設定は不要ですが、署名や許可が必要な場合があります。
  • Windows: COMポートの競合に注意してください。