lib60870 0.4.0

Safe Rust bindings to lib60870-C, an IEC 60870-5-101/104 protocol implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! IEC 60870-5-104 client (master) implementation.
//!
//! The client connects to a server (slave/RTU) and can send commands
//! and receive data.

use std::ffi::CString;
use std::os::raw::c_void;
use std::ptr::NonNull;
use std::sync::Arc;

use crate::asdu::Asdu;
use crate::sys;
use crate::time::Timestamp;
use crate::types::{CauseOfTransmission, ConnectionEvent};

/// Callback for connection state changes.
pub type ConnectionHandler = Box<dyn Fn(ConnectionEvent) + Send + Sync>;

/// Callback for received ASDUs.
///
/// The ASDU is cloned before being passed to the callback, so it's safe
/// to store or send to another thread.
///
/// Return `true` to indicate the ASDU was handled, `false` otherwise.
pub type AsduHandler = Box<dyn Fn(Asdu) -> bool + Send + Sync>;

/// Builder for configuring a connection.
pub struct ConnectionBuilder {
    hostname: String,
    port: i32,
    originator_address: u8,
    connect_timeout_ms: u32,
}

impl ConnectionBuilder {
    /// Create a new connection builder.
    pub fn new(hostname: &str, port: u16) -> Self {
        Self {
            hostname: hostname.to_string(),
            port: port as i32,
            originator_address: 0,
            connect_timeout_ms: 10000,
        }
    }

    /// Set the originator address (0-255).
    pub fn originator_address(mut self, oa: u8) -> Self {
        self.originator_address = oa;
        self
    }

    /// Set the connection timeout in milliseconds.
    pub fn connect_timeout_ms(mut self, timeout: u32) -> Self {
        self.connect_timeout_ms = timeout;
        self
    }

    /// Build the connection.
    pub fn build(self) -> Option<Connection> {
        Connection::new_with_config(
            &self.hostname,
            self.port,
            self.originator_address,
            self.connect_timeout_ms,
        )
    }
}

/// Internal state for callbacks.
struct CallbackState {
    connection_handler: Option<ConnectionHandler>,
    asdu_handler: Option<AsduHandler>,
}

/// An IEC 60870-5-104 client connection.
///
/// This represents a connection to a server (slave/RTU). The connection
/// is automatically destroyed when dropped.
///
/// # Example
///
/// ```no_run
/// use lib60870::client::{Connection, ConnectionBuilder};
/// use lib60870::types::{CauseOfTransmission, ConnectionEvent, QOI_STATION};
///
/// let mut conn = ConnectionBuilder::new("127.0.0.1", 2404)
///     .originator_address(3)
///     .build()
///     .expect("Failed to create connection");
///
/// conn.set_connection_handler(|event| {
///     println!("Connection event: {:?}", event);
/// });
///
/// conn.set_asdu_handler(|asdu| {
///     println!("Received: {:?}", asdu);
///     for obj in asdu.parse_objects() {
///         println!("  {:?}", obj);
///     }
///     true // asdu is owned, can be stored if needed
/// });
///
/// if conn.connect() {
///     conn.send_start_dt();
///     conn.send_interrogation(CauseOfTransmission::Activation, 1, QOI_STATION);
/// }
/// ```
pub struct Connection {
    ptr: NonNull<sys::sCS104_Connection>,
    // Must be pinned because C callbacks hold a pointer to it
    callback_state: Option<Arc<CallbackState>>,
}

unsafe impl Send for Connection {}

impl Drop for Connection {
    fn drop(&mut self) {
        unsafe {
            sys::CS104_Connection_destroy(self.ptr.as_ptr());
        }
    }
}

impl Connection {
    /// Create a new connection with default settings.
    pub fn new(hostname: &str, port: u16) -> Option<Self> {
        Self::new_with_config(hostname, port as i32, 0, 10000)
    }

    fn new_with_config(
        hostname: &str,
        port: i32,
        originator_address: u8,
        timeout_ms: u32,
    ) -> Option<Self> {
        let c_hostname = CString::new(hostname).ok()?;
        let ptr = unsafe { sys::CS104_Connection_create(c_hostname.as_ptr(), port) };
        let ptr = NonNull::new(ptr)?;

        // Configure originator address
        unsafe {
            let al_params = sys::CS104_Connection_getAppLayerParameters(ptr.as_ptr());
            if !al_params.is_null() {
                (*al_params).originatorAddress = originator_address as i32;
            }
            sys::CS104_Connection_setConnectTimeout(ptr.as_ptr(), timeout_ms as i32);
        }

        Some(Self {
            ptr,
            callback_state: None,
        })
    }

