rust-ethernet-ip 0.7.0

High-performance EtherNet/IP communication library for Allen-Bradley CompactLogix and ControlLogix PLCs
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
// tag_path.rs - Advanced Tag Path Parsing for Allen-Bradley PLCs
// =========================================================================
//
// This module provides comprehensive tag path parsing and generation for
// Allen-Bradley CompactLogix and ControlLogix PLCs, supporting:
//
// - Program-scoped tags: "Program:MainProgram.Tag1"
// - Array elements: "MyArray[5]", "MyArray[1,2,3]"
// - Bit access: "MyDINT.15" (access individual bits)
// - UDT members: "MyUDT.Member1.SubMember"
// - String operations: "MyString.LEN", "MyString.DATA[5]"
//
// =========================================================================

use crate::error::{EtherNetIpError, Result};
use std::fmt;

/// Represents different types of tag addressing supported by Allen-Bradley PLCs
#[derive(Debug, Clone, PartialEq)]
pub enum TagPath {
    /// Simple controller-scoped tag: `MyTag`
    Controller { tag_name: String },

    /// Program-scoped tag: `Program:MainProgram.MyTag`
    Program {
        program_name: String,
        tag_name: String,
    },

    /// Array element access: `MyArray[5]` or `MyArray[1,2,3]`
    Array {
        base_path: Box<TagPath>,
        indices: Vec<u32>,
    },

    /// Bit access within a tag: "MyDINT.15"
    Bit {
        base_path: Box<TagPath>,
        bit_index: u8,
    },

    /// UDT member access: "MyUDT.Member1"
    Member {
        base_path: Box<TagPath>,
        member_name: String,
    },

    /// String length access: "MyString.LEN"
    StringLength { base_path: Box<TagPath> },

    /// String data access: "MyString.DATA[5]"
    StringData { base_path: Box<TagPath>, index: u32 },
}

