Skip to main content

request_sample/
request-sample.rs

1#![allow(clippy::expect_used, reason = "helps to reduce verbosity")]
2
3use rsomeip_bytes::{BytesMut, Serialize};
4use rsomeip_proto::{ClientId, Endpoint, Interface, SessionId};
5use std::net::UdpSocket;
6
7mod common;
8use common::{SAMPLE_METHOD_ID, SAMPLE_SERVICE_ID, proxy_address, stub_address};
9
10// A SOME/IP message.
11type Message = rsomeip_proto::Message<Vec<u8>>;
12
13fn main() {
14    // Bind an UDP socket.
15    let socket = UdpSocket::bind(proxy_address()).expect("should bind the socket");
16
17    // Create the SOME/IP endpoint.
18    let endpoint = Endpoint::new().with_interface(
19        SAMPLE_SERVICE_ID,
20        Interface::default()
21            .with_method(SAMPLE_METHOD_ID)
22            .into_proxy(),
23    );
24
25    // Send requests to the service and process the responses.
26    send_requests(&socket, &endpoint);
27}
28
29fn send_requests(socket: &UdpSocket, endpoint: &Endpoint) {
30    // Create a request to send to the service provider.
31    let mut session_id = SessionId::ENABLED;
32    let request = Message::default()
33        .with_service(SAMPLE_SERVICE_ID)
34        .with_method(SAMPLE_METHOD_ID)
35        .with_client(ClientId::new(0x0001))
36        .with_body((0..10).collect::<Vec<u8>>());
37
38    // Continuously send requests to the service provider.
39    loop {
40        // Clone the request and increment the session id.
41        let request = request.clone().with_session(session_id.increment());
42        println!("> {request} {:02x?}", request.body);
43
44        // Process the request into bytes.
45        let mut buffer = BytesMut::with_capacity(request.size_hint());
46        endpoint
47            .process(request, &mut buffer)
48            .expect("should process the request");
49
50        // Send the data through the socket.
51        socket
52            .send_to(&buffer.freeze(), stub_address())
53            .expect("should send the data.");
54
55        // Wait for a response.
56        let mut buffer = BytesMut::zeroed(64);
57        let (size, _) = socket
58            .recv_from(&mut buffer[..])
59            .expect("should receive the data");
60
61        // Process the response.
62        let response: Message = endpoint
63            .poll(&mut buffer.split_to(size).freeze())
64            .expect("should process the response");
65        println!("< {response} {:02x?}", response.body);
66
67        // Wait before sending another request.
68        std::thread::sleep(std::time::Duration::from_secs(1));
69    }
70}