    /// Get the raw pointer (for advanced use).
    pub fn as_ptr(&self) -> sys::CS104_Connection {
        self.ptr.as_ptr()
    }

    /// Set the connection event handler.
    ///
    /// Note: Setting handlers individually may reset previously set handlers.
    /// Use `set_handlers()` to set both at once.
    pub fn set_connection_handler<F>(&mut self, handler: F)
    where
        F: Fn(ConnectionEvent) + Send + Sync + 'static,
    {
        let state = Arc::new(CallbackState {
            connection_handler: Some(Box::new(handler)),
            asdu_handler: None,
        });

        let state_ptr = Arc::as_ptr(&state) as *mut c_void;
        self.callback_state = Some(state);

        unsafe {
            sys::CS104_Connection_setConnectionHandler(
                self.ptr.as_ptr(),
                Some(connection_handler_trampoline),
                state_ptr,
            );
        }
    }

    /// Set the ASDU received handler.
    ///
    /// The ASDU passed to the callback is an owned clone, safe to store.
    pub fn set_asdu_handler<F>(&mut self, handler: F)
    where
        F: Fn(Asdu) -> bool + Send + Sync + 'static,
    {
        let state = Arc::new(CallbackState {
            connection_handler: None,
            asdu_handler: Some(Box::new(handler)),
        });

        let state_ptr = Arc::as_ptr(&state) as *mut c_void;
        self.callback_state = Some(state);

        unsafe {
            sys::CS104_Connection_setASDUReceivedHandler(
                self.ptr.as_ptr(),
                Some(asdu_handler_trampoline),
                state_ptr,
            );
        }
    }

    /// Set both connection and ASDU handlers at once.
    ///
    /// This is the recommended way to set handlers as it avoids issues
    /// with handler state management.
    pub fn set_handlers<C, A>(&mut self, connection_handler: C, asdu_handler: A)
    where
        C: Fn(ConnectionEvent) + Send + Sync + 'static,
        A: Fn(Asdu) -> bool + Send + Sync + 'static,
    {
        let state = Arc::new(CallbackState {
            connection_handler: Some(Box::new(connection_handler)),
            asdu_handler: Some(Box::new(asdu_handler)),
        });

        let state_ptr = Arc::as_ptr(&state) as *mut c_void;
        self.callback_state = Some(state);

        unsafe {
            sys::CS104_Connection_setConnectionHandler(
                self.ptr.as_ptr(),
                Some(connection_handler_trampoline),
                state_ptr,
            );
            sys::CS104_Connection_setASDUReceivedHandler(
                self.ptr.as_ptr(),
                Some(asdu_handler_trampoline),
                state_ptr,
            );
        }
    }

    /// Connect to the server (blocking).
    ///
    /// Returns `true` if the connection was successful.
    pub fn connect(&self) -> bool {
        unsafe { sys::CS104_Connection_connect(self.ptr.as_ptr()) }
    }

    /// Start an asynchronous connection.
    ///
    /// Use the connection handler to be notified when the connection
    /// is established or fails.
    pub fn connect_async(&self) {
        unsafe { sys::CS104_Connection_connectAsync(self.ptr.as_ptr()) }
    }

    /// Send STARTDT (start data transfer) activation.
    ///
    /// This must be called after connecting to enable data transfer.
    pub fn send_start_dt(&self) {
        unsafe { sys::CS104_Connection_sendStartDT(self.ptr.as_ptr()) }
    }

    /// Send STOPDT (stop data transfer) activation.
    pub fn send_stop_dt(&self) {
        unsafe { sys::CS104_Connection_sendStopDT(self.ptr.as_ptr()) }
    }

    /// Close the connection.
    pub fn close(&self) {
        unsafe { sys::CS104_Connection_close(self.ptr.as_ptr()) }
    }