impl TagPath {
    /// Parses a tag path string into a structured `TagPath`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rust_ethernet_ip::TagPath;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// // Simple controller tag
    /// let path = TagPath::parse("MyTag")?;
    ///
    /// // Program-scoped tag
    /// let path = TagPath::parse("Program:MainProgram.MyTag")?;
    ///
    /// // Array element
    /// let path = TagPath::parse("MyArray[5]")?;
    ///
    /// // Multi-dimensional array
    /// let path = TagPath::parse("Matrix[1,2,3]")?;
    ///
    /// // Bit access
    /// let path = TagPath::parse("StatusWord.15")?;
    ///
    /// // UDT member
    /// let path = TagPath::parse("MotorData.Speed")?;
    ///
    /// // Complex nested path
    /// let path = TagPath::parse("Program:Safety.Devices[2].Status.15")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn parse(path_str: &str) -> Result<Self> {
        let parser = TagPathParser::new(path_str);
        parser.parse()
    }

    /// Converts the `TagPath` back to a string representation
    pub fn as_string(&self) -> String {
        match self {
            TagPath::Controller { tag_name } => tag_name.clone(),
            TagPath::Program {
                program_name,
                tag_name,
            } => {
                format!("Program:{program_name}.{tag_name}")
            }
            TagPath::Array { base_path, indices } => {
                let base = base_path.as_string();
                let indices_str = indices
                    .iter()
                    .map(u32::to_string)
                    .collect::<Vec<_>>()
                    .join(",");
                format!("{base}[{indices_str}]")
            }
            TagPath::Bit {
                base_path,
                bit_index,
            } => {
                format!("{base_path}.{bit_index}")
            }
            TagPath::Member {
                base_path,
                member_name,
            } => {
                format!("{base_path}.{member_name}")
            }
            TagPath::StringLength { base_path } => {
                format!("{base_path}.LEN")
            }
            TagPath::StringData { base_path, index } => {
                format!("{base_path}.DATA[{index}]")
            }
        }
    }

    /// Generates the CIP path bytes for this tag path
    ///
    /// This converts the structured tag path into the binary format
    /// required by the CIP protocol for EtherNet/IP communication.
    pub fn to_cip_path(&self) -> Result<Vec<u8>> {
        let mut path = Vec::new();
        self.build_cip_path(&mut path)?;

        // Pad to even length if necessary
        if path.len() % 2 != 0 {
            path.push(0x00);
        }

        Ok(path)
    }

    /// Recursively builds the CIP path bytes
    fn build_cip_path(&self, path: &mut Vec<u8>) -> Result<()> {
        match self {
            TagPath::Controller { tag_name } => {
                // ANSI Extended Symbol Segment
                path.push(0x91);
                path.push(tag_name.len() as u8);
                path.extend_from_slice(tag_name.as_bytes());
            }

            TagPath::Program {
                program_name,
                tag_name,
            } => {
                // Program scope requires special handling
                // First add program name segment
                path.push(0x91);
                let program_path = format!("Program:{program_name}");
                path.push(program_path.len() as u8);
                path.extend_from_slice(program_path.as_bytes());

                // Pad to even length if necessary after program segment
                if path.len() % 2 != 0 {
                    path.push(0x00);
                }

                // Then add tag name segment
                path.push(0x91);
                path.push(tag_name.len() as u8);
                path.extend_from_slice(tag_name.as_bytes());
            }

            TagPath::Array { base_path, indices } => {
                // Build base path first
                base_path.build_cip_path(path)?;

                // Pad to even length if necessary before adding array segments
                if path.len() % 2 != 0 {
                    path.push(0x00);
                }

                // Add array indices using proper Element ID segment format
                // Reference: 1756-PM020, Pages 603-611, 870-890
                // Element ID segments use different sizes based on index value:
                // - 0-255: 8-bit Element ID (0x28 + 1 byte value)
                // - 256-65535: 16-bit Element ID (0x29 0x00 + 2 bytes low, high)
                // - 65536+: 32-bit Element ID (0x2A 0x00 + 4 bytes lowest to highest)
                for &index in indices {
                    if index <= 255 {
                        // 8-bit Element ID: 0x28 + index (2 bytes total)
                        path.push(0x28);
                        path.push(index as u8);
                    } else if index <= 65535 {
                        // 16-bit Element ID: 0x29, 0x00, low_byte, high_byte (4 bytes total)
                        path.push(0x29);
                        path.push(0x00); // Padding byte
                        path.extend_from_slice(&(index as u16).to_le_bytes());
                    } else {
                        // 32-bit Element ID: 0x2A, 0x00, byte0, byte1, byte2, byte3 (6 bytes total)
                        path.push(0x2A);
                        path.push(0x00); // Padding byte
                        path.extend_from_slice(&index.to_le_bytes());
                    }
                }
            }

            TagPath::Bit {
                base_path,
                bit_index,
            } => {
                // Build base path first
                base_path.build_cip_path(path)?;

                // Pad to even length if necessary before adding bit segment
                if path.len() % 2 != 0 {
                    path.push(0x00);
                }

                // Add bit segment
                path.push(0x29); // Bit segment
                path.push(*bit_index);
            }

            TagPath::Member {
                base_path,
                member_name,
            } => {
                // Build base path first
                base_path.build_cip_path(path)?;

                // Pad to even length if necessary before adding member segment
                if path.len() % 2 != 0 {
                    path.push(0x00);
                }

                // Add member segment
                path.push(0x91);
                path.push(member_name.len() as u8);
                path.extend_from_slice(member_name.as_bytes());
            }

            TagPath::StringLength { base_path } => {
                // Build base path first
                base_path.build_cip_path(path)?;

                // Pad to even length if necessary before adding member segment
                if path.len() % 2 != 0 {
                    path.push(0x00);
                }

                // Add LEN member
                path.push(0x91);
                path.push(3); // "LEN".len()
                path.extend_from_slice(b"LEN");
            }

            TagPath::StringData { base_path, index } => {
                // Build base path first
                base_path.build_cip_path(path)?;

                // Pad to even length if necessary before adding member segment
                if path.len() % 2 != 0 {
                    path.push(0x00);
                }

                // Add DATA member
                path.push(0x91);
                path.push(4); // "DATA".len()
                path.extend_from_slice(b"DATA");

                // Pad to even length if necessary before adding array segment
                if path.len() % 2 != 0 {
                    path.push(0x00);
                }

                // Add array index
                path.push(0x28); // Element segment
                path.push(0x04); // Size: 4 bytes for 32-bit index (DINT)
                let index_u32 = *index;
                path.extend_from_slice(&index_u32.to_le_bytes());
            }
        }

        Ok(())
    }

    /// Returns the base tag name without any path qualifiers
    pub fn base_tag_name(&self) -> String {
        match self {
            TagPath::Controller { tag_name } => tag_name.clone(),
            TagPath::Program { tag_name, .. } => tag_name.clone(),
            TagPath::Array { base_path, .. } => base_path.base_tag_name(),
            TagPath::Bit { base_path, .. } => base_path.base_tag_name(),
            TagPath::Member { base_path, .. } => base_path.base_tag_name(),
            TagPath::StringLength { base_path } => base_path.base_tag_name(),
            TagPath::StringData { base_path, .. } => base_path.base_tag_name(),
        }
    }

    /// Returns true if this is a program-scoped tag
    pub fn is_program_scoped(&self) -> bool {
        match self {
            TagPath::Program { .. } => true,
            TagPath::Array { base_path, .. } => base_path.is_program_scoped(),
            TagPath::Bit { base_path, .. } => base_path.is_program_scoped(),
            TagPath::Member { base_path, .. } => base_path.is_program_scoped(),
            TagPath::StringLength { base_path } => base_path.is_program_scoped(),
            TagPath::StringData { base_path, .. } => base_path.is_program_scoped(),
            TagPath::Controller { .. } => false,
        }
    }

    /// Returns the program name if this is a program-scoped tag
    pub fn program_name(&self) -> Option<String> {
        match self {
            TagPath::Program { program_name, .. } => Some(program_name.clone()),
            TagPath::Array { base_path, .. } => base_path.program_name(),
            TagPath::Bit { base_path, .. } => base_path.program_name(),
            TagPath::Member { base_path, .. } => base_path.program_name(),
            TagPath::StringLength { base_path } => base_path.program_name(),
            TagPath::StringData { base_path, .. } => base_path.program_name(),
            TagPath::Controller { .. } => None,
        }
    }
}

