mechutil 0.8.0

Utility structures and functions for mechatronics applications.
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
//
// Copyright (C) 2024 - 2025 Automated Design Corp. All Rights Reserved.
//

//! CommandMessage - the core message type for IPC communication.
//!
//! This is the unified message format used for all communication between:
//! - autocore-server and external modules (over TCP)
//! - Internal servelets within autocore-server
//! - WebSocket clients and the backend
//!
//! ## Topic Format (FQDN)
//!
//! Topics use a dot-separated fully-qualified naming convention:
//! - `ads.plc1.GM.stDataResults` - ADS symbol access
//! - `modbus.server1.holding_0` - Modbus register
//! - `python.load_project` - Python command
//! - `gnv.app.version` - Config value
//!
//! The first segment typically identifies the module/domain.

use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use crc32fast::Hasher;
use num_derive::{FromPrimitive, ToPrimitive};
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
use serde_json::Value;

/// Global counter for generating unique transaction IDs
static TRANSACTION_ID_COUNTER: AtomicU32 = AtomicU32::new(1);

/// Generate a unique transaction ID
pub fn next_transaction_id() -> u32 {
    TRANSACTION_ID_COUNTER.fetch_add(1, Ordering::SeqCst)
}

/// Get the current timestamp in milliseconds since UNIX epoch
pub fn current_timecode() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

/// Message types for IPC communication.
///
/// These define the semantic meaning of each message in the protocol.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize_repr, Deserialize_repr, FromPrimitive, ToPrimitive)]
#[repr(u8)]
pub enum MessageType {
    /// Invalid or no operation. Used for keepalive/ping.
    NoOp = 0,

    /// Response to a previous request.
    Response = 1,

    /// Read request - module should return data for the specified topic.
    Read = 2,

    /// Write request - module should store the provided data.
    Write = 3,

    /// Subscribe to updates on a topic.
    Subscribe = 4,

    /// Unsubscribe from a topic.
    Unsubscribe = 5,

    /// Broadcast message (unsolicited push from module to server or vice versa).
    Broadcast = 6,

    /// Heartbeat/keepalive message.
    Heartbeat = 7,

    /// Control message (initialize, finalize, configuration).
    Control = 8,

    /// Generic request - module parses topic to determine action.
    Request = 10,
}

impl Default for MessageType {
    fn default() -> Self {
        MessageType::NoOp
    }
}

impl From<u8> for MessageType {
    fn from(value: u8) -> Self {
        match value {
            0 => MessageType::NoOp,
            1 => MessageType::Response,
            2 => MessageType::Read,
            3 => MessageType::Write,
            4 => MessageType::Subscribe,
            5 => MessageType::Unsubscribe,
            6 => MessageType::Broadcast,
            7 => MessageType::Heartbeat,
            8 => MessageType::Control,
            10 => MessageType::Request,
            _ => MessageType::NoOp,
        }
    }
}

impl From<MessageType> for u8 {
    fn from(value: MessageType) -> Self {
        value as u8
    }
}

/// CommandMessage is the unified message format for all IPC communication.
///
/// This struct serves as both request and response, with `message_type` indicating
/// the role and `success`/`error_message` fields populated for responses.
///
/// ## Example: Creating a read request
/// ```
/// use mechutil::ipc::{CommandMessage, MessageType};
///
/// let msg = CommandMessage::read("modbus.server1.holding_0");
/// assert_eq!(msg.message_type, MessageType::Read);
/// ```
///
/// ## Example: Creating a response
/// ```
/// use mechutil::ipc::CommandMessage;
/// use serde_json::json;
///
/// let mut response = CommandMessage::response(42, json!({"value": 123}));
/// assert!(response.success);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandMessage {
    /// Unique identifier to match responses to requests.
    /// Generated automatically if not specified.
    pub transaction_id: u32,

    /// Timestamp in milliseconds since UNIX epoch.
    /// Set automatically on message creation.
    pub timecode: i64,

    /// Fully-qualified topic name (FQDN).
    /// Format: "domain.subtopic.path" e.g., "ads.plc1.GM.stData"
    pub topic: String,

    /// The type/purpose of this message.
    pub message_type: MessageType,

    /// The payload data.
    /// - For requests: arguments/parameters
    /// - For responses: result data
    pub data: Value,

    /// CRC32 checksum of the message (optional, for integrity verification).
    #[serde(default)]
    pub crc: u32,

    /// Whether the operation was successful (for responses).
    #[serde(default)]
    pub success: bool,

    /// Error message if the operation failed (for responses).
    #[serde(default)]
    pub error_message: String,
}

