sonos-sdk-stream 0.5.2

Internal event streaming and subscription management for sonos-sdk
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
//! Basic usage example demonstrating optimal state management pattern
//!
//! This example shows the recommended approach for maintaining local state from Sonos events:
//! 1. Initialize local state through direct queries (not from events)
//! 2. Process change events to maintain local state using sync iterator (best practice)
//! 3. Handle events from both UPnP notifications and polling transparently
//! 4. Get clear feedback about firewall detection and polling reasons

use sonos_api::services::av_transport::{
    GetTransportInfoOperation, GetTransportInfoOperationRequest,
};
use sonos_api::services::rendering_control::{GetVolumeOperation, GetVolumeOperationRequest};
use sonos_api::{OperationBuilder, Service, SonosClient};
use sonos_stream::{BrokerConfig, EventBroker, EventData, PollingReason};
use std::net::IpAddr;

/// Local transport state maintained by the consumer
#[derive(Debug, Clone)]
struct LocalTransportState {
    transport_state: String,
    current_track_uri: String,
    track_duration: String,
    rel_time: String,
    track_metadata: String,
}

/// Local rendering control state maintained by the consumer
#[derive(Debug, Clone)]
struct LocalVolumeState {
    volume: u16,
    mute: bool,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("๐ŸŽต Sonos Stream - Basic State Management Example");
    println!("=================================================");

    // Create broker with default configuration (includes proactive firewall detection)
    let mut broker = EventBroker::new(BrokerConfig::default()).await?;
    let client = SonosClient::new();

    // Discover Sonos devices on the network
    println!("\n๐Ÿ” Discovering Sonos devices on the network...");
    let devices = tokio::task::spawn_blocking(|| {
        sonos_discovery::get_with_timeout(std::time::Duration::from_secs(5))
    })
    .await?;

    if devices.is_empty() {
        println!("โŒ No Sonos devices found on the network!");
        println!(
            "   Make sure your Sonos speakers are powered on and connected to the same network."
        );
        return Ok(());
    }

    println!("โœ… Found {} Sonos device(s):", devices.len());
    for (i, device) in devices.iter().enumerate() {
        println!(
            "   {}. {} ({}) - {} at {}:{}",
            i + 1,
            device.name,
            device.room_name,
            device.model_name,
            device.ip_address,
            device.port
        );
    }

    // Use a device that supports subscriptions - try to find the Sonos Playbar or Amp
    let selected_device = devices
        .iter()
        .find(|d| d.model_name.contains("Playbar") || d.model_name.contains("Amp"))
        .unwrap_or(&devices[0]);
    let device_ip: IpAddr = selected_device.ip_address.parse()?;

    println!(
        "\n๐ŸŽฏ Using device: {} ({}) at {}",
        selected_device.name, selected_device.room_name, device_ip
    );

    println!("\n๐Ÿ“‹ Registering Sonos services...");

    // Register services with enhanced firewall detection feedback
    let transport_reg = broker
        .register_speaker_service(device_ip, Service::AVTransport)
        .await?;
    let volume_reg = broker
        .register_speaker_service(device_ip, Service::RenderingControl)
        .await?;
    let group_mgmt_reg = broker
        .register_speaker_service(device_ip, Service::GroupManagement)
        .await?;
    let group_rc_reg = broker
        .register_speaker_service(device_ip, Service::GroupRenderingControl)
        .await?;

    // Provide user feedback based on firewall detection results
    println!("\n๐Ÿ” Registration Results:");
    print_registration_feedback(
        &transport_reg.firewall_status,
        transport_reg.polling_reason.as_ref(),
        "AVTransport",
    );
    print_registration_feedback(
        &volume_reg.firewall_status,
        volume_reg.polling_reason.as_ref(),
        "RenderingControl",
    );
    print_registration_feedback(
        &group_mgmt_reg.firewall_status,
        group_mgmt_reg.polling_reason.as_ref(),
        "GroupManagement",
    );
    print_registration_feedback(
        &group_rc_reg.firewall_status,
        group_rc_reg.polling_reason.as_ref(),
        "GroupRenderingControl",
    );

    println!("\n๐Ÿ“Š STEP 1: Initialize local state through direct queries");
    println!("(This is how consumers should handle initial state population)");

    // Initialize local state through direct device queries - NOT from events
    let mut local_transport_state = query_initial_transport_state(&client, &device_ip).await?;
    let mut local_volume_state = query_initial_volume_state(&client, &device_ip).await?;

    println!("โœ… Initial state loaded:");
    println!(
        "  Transport: {} | Track: {} | Position: {}",
        local_transport_state.transport_state,
        extract_track_title(&local_transport_state.track_metadata),
        local_transport_state.rel_time
    );
    println!(
        "  Volume: {} | Muted: {}",
        local_volume_state.volume, local_volume_state.mute
    );

    println!("\n๐Ÿ”„ STEP 2: Process change events to maintain local state");
    println!("(Using async iterator for real-time event processing)");
    println!(
        "Waiting for events... (try changing volume or playing/pausing on your Sonos device)\n"
    );

