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
use super::{
    config::Config,
    data_interface::Protocol,
    encoding::{
        json::{FileDescription, OtaJob},
        FileContext,
    },
    pal::Version,
};

pub mod mock;

pub const TEST_TIMER_HZ: u32 = 8_000_000;

pub fn test_job_doc() -> OtaJob<'static> {
    OtaJob {
        protocols: heapless::Vec::from_slice(&[Protocol::Mqtt]).unwrap(),
        streamname: "test_stream",
        files: heapless::Vec::from_slice(&[FileDescription {
            filepath: "",
            filesize: 123456,
            fileid: 0,
            certfile: "cert",
            update_data_url: None,
            auth_scheme: None,
            sha1_rsa: Some(""),
            file_type: Some(0),
            sha256_rsa: None,
            sha1_ecdsa: None,
            sha256_ecdsa: None,
        }])
        .unwrap(),
    }
}

pub fn test_file_ctx(config: &Config) -> FileContext {
    let ota_job = test_job_doc();
    FileContext::new_from("Job-name", &ota_job, None, 0, config, Version::default()).unwrap()
}

pub mod ota_tests {
    use crate::jobs::data_types::{DescribeJobExecutionResponse, JobExecution, JobStatus};
    use crate::ota::data_interface::Protocol;
    use crate::ota::encoding::json::{FileDescription, OtaJob};
    use crate::ota::error::OtaError;
    use crate::ota::state::{Error, Events, States};
    use crate::ota::test::test_job_doc;
    use crate::ota::{
        agent::OtaAgent,
        control_interface::ControlInterface,
        data_interface::{DataInterface, NoInterface},
        pal::OtaPal,
        test::mock::{MockPal, MockTimer},
    };
    use crate::test::MockMqtt;
    use mqttrust::encoding::v4::{decode_slice, utils::Pid, PacketType};
    use mqttrust::{MqttError, Packet, QoS, SubscribeTopic};
    use serde::Deserialize;
    use serde_json_core::from_slice;

    use super::TEST_TIMER_HZ;

    /// All known job document that the device knows how to process.
    #[derive(Debug, PartialEq, Deserialize)]
    pub enum JobDetails<'a> {
        #[serde(rename = "afr_ota")]
        #[serde(borrow)]
        Ota(OtaJob<'a>),

        #[serde(other)]
        Unknown,
    }

    fn new_agent(
        mqtt: &MockMqtt,
    ) -> OtaAgent<'_, MockMqtt, &MockMqtt, NoInterface, MockTimer, MockTimer, MockPal, TEST_TIMER_HZ>
    {
        let request_timer = MockTimer::new();
        let self_test_timer = MockTimer::new();
        let pal = MockPal {};

        OtaAgent::builder(mqtt, mqtt, request_timer, pal)
            .with_self_test_timeout(self_test_timer, 16000)
            .build()
    }