impl fmt::Display for TagPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_string())
    }
}

/// Internal parser for tag path strings
struct TagPathParser<'a> {
    input: &'a str,
    position: usize,
}

impl<'a> TagPathParser<'a> {
    fn new(input: &'a str) -> Self {
        Self { input, position: 0 }
    }

    fn parse(mut self) -> Result<TagPath> {
        self.parse_path()
    }

    fn parse_path(&mut self) -> Result<TagPath> {
        // Check for program scope
        if self.input.starts_with("Program:") {
            self.parse_program_scoped()
        } else {
            self.parse_controller_scoped()
        }
    }

    fn parse_program_scoped(&mut self) -> Result<TagPath> {
        // Skip "Program:"
        self.position = 8;

        // Parse program name (until first dot)
        let program_name = self.parse_identifier()?;

        // Expect dot
        if !self.consume_char('.') {
            return Err(EtherNetIpError::Protocol(
                "Expected '.' after program name".to_string(),
            ));
        }

        // Parse tag name
        let tag_name = self.parse_identifier()?;

        let mut path = TagPath::Program {
            program_name,
            tag_name,
        };

        // Parse any additional qualifiers (arrays, members, bits)
        while self.position < self.input.len() {
            path = self.parse_qualifier(path)?;
        }

        Ok(path)
    }

    fn parse_controller_scoped(&mut self) -> Result<TagPath> {
        let tag_name = self.parse_identifier()?;
        let mut path = TagPath::Controller { tag_name };

        // Parse any additional qualifiers
        while self.position < self.input.len() {
            path = self.parse_qualifier(path)?;
        }

        Ok(path)
    }