    // Get event iterator and use async pattern for real-time event processing
    let mut events = broker.event_iterator()?;
    let mut event_count = 0;

    // ASYNC ITERATOR PATTERN - Real-time event processing within async context
    while let Some(event) = events.next_async().await {
        event_count += 1;

        println!(
            "๐Ÿ“จ Event #{} received from {} ({})",
            event_count,
            event.speaker_ip,
            format_event_source(&event.event_source)
        );

        match event.event_data {
            // Complete event data - all services now provide full state
            EventData::AVTransport(transport_event) => {
                println!("๐ŸŽต Transport event received:");
                if let Some(ref state) = transport_event.transport_state {
                    println!("   โ†’ Transport state: {state}");
                    local_transport_state.transport_state = state.clone();
                }
                if let Some(ref uri) = transport_event.current_track_uri {
                    println!("   โ†’ Track URI: {uri}");
                    local_transport_state.current_track_uri = uri.clone();
                }
                if let Some(ref position) = transport_event.rel_time {
                    println!("   โ†’ Position: {position}");
                    local_transport_state.rel_time = position.clone();
                }
                if let Some(ref metadata) = transport_event.track_metadata {
                    local_transport_state.track_metadata = metadata.clone();
                }
                if let Some(ref duration) = transport_event.track_duration {
                    local_transport_state.track_duration = duration.clone();
                }

                println!(
                    "   โ†’ Updated state: {} | Position: {}",
                    local_transport_state.transport_state, local_transport_state.rel_time
                );
            }

            EventData::RenderingControl(volume_event) => {
                println!("๐Ÿ”Š Volume event received:");
                if let Some(ref volume) = volume_event.master_volume {
                    if let Ok(vol_num) = volume.parse::<u16>() {
                        println!("   โ†’ Volume level: {vol_num}");
                        local_volume_state.volume = vol_num;
                    }
                }
                if let Some(ref mute) = volume_event.master_mute {
                    let mute_bool = mute == "1" || mute.to_lowercase() == "true";
                    println!("   โ†’ Mute state: {mute_bool}");
                    local_volume_state.mute = mute_bool;
                }

                println!(
                    "   โ†’ Updated state: Volume {} | Muted: {}",
                    local_volume_state.volume, local_volume_state.mute
                );
            }

            // ZoneGroupTopology events - complete speaker topology information
            EventData::ZoneGroupTopology(topology) => {
                println!("๐Ÿ  Speaker topology event received:");
                println!("   โ†’ {} zone group(s) found", topology.zone_groups.len());

                for (i, group) in topology.zone_groups.iter().enumerate() {
                    println!(
                        "   โ†’ Group {}: Coordinator {} with {} member(s)",
                        i + 1,
                        group.coordinator,
                        group.members.len()
                    );

                    for member in &group.members {
                        let wireless_status = if member.network_info.wifi_enabled == "1" {
                            format!("WiFi ({}MHz)", member.network_info.channel_freq)
                        } else {
                            "Ethernet".to_string()
                        };

                        println!(
                            "     โ€ข {} ({}) - {} - {}",
                            member.zone_name, member.uuid, member.software_version, wireless_status
                        );

                        if !member.satellites.is_empty() {
                            println!("       โ””โ”€ {} satellite speaker(s)", member.satellites.len());
                        }
                    }
                }
            }

            // Device properties events
            EventData::DeviceProperties(device_event) => {
                println!("โš™๏ธ  Device properties event received:");
                if let Some(ref zone_name) = device_event.zone_name {
                    println!("   โ†’ Zone name: {zone_name}");
                }
                if let Some(ref model) = device_event.model_name {
                    println!("   โ†’ Model: {model}");
                }
                if let Some(ref version) = device_event.software_version {
                    println!("   โ†’ Software version: {version}");
                }
            }

            // GroupManagement events
            EventData::GroupManagement(gm_event) => {
                println!("๐Ÿ”— Group management event received:");
                if let Some(is_local) = gm_event.group_coordinator_is_local {
                    println!("   โ†’ Coordinator is local: {is_local}");
                }
                if let Some(ref group_uuid) = gm_event.local_group_uuid {
                    println!("   โ†’ Local group UUID: {group_uuid}");
                }
                if let Some(reset_vol) = gm_event.reset_volume_after {
                    println!("   โ†’ Reset volume after ungroup: {reset_vol}");
                }
            }

            // GroupRenderingControl events
            EventData::GroupRenderingControl(grc_event) => {
                println!("๐Ÿ”Š Group rendering control event received:");
                if let Some(volume) = grc_event.group_volume {
                    println!("   โ†’ Group volume: {volume}");
                }
                if let Some(mute) = grc_event.group_mute {
                    println!("   โ†’ Group mute: {mute}");
                }
                if let Some(changeable) = grc_event.group_volume_changeable {
                    println!("   โ†’ Group volume changeable: {changeable}");
                }
            }
        }

        // Show current combined state
        println!("๐Ÿ“Š Current State Summary:");
        println!(
            "   Transport: {} | Track: {} | Position: {}",
            local_transport_state.transport_state,
            extract_track_title(&local_transport_state.track_metadata),
            local_transport_state.rel_time
        );
        println!(
            "   Volume: {} | Muted: {}",
            local_volume_state.volume, local_volume_state.mute
        );
        println!();

        // Stop after 10 events for demonstration purposes
        if event_count >= 10 {
            println!("๐Ÿ“‹ Processed {event_count} events, stopping demonstration");
            break;
        }
    }