impl Default for CommandMessage {
    fn default() -> Self {
        Self::new()
    }
}

impl CommandMessage {
    // =========================================================================
    // Constructors
    // =========================================================================

    /// Create an empty CommandMessage with auto-generated transaction_id and timecode.
    pub fn new() -> Self {
        Self {
            transaction_id: next_transaction_id(),
            timecode: current_timecode(),
            topic: String::new(),
            message_type: MessageType::NoOp,
            data: Value::Null,
            crc: 0,
            success: false,
            error_message: String::new(),
        }
    }

    /// Create a request message with the specified topic and data.
    pub fn request(topic: &str, data: Value) -> Self {
        Self {
            transaction_id: next_transaction_id(),
            timecode: current_timecode(),
            topic: topic.to_string(),
            message_type: MessageType::Request,
            data,
            crc: 0,
            success: false,
            error_message: String::new(),
        }
    }

    /// Create a read request for the specified topic.
    pub fn read(topic: &str) -> Self {
        Self {
            transaction_id: next_transaction_id(),
            timecode: current_timecode(),
            topic: topic.to_string(),
            message_type: MessageType::Read,
            data: Value::Null,
            crc: 0,
            success: false,
            error_message: String::new(),
        }
    }

    /// Create a write request for the specified topic with data.
    pub fn write(topic: &str, data: Value) -> Self {
        Self {
            transaction_id: next_transaction_id(),
            timecode: current_timecode(),
            topic: topic.to_string(),
            message_type: MessageType::Write,
            data,
            crc: 0,
            success: false,
            error_message: String::new(),
        }
    }

    /// Create a subscribe request for the specified topic.
    pub fn subscribe(topic: &str) -> Self {
        Self {
            transaction_id: next_transaction_id(),
            timecode: current_timecode(),
            topic: topic.to_string(),
            message_type: MessageType::Subscribe,
            data: Value::Null,
            crc: 0,
            success: false,
            error_message: String::new(),
        }
    }

    /// Create an unsubscribe request for the specified topic.
    pub fn unsubscribe(topic: &str) -> Self {
        Self {
            transaction_id: next_transaction_id(),
            timecode: current_timecode(),
            topic: topic.to_string(),
            message_type: MessageType::Unsubscribe,
            data: Value::Null,
            crc: 0,
            success: false,
            error_message: String::new(),
        }
    }

    /// Create a successful response to a request.
    pub fn response(transaction_id: u32, data: Value) -> Self {
        Self {
            transaction_id,
            timecode: current_timecode(),
            topic: String::new(),
            message_type: MessageType::Response,
            data,
            crc: 0,
            success: true,
            error_message: String::new(),
        }
    }

    /// Create an error response to a request.
    pub fn error_response(transaction_id: u32, error: &str) -> Self {
        Self {
            transaction_id,
            timecode: current_timecode(),
            topic: String::new(),
            message_type: MessageType::Response,
            data: Value::Null,
            crc: 0,
            success: false,
            error_message: error.to_string(),
        }
    }

    /// Create a broadcast message with the specified topic and data.
    pub fn broadcast(topic: &str, data: Value) -> Self {
        Self {
            transaction_id: next_transaction_id(),
            timecode: current_timecode(),
            topic: topic.to_string(),
            message_type: MessageType::Broadcast,
            data,
            crc: 0,
            success: true,
            error_message: String::new(),
        }
    }

    /// Create a heartbeat message.
    pub fn heartbeat() -> Self {
        Self {
            transaction_id: next_transaction_id(),
            timecode: current_timecode(),
            topic: String::new(),
            message_type: MessageType::Heartbeat,
            data: Value::Null,
            crc: 0,
            success: true,
            error_message: String::new(),
        }
    }

    /// Create a control message.
    pub fn control(topic: &str, data: Value) -> Self {
        Self {
            transaction_id: next_transaction_id(),
            timecode: current_timecode(),
            topic: topic.to_string(),
            message_type: MessageType::Control,
            data,
            crc: 0,
            success: false,
            error_message: String::new(),
        }
    }

    // =========================================================================
    // Builder methods
    // =========================================================================

    /// Set the transaction ID.
    pub fn with_transaction_id(mut self, id: u32) -> Self {
        self.transaction_id = id;
        self
    }

    /// Set the topic.
    pub fn with_topic(mut self, topic: &str) -> Self {
        self.topic = topic.to_string();
        self
    }

    /// Set the data payload.
    pub fn with_data(mut self, data: Value) -> Self {
        self.data = data;
        self
    }

