AI write rust code

I tried to use AI to write a rust code, but it's not very good.

It's good because the basic code followed my input requirement. But there are two build errors the AI can't fix. Finally I changed the requirement and fixed these two errors.

Here is the code:

use serialport::{SerialPort, SerialPortSettings};

// Define a trait for the serial port operations
trait SerialOperations {
    fn open(&mut self) -> Result<(), std::io::Error>;
    fn write(&mut self, data: &[u8]) -> Result<(), std::io::Error>;
    fn receive(&mut self, buffer: &mut [u8]) -> Result<usize, std::io::Error>;
}

// Implement the SerialOperations trait for the Comm struct
struct Comm {
    port_name: String,
    port: Option<Box<dyn SerialPort>>,
}

impl SerialOperations for Comm {
    fn open(&mut self) -> Result<(), std::io::Error> {
        // Create the serial port settings
        let settings = SerialPortSettings {
            baud_rate: 9600,
            ..Default::default()
        };

        // Try to open the serial port with the specified settings
        match serialport::open_with_settings(&self.port_name, &settings) {
            Ok(p) => {
                self.port = Some(p);
                Ok(())
            },
            Err(e) => {
                println!("Error opening serial port: {}", e);
                Err(e.into())
            }
        }
    }

    fn write(&mut self, data: &[u8]) -> Result<(), std::io::Error> {
        if let Some(port) = &mut self.port {
            port.write(data)?;
            Ok(())
        } else {
            Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                "Serial port not open",
            ))
        }
    }

    fn receive(&mut self, buffer: &mut [u8]) -> Result<usize, std::io::Error> {
        if let Some(port) = &mut self.port {
            //Ok(port.read(buffer)?)
            match port.read(buffer) {
                Ok(bytes_read) => Ok(bytes_read),
                Err(e) => {
                    println!("Error reading from serial port: {}", e);
                    Err(e.into())
                }
            }
        } else {
            Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                "Serial port not open",
            ))
        }
    }
}

fn main() {
    let mut comm_send = Comm {
        port_name: "/dev/ttyVSP0".to_string(),
        port: None,
    };
    let mut comm_recv = Comm {
        port_name: "/dev/ttyVSP4".to_string(),
        port: None,
    };

    // Open the serial port
    match comm_send.open() {
        Ok(p) => p,
        Err(e) => {
            println!("Error opening serial port: {}", e);
            return;
        }
    };
    // Open the serial port
    match comm_recv.open() {
        Ok(p) => p,
        Err(e) => {
            println!("Error opening serial port: {}", e);
            return;
        }
    };

    // Write data to the serial port
    if let Err(e) = comm_send.write(b"Hello World!\n") {
        println!("Error writing to serial port: {}", e);
        return;
    }

    // Receive data from the serial port
    let mut buffer = [0; 64];
    if let Err(e) = comm_recv.receive(&mut buffer) {
        println!("Error receiving from serial port: {}", e);
        return;
    }

    match std::str::from_utf8(&buffer) {
        Ok(s) => println!("{}", s),
        Err(_) => println!("Invalid UTF-8 sequence"),
    }
    //println!("Received data: {:?}", &buffer[..]);
}

 It needs serialport lib in toml file

[dependencies]
serialport = "3.1"

 And better to use fast lib source of rust, such as: .cargo/config in your project folder.

[source.crates-io] 
replace-with = 'tuna' 
  
[source.tuna] 
registry = 'https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index'

 This code use virtual serial to transfer data. I connect ttyVSP0 and ttyVSP4 by socat:

sudo socat -d -d pty,raw,echo=0,link=/dev/ttyVSP0 pty,raw,echo=0,link=/dev/ttyVSP4 &

And it can build and run as:

/local/study_rust/vserial$ cargo build
Compiling vserial v0.1.0 (/local/study_rust/vserial)
Finished dev [unoptimized + debuginfo] target(s) in 0.39s

/local/study_rust/vserial$ sudo ./target/debug/vserial
Hello World!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值