bcms 0.1.12

Bluetooth Client Manager Service for IoT device management
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
use crate::data::IoTData;
use crate::{Error, Result};
use ones_oidc::{OpenIdconnectClient, get_well_known_application_by_client_identifier};
use openidconnect::OAuth2TokenResponse;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

/// Response for iot_device_exists
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IotDeviceExistsResponse {
    pub exists: bool,
    #[serde(default)]
    pub remember_device: bool,
    pub id: Option<String>,
}

/// Response for create_iot_device
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IotDeviceCreateResponse {
    pub hardware_identifier: String,
    pub model: String,
    pub connection_type: String,
    pub connection_meta: HashMap<String, serde_json::Value>,
    pub supported_data_types: Vec<String>,
    pub id: String,
    pub created_at: String,
    pub modified_at: String,
    pub revision: i32,
}

/// API submission payload matching SubmitIotDeviceDataDto
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiSubmissionPayload {
    pub data: Vec<ApiDeviceDataItem>,
}

/// API device data item matching IotDeviceDataBaseDto
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiDeviceDataItem {
    pub iot_device_id: String,
    pub data_type: String,
    pub data: Vec<ApiDataPoint>,
}

/// Individual data point with timestamp and data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiDataPoint {
    pub timestamp: i64,
    pub data: HashMap<String, serde_json::Value>,
}

/// Device info with backend registration details
#[derive(Debug, Clone)]
pub struct RegisteredDeviceInfo {
    pub address: String,
    pub backend_device_id: Option<String>,
    pub approved: bool,
}

/// Backend API client - identical interface to Python api.py
pub struct BackendAPI {
    client: reqwest::Client,
    auth_host: Option<String>,
    app_host: Option<String>,
    identifier: Option<String>,
    timeout: Duration,
    oidc_client: Option<Arc<OpenIdconnectClient>>,
    /// Mock bearer token (bypasses OIDC when set)
    mock_token: Option<String>,
}

impl BackendAPI {
    pub fn new(
        identifier: Option<String>,
        timeout: Duration,
        oidc_client: Option<Arc<OpenIdconnectClient>>,
        mock_backend_url: Option<String>,
        mock_bearer_token: Option<String>,
    ) -> Self {
        let client = reqwest::Client::builder()
            .timeout(timeout)
            .build()
            .expect("Failed to create HTTP client");

        Self {
            client,
            auth_host: None,
            app_host: mock_backend_url,
            identifier,
            timeout,
            oidc_client,
            mock_token: mock_bearer_token,
        }
    }

    /// Check if running in mock mode
    pub fn is_mock_mode(&self) -> bool {
        self.mock_token.is_some()
    }

    /// Check if identifier is set and get access token
    pub async fn ready_api(&mut self) -> Result<()> {
        // In mock mode, app_host is already set and we skip OIDC
        if self.is_mock_mode() {
            if self.app_host.is_none() {
                return Err(Error::Config("Mock mode requires mock_backend_url to be set".to_string()));
            }
            return Ok(());
        }

        if self.identifier.is_none() {
            return Err(Error::Config("Well known identifier is not set".to_string()));
        }

        // Get access token and setup hosts
        let (_access_token, app_host) = self.access_token_and_host().await?;
        self.app_host = Some(app_host);

        Ok(())
    }

    /// Get access token and host using ones-oidc
    pub async fn access_token_and_host(&self) -> Result<(String, String)> {
        let identifier = self.identifier.as_ref()
            .ok_or_else(|| Error::Config("Identifier not set".to_string()))?;

        let oidc_client = self.oidc_client.as_ref()
            .ok_or_else(|| Error::Config("OIDC client not initialized".to_string()))?;

        // Get device access token without caching
        let token_response = oidc_client.device_access_token().await
            .map_err(|e| Error::Api(format!("Failed to get device access token: {}", e)))?;
        let access_token = token_response.access_token().secret();

        // Get application URL using identifier
        let app_info = get_well_known_application_by_client_identifier(
            oidc_client.provider_metadata(),
            &access_token,
            identifier
        ).await
        .map_err(|e| Error::Api(format!("Failed to get application info: {}", e)))?;

        let app_host = app_info.url(oidc_client.issuer_url().as_str());

        Ok((access_token.to_string(), app_host))
    }

    /// Get access token
    pub async fn access_token(&self) -> Result<String> {
        // In mock mode, return the mock token
        if let Some(ref token) = self.mock_token {
            return Ok(token.clone());
        }
        let (access_token, _) = self.access_token_and_host().await?;
        Ok(access_token)
    }

