libindigo 0.3.2+INDIGO.2.0.300

Core API for developing INDIGO astronomy clients and devices.
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
# libindigo-rs

Rust API for writing client applications and device drivers for astronomy equipment using the [INDIGO](https://www.indigo-astronomy.org/index.html) protocol and architecture.

## πŸŽ‰ Refactoring Complete

The project has been successfully refactored into a multi-crate workspace! See [`REFACTORING_COMPLETE.md`](REFACTORING_COMPLETE.md) for full details.

## Architecture

This project is organized as a Cargo workspace with multiple crates:

| Crate | Purpose | FFI Dependencies |
|-------|---------|------------------|
| [`libindigo`]src/ | Core API, traits, and types | None |
| [`libindigo-rs`]rs/ | Pure Rust implementation | None |
| [`libindigo-ffi`]ffi/ | FFI-based implementation | Yes (via libindigo-sys) |
| [`libindigo-sys`]sys/ | Raw C bindings | Yes |

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  libindigo      β”‚  ← Core API (traits, types, constants)
β”‚  (root crate)   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
    β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”
    β”‚         β”‚
    β–Ό         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚libindigoβ”‚ β”‚ libindigo-ffiβ”‚
β”‚   -rs   β”‚ β”‚              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚
                   β–Ό
            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
            β”‚ libindigo-sysβ”‚
            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

## Goal

- A pure Rust API that is 100% compatible with the INDIGO platform and its default C-implementation

## Objectives

- βœ… Provide an API that uses idiomatic Rust for integrating with the INDIGO Bus
- βœ… Provide a Service Provider Interface (SPI) for decoupling the API from its implementation
- βœ… Provide a default RS (Rust) implementation of the SPI without any FFI bindings to the INDIGO C-libraries or other non-rust dependencies
- βœ… Provide an FFI implementation of the SPI that uses the INDIGO C-library with any necessary dependencies

## Quick Start

### ⚠️ Important: Crate Name vs Import Name

**The crate `libindigo-rs` must be imported as `libindigo_rs` (with underscore) in your code.**

Rust automatically converts hyphens to underscores in crate names. Always use:

```rust
use libindigo_rs::{...};  // βœ… CORRECT (underscore)
// NOT: use libindigo::{...};  // ❌ WRONG
```

### Pure Rust Client (Recommended - No C Dependencies)

Add to your `Cargo.toml`:

```toml
[dependencies]
libindigo-rs = "0.3"
tokio = { version = "1.35", features = ["full"] }
```

Example code:

```rust
use libindigo_rs::{Client, ClientBuilder, RsClientStrategy};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create client with pure Rust strategy
    let strategy = RsClientStrategy::new();
    let mut client = ClientBuilder::new()
        .with_strategy(strategy)
        .build();

    // Connect to INDIGO server
    client.connect("localhost:7624").await?;

    // Enumerate all properties
    client.enumerate_properties(None).await?;

    // Disconnect
    client.disconnect().await?;

    Ok(())
}
```

### FFI-Based Client (Maximum Compatibility)

Add to your `Cargo.toml`:

```toml
[dependencies]
libindigo-ffi = "0.3"
tokio = { version = "1.35", features = ["full"] }
```

Example code:

```rust
use libindigo_ffi::{Client, ClientBuilder, FfiClientStrategy};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Note: FFI implementation is currently stubbed
    let strategy = FfiClientStrategy::new()?;
    let mut client = ClientBuilder::new()
        .with_strategy(strategy)
        .build();

    client.connect("localhost:7624").await?;
    client.enumerate_properties(None).await?;
    client.disconnect().await?;

    Ok(())
}
```

## Features

### Pure Rust Strategy ([`libindigo-rs`]rs/)

The pure Rust strategy provides a complete INDIGO client implementation without C FFI dependencies:

- βœ… **Zero FFI**: No C dependencies, pure Rust implementation
- βœ… **Async-First**: Built on tokio for efficient async I/O
- βœ… **Type Safe**: Leverages Rust's type system for protocol correctness
- βœ… **Cross-Platform**: Works anywhere Rust compiles
- βœ… **Dual Protocol**: Full INDIGO JSON and XML protocol support with automatic negotiation
- βœ… **JSON-First**: Defaults to modern JSON protocol with XML fallback
- βœ… **mDNS Discovery**: Optional pure Rust server discovery (no FFI)

**Feature Flags**:

- `client` (default): Client functionality
- `device`: Device driver support (stub for future)
- `discovery`: mDNS server discovery via pure Rust `mdns-sd` crate

### FFI Strategy ([`libindigo-ffi`]ffi/)

The FFI strategy wraps the official C INDIGO library:

- ⚠️ **Status**: Structure in place, implementation pending
- βœ… **Maximum Compatibility**: Uses the official INDIGO C library
- βœ… **Async Support**: Async wrappers around synchronous FFI calls
- βœ… **Battle-Tested**: Leverages mature C implementation
- βœ… **Feature Complete**: Access to all INDIGO features (when implemented)

**Feature Flags**:

- `client` (default): Client functionality
- `device`: Device driver support (stub for future)
- `async`: Async wrapper for non-blocking operations

## JSON Protocol Support βœ…

libindigo-rs supports both INDIGO JSON and XML protocols with intelligent negotiation:

### Automatic Protocol Negotiation (Default)

The client automatically negotiates the best protocol with the server:

```rust
use libindigo_rs::{Client, ClientBuilder, RsClientStrategy};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // JSON-first with XML fallback (default behavior)
    let strategy = RsClientStrategy::new();
    let mut client = ClientBuilder::new()
        .with_strategy(strategy)
        .build();

    client.connect("localhost:7624").await?;
    // Client automatically negotiates protocol with server
    // Prefers JSON, falls back to XML if server doesn't support JSON

    client.enumerate_properties(None).await?;
    client.disconnect().await?;
    Ok(())
}
```

### Protocol Comparison

| Feature | JSON Protocol | XML Protocol |
|---------|--------------|--------------|
| **Version** | 512 (numeric) | "2.0" (string) |
| **Switch Values** | `true`/`false` | `On`/`Off` |
| **Number Format** | Native JSON numbers | String with format |
| **BLOBs** | URL only | URL or BASE64 |
| **Parsing Speed** | ⚑ Faster | Slightly slower |
| **Size** | πŸ“¦ More compact | More verbose |
| **Use Case** | Modern clients, web apps | Legacy compatibility |
| **Server Support** | INDIGO 2.0+ | All INDIGO versions |

### Protocol Selection Examples

See [`rs/src/lib.rs`](rs/src/lib.rs) documentation for advanced protocol negotiation options.

## Server Discovery

The pure Rust implementation includes optional mDNS server discovery:

```toml
[dependencies]
libindigo-rs = { version = "0.3", features = ["discovery"] }
```

```rust
use libindigo_rs::discovery::{DiscoveryBuilder, DiscoveryEvent};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut discovery = DiscoveryBuilder::new()
        .with_timeout(std::time::Duration::from_secs(5))
        .build()?;

    let mut receiver = discovery.start().await?;

    while let Some(event) = receiver.recv().await {
        match event {
            DiscoveryEvent::ServerFound { name, address, port } => {
                println!("Found server: {} at {}:{}", name, address, port);
            }
            DiscoveryEvent::ServerLost { name } => {
                println!("Lost server: {}", name);
            }
        }
    }

    Ok(())
}
```

See [`rs/PHASE5_DISCOVERY_MIGRATION.md`](rs/PHASE5_DISCOVERY_MIGRATION.md) for migration details.

## Strategy Comparison

| Feature | libindigo-rs | libindigo-ffi |
|---------|--------------|---------------|
| **C Dependencies** | ❌ None | βœ… Required |
| **Async Support** | βœ… Native | βœ… Wrapped |
| **Cross-Platform** | βœ… Excellent | ⚠️ Limited |
| **Performance** | βœ… Fast | βœ… Fast |
| **JSON Protocol** | βœ… Yes | ⚠️ Via C lib |
| **XML Protocol** | βœ… Yes | βœ… Yes |
| **Protocol Negotiation** | βœ… Automatic | ❌ No |
| **mDNS Discovery** | βœ… Pure Rust | ❌ No |
| **Maturity** | βœ… Production | ⚠️ Stub |
| **Use Case** | Modern apps | Legacy compat |

## Usage Examples

### Receiving Property Updates

```rust
use libindigo_rs::{Client, ClientBuilder, RsClientStrategy};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut strategy = RsClientStrategy::new();

    // Connect to server
    strategy.connect("localhost:7624").await?;

    // Get property receiver
    let mut rx = strategy.property_receiver().await.unwrap();

    // Spawn task to receive properties
    tokio::spawn(async move {
        while let Some(property) = rx.recv().await {
            println!("Property: {}.{} = {:?}",
                property.device,
                property.name,
                property.values
            );
        }
    });

    // Enumerate properties
    strategy.enumerate_properties(None).await?;

    // Keep running...
    tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;

    strategy.disconnect().await?;
    Ok(())
}
```

### Sending Property Updates

```rust
use libindigo_rs::{Client, ClientBuilder, RsClientStrategy};
use libindigo_rs::types::{Property, PropertyType, PropertyValue, SwitchState};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let strategy = RsClientStrategy::new();
    let mut client = ClientBuilder::new()
        .with_strategy(strategy)
        .build();

    client.connect("localhost:7624").await?;

    // Create a switch property to connect a device
    let mut property = Property::new(
        "CCD Simulator".to_string(),
        "CONNECTION".to_string(),
        PropertyType::Switch,
    );

    property.values.push(PropertyValue::Switch {
        name: "CONNECTED".to_string(),
        label: Some("Connected".to_string()),
        value: SwitchState::On,
    });

    // Send the property update
    client.send_property(property).await?;

    client.disconnect().await?;
    Ok(())
}
```

## Documentation

### Crate Documentation

- **This README**: Overview and quick start
- [`libindigo`]src/ - Core API documentation in source
- [`libindigo-rs`]rs/ - Pure Rust implementation (see [`rs/src/lib.rs`]rs/src/lib.rs)
- [`libindigo-ffi`]ffi/ - FFI implementation (see [`ffi/README.md`]ffi/README.md)
- [`libindigo-sys`]sys/ - Raw bindings (see [`sys/README.md`]sys/README.md)

### Architecture & Planning

- [`REFACTORING_COMPLETE.md`]REFACTORING_COMPLETE.md - **Complete refactoring summary**
- [`doc/reviews/issue-6-refactoring-review.md`]doc/reviews/issue-6-refactoring-review.md - Detailed review
- [`doc/architecture/client-strategies.md`]doc/architecture/client-strategies.md - Strategy pattern
- [`plans/code-review-and-architecture.md`]plans/code-review-and-architecture.md - Architecture plan

### Phase Documentation

- [`plans/archive/phase1-complete.md`]plans/archive/phase1-complete.md - Foundation & Core Types
- [`plans/archive/phase2-complete.md`]plans/archive/phase2-complete.md - Async FFI Strategy
- [`plans/archive/phase3-complete.md`]plans/archive/phase3-complete.md - Rust Client Strategy
- [`plans/archive/phase3-json-complete.md`]plans/archive/phase3-json-complete.md - JSON Protocol
- [`rs/PHASE5_DISCOVERY_MIGRATION.md`]rs/PHASE5_DISCOVERY_MIGRATION.md - Discovery Migration
- [`PHASE6_CONSTANTS_EXTRACTION.md`]PHASE6_CONSTANTS_EXTRACTION.md - Constants Extraction
- [`sys/REFACTORING_PHASE4.md`]sys/REFACTORING_PHASE4.md - FFI Refactoring

### Additional Documentation

- [`doc/constants-extraction.md`]doc/constants-extraction.md - Constants generation
- [`BUILD.md`]BUILD.md - Build instructions
- [`CHANGES.md`]CHANGES.md - Changelog

## Testing

### Run All Tests

```bash
cargo test --workspace
```

### Run Pure Rust Tests

```bash
# All pure Rust tests (including JSON protocol tests)
cargo test -p libindigo-rs

# JSON protocol tests only (61 tests)
cargo test -p libindigo-rs --test json_protocol_tests

# Protocol negotiation tests only (59 tests)
cargo test -p libindigo-rs --test protocol_negotiation_tests
```

### Run Discovery Tests

```bash
cargo test -p libindigo-rs --features discovery
```

### Integration Tests

Integration tests require a running INDIGO server:

```bash
# Start INDIGO server (in another terminal)
indigo_server

# Run integration tests
cargo test --test discovery_tests --features discovery
```

### Test Coverage Summary

| Test Suite | Tests | Coverage |
|------------|-------|----------|
| JSON Protocol | 61 | All PROTOCOLS.md examples + edge cases |
| Protocol Negotiation | 59 | Auto-detection, fallback, preferences |
| Rust Client | ~50 | Connection, properties, lifecycle |
| Discovery | ~20 | mDNS discovery, filtering |
| **Total** | **~190** | **Comprehensive coverage** |

## Examples

The [`examples/`](examples/) directory contains usage examples:

- [`discover_servers.rs`]examples/discover_servers.rs - Server discovery
- [`discovery_with_filter.rs`]examples/discovery_with_filter.rs - Filtered discovery
- [`auto_connect.rs`]examples/auto_connect.rs - Auto-connect to discovered servers (⚠️ needs update)
- [`continuous_discovery.rs`]examples/continuous_discovery.rs - Continuous discovery (⚠️ needs update)

Run examples:

```bash
# Server discovery
cargo run --example discover_servers --features discovery

# Discovery with filter
cargo run --example discovery_with_filter --features discovery
```

**Note**: Some examples use deprecated features and need updating. See [`REFACTORING_COMPLETE.md`](REFACTORING_COMPLETE.md) for details.

## Project Structure

```
libindigo-rs/
β”œβ”€β”€ Cargo.toml                    # Workspace root
β”œβ”€β”€ README.md                     # This file
β”œβ”€β”€ REFACTORING_COMPLETE.md       # Refactoring summary
β”œβ”€β”€ src/                          # libindigo (core API)
β”‚   β”œβ”€β”€ lib.rs                    # Main library entry point
β”‚   β”œβ”€β”€ error.rs                  # Error types
β”‚   β”œβ”€β”€ constants.rs              # INDIGO protocol constants
β”‚   β”œβ”€β”€ client/                   # Client API
β”‚   β”‚   β”œβ”€β”€ mod.rs
β”‚   β”‚   β”œβ”€β”€ builder.rs            # Client builder
β”‚   β”‚   └── strategy.rs           # ClientStrategy trait (SPI)
β”‚   └── types/                    # Core types
β”‚       β”œβ”€β”€ mod.rs
β”‚       β”œβ”€β”€ property.rs           # Property types
β”‚       β”œβ”€β”€ device.rs             # Device types
β”‚       └── value.rs              # Value types
β”œβ”€β”€ rs/                           # libindigo-rs (pure Rust)
β”‚   β”œβ”€β”€ Cargo.toml
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ lib.rs                # Re-exports + RS strategy
β”‚   β”‚   β”œβ”€β”€ client.rs             # RsClientStrategy
β”‚   β”‚   β”œβ”€β”€ protocol.rs           # XML protocol parser
β”‚   β”‚   β”œβ”€β”€ protocol_json.rs      # JSON protocol parser
β”‚   β”‚   β”œβ”€β”€ protocol_negotiation.rs
β”‚   β”‚   β”œβ”€β”€ transport.rs          # TCP transport layer
β”‚   β”‚   └── discovery/            # mDNS discovery (optional)
β”‚   β”‚       β”œβ”€β”€ mod.rs
β”‚   β”‚       β”œβ”€β”€ api.rs
β”‚   β”‚       β”œβ”€β”€ error.rs
β”‚   β”‚       └── mdns_impl.rs
β”œβ”€β”€ ffi/                          # libindigo-ffi (FFI-based)
β”‚   β”œβ”€β”€ Cargo.toml
β”‚   β”œβ”€β”€ README.md
β”‚   └── src/
β”‚       β”œβ”€β”€ lib.rs                # Re-exports + FFI strategy
β”‚       β”œβ”€β”€ ffi.rs                # FfiClientStrategy
β”‚       └── async_ffi.rs          # AsyncFfiStrategy
β”œβ”€β”€ sys/                          # libindigo-sys (raw bindings)
β”‚   β”œβ”€β”€ Cargo.toml
β”‚   β”œβ”€β”€ README.md
β”‚   β”œβ”€β”€ build.rs                  # C library build
β”‚   └── src/lib.rs                # bindgen output
β”œβ”€β”€ relm/                         # libindigo-relm (GTK demo, excluded)
β”œβ”€β”€ examples/                     # Usage examples
β”œβ”€β”€ tests/                        # Integration tests
β”œβ”€β”€ doc/                          # Documentation
β”œβ”€β”€ plans/                        # Planning documents
└── scripts/                      # Utility scripts
    └── update_constants.sh       # Update INDIGO constants
```

## Migration from Old API

If you're upgrading from the old monolithic API, see the migration guide in [`REFACTORING_COMPLETE.md`](REFACTORING_COMPLETE.md#migration-guide).

**Quick summary**:

```diff
# Cargo.toml
- libindigo = { version = "0.1", features = ["rs"] }
+ libindigo-rs = "0.3"

# Code
- use libindigo::strategies::RsClientStrategy;
- use libindigo::client::ClientBuilder;
+ use libindigo_rs::{RsClientStrategy, ClientBuilder};
```

### Troubleshooting: "unresolved module `libindigo`" Error

If you see this error after adding `libindigo-rs` to your dependencies:

```
error[E0432]: unresolved import `libindigo`
```

**Solution**: The crate name uses a hyphen (`libindigo-rs`) but imports must use an underscore (`libindigo_rs`).

```rust
// ❌ WRONG - causes "unresolved module" error
use libindigo::{Client, ClientBuilder};

// βœ… CORRECT - use underscore in imports
use libindigo_rs::{Client, ClientBuilder};
```

This is a Rust convention: hyphens in crate names are automatically converted to underscores for imports.

## Contributing

Contributions are welcome! Please:

1. Read [`doc/ways-of-working.md`]doc/ways-of-working.md
2. Follow [`doc/roo-workflow-scheme.md`]doc/roo-workflow-scheme.md
3. Use appropriate issue templates
4. Write tests for new features
5. Update documentation

## Known Issues & Future Work

See [`REFACTORING_COMPLETE.md`](REFACTORING_COMPLETE.md#known-todos-and-future-work) for:

- FFI implementation status
- BLOB handling improvements
- Device driver support (future)
- Example updates needed

## License

This project is licensed under the MIT License - see the [`LICENSE.md`](LICENSE.md) file for details.

## Acknowledgments

- [INDIGO Astronomy]https://www.indigo-astronomy.org/ - The INDIGO protocol and C library
- The Rust community for excellent async ecosystem tools

## Related Projects

- [INDIGO]https://github.com/indigo-astronomy/indigo - Official C implementation
- [`libindigo-sys`]sys/ - Low-level FFI bindings to INDIGO C library

## Status

**Current Version**: 0.3.0

**Status**: Production-ready for pure Rust client applications

- βœ… **libindigo-rs**: Complete and production-ready
- ⚠️ **libindigo-ffi**: Structure in place, implementation pending
- βœ… **Multi-crate refactoring**: Complete (see [`REFACTORING_COMPLETE.md`]REFACTORING_COMPLETE.md)

For production use, we recommend:

- **Pure Rust Strategy** ([`libindigo-rs`]rs/) for new projects without C dependencies
- **FFI Strategy** ([`libindigo-ffi`]ffi/) for maximum compatibility (when implementation is complete)

## Support

For questions, issues, or contributions:

- Open an issue on [GitHub]https://github.com/chrsoo/libindigo-rs/issues
- Check existing documentation
- Review the architecture plan