pvxs-sys 0.1.1

Low-level FFI bindings for EPICS PVXS library
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
// Copyright 2026 Tine Zata
// SPDX-License-Identifier: MPL-2.0
mod test_pvxs_monitor_callbacks {
    use pvxs_sys::{AtomicUsize, Context, MonitorEvent, NTScalarMetadataBuilder, Ordering, Server};
    use std::thread;
    use std::time::Duration;

    // Global counters for callback testing
    static CONNECT_COUNTER: AtomicUsize = AtomicUsize::new(0);
    static DISCONNECT_COUNTER: AtomicUsize = AtomicUsize::new(0);
    static EVENT_COUNTER: AtomicUsize = AtomicUsize::new(0);

    extern "C" fn connection_callback() {
        CONNECT_COUNTER.fetch_add(1, Ordering::SeqCst);
        println!(
            "Connection event detected! Count: {}",
            CONNECT_COUNTER.load(Ordering::SeqCst)
        );
    }

    extern "C" fn disconnection_callback() {
        DISCONNECT_COUNTER.fetch_add(1, Ordering::SeqCst);
        println!(
            "Disconnection event detected! Count: {}",
            DISCONNECT_COUNTER.load(Ordering::SeqCst)
        );
    }

    extern "C" fn generic_event_callback() {
        EVENT_COUNTER.fetch_add(1, Ordering::SeqCst);
        println!(
            "Event detected! Count: {}",
            EVENT_COUNTER.load(Ordering::SeqCst)
        );
    }

    #[test]
    fn test_monitor_connection_and_disconnection_events_off() {
        // Create a server with a PV
        let srv = Server::start_from_env().expect("Failed to create server");
        srv.create_pv_double("callback:test:stop", 2.71, NTScalarMetadataBuilder::new())
            .expect("Failed to create PV");

        thread::sleep(Duration::from_millis(500));

        let mut ctx = Context::from_env().expect("Failed to create context");

        // Test 1: connect_exception(false) should suppress Connected exceptions (maskConnected(true))
        let mut monitor1 = ctx
            .monitor_builder("callback:test:stop")
            .expect("Failed to create monitor builder")
            .connect_exception(false) // maskConnected(true) - suppresses connection exceptions
            .disconnect_exception(false) // maskDisconnected(true) - suppresses disconnection exceptions
            .exec()
            .expect("Failed to create monitor1");

        monitor1.start().expect("Failed to start monitor1");
        thread::sleep(Duration::from_millis(500));

        // Pop events - we expect to get either data or Connected exception
        let mut got_connected_exception = false;
        let mut got_disconnected_exception = false;
        let mut got_finished_exception = false;
        let mut got_remote_error_exception = false;
        let mut got_generic_exception = false;

        let mut data_count1 = 0;
        for _ in 0..20 {
            match monitor1.pop() {
                Ok(Some(_)) => data_count1 += 1,
                Ok(None) => break,
                Err(MonitorEvent::Connected(_)) => {
                    got_connected_exception = true;
                }
                Err(MonitorEvent::Disconnected(_)) => {
                    got_disconnected_exception = true;
                }
                Err(MonitorEvent::Finished(_)) => {
                    got_finished_exception = true;
                }
                Err(MonitorEvent::RemoteError(_)) => {
                    got_remote_error_exception = true;
                }
                Err(MonitorEvent::ClientError(_)) => {
                    got_generic_exception = true;
                }
            }
        }

        monitor1.stop().expect("Failed to stop monitor1");

        // Verify: with connect_exception(false), do not get a connection exception
        assert!(
            !got_connected_exception,
            "Did not expect a connection exception with connect_exception(false)"
        );
        assert!(
            !got_disconnected_exception,
            "Did not expect a disconnection exception with disconnect_exception(false)"
        );
        assert!(
            !got_finished_exception,
            "Did not expect a finished exception with disconnect_exception(false)"
        );
        assert!(
            !got_remote_error_exception,
            "Did not expect a remote error exception"
        );
        assert!(
            !got_generic_exception,
            "Did not expect a generic client error exception"
        );
        assert_eq!(
            data_count1, 1,
            "Expected data with as pop returns data after the initial connection"
        );

        srv.stop_drop().expect("Failed to stop server");
    }