    fn parse_qualifier(&mut self, base_path: TagPath) -> Result<TagPath> {
        match self.peek_char() {
            Some('[') => self.parse_array_access(base_path),
            Some('.') => self.parse_member_or_bit_access(base_path),
            _ => Err(EtherNetIpError::Protocol(format!(
                "Unexpected character at position {}",
                self.position
            ))),
        }
    }

    fn parse_array_access(&mut self, base_path: TagPath) -> Result<TagPath> {
        // Consume '['
        self.consume_char('[');

        let mut indices = Vec::new();

        // Parse first index
        indices.push(self.parse_number()?);

        // Parse additional indices separated by commas
        while self.peek_char() == Some(',') {
            self.consume_char(',');
            indices.push(self.parse_number()?);
        }

        // Expect ']'
        if !self.consume_char(']') {
            return Err(EtherNetIpError::Protocol(
                "Expected ']' after array indices".to_string(),
            ));
        }

        Ok(TagPath::Array {
            base_path: Box::new(base_path),
            indices,
        })
    }

    fn parse_member_or_bit_access(&mut self, base_path: TagPath) -> Result<TagPath> {
        // Consume '.'
        self.consume_char('.');

        // Check for special string operations — only match if it's the complete segment
        let remaining = &self.input[self.position..];
        if remaining.starts_with("LEN")
            && (remaining.len() == 3
                || remaining.as_bytes()[3] == b'.'
                || remaining.as_bytes()[3] == b'[')
        {
            self.position += 3;
            return Ok(TagPath::StringLength {
                base_path: Box::new(base_path),
            });
        }

        if remaining.starts_with("DATA[") {
            self.position += 5; // Skip "DATA["
            let index = self.parse_number()?;
            if !self.consume_char(']') {
                return Err(EtherNetIpError::Protocol(
                    "Expected ']' after DATA index".to_string(),
                ));
            }
            return Ok(TagPath::StringData {
                base_path: Box::new(base_path),
                index,
            });
        }

        // Parse identifier (could be member name or bit index)
        let identifier = self.parse_identifier()?;

        // Check if it's a numeric bit index
        if let Ok(bit_index) = identifier.parse::<u8>() {
            if bit_index < 32 {
                // Valid bit range for DINT
                return Ok(TagPath::Bit {
                    base_path: Box::new(base_path),
                    bit_index,
                });
            }
        }

        // It's a member name
        Ok(TagPath::Member {
            base_path: Box::new(base_path),
            member_name: identifier,
        })
    }

    fn parse_identifier(&mut self) -> Result<String> {
        let start = self.position;

        while self.position < self.input.len() {
            let ch = self.input.as_bytes()[self.position];
            if ch.is_ascii_alphanumeric() || ch == b'_' {
                self.position += 1;
            } else {
                break;
            }
        }

        if start == self.position {
            return Err(EtherNetIpError::Protocol("Expected identifier".to_string()));
        }

        Ok(self.input[start..self.position].to_string())
    }

    fn parse_number(&mut self) -> Result<u32> {
        let start = self.position;

        while self.position < self.input.len() {
            let ch = self.input.as_bytes()[self.position];
            if ch.is_ascii_digit() {
                self.position += 1;
            } else {
                break;
            }
        }

        if start == self.position {
            return Err(EtherNetIpError::Protocol("Expected number".to_string()));
        }

        self.input[start..self.position]
            .parse()
            .map_err(|_| EtherNetIpError::Protocol("Invalid number".to_string()))
    }

    fn peek_char(&self) -> Option<char> {
        self.input
            .as_bytes()
            .get(self.position)
            .map(|byte| *byte as char)
    }