    /// Set as successful with data.
    pub fn with_success(mut self, data: Value) -> Self {
        self.success = true;
        self.data = data;
        self.error_message.clear();
        self
    }

    /// Set as error with message.
    pub fn with_error(mut self, error: &str) -> Self {
        self.success = false;
        self.error_message = error.to_string();
        self
    }

    // =========================================================================
    // Mutation methods
    // =========================================================================

    /// Set successful result on this message.
    pub fn set_success(&mut self, data: Value) {
        self.message_type = MessageType::Response;
        self.success = true;
        self.data = data;
        self.error_message.clear();
    }

    /// Set error result on this message.
    pub fn set_error(&mut self, error: &str) {
        self.message_type = MessageType::Response;
        self.success = false;
        self.error_message = error.to_string();
    }

    /// Convert this request into a successful response.
    pub fn into_response(mut self, data: Value) -> Self {
        self.message_type = MessageType::Response;
        self.timecode = current_timecode();
        self.success = true;
        self.data = data;
        self.error_message.clear();
        self
    }

    /// Convert this request into an error response.
    pub fn into_error_response(mut self, error: &str) -> Self {
        self.message_type = MessageType::Response;
        self.timecode = current_timecode();
        self.success = false;
        self.error_message = error.to_string();
        self
    }

    // =========================================================================
    // Query methods
    // =========================================================================

    /// Check if this is a response message.
    pub fn is_response(&self) -> bool {
        self.message_type == MessageType::Response
    }

    /// Check if this is a broadcast message.
    pub fn is_broadcast(&self) -> bool {
        self.message_type == MessageType::Broadcast
    }

    /// Check if this is a heartbeat message.
    pub fn is_heartbeat(&self) -> bool {
        self.message_type == MessageType::Heartbeat
    }

    /// Check if this is a request (Read, Write, Subscribe, Unsubscribe, or Request).
    pub fn is_request(&self) -> bool {
        matches!(
            self.message_type,
            MessageType::Read
                | MessageType::Write
                | MessageType::Subscribe
                | MessageType::Unsubscribe
                | MessageType::Request
        )
    }

    /// Get the domain (first segment of the topic).
    pub fn domain(&self) -> &str {
        self.topic.split('.').next().unwrap_or("")
    }

    /// Get the subtopic (everything after the first dot), normalized to lowercase.
    pub fn subtopic(&self) -> String {
        self.topic.split_once('.')
            .map(|(_, rest)| rest.to_ascii_lowercase())
            .unwrap_or_default()
    }

    // =========================================================================
    // CRC methods
    // =========================================================================

    /// Compute CRC32 of the message content.
    pub fn compute_crc(&self) -> u32 {
        let mut hasher = Hasher::new();
        hasher.update(&self.transaction_id.to_le_bytes());
        hasher.update(&self.timecode.to_le_bytes());
        hasher.update(self.topic.as_bytes());
        hasher.update(&[self.message_type as u8]);
        if let Ok(data_bytes) = serde_json::to_vec(&self.data) {
            hasher.update(&data_bytes);
        }
        hasher.update(&[self.success as u8]);
        hasher.update(self.error_message.as_bytes());
        hasher.finalize()
    }

    /// Update the CRC field with the computed value.
    pub fn update_crc(&mut self) {
        self.crc = self.compute_crc();
    }

    /// Verify that the CRC matches the message content.
    pub fn verify_crc(&self) -> bool {
        self.crc == 0 || self.crc == self.compute_crc()
    }
}

// =============================================================================
// Legacy compatibility types (deprecated, will be removed)
// =============================================================================

/// Defines an action that can be executed on a servelet.
///
/// **Deprecated**: Use CommandMessage directly with topic field.
#[deprecated(since = "0.6.0", note = "Use CommandMessage with topic field instead")]
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Action {
    /// The name of the target servelet instance of this command.
    pub domain: String,
    /// The name of the function in the servelet to execute.
    pub fname: String,
    /// The arguments to pass with this command.
    pub args: serde_json::Value,
}

#[allow(deprecated)]
impl Action {
    pub fn new() -> Self {
        Self {
            domain: String::new(),
            fname: String::new(),
            args: serde_json::Value::Null,
        }
    }

    /// Convert to a topic string.
    pub fn to_topic(&self) -> String {
        if self.fname.is_empty() {
            self.domain.to_lowercase()
        } else {
            format!("{}.{}", self.domain.to_lowercase(), self.fname.to_lowercase())
        }
    }
}