    #[test]
    fn test_monitor_connection_on_and_disconnection_off() {
        // Create a server with a PV
        let srv = Server::start_from_env().expect("Failed to create server");
        srv.create_pv_double("callback:test:stop", 2.71, NTScalarMetadataBuilder::new())
            .expect("Failed to create PV");

        let mut ctx = Context::from_env().expect("Failed to create context");

        thread::sleep(Duration::from_millis(500));

        // Reset flags for next test
        let mut got_connected_exception = false;
        let mut got_disconnected_exception = false;
        let mut got_finished_exception = false;
        let mut got_remote_error_exception = false;
        let mut got_generic_exception = false;

        // Test 2: connect_exception(true) should queue connection exceptions as data (no exception)
        let mut monitor2 = ctx
            .monitor_builder("callback:test:stop")
            .expect("Failed to create monitor builder")
            .connect_exception(true) // maskConnected(false) - exceptions queued
            .disconnect_exception(false) // maskDisconnected(true) - throws exception
            .exec()
            .expect("Failed to create monitor2");

        monitor2.start().expect("Failed to start monitor2");
        thread::sleep(Duration::from_millis(500));

        let mut data_count2 = 0;
        for _ in 0..20 {
            match monitor2.pop() {
                Ok(Some(_)) => data_count2 += 1,
                Ok(None) => break,
                Err(MonitorEvent::Connected(_)) => {
                    got_connected_exception = true;
                }
                Err(MonitorEvent::Disconnected(_)) => {
                    got_disconnected_exception = true;
                }
                Err(MonitorEvent::Finished(_)) => {
                    got_finished_exception = true;
                }
                Err(MonitorEvent::RemoteError(_)) => {
                    got_remote_error_exception = true;
                }
                Err(MonitorEvent::ClientError(_)) => {
                    got_generic_exception = true;
                }
            }
        }

        monitor2.stop().expect("Failed to stop monitor2");

        assert!(
            got_connected_exception,
            "Expected connection exception to be queued as data with connect_exception(true)"
        );
        assert!(
            !got_disconnected_exception,
            "Did not expect disconnection exception with disconnect_exception(false)"
        );
        assert!(!got_finished_exception, "Did not expect finished exception");
        assert!(
            !got_remote_error_exception,
            "Did not expect a remote error exception"
        );
        assert!(
            !got_generic_exception,
            "Did not expect a generic client error exception"
        );
        assert!(
            data_count2 > 0,
            "Expected data before disconnection occurred, but got {}",
            data_count2
        );

        srv.stop_drop().expect("Failed to stop server");
    }