    /// Send a general interrogation command.
    ///
    /// # Arguments
    /// * `cot` - Cause of transmission (usually `Activation`)
    /// * `ca` - Common address (station address)
    /// * `qoi` - Qualifier of interrogation (use `QOI_STATION` for station interrogation)
    pub fn send_interrogation(&self, cot: CauseOfTransmission, ca: u16, qoi: u8) -> bool {
        unsafe {
            sys::CS104_Connection_sendInterrogationCommand(
                self.ptr.as_ptr(),
                cot.as_raw(),
                ca as i32,
                qoi,
            )
        }
    }

    /// Send a counter interrogation command.
    pub fn send_counter_interrogation(&self, cot: CauseOfTransmission, ca: u16, qcc: u8) -> bool {
        unsafe {
            sys::CS104_Connection_sendCounterInterrogationCommand(
                self.ptr.as_ptr(),
                cot.as_raw(),
                ca as i32,
                qcc,
            )
        }
    }

    /// Send a clock synchronization command.
    pub fn send_clock_sync(&self, ca: u16, time: &Timestamp) -> bool {
        unsafe {
            sys::CS104_Connection_sendClockSyncCommand(
                self.ptr.as_ptr(),
                ca as i32,
                time.as_raw() as *const _ as *mut _,
            )
        }
    }

    /// Send a test command.
    pub fn send_test_command(&self, ca: u16) -> bool {
        unsafe { sys::CS104_Connection_sendTestCommand(self.ptr.as_ptr(), ca as i32) }
    }

    /// Send a test command with timestamp.
    pub fn send_test_command_with_time(&self, ca: u16, tsc: u16, time: &Timestamp) -> bool {
        unsafe {
            sys::CS104_Connection_sendTestCommandWithTimestamp(
                self.ptr.as_ptr(),
                ca as i32,
                tsc,
                time.as_raw() as *const _ as *mut _,
            )
        }
    }

    /// Send a single command (C_SC_NA_1).
    ///
    /// # Arguments
    /// * `cot` - Cause of transmission
    /// * `ca` - Common address
    /// * `ioa` - Information object address
    /// * `state` - Command state (true = ON, false = OFF)
    /// * `select` - Select/Execute (true = select, false = execute)
    /// * `qualifier` - Qualifier (0 = no additional definition)
    pub fn send_single_command(
        &self,
        cot: CauseOfTransmission,
        ca: u16,
        ioa: u32,
        state: bool,
        select: bool,
        qualifier: u8,
    ) -> bool {
        unsafe {
            let sc = sys::SingleCommand_create(
                std::ptr::null_mut(),
                ioa as i32,
                state,
                select,
                qualifier as i32,
            );
            if sc.is_null() {
                return false;
            }
            let result = sys::CS104_Connection_sendProcessCommandEx(
                self.ptr.as_ptr(),
                cot.as_raw(),
                ca as i32,
                sc as sys::InformationObject,
            );
            sys::SingleCommand_destroy(sc);
            result
        }
    }

    /// Check if the transmit buffer is full.
    pub fn is_transmit_buffer_full(&self) -> bool {
        unsafe { sys::CS104_Connection_isTransmitBufferFull(self.ptr.as_ptr()) }
    }
}

// C callback trampolines

unsafe extern "C" fn connection_handler_trampoline(
    parameter: *mut c_void,
    _connection: sys::CS104_Connection,
    event: sys::CS104_ConnectionEvent,
) {
    if parameter.is_null() {
        return;
    }
    let state = &*(parameter as *const CallbackState);
    if let Some(ref handler) = state.connection_handler {
        if let Some(event) = ConnectionEvent::from_raw(event) {
            handler(event);
        }
    }
}

unsafe extern "C" fn asdu_handler_trampoline(
    parameter: *mut c_void,
    _address: i32,
    asdu: sys::CS101_ASDU,
) -> bool {
    if parameter.is_null() || asdu.is_null() {
        return false;
    }
    let state = &*(parameter as *const CallbackState);
    if let Some(ref handler) = state.asdu_handler {
        // Clone the ASDU so the callback gets an owned copy
        if let Some(owned_asdu) = Asdu::clone_from_ptr(asdu) {
            handler(owned_asdu)
        } else {
            false
        }
    } else {
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_connection_builder() {
        let conn = ConnectionBuilder::new("127.0.0.1", 2404)
            .originator_address(3)
            .connect_timeout_ms(5000)
            .build();
        assert!(conn.is_some());
    }

    #[test]
    fn test_connection_create() {
        let conn = Connection::new("127.0.0.1", 2404);
        assert!(conn.is_some());
    }
}