    fn run_to_state<'a, C, DP, DS, T, ST, PAL, const TIMER_HZ: u32>(
        agent: &mut OtaAgent<'a, C, DP, DS, T, ST, PAL, TIMER_HZ>,
        state: States,
    ) where
        C: ControlInterface,
        DP: DataInterface,
        DS: DataInterface,
        T: fugit_timer::Timer<TIMER_HZ>,
        ST: fugit_timer::Timer<TIMER_HZ>,
        PAL: OtaPal,
    {
        if agent.state.state() == &state {
            return;
        }

        match state {
            States::Ready => {
                println!(
                    "Running to 'States::Ready', events: {}",
                    agent.state.context().events.len()
                );
                agent.state.process_event(Events::Shutdown).unwrap();
            }
            States::CreatingFile => {
                println!(
                    "Running to 'States::CreatingFile', events: {}",
                    agent.state.context().events.len()
                );
                run_to_state(agent, States::WaitingForJob);

                let job_doc = test_job_doc();
                agent.job_update("Test-job", &job_doc, None).unwrap();
                agent.state.context_mut().events.dequeue();
            }
            States::RequestingFileBlock => {
                println!(
                    "Running to 'States::RequestingFileBlock', events: {}",
                    agent.state.context().events.len()
                );
                run_to_state(agent, States::CreatingFile);
                agent.state.process_event(Events::CreateFile).unwrap();
                agent.state.context_mut().events.dequeue();
            }
            States::RequestingJob => {
                println!(
                    "Running to 'States::RequestingJob', events: {}",
                    agent.state.context().events.len()
                );
                run_to_state(agent, States::Ready);
                agent.state.process_event(Events::Start).unwrap();
                agent.state.context_mut().events.dequeue();
            }
            States::Suspended => {
                println!(
                    "Running to 'States::Suspended', events: {}",
                    agent.state.context().events.len()
                );
                run_to_state(agent, States::Ready);
                agent.suspend().unwrap();
            }
            States::WaitingForFileBlock => {
                println!(
                    "Running to 'States::Suspended', events: {}",
                    agent.state.context().events.len()
                );
                run_to_state(agent, States::RequestingFileBlock);
                agent.state.process_event(Events::RequestFileBlock).unwrap();
                agent.state.context_mut().events.dequeue();
            }
            States::WaitingForJob => {
                println!(
                    "Running to 'States::WaitingForJob', events: {}",
                    agent.state.context().events.len()
                );
                run_to_state(agent, States::RequestingJob);
                agent.check_for_update().unwrap();
            }
            States::Restarting => {}
        }
    }

    pub fn set_pid(buf: &mut [u8], pid: Pid) -> Result<(), ()> {
        let mut offset = 0;
        let (header, _) = mqttrust::encoding::v4::decoder::read_header(buf, &mut offset)
            .map_err(|_| ())?
            .ok_or(())?;

        match (header.typ, header.qos) {
            (PacketType::Publish, QoS::AtLeastOnce | QoS::ExactlyOnce) => {
                if buf[offset..].len() < 2 {
                    return Err(());
                }
                let len = ((buf[offset] as usize) << 8) | buf[offset + 1] as usize;

                offset += 2;
                if len > buf[offset..].len() {
                    return Err(());
                } else {
                    offset += len;
                }
            }
            (PacketType::Subscribe | PacketType::Unsubscribe | PacketType::Suback, _) => {}
            (
                PacketType::Puback
                | PacketType::Pubrec
                | PacketType::Pubrel
                | PacketType::Pubcomp
                | PacketType::Unsuback,
                _,
            ) => {}
            _ => return Ok(()),
        }

        pid.to_buffer(buf, &mut offset).map_err(|_| ())
    }

    #[test]
    fn ready_when_stopped() {
        let mqtt = MockMqtt::new();
        let mut ota_agent = new_agent(&mqtt);

        assert!(matches!(ota_agent.state.state(), &States::Ready));
        run_to_state(&mut ota_agent, States::Ready);
        assert!(matches!(ota_agent.state.state(), &States::Ready));
        assert_eq!(ota_agent.state.context().events.len(), 0);
        assert_eq!(mqtt.tx.borrow_mut().len(), 0);
    }

    #[test]
    fn abort_when_stopped() {
        let mqtt = MockMqtt::new();
        let mut ota_agent = new_agent(&mqtt);

        run_to_state(&mut ota_agent, States::Ready);
        assert_eq!(ota_agent.state.context().events.len(), 0);

        assert_eq!(
            ota_agent.abort().err(),
            Some(Error::GuardFailed(OtaError::NoActiveJob))
        );
        ota_agent.process_event().unwrap();
        assert!(matches!(ota_agent.state.state(), &States::Ready));
        assert_eq!(mqtt.tx.borrow_mut().len(), 0);
    }

    #[test]
    fn resume_when_stopped() {
        let mqtt = MockMqtt::new();
        let mut ota_agent = new_agent(&mqtt);

        run_to_state(&mut ota_agent, States::Ready);
        assert_eq!(ota_agent.state.context().events.len(), 0);

        assert!(matches!(
            ota_agent.resume().err().unwrap(),
            Error::InvalidEvent
        ));
        ota_agent.process_event().unwrap();
        assert!(matches!(ota_agent.state.state(), &States::Ready));
        assert_eq!(mqtt.tx.borrow_mut().len(), 0);
    }

    #[test]
    fn resume_when_suspended() {
        let mqtt = MockMqtt::new();
        let mut ota_agent = new_agent(&mqtt);

        run_to_state(&mut ota_agent, States::Suspended);
        assert_eq!(ota_agent.state.context().events.len(), 0);

        assert!(matches!(
            ota_agent.resume().unwrap(),
            &States::RequestingJob
        ));
        assert_eq!(mqtt.tx.borrow_mut().len(), 1);
    }

    #[test]
    fn check_for_update() {
        let mqtt = MockMqtt::new();
        let mut ota_agent = new_agent(&mqtt);

        run_to_state(&mut ota_agent, States::RequestingJob);
        assert!(matches!(ota_agent.state.state(), &States::RequestingJob));

        assert_eq!(ota_agent.state.context().events.len(), 0);

        assert!(matches!(
            ota_agent.check_for_update().unwrap(),
            &States::WaitingForJob
        ));

        let bytes = mqtt.tx.borrow_mut().pop_front().unwrap();

        let packet = decode_slice(bytes.as_slice()).unwrap();
        let topics = match packet {
            Some(Packet::Subscribe(ref s)) => s.topics().collect::<Vec<_>>(),
            _ => panic!(),
        };

        assert_eq!(
            topics,
            vec![SubscribeTopic {
                topic_path: "$aws/things/test_client/jobs/notify-next",
                qos: QoS::AtLeastOnce
            }]
        );

        let mut bytes = mqtt.tx.borrow_mut().pop_front().unwrap();
        set_pid(bytes.as_mut_slice(), Pid::new()).expect("Failed to set valid PID");
        let packet = decode_slice(bytes.as_slice()).unwrap();

        let publish = match packet {
            Some(Packet::Publish(p)) => p,
            _ => panic!(),
        };

        assert_eq!(
            publish,
            mqttrust::encoding::v4::publish::Publish {
                dup: false,
                qos: QoS::AtLeastOnce,
                retain: false,
                topic_name: "$aws/things/test_client/jobs/$next/get",
                payload: &[123, 125],
                pid: Some(Pid::new()),
            }
        );
        assert_eq!(mqtt.tx.borrow_mut().len(), 0);
    }

    #[test]
    #[ignore]
    fn request_job_retry_fail() {
        let mut mqtt = MockMqtt::new();

        // Let MQTT publish fail so request job will also fail
        mqtt.publish_fail();

        let mut ota_agent = new_agent(&mqtt);

        // Place the OTA Agent into the state for requesting a job
        run_to_state(&mut ota_agent, States::RequestingJob);
        assert!(matches!(ota_agent.state.state(), &States::RequestingJob));
        assert_eq!(ota_agent.state.context().events.len(), 0);

        assert_eq!(
            ota_agent.check_for_update().err(),
            Some(Error::GuardFailed(OtaError::Mqtt(MqttError::Full)))
        );

        // Fail the maximum number of attempts to request a job document
        for _ in 0..ota_agent.state.context().config.max_request_momentum {
            ota_agent.process_event().unwrap();
            assert!(ota_agent.state.context().request_timer.is_started);
            ota_agent.timer_callback().ok();
            assert!(matches!(ota_agent.state.state(), &States::RequestingJob));
        }

        // Attempt to request another job document after failing the maximum
        // number of times, triggering a shutdown event.
        ota_agent.process_event().unwrap();
        assert!(matches!(ota_agent.state.state(), &States::Ready));
        assert_eq!(mqtt.tx.borrow_mut().len(), 4);
    }

    #[test]
    fn init_file_transfer_mqtt() {
        let mqtt = MockMqtt::new();

        let mut ota_agent = new_agent(&mqtt);

        // Place the OTA Agent into the state for creating file
        run_to_state(&mut ota_agent, States::CreatingFile);
        assert!(matches!(ota_agent.state.state(), &States::CreatingFile));
        assert_eq!(ota_agent.state.context().events.len(), 0);

        ota_agent.process_event().unwrap();
        assert!(matches!(ota_agent.state.state(), &States::CreatingFile));
        ota_agent.process_event().unwrap();

        ota_agent.state.process_event(Events::CreateFile).unwrap();

        // Above will automatically enqueue `RequestFileBlock`
        assert!(matches!(
            ota_agent.state.state(),
            &States::RequestingFileBlock
        ));

        // Check the latest MQTT message
        let bytes = mqtt.tx.borrow_mut().pop_back().unwrap();

        let packet = decode_slice(bytes.as_slice()).unwrap();
        let topics = match packet {
            Some(Packet::Subscribe(ref s)) => s.topics().collect::<Vec<_>>(),
            _ => panic!(),
        };

        assert_eq!(
            topics,
            vec![SubscribeTopic {
                topic_path: "$aws/things/test_client/streams/test_stream/data/cbor",
                qos: QoS::AtLeastOnce
            }]
        );

        // Should still contain:
        // - subscription to `$aws/things/test_client/jobs/notify-next`
        // - publish to `$aws/things/test_client/jobs/$next/get`
        assert_eq!(mqtt.tx.borrow_mut().len(), 2);
    }

    #[test]
    fn request_file_block_mqtt() {
        let mqtt = MockMqtt::new();

        let mut ota_agent = new_agent(&mqtt);

        // Place the OTA Agent into the state for requesting file block
        run_to_state(&mut ota_agent, States::RequestingFileBlock);
        assert!(matches!(
            ota_agent.state.state(),
            &States::RequestingFileBlock
        ));
        assert_eq!(ota_agent.state.context().events.len(), 0);

        ota_agent
            .state
            .process_event(Events::RequestFileBlock)
            .unwrap();

        assert!(matches!(
            ota_agent.state.state(),
            &States::WaitingForFileBlock
        ));

        let bytes = mqtt.tx.borrow_mut().pop_back().unwrap();

        let publish = match decode_slice(bytes.as_slice()).unwrap() {
            Some(Packet::Publish(p)) => p,
            _ => panic!(),
        };

        // Check the latest MQTT message
        assert_eq!(
            publish,
            mqttrust::encoding::v4::publish::Publish {
                dup: false,
                qos: QoS::AtMostOnce,
                retain: false,
                topic_name: "$aws/things/test_client/streams/test_stream/get/cbor",
                payload: &[
                    164, 97, 102, 0, 97, 108, 25, 1, 0, 97, 111, 0, 97, 98, 68, 255, 255, 255, 127
                ],
                pid: None
            }
        );

        // Should still contain:
        // - subscription to `$aws/things/test_client/jobs/notify-next`
        // - publish to `$aws/things/test_client/jobs/$next/get`
        // - subscription to
        //   `$aws/things/test_client/streams/test_stream/data/cbor`
        assert_eq!(mqtt.tx.borrow_mut().len(), 3);
    }

    #[test]
    fn deserialize_describe_job_execution_response_ota() {
        let payload = br#"{
            "clientToken":"0:rustot-test",
            "timestamp":1624445100,
            "execution":{
                "jobId":"AFR_OTA-rustot_test_1",
                "status":"QUEUED",
                "queuedAt":1624440618,
                "lastUpdatedAt":1624440618,
                "versionNumber":1,
                "executionNumber":1,
                "jobDocument":{
                    "afr_ota":{
                        "protocols":["MQTT"],
                        "streamname":"AFR_OTA-0ba01295-9417-4ba7-9a99-4b31fb03d252",
                        "files":[{
                            "filepath":"IMG_test.jpg",
                            "filesize":2674792,
                            "fileid":0,
                            "certfile":"nope",
                            "fileType":0,
                            "sig-sha256-ecdsa":"This is my signature! Better believe it!"
                        }]
                    }
                }
            }
        }"#;

        let (response, _) =
            from_slice::<DescribeJobExecutionResponse<JobDetails>>(payload).unwrap();

        assert_eq!(
            response,
            DescribeJobExecutionResponse {
                execution: Some(JobExecution {
                    execution_number: Some(1),
                    job_document: Some(JobDetails::Ota(OtaJob {
                        protocols: heapless::Vec::from_slice(&[Protocol::Mqtt]).unwrap(),
                        streamname: "AFR_OTA-0ba01295-9417-4ba7-9a99-4b31fb03d252",
                        files: heapless::Vec::from_slice(&[FileDescription {
                            filepath: "IMG_test.jpg",
                            filesize: 2674792,
                            fileid: 0,
                            certfile: "nope",
                            update_data_url: None,
                            auth_scheme: None,
                            sha1_rsa: None,
                            sha256_rsa: None,
                            sha1_ecdsa: None,
                            sha256_ecdsa: Some("This is my signature! Better believe it!"),
                            file_type: Some(0),
                        }])
                        .unwrap(),
                    })),
                    job_id: "AFR_OTA-rustot_test_1",
                    last_updated_at: 1624440618,
                    queued_at: 1624440618,
                    status_details: None,
                    status: JobStatus::Queued,
                    version_number: 1,
                    approximate_seconds_before_timed_out: None,
                    started_at: None,
                    thing_name: None,
                }),
                timestamp: 1624445100,
                client_token: Some("0:rustot-test"),
            }
        );
    }
}