    #[test]
    fn test_monitor_connection_off_disconnection_on() {
        // Create a server with a PV
        let mut srv = Some(Server::start_from_env().expect("Failed to create server"));
        srv.as_ref()
            .unwrap()
            .create_pv_double("callback:test:stop", 2.71, NTScalarMetadataBuilder::new())
            .expect("Failed to create PV");

        let mut ctx = Context::from_env().expect("Failed to create context");
        thread::sleep(Duration::from_millis(500));

        // Reset flags for next test
        let mut got_connected_exception = false;
        let mut got_disconnected_exception = false;
        let mut got_finished_exception = false;
        let mut got_remote_error_exception = false;
        let mut got_generic_exception = false;

        // Test 3: disconnect_exception(true) should throw disconnection exceptions (maskDisconnected(false))
        let mut monitor3 = ctx
            .monitor_builder("callback:test:stop")
            .expect("Failed to create monitor builder")
            .connect_exception(false) // maskConnected(true) - suppresses connection exceptions
            .disconnect_exception(true) // maskDisconnected(false) - throws disconnection exceptions
            .exec()
            .expect("Failed to create monitor3");

        monitor3.start().expect("Failed to start monitor3");
        thread::sleep(Duration::from_millis(500)); // Wait for connection

        let mut data_count3 = 0;
        for i in 0..20 {
            match monitor3.pop() {
                Ok(Some(_)) => data_count3 += 1,
                Ok(None) => { // Do nothing, continue
                }
                Err(MonitorEvent::Connected(e)) => {
                    got_connected_exception = true;
                    println!("Unexpected connected exception: {}", e);
                }
                Err(MonitorEvent::Disconnected(e)) => {
                    got_disconnected_exception = true;
                    println!("Disconnection event detected: {}", e);
                }
                Err(MonitorEvent::Finished(e)) => {
                    got_finished_exception = true;
                    println!("Finished event detected: {}", e);
                }
                Err(MonitorEvent::RemoteError(e)) => {
                    got_remote_error_exception = true;
                    println!("Remote error event detected: {}", e);
                }
                Err(MonitorEvent::ClientError(e)) => {
                    got_generic_exception = true;
                    println!("Generic client error: {}", e);
                }
            }
            if i == 10 {
                // Stop the SERVER to trigger disconnection event
                srv.take()
                    .unwrap()
                    .stop_drop()
                    .expect("Failed to stop server to trigger disconnection");
                thread::sleep(Duration::from_millis(500));
            }
        }

        // Cleanup - server already stopped above
        thread::sleep(Duration::from_millis(500));

        assert!(
            got_disconnected_exception,
            "Expected disconnection exception to be thrown with disconnect_exception(true)"
        );
        assert!(
            !got_connected_exception,
            "Did not expect a connection exception with connect_exception(false)"
        );
        assert!(!got_finished_exception, "Did not expect finished exception");
        assert!(
            !got_remote_error_exception,
            "Did not expect a remote error exception"
        );
        assert!(
            !got_generic_exception,
            "Did not expect a generic client error exception"
        );
        assert!(
            data_count3 > 0,
            "Expected data before disconnection occurred, but got {}",
            data_count3
        );
    }

    #[test]
    fn test_monitor_multiple_callbacks() {
        // Test using different callbacks for different scenarios
        CONNECT_COUNTER.store(0, Ordering::SeqCst);
        DISCONNECT_COUNTER.store(0, Ordering::SeqCst);

        let srv = Server::start_from_env().expect("Failed to create server");
        let _pv = srv
            .create_pv_double("callback:test:multi", 4.56, NTScalarMetadataBuilder::new())
            .expect("Failed to create PV");

        thread::sleep(Duration::from_millis(500));

        let mut ctx = Context::from_env().expect("Failed to create context");

        // Monitor focused on connection exceptions
        let mut mon_connect = ctx
            .monitor_builder("callback:test:multi")
            .expect("Failed to create monitor builder")
            .connect_exception(true)
            .disconnect_exception(false)
            .event(connection_callback)
            .exec()
            .expect("Failed to create connection monitor");

        // Monitor focused on disconnection exceptions
        let mut mon_disconnect = ctx
            .monitor_builder("callback:test:multi")
            .expect("Failed to create monitor builder")
            .connect_exception(false)
            .disconnect_exception(true)
            .event(disconnection_callback)
            .exec()
            .expect("Failed to create disconnection monitor");

        mon_connect
            .start()
            .expect("Failed to start connection monitor");
        mon_disconnect
            .start()
            .expect("Failed to start disconnection monitor");

        thread::sleep(Duration::from_millis(1000));

        let connect_count = CONNECT_COUNTER.load(Ordering::SeqCst);
        let disconnect_count = DISCONNECT_COUNTER.load(Ordering::SeqCst);

        println!("Connection callbacks: {}", connect_count);
        println!("Disconnection callbacks: {}", disconnect_count);

        // We should see connection callbacks when monitors start
        assert!(connect_count > 0, "Expected connection callbacks");

        // Cleanup
        mon_connect
            .stop()
            .expect("Failed to stop connection monitor");
        mon_disconnect
            .stop()
            .expect("Failed to stop disconnection monitor");
        srv.stop_drop().expect("Failed to stop server");
    }