    fn consume_char(&mut self, expected: char) -> bool {
        if self.peek_char() == Some(expected) {
            self.position += 1;
            true
        } else {
            false
        }
    }
}

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

    #[test]
    fn test_controller_scoped_tag() {
        let path = TagPath::parse("MyTag").unwrap();
        assert_eq!(
            path,
            TagPath::Controller {
                tag_name: "MyTag".to_string()
            }
        );
        assert_eq!(path.to_string(), "MyTag");
    }

    #[test]
    fn test_program_scoped_tag() {
        let path = TagPath::parse("Program:MainProgram.MyTag").unwrap();
        assert_eq!(
            path,
            TagPath::Program {
                program_name: "MainProgram".to_string(),
                tag_name: "MyTag".to_string()
            }
        );
        assert_eq!(path.to_string(), "Program:MainProgram.MyTag");
        assert!(path.is_program_scoped());
        assert_eq!(path.program_name(), Some("MainProgram".to_string()));
    }

    #[test]
    fn test_array_access() {
        let path = TagPath::parse("MyArray[5]").unwrap();
        if let TagPath::Array { base_path, indices } = path {
            assert_eq!(
                *base_path,
                TagPath::Controller {
                    tag_name: "MyArray".to_string()
                }
            );
            assert_eq!(indices, vec![5]);
        } else {
            panic!("Expected Array path");
        }
    }

    #[test]
    fn test_multi_dimensional_array() {
        let path = TagPath::parse("Matrix[1,2,3]").unwrap();
        if let TagPath::Array { base_path, indices } = path {
            assert_eq!(
                *base_path,
                TagPath::Controller {
                    tag_name: "Matrix".to_string()
                }
            );
            assert_eq!(indices, vec![1, 2, 3]);
        } else {
            panic!("Expected Array path");
        }
    }

    #[test]
    fn test_bit_access() {
        let path = TagPath::parse("StatusWord.15").unwrap();
        if let TagPath::Bit {
            base_path,
            bit_index,
        } = path
        {
            assert_eq!(
                *base_path,
                TagPath::Controller {
                    tag_name: "StatusWord".to_string()
                }
            );
            assert_eq!(bit_index, 15);
        } else {
            panic!("Expected Bit path");
        }
    }

    #[test]
    fn test_member_access() {
        let path = TagPath::parse("MotorData.Speed").unwrap();
        if let TagPath::Member {
            base_path,
            member_name,
        } = path
        {
            assert_eq!(
                *base_path,
                TagPath::Controller {
                    tag_name: "MotorData".to_string()
                }
            );
            assert_eq!(member_name, "Speed");
        } else {
            panic!("Expected Member path");
        }
    }

    #[test]
    fn test_string_length() {
        let path = TagPath::parse("MyString.LEN").unwrap();
        if let TagPath::StringLength { base_path } = path {
            assert_eq!(
                *base_path,
                TagPath::Controller {
                    tag_name: "MyString".to_string()
                }
            );
        } else {
            panic!("Expected StringLength path");
        }
    }

    #[test]
    fn test_string_data() {
        let path = TagPath::parse("MyString.DATA[5]").unwrap();
        if let TagPath::StringData { base_path, index } = path {
            assert_eq!(
                *base_path,
                TagPath::Controller {
                    tag_name: "MyString".to_string()
                }
            );
            assert_eq!(index, 5);
        } else {
            panic!("Expected StringData path");
        }
    }

    #[test]
    fn test_complex_nested_path() {
        let path = TagPath::parse("Program:Safety.Devices[2].Status.15").unwrap();

        // This should parse as:
        // Program:Safety.Devices -> Array[2] -> Member(Status) -> Bit(15)
        if let TagPath::Bit {
            base_path,
            bit_index,
        } = path
        {
            assert_eq!(bit_index, 15);

            if let TagPath::Member {
                base_path,
                member_name,
            } = *base_path
            {
                assert_eq!(member_name, "Status");

                if let TagPath::Array { base_path, indices } = *base_path {
                    assert_eq!(indices, vec![2]);

                    if let TagPath::Program {
                        program_name,
                        tag_name,
                    } = *base_path
                    {
                        assert_eq!(program_name, "Safety");
                        assert_eq!(tag_name, "Devices");
                    } else {
                        panic!("Expected Program path");
                    }
                } else {
                    panic!("Expected Array path");
                }
            } else {
                panic!("Expected Member path");
            }
        } else {
            panic!("Expected Bit path");
        }
    }

    #[test]
    fn test_cip_path_generation() {
        let path = TagPath::parse("MyTag").unwrap();
        let cip_path = path.to_cip_path().unwrap();

        // Should be: [0x91, 0x05, 'M', 'y', 'T', 'a', 'g', 0x00] (padded)
        assert_eq!(cip_path[0], 0x91); // ANSI Extended Symbol Segment
        assert_eq!(cip_path[1], 5); // Length of "MyTag"
        assert_eq!(&cip_path[2..7], b"MyTag");
        assert_eq!(cip_path[7], 0x00); // Padding
    }

    #[test]
    fn test_array_cip_path_generation() {
        let path = TagPath::parse("MyArray[5]").unwrap();
        let cip_path = path.to_cip_path().unwrap();

        // Should be: [0x91, 0x07, 'M', 'y', 'A', 'r', 'r', 'a', 'y', 0x00, 0x28, 0x05]
        // Tag segment: 0x91, length 7, "MyArray", padding
        assert_eq!(cip_path[0], 0x91); // ANSI Extended Symbol Segment
        assert_eq!(cip_path[1], 7); // Length of "MyArray"
        assert_eq!(&cip_path[2..9], b"MyArray");
        assert_eq!(cip_path[9], 0x00); // Padding

        // Array element segment: 0x28 (8-bit Element ID), index 5
        // Reference: 1756-PM020, Pages 603-611 (Element ID Segment Format)
        assert_eq!(cip_path[10], 0x28); // 8-bit Element ID segment
        assert_eq!(cip_path[11], 0x05); // Index 5
        assert_eq!(cip_path.len(), 12); // Total: 9 (tag) + 1 (padding) + 2 (element segment) = 12
    }

    #[test]
    fn test_program_array_cip_path_generation() {
        let path = TagPath::parse("Program:MainProgram.ArrayTest[0]").unwrap();
        let cip_path = path.to_cip_path().unwrap();

        tracing::debug!(
            "Program array CIP path ({} bytes): {:02X?}",
            cip_path.len(),
            cip_path
        );

        // Verify structure:
        // 1. Program segment: 0x91, length 19, "Program:MainProgram", padding
        assert_eq!(cip_path[0], 0x91);
        assert_eq!(cip_path[1], 19); // "Program:MainProgram".len()
        assert_eq!(&cip_path[2..21], b"Program:MainProgram");
        assert_eq!(cip_path[21], 0x00); // Padding after program segment

        // 2. Tag segment: 0x91, length 9, "ArrayTest", padding
        assert_eq!(cip_path[22], 0x91);
        assert_eq!(cip_path[23], 9); // "ArrayTest".len()
        assert_eq!(&cip_path[24..33], b"ArrayTest");
        assert_eq!(cip_path[33], 0x00); // Padding after tag segment

        // 3. Array element segment: 0x28 (8-bit Element ID), index 0
        // Reference: 1756-PM020, Pages 603-611 (Element ID Segment Format)
        assert_eq!(cip_path[34], 0x28); // 8-bit Element ID segment
        assert_eq!(cip_path[35], 0x00); // Index 0

        // Total should be 36 bytes (18 words)
        // Program segment: 20 bytes + Tag segment: 12 bytes + Element segment: 2 bytes + padding: 2 bytes = 36 bytes
        assert_eq!(cip_path.len(), 36);
    }

    #[test]
    fn test_base_tag_name() {
        let path = TagPath::parse("Program:Main.MotorData[1].Speed.15").unwrap();
        assert_eq!(path.base_tag_name(), "MotorData");
    }

    #[test]
    fn test_invalid_paths() {
        assert!(TagPath::parse("").is_err());
        assert!(TagPath::parse("Program:").is_err());
        assert!(TagPath::parse("MyArray[").is_err());
        assert!(TagPath::parse("MyArray]").is_err());
        assert!(TagPath::parse("MyTag.").is_err());
    }
}