    /// Create authorization headers
    fn make_bearer_headers(&self, access_token: &str) -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.insert(
            AUTHORIZATION,
            HeaderValue::from_str(&format!("Bearer {}", access_token))
                .expect("Invalid authorization header"),
        );
        headers.insert(
            CONTENT_TYPE,
            HeaderValue::from_static("application/json"),
        );
        headers
    }

    /// Submit IoT data to server using proper API format
    pub async fn submit_iot_data_formatted(&mut self, payload: ApiSubmissionPayload) -> Result<()> {
        self.ready_api().await?;
        
        let app_host = self.app_host.as_ref()
            .ok_or_else(|| Error::Api("App host not set".to_string()))?;
        
        let access_token = self.access_token().await?;
        let url = format!("{}/api/iot-devices/data/submit", app_host);
        
        let response = self.client
            .post(&url)
            .headers(self.make_bearer_headers(&access_token))
            .json(&payload)
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await?;
            return Err(Error::Api(format!("HTTP {}: {}", status, body)));
        }

        Ok(())
    }
    
    /// Submit IoT data to server (legacy method - transforms data automatically)
    pub async fn submit_iot_data(&mut self, data: Vec<IoTData>) -> Result<()> {
        // For backward compatibility, transform data with empty registered devices
        // This should be replaced with submit_iot_data_formatted() calls
        let payload = Self::dump_iot_data_for_api_submission(data, &[]);
        self.submit_iot_data_formatted(payload).await
    }

    /// Submit IoT data to server (sync version for compatibility)
    pub async fn submit_iot_data_sync(&mut self, data: Vec<IoTData>) -> Result<()> {
        self.submit_iot_data(data).await
    }

    /// Check if IoT device exists
    pub async fn iot_device_exists(&mut self, address: &str) -> Result<IotDeviceExistsResponse> {
        self.ready_api().await?;
        
        let app_host = self.app_host.as_ref()
            .ok_or_else(|| Error::Api("App host not set".to_string()))?;
        
        let access_token = self.access_token().await?;
        let url = format!("{}/api/iot-devices/exists", app_host);
        
        let payload = serde_json::json!({
            "hardwareIdentifier": address
        });

        let response = self.client
            .post(&url)
            .headers(self.make_bearer_headers(&access_token))
            .json(&payload)
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await?;
            return Err(Error::Api(format!("HTTP {}: {}", status, body)));
        }

        let data: serde_json::Value = response.json().await?;
        
        let exists = data.get("exists")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        
        let remember_device = data.get("rememberDevice")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        
        let id = if exists && remember_device {
            data.get("id")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string())
        } else {
            None
        };

        Ok(IotDeviceExistsResponse {
            exists,
            remember_device,
            id,
        })
    }

    /// Create IoT device
    pub async fn create_iot_device(
        &mut self,
        hardware_identifier: &str,
        model: Option<&str>,
        connection_type: Option<&str>,
        connection_meta: Option<HashMap<String, serde_json::Value>>,
        supported_data_types: Option<Vec<String>>,
    ) -> Result<IotDeviceCreateResponse> {
        self.ready_api().await?;
        
        let app_host = self.app_host.as_ref()
            .ok_or_else(|| Error::Api("App host not set".to_string()))?;
        
        let access_token = self.access_token().await?;
        let url = format!("{}/api/iot-devices", app_host);
        
        let payload = serde_json::json!({
            "hardwareIdentifier": hardware_identifier,
            "model": model.unwrap_or("generic"),
            "connectionType": connection_type.unwrap_or("bluetooth_le"),
            "connectionMeta": connection_meta.unwrap_or_default(),
            "supportedDataTypes": supported_data_types.unwrap_or_default(),
        });

        let response = self.client
            .post(&url)
            .headers(self.make_bearer_headers(&access_token))
            .json(&payload)
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await?;
            return Err(Error::Api(format!("HTTP {}: {}", status, body)));
        }

        let device: IotDeviceCreateResponse = response.json().await?;
        Ok(device)
    }

    /// Create IoT device if it doesn't exist
    pub async fn create_iot_device_if_not_exists(
        &mut self,
        address: &str,
        model: Option<&str>,
        connection_type: Option<&str>,
        connection_meta: Option<HashMap<String, serde_json::Value>>,
        supported_data_types: Option<Vec<String>>,
    ) -> Result<serde_json::Value> {
        let exists = self.iot_device_exists(address).await?;
        
        if exists.exists {
            Ok(serde_json::json!({
                "exists": exists.exists,
                "remember_device": exists.remember_device,
                "id": exists.id
            }))
        } else {
            let device = self.create_iot_device(address, model, connection_type, connection_meta, supported_data_types).await?;
            Ok(serde_json::to_value(device)?)
        }
    }

    /// Transform IoT data for API submission (equivalent to Python's dump_iot_data_for_api_submission)
    pub fn dump_iot_data_for_api_submission(
        input_data: Vec<IoTData>,
        registered_devices: &[RegisteredDeviceInfo],
    ) -> ApiSubmissionPayload {
        use tracing::{debug, warn};
        
        // Create mapping of address -> backend device ID for registered devices
        let mut device_id_map: HashMap<String, String> = HashMap::new();
        for device in registered_devices {
            if device.approved {
                if let Some(ref backend_id) = device.backend_device_id {
                    device_id_map.insert(device.address.clone(), backend_id.clone());
                }
            }
        }
        
        // Group data by device address
        let mut data_by_device: HashMap<String, Vec<IoTData>> = HashMap::new();
        for data in input_data {
            // Only include data from registered devices
            if device_id_map.contains_key(data.address()) {
                data_by_device
                    .entry(data.address().to_string())
                    .or_insert_with(Vec::new)
                    .push(data);
            } else {
                debug!("Skipping unregistered device {}", data.address());
            }
        }
        
        let mut api_data_items = Vec::new();
        
        // Process each device's data
        for (address, device_data) in data_by_device {
            if let Some(backend_device_id) = device_id_map.get(&address) {
                // Group by data type
                let mut data_by_type: HashMap<String, Vec<ApiDataPoint>> = HashMap::new();
                
                for data in device_data {
                    let data_type = data.name().to_string();
                    let api_point = ApiDataPoint {
                        timestamp: data.timestamp(),
                        data: match &data {
                            IoTData::BatteryLevel(d) => {
                                let mut m = HashMap::new();
                                m.insert("level".to_string(), serde_json::json!(d.level));
                                m
                            },
                            IoTData::HeartRate(d) => {
                                let mut m = HashMap::new();
                                m.insert("rate".to_string(), serde_json::json!(d.rate));
                                m
                            },
                            IoTData::Temperature(d) => {
                                let mut m = HashMap::new();
                                m.insert("level".to_string(), serde_json::json!(d.level));
                                m
                            },
                            IoTData::Pressure(d) => {
                                let mut m = HashMap::new();
                                m.insert("level".to_string(), serde_json::json!(d.level));
                                m
                            },
                            IoTData::BloodPressure(d) => {
                                let mut m = HashMap::new();
                                m.insert("sys".to_string(), serde_json::json!(d.sys));
                                m.insert("dias".to_string(), serde_json::json!(d.dias));
                                m
                            },
                            IoTData::Humidity(d) => {
                                let mut m = HashMap::new();
                                m.insert("level".to_string(), serde_json::json!(d.level));
                                m
                            },
                            IoTData::Alert(d) => {
                                let mut m = HashMap::new();
                                m.insert("id".to_string(), serde_json::json!(d.id));
                                m
                            },
                            IoTData::Generic(d) => d.data.clone(),
                        },
                    };
                    
                    data_by_type
                        .entry(data_type)
                        .or_insert_with(Vec::new)
                        .push(api_point);
                }
                
                // Create API data items for each data type
                for (data_type, data_points) in data_by_type {
                    api_data_items.push(ApiDeviceDataItem {
                        iot_device_id: backend_device_id.clone(),
                        data_type,
                        data: data_points,
                    });
                }
            }
        }
        
        ApiSubmissionPayload {
            data: api_data_items,
        }
    }
    
    /// Get last IoT device data submission timestamp
    pub async fn last_iot_device_data_submission(&mut self, iot_device_id: &str) -> Result<i64> {
        self.ready_api().await?;
        
        let app_host = self.app_host.as_ref()
            .ok_or_else(|| Error::Api("App host not set".to_string()))?;
        
        let access_token = self.access_token().await?;
        let url = format!("{}/api/iot-devices/{}/last-data-submission", app_host, iot_device_id);

        let response = self.client
            .get(&url)
            .headers(self.make_bearer_headers(&access_token))
            .send()
            .await?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await?;
            return Err(Error::Api(format!("HTTP {}: {}", status, body)));
        }

        let data: serde_json::Value = response.json().await?;
        let timestamp = data.get("timestamp")
            .and_then(|v| v.as_i64())
            .unwrap_or(0);

        Ok(timestamp)
    }
}