    #[test]
    fn test_monitor_callback_with_updates() {
        // Test that callbacks are invoked when values update
        EVENT_COUNTER.store(0, Ordering::SeqCst);

        let name = "callback:test:updates";

        let srv = Server::start_from_env().expect("Failed to create server");
        srv.create_pv_double(name, 0.0, NTScalarMetadataBuilder::new())
            .expect("Failed to create PV");

        thread::sleep(Duration::from_millis(500));

        let mut ctx = Context::from_env().expect("Failed to create context");
        let mut monitor = ctx
            .monitor_builder(name)
            .expect("Failed to create monitor builder")
            .connect_exception(true)
            .disconnect_exception(false)
            .event(generic_event_callback)
            .exec()
            .expect("Failed to create monitor");

        monitor.start().expect("Failed to start monitor");
        thread::sleep(Duration::from_millis(500));

        // Drain the queue completely before resetting the counter.
        // PVXS event callbacks only fire on the empty→non-empty queue transition,
        // so any items left in the queue from the initial connection will prevent
        // subsequent posts from triggering the callback.
        loop {
            match monitor.pop() {
                Ok(Some(_)) => {}
                Ok(None) => break,
                Err(_) => {}
            }
        }

        // Reset counter after draining, so queue is empty and the next post triggers the callback
        EVENT_COUNTER.store(0, Ordering::SeqCst);

        // Post some values to trigger callbacks.
        // Between each post we must drain the queue completely: PVXS only fires the
        // event callback on the empty→non-empty queue transition, so if the previous
        // item is still sitting in the queue the next post never triggers the callback.
        for i in 1..=5 {
            srv.post_double(name, i as f64)
                .expect("Failed to post value");
            // Wait long enough for the item to arrive in the subscription queue
            thread::sleep(Duration::from_millis(100));
            // Drain so the queue is empty before the next post
            loop {
                match monitor.pop() {
                    Ok(Some(_)) => {}
                    Ok(None) => break,
                    Err(_) => {}
                }
            }
        }

        // Wait for any in-flight callbacks to complete
        thread::sleep(Duration::from_millis(200));

        let event_count = EVENT_COUNTER.load(Ordering::SeqCst);
        println!("Callbacks after {} updates: {}", 5, event_count);

        // Each post should trigger exactly one callback (one empty→non-empty transition each)
        assert_eq!(
            event_count, 5,
            "Expected 5 callbacks, one per post (got {})",
            event_count
        );

        // Cleanup
        monitor.stop().expect("Failed to stop monitor");
        srv.stop_drop().expect("Failed to stop server");
    }

    #[test]
    fn test_monitor_multiple_client_monitors() {
        // Test that mask configuration works correctly

        // Create a server
        let srv = Server::start_from_env().expect("Failed to create server");
        srv.create_pv_double("callback:test:mask", 1.23, NTScalarMetadataBuilder::new())
            .expect("Failed to create PV");

        thread::sleep(Duration::from_millis(500));

        let mut ctx = Context::from_env().expect("Failed to create context");

        // Test 1: With connection events masked out (should not get connection events)
        EVENT_COUNTER.store(0, Ordering::SeqCst);
        let mut monitor1 = ctx
            .monitor_builder("callback:test:mask")
            .expect("Failed to create monitor builder")
            .connect_exception(false) // Mask out connection exceptions
            .disconnect_exception(false)
            .event(generic_event_callback)
            .exec()
            .expect("Failed to create monitor1");

        monitor1.start().expect("Failed to start monitor1");
        thread::sleep(Duration::from_millis(500));

        let count1 = EVENT_COUNTER.load(Ordering::SeqCst);
        println!("Events with connection masked: {}", count1);

        // Test 2: With connection events enabled
        EVENT_COUNTER.store(0, Ordering::SeqCst);
        let mut monitor2 = ctx
            .monitor_builder("callback:test:mask")
            .expect("Failed to create monitor builder")
            .connect_exception(true) // Include connection exceptions
            .disconnect_exception(false)
            .event(generic_event_callback)
            .exec()
            .expect("Failed to create monitor2");

        monitor2.start().expect("Failed to start monitor2");
        thread::sleep(Duration::from_millis(500));

        let count2 = EVENT_COUNTER.load(Ordering::SeqCst);
        println!("Events with connection enabled: {}", count2);

        // With connection events enabled, we should get more events
        assert!(
            count2 >= count1,
            "Expected more events with connection enabled ({}) vs masked ({})",
            count2,
            count1
        );

        // Cleanup
        monitor1.stop().expect("Failed to stop monitor1");
        monitor2.stop().expect("Failed to stop monitor2");
        srv.stop_drop().expect("Failed to stop server");
    }
}