    println!("\n๐Ÿ›‘ Shutting down EventBroker...");
    broker.shutdown().await?;
    println!("โœ… Example completed successfully!");

    Ok(())
}

/// Query initial transport state directly from the device
/// This demonstrates how consumers should handle initial state population
async fn query_initial_transport_state(
    client: &SonosClient,
    device_ip: &IpAddr,
) -> Result<LocalTransportState, Box<dyn std::error::Error>> {
    // Get transport info using proper operation API
    let request = GetTransportInfoOperationRequest { instance_id: 0 };
    let operation = OperationBuilder::<GetTransportInfoOperation>::new(request).build()?;
    let transport_info = client.execute_enhanced(&device_ip.to_string(), operation)?;

    Ok(LocalTransportState {
        transport_state: transport_info.current_transport_state,
        current_track_uri: "N/A".to_string(), // Position info not available in current API
        track_duration: "N/A".to_string(),
        rel_time: "N/A".to_string(),
        track_metadata: "N/A".to_string(),
    })
}

/// Query initial volume state directly from the device
async fn query_initial_volume_state(
    client: &SonosClient,
    device_ip: &IpAddr,
) -> Result<LocalVolumeState, Box<dyn std::error::Error>> {
    // Get volume using proper operation API
    let request = GetVolumeOperationRequest {
        instance_id: 0,
        channel: "Master".to_string(),
    };
    let operation = OperationBuilder::<GetVolumeOperation>::new(request).build()?;
    let volume_response = client.execute_enhanced(&device_ip.to_string(), operation)?;

    Ok(LocalVolumeState {
        volume: volume_response.current_volume as u16,
        mute: false, // Mute status not available in current API
    })
}

/// Print user-friendly registration feedback based on firewall status
fn print_registration_feedback(
    firewall_status: &callback_server::firewall_detection::FirewallStatus,
    polling_reason: Option<&PollingReason>,
    service_name: &str,
) {
    use callback_server::firewall_detection::FirewallStatus;

    match firewall_status {
        FirewallStatus::Accessible => {
            if let Some(reason) = polling_reason {
                match reason {
                    PollingReason::EventTimeout => {
                        println!(
                            "  {service_name} ๐Ÿ“กโ†’๐Ÿ”„ UPnP events timed out - switched to polling"
                        );
                    }
                    PollingReason::SubscriptionFailed => {
                        println!("  {service_name} โŒโ†’๐Ÿ”„ UPnP subscription failed - using polling");
                    }
                    _ => {
                        println!("  {service_name} ๐Ÿ”„ Using polling mode: {reason:?}");
                    }
                }
            } else {
                println!("  {service_name} ๐Ÿ“ก UPnP events active - real-time updates enabled");
            }
        }
        FirewallStatus::Blocked => {
            println!("  {service_name} ๐Ÿ”ฅ Firewall detected - using polling for immediate updates");
        }
        FirewallStatus::Unknown => {
            if polling_reason.is_some() {
                println!("  {service_name} โ“ Firewall status unknown - using polling as fallback");
            } else {
                println!("  {service_name} โ“ Firewall status unknown - monitoring events closely");
            }
        }
        FirewallStatus::Error => {
            println!(
                "  {service_name} โš ๏ธ  Firewall detection error - using polling as safe fallback"
            );
        }
    }
}

/// Format event source for display
fn format_event_source(source: &sonos_stream::events::types::EventSource) -> String {
    use sonos_stream::events::types::EventSource;

    match source {
        EventSource::UPnPNotification { .. } => "UPnP Event".to_string(),
        EventSource::PollingDetection { poll_interval } => {
            format!("Polling ({}s interval)", poll_interval.as_secs())
        }
    }
}

/// Extract track title from metadata (simplified)
fn extract_track_title(metadata: &str) -> String {
    if metadata.is_empty() || metadata == "NOT_IMPLEMENTED" {
        return "No Track".to_string();
    }

    // This is a simplified extraction - in practice you'd parse the DIDL-Lite XML
    if metadata.contains("<dc:title>") {
        if let Some(start) = metadata.find("<dc:title>") {
            let start = start + "<dc:title>".len();
            if let Some(end) = metadata[start..].find("</dc:title>") {
                return metadata[start..start + end].to_string();
            }
        }
    }

    "Unknown Track".to_string()
}