/// The result portion of a CommandMessage.
///
/// **Deprecated**: Success and error fields are now directly on CommandMessage.
#[deprecated(since = "0.6.0", note = "Use CommandMessage.success and CommandMessage.error_message directly")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandMessageResult {
    /// If true, the message was actually processed and the result updated.
    pub valid: bool,
    /// JSON object containing the result of the command.
    pub data: Value,
    /// If true, the command was processed successfully.
    pub success: bool,
    /// Error message if failed.
    pub error_message: String,
}

#[allow(deprecated)]
impl Default for CommandMessageResult {
    fn default() -> Self {
        CommandMessageResult {
            valid: false,
            data: Value::Null,
            success: false,
            error_message: String::new(),
        }
    }
}

#[allow(deprecated)]
impl CommandMessageResult {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn success(data: Value) -> Self {
        Self {
            valid: true,
            data,
            success: true,
            error_message: String::new(),
        }
    }

    pub fn error(message: &str) -> Self {
        Self {
            valid: true,
            data: Value::Null,
            success: false,
            error_message: message.to_string(),
        }
    }
}

// =============================================================================
// Tests
// =============================================================================

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

    #[test]
    fn test_read_request() {
        let msg = CommandMessage::read("modbus.server1.holding_0");
        assert_eq!(msg.message_type, MessageType::Read);
        assert_eq!(msg.topic, "modbus.server1.holding_0");
        assert_eq!(msg.domain(), "modbus");
        assert_eq!(msg.subtopic(), "server1.holding_0");
        assert!(msg.is_request());
        assert!(!msg.is_response());
    }

    #[test]
    fn test_write_request() {
        let msg = CommandMessage::write("gnv.app.theme", serde_json::json!("dark"));
        assert_eq!(msg.message_type, MessageType::Write);
        assert_eq!(msg.data, serde_json::json!("dark"));
        assert!(msg.is_request());
    }

    #[test]
    fn test_response() {
        let msg = CommandMessage::response(42, serde_json::json!({"value": 123}));
        assert_eq!(msg.transaction_id, 42);
        assert!(msg.is_response());
        assert!(msg.success);
        assert_eq!(msg.data, serde_json::json!({"value": 123}));
    }

    #[test]
    fn test_error_response() {
        let msg = CommandMessage::error_response(42, "Something went wrong");
        assert_eq!(msg.transaction_id, 42);
        assert!(msg.is_response());
        assert!(!msg.success);
        assert_eq!(msg.error_message, "Something went wrong");
    }

    #[test]
    fn test_broadcast() {
        let msg = CommandMessage::broadcast("ads.plc1.notifications", serde_json::json!({"symbol": "test"}));
        assert!(msg.is_broadcast());
        assert!(msg.success);
    }

    #[test]
    fn test_into_response() {
        let request = CommandMessage::read("test.value");
        let tid = request.transaction_id;

        let response = request.into_response(serde_json::json!(42));
        assert_eq!(response.transaction_id, tid);
        assert!(response.is_response());
        assert!(response.success);
        assert_eq!(response.data, serde_json::json!(42));
    }

    #[test]
    fn test_into_error_response() {
        let request = CommandMessage::read("test.value");
        let tid = request.transaction_id;

        let response = request.into_error_response("Not found");
        assert_eq!(response.transaction_id, tid);
        assert!(response.is_response());
        assert!(!response.success);
        assert_eq!(response.error_message, "Not found");
    }

    #[test]
    fn test_crc() {
        let mut msg = CommandMessage::read("test.topic");
        msg.update_crc();
        assert!(msg.verify_crc());
        assert_ne!(msg.crc, 0);

        // Modify and verify CRC fails
        let original_crc = msg.crc;
        msg.topic = "modified.topic".to_string();
        assert_ne!(msg.compute_crc(), original_crc);
    }

    #[test]
    fn test_serialization() {
        let msg = CommandMessage::write("test.value", serde_json::json!({"key": "value"}));
        let json = serde_json::to_string(&msg).unwrap();
        let decoded: CommandMessage = serde_json::from_str(&json).unwrap();

        assert_eq!(decoded.topic, msg.topic);
        assert_eq!(decoded.message_type, msg.message_type);
        assert_eq!(decoded.data, msg.data);
    }

    #[test]
    fn test_domain_extraction() {
        let msg = CommandMessage::read("ads.plc1.GM.stDataResults");
        assert_eq!(msg.domain(), "ads");
        assert_eq!(msg.subtopic(), "plc1.gm.stdataresults");

        let msg2 = CommandMessage::read("simple");
        assert_eq!(msg2.domain(), "simple");
        assert_eq!(msg2.subtopic(), "");
    }
}