9b498ce64a5cec5e7f76be504fab5395a80ac41c
[gps-watch.git] / src / common / logger.rs
1 /*
2  * Copyright (c) 2017-2020 Tilman Sauerbeck (tilman at code-monkey de)
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining
5  * a copy of this software and associated documentation files (the
6  * "Software"), to deal in the Software without restriction, including
7  * without limitation the rights to use, copy, modify, merge, publish,
8  * distribute, sublicense, and/or sell copies of the Software, and to
9  * permit persons to whom the Software is furnished to do so, subject to
10  * the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be
13  * included in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22  */
23
24 use gps::TimeAndPos;
25 use storage::Storage;
26 use varint;
27 use systick::elapsed_ms;
28 use buffer::Buffer;
29 use yencode::Yencode;
30 use fmt::*;
31 use time::Time;
32
33 pub const MEMORY_SIZE: usize = 2 << 20;
34 const SECTOR_SIZE: usize = 4 << 10;
35
36 const NUM_SECTORS: usize = MEMORY_SIZE / SECTOR_SIZE;
37
38 #[derive(Clone, Copy, PartialEq, Debug)]
39 pub enum Error {
40     NoSuchRecording,
41     StorageError,
42 }
43
44 enum SectorFlag {
45     InUse      = 1 << 0,
46     DataRecord = 1 << 1,
47
48     // Overrides InUse. The idea is to have erased flash sectors
49     // (0xff..ff) be detected as not in use.
50     NotInUse   = 1 << 7,
51 }
52
53 #[repr(C)]
54 #[derive(Clone, Copy)]
55 struct SectorHeader {
56     flags: u16, // Combination of SectorFlag items.
57     recording_id: u16, // Zero is considered invalid.
58     start_time: u32, // UNIX time. Only present if flag DataRecord isn't set.
59 }
60
61 impl SectorHeader {
62     fn new() -> SectorHeader {
63         SectorHeader {
64             flags: 0,
65             recording_id: 0,
66             start_time: 0,
67         }
68     }
69
70     fn is_in_use(&self) -> bool {
71         let mask = (SectorFlag::InUse as u16) | (SectorFlag::NotInUse as u16);
72         let value = SectorFlag::InUse as u16;
73
74         (self.flags & mask) == value
75     }
76
77     fn starts_recording(&self) -> bool {
78         let mask = (SectorFlag::InUse as u16)
79                  | (SectorFlag::DataRecord as u16)
80                  | (SectorFlag::NotInUse as u16);
81         let value = SectorFlag::InUse as u16;
82
83         (self.flags & mask) == value
84     }
85
86     fn belongs_to(&self, recording_id: u16) -> bool {
87         self.is_in_use() && self.recording_id == recording_id
88     }
89 }
90
91 #[derive(Clone, Copy)]
92 struct InFlight {
93     d_time_s: u32,
94     d_lat: i32,
95     d_lon: i32,
96 }
97
98 impl InFlight {
99     fn new() -> InFlight {
100         InFlight {
101             d_time_s: 0,
102             d_lat: 0,
103             d_lon: 0,
104         }
105     }
106 }
107
108 pub struct Logger<'a> {
109     pub storage: &'a mut dyn Storage,
110
111     recording_id: u16, // Zero is considered invalid.
112
113     // The index of the first sector of the currently running recording.
114     // Only written in logger_start_recording.
115     first_sector: u16,
116
117     recording_started: u32,
118
119     // The number of slots filled in num_flight.
120     num_in_flight: usize,
121
122     // Deltas not yet written out to write_buffer.
123     //
124     // Limiting ourselves to 7 items here means we can use
125     // 0xff as a padding byte.
126     in_flight: [InFlight; 7],
127
128     sector_header: [SectorHeader; NUM_SECTORS],
129
130     sectors_written: u16,
131
132     write_buffer_offset: usize,
133     write_buffer: [u8; SECTOR_SIZE],
134 }
135
136 struct SectorHeaderIter<'a> {
137     sector_header: &'a [SectorHeader; NUM_SECTORS],
138     it_front: usize,
139     it_back: usize,
140     indices: [u16; NUM_SECTORS],
141 }
142
143 fn cmp_sector_header_indices(a: u16, b: u16,
144                              sector_header: &[SectorHeader]) -> i32 {
145     let header_a = &sector_header[a as usize];
146     let header_b = &sector_header[b as usize];
147
148     if header_a.starts_recording() && header_b.starts_recording() {
149         // Latest entries come first.
150         if header_a.start_time > header_b.start_time {
151             -1
152         } else if header_a.start_time < header_b.start_time {
153             1
154         } else {
155             0
156         }
157     } else if header_a.starts_recording() {
158         -1
159     } else if header_b.starts_recording() {
160         1
161     } else if a < b {
162         -1
163     } else if a > b {
164         1
165     } else {
166         0
167     }
168 }
169
170 fn downheap(heap: &mut [u16], mut index: usize, num_elts: usize,
171             sector_header: &[SectorHeader]) {
172     let orig = heap[index];
173
174     loop {
175         let mut worker = index * 2;
176
177         if worker < num_elts &&
178            cmp_sector_header_indices(heap[worker], heap[worker + 1], sector_header) < 0 {
179             worker += 1;
180         }
181
182         if worker > num_elts ||
183            cmp_sector_header_indices(orig, heap[worker], sector_header) >= 0 {
184             break;
185         }
186
187         heap[index] = heap[worker];
188         index = worker;
189     }
190
191     heap[index] = orig;
192 }
193
194 impl<'a> SectorHeaderIter<'a> {
195     fn new(logger: &'a Logger) -> SectorHeaderIter<'a> {
196         let mut iter = SectorHeaderIter {
197             sector_header: &logger.sector_header,
198             it_front: 0,
199             it_back: NUM_SECTORS,
200             indices: [0; NUM_SECTORS]
201         };
202
203         for i in 0..NUM_SECTORS {
204             iter.indices[i] = i as u16;
205         }
206
207         iter.sort(NUM_SECTORS);
208
209         // XXX:
210         // Need to handle those sectors that don't start recordings
211         // but that are still used.
212
213         iter
214     }
215
216     fn sort(&mut self, num_elts_to_sort: usize) {
217         for i in (1..((num_elts_to_sort + 1) / 2) + 1).rev() {
218             downheap(&mut self.indices, i - 1, num_elts_to_sort - 1,
219                      self.sector_header);
220         }
221
222         for i in (1..num_elts_to_sort).rev() {
223             self.indices.swap(0, i);
224
225             downheap(&mut self.indices, 0, i - 1, self.sector_header);
226         }
227     }
228 }
229
230 impl<'a> Iterator for SectorHeaderIter<'a> {
231     type Item = usize;
232
233     fn next(&mut self) -> Option<usize> {
234         if self.it_front == self.it_back {
235             None
236         } else {
237             let next_index = self.indices[self.it_front] as usize;
238
239             self.it_front += 1;
240
241             Some(next_index)
242         }
243     }
244 }
245
246 impl<'a> DoubleEndedIterator for SectorHeaderIter<'a> {
247     fn next_back(&mut self) -> Option<usize> {
248         if self.it_back == self.it_front {
249             None
250         } else {
251             self.it_back -= 1;
252
253             let next_index = self.indices[self.it_back] as usize;
254
255             Some(next_index)
256         }
257     }
258 }
259
260 fn normalize_angle(mut angle: i32) -> i32 {
261     let deg90 = 90 * 60 * 10000;
262     let deg180 = deg90 << 1;
263     let deg360 = deg180 << 1;
264
265     while angle >= deg180 {
266         angle -= deg360;
267     }
268
269     while angle <= -deg180 {
270         angle += deg360;
271     }
272
273     angle
274 }
275
276 fn max<T>(a: T, b: T) -> T
277           where T: PartialOrd {
278     if a > b {
279         a
280     } else {
281         b
282     }
283 }
284
285 impl<'a> Logger<'a> {
286     pub fn new(storage: &'a mut dyn Storage) -> Logger {
287         Logger {
288             storage: storage,
289
290             recording_id: 0,
291             first_sector: 0,
292             recording_started: 0,
293             num_in_flight: 0,
294
295             in_flight: [InFlight::new(); 7],
296             sector_header: [SectorHeader::new(); NUM_SECTORS],
297
298             sectors_written: 0,
299
300             write_buffer_offset: 0,
301             write_buffer: [0xff; SECTOR_SIZE],
302         }
303     }
304
305     pub fn init(&mut self) {
306         // Reading the directory entries one by one means
307         // we won't need an as large buffer on the stack.
308         for i in 0..NUM_SECTORS {
309             self.read_sector_header(i);
310         }
311     }
312
313     fn read_sector_header(&mut self, sector_index: usize) {
314         let address = sector_index * SECTOR_SIZE;
315         let mut chunk = [0u8; 8];
316
317         self.storage.read(address, &mut chunk);
318
319         let sector_header_ptr: *mut SectorHeader =
320             &mut self.sector_header[sector_index];
321
322         unsafe {
323             core::ptr::copy(chunk.as_ptr(),
324                             sector_header_ptr as *mut u8,
325                             chunk.len());
326         }
327     }
328
329     fn prepare_write_buffer(&mut self, is_initial: bool) {
330         self.write_buffer = [0xff; SECTOR_SIZE];
331
332         let flags = if is_initial {
333             (SectorFlag::InUse as u16)
334         } else {
335             (SectorFlag::InUse as u16) | (SectorFlag::DataRecord as u16)
336         };
337
338         // Write sector header.
339         self.write_buffer[0..2].copy_from_slice(&flags.to_le_bytes());
340         self.write_buffer[2..4].copy_from_slice(&self.recording_id.to_le_bytes());
341
342         self.write_buffer_offset = 4;
343
344         if is_initial {
345             let start = self.write_buffer_offset;
346             let end = start + 4;
347
348             self.write_buffer[start..end].copy_from_slice(
349                 &self.recording_started.to_le_bytes());
350
351             self.write_buffer_offset += 4;
352         }
353     }
354
355     pub fn start_recording(&mut self, tap: &TimeAndPos) -> u16 {
356         self.find_next_record_slot();
357
358         self.sectors_written = 0;
359         self.recording_started = tap.unix_time;
360         self.num_in_flight = 0;
361
362         self.prepare_write_buffer(true);
363
364         self.write_packet(0, tap.latitude_deg, tap.longitude_deg);
365
366         self.recording_id
367     }
368
369     pub fn log(&mut self, prev_tap: &TimeAndPos, tap: &TimeAndPos) {
370         let d_time_ms = elapsed_ms(tap.system_time, prev_tap.system_time);
371
372         // We know that our hardware cannot deliver updates more often
373         // than once a second. However when there's a delay in evaluating
374         // the hardware's messages, we will end up with intervals like
375         // 1050ms and 950ms (the latter will "make up" for the slowness
376         // in the former). To avoid logging deltas of 0 seconds, we round
377         // the intervals to full seconds.
378         let d_time_s = (d_time_ms + 500) / 1000;
379
380         let d_lat = tap.latitude_deg - prev_tap.latitude_deg;
381         let d_lon = tap.longitude_deg - prev_tap.longitude_deg;
382
383         if self.write_packet(d_time_s, d_lat, d_lon) {
384             self.flush_in_flight(false);
385         }
386     }
387
388     pub fn stop_recording(&mut self, tap: &TimeAndPos) -> u16 {
389         // Mark the end of the points stream.
390         self.write_packet(0xffffffff, 0, 0);
391         self.flush_in_flight(true);
392
393         // Write footer.
394         let duration = (tap.unix_time - self.recording_started) as u16;
395
396         let start = self.write_buffer_offset;
397         let end = start + 2;
398         let dst = &mut self.write_buffer[start..end];
399
400         dst.copy_from_slice(&duration.to_le_bytes());
401
402         let this_sector = self.first_sector + self.sectors_written;
403
404         if self.storage.write(this_sector as usize * SECTOR_SIZE,
405                               &self.write_buffer).is_err() {
406             // XXX
407         }
408
409         self.sectors_written += 1;
410
411         for i in 0..self.sectors_written {
412             self.read_sector_header((self.first_sector + i) as usize);
413         }
414
415         self.sectors_written
416     }
417
418     fn sector_header_iter(&self) -> SectorHeaderIter {
419         SectorHeaderIter::new(self)
420     }
421
422     fn find_next_record_slot(&mut self) {
423         let mut candidate_index = 0;
424         let mut max_recording_id = 0;
425
426         for index in self.sector_header_iter() {
427             candidate_index = index;
428
429             let sector_header = &self.sector_header[index];
430
431             if !sector_header.is_in_use() {
432                 // Due to our sorting we know that there will be no more
433                 // used directory entries following. At this point
434                 // we aren't interested in unused ones, so break the loop.
435                 break;
436             }
437
438             max_recording_id =
439                 max(max_recording_id, sector_header.recording_id);
440         }
441
442         self.first_sector = candidate_index as u16;
443         self.recording_id = max_recording_id.wrapping_add(1);
444     }
445
446     fn write_packet(&mut self, d_time_s: u32, d_lat: i32, d_lon: i32) -> bool {
447         {
448             let in_flight = &mut self.in_flight[self.num_in_flight];
449
450             in_flight.d_time_s = d_time_s;
451             in_flight.d_lat = normalize_angle(d_lat);
452             in_flight.d_lon = normalize_angle(d_lon);
453         }
454
455         self.num_in_flight += 1;
456
457         self.num_in_flight == self.in_flight.len()
458     }
459
460     // Flushes the "in flight" items to the write buffer.
461     //
462     // @param is_final @c true iff this is the final flush in this recording.
463     //
464     // @note May only be called if logger.num_in_flight is greater than zero.
465     fn flush_in_flight(&mut self, is_final: bool) {
466         let mut flags = 0u8;
467
468         // Normally our items will have a time delta of one second.
469         // Mark the ones that differ from that.
470         for i in 0..self.num_in_flight {
471             if self.in_flight[i].d_time_s != 1 {
472                 flags |= 1 << i;
473             }
474         }
475
476         let mut buffer = [0u8; 128];
477         let mut offset = 0;
478
479         buffer[offset] = flags;
480         offset += 1;
481
482         for i in 0..(self.num_in_flight - 1) {
483             let in_flight = &self.in_flight[i];
484
485             // Only write the time delta for the atypical cases.
486             if (flags & (1 << i)) != 0 {
487                 offset +=
488                     varint::write_u32(&mut buffer[offset..], in_flight.d_time_s);
489             }
490
491             offset +=
492                 varint::write_s32(&mut buffer[offset..], in_flight.d_lat);
493
494             offset +=
495                 varint::write_s32(&mut buffer[offset..], in_flight.d_lon);
496         }
497
498         let i = self.num_in_flight - 1;
499         let in_flight = &self.in_flight[i];
500
501         // Only write the time delta for the atypical cases.
502         if (flags & (1 << i)) != 0 {
503             offset +=
504                 varint::write_u32(&mut buffer[offset..], in_flight.d_time_s);
505         }
506
507         // The final point is an end-of-stream marker and doesn't store
508         // d_lat or d_lon.
509         if !is_final {
510             offset +=
511                 varint::write_s32(&mut buffer[offset..], in_flight.d_lat);
512
513             offset +=
514                 varint::write_s32(&mut buffer[offset..], in_flight.d_lon);
515         }
516
517         self.num_in_flight = 0;
518
519         let num_bytes_written = offset;
520
521         let remaining = self.write_buffer.len() - self.write_buffer_offset;
522
523         if remaining < num_bytes_written {
524             // We may use 0xff as padding bytes, since 0xff isn't a valid
525             // first byte in a points batch. prepare_write_buffer() fills
526             // our buffer with 0xff, so we don't need to do anything here.
527             let this_sector = self.first_sector + self.sectors_written;
528
529             if self.storage.write(this_sector as usize * SECTOR_SIZE,
530                                   &self.write_buffer).is_err() {
531                 // XXX
532             }
533
534             self.sectors_written += 1;
535
536             self.prepare_write_buffer(false);
537         }
538
539         let start = self.write_buffer_offset;
540         let end = start + num_bytes_written;
541         let dst = &mut self.write_buffer[start..end];
542
543         dst.copy_from_slice(&buffer[0..num_bytes_written]);
544
545         self.write_buffer_offset += num_bytes_written;
546     }
547
548     ///
549     /// Write a listing of the stored recordings to @p tx_buf.
550     pub fn list_recordings(&mut self, tx_buf: &mut Buffer) {
551         for index in self.sector_header_iter().rev() {
552             let sector_header = &self.sector_header[index as usize];
553
554             if !sector_header.starts_recording() {
555                 continue;
556             }
557
558             let mut num_data_sectors = 0;
559
560             for d in 1..NUM_SECTORS {
561                 let wrapped_index = ((index + d) & (NUM_SECTORS - 1)) as usize;
562                 let other_sector_header = &self.sector_header[wrapped_index];
563
564                 if other_sector_header.belongs_to(sector_header.recording_id) {
565                     num_data_sectors += 1;
566                 }
567             }
568
569             let mut date_time_s = [b' '; 19];
570
571             if let Some(tm) = Time::from_unix_time(sector_header.start_time) {
572                 tm.fmt_date(&mut date_time_s[0..]);
573                 tm.fmt_time(&mut date_time_s[11..]);
574             }
575
576             let recording_size = (num_data_sectors + 1) * (SECTOR_SIZE >> 10);
577
578             let mut recording_size_s = [b'0'; 9];
579             let recording_size_s_len = fmt_u32_pad(&mut recording_size_s,
580                                                    recording_size as u32,
581                                                    8, b' ');
582
583             let mut recording_id_s = [b'0'; 9];
584             let recording_id_s_len =
585                 fmt_u32_pad(&mut recording_id_s,
586                             sector_header.recording_id as u32,
587                             8, b' ');
588
589             tx_buf.write(&date_time_s);
590             tx_buf.write(&recording_size_s[0..recording_size_s_len]);
591             tx_buf.write(b"K");
592             tx_buf.write(&recording_id_s[0..recording_id_s_len]);
593             tx_buf.write(b"\n");
594
595             tx_buf.flush();
596         }
597     }
598
599     ///
600     /// Check whether or not recording @p recording_id exists.
601     pub fn has_recording(&mut self, recording_id: u16) -> bool {
602         if recording_id == 0 {
603             return false;
604         }
605
606         self.sector_header_iter().find(|&index| {
607             let sector_header = &self.sector_header[index as usize];
608
609             sector_header.recording_id == recording_id &&
610             sector_header.starts_recording()
611         }).is_some()
612     }
613
614     ///
615     /// Retrieve recording @p recording_id and
616     /// write it to @p tx_buf in yencoded form.
617     pub fn get_recording(&mut self, recording_id: u16,
618                          tx_buf: &mut Buffer) -> Result<(), Error> {
619         if recording_id == 0 {
620             return Err(Error::NoSuchRecording);
621         }
622
623         if let Some(found_index) = self.sector_header_iter().find(|&index| {
624             let sector_header = &self.sector_header[index as usize];
625
626             sector_header.recording_id == recording_id &&
627             sector_header.starts_recording()
628         }) {
629             let mut filename = [b' '; 29];
630
631             filename[0..].copy_from_slice(b"gps-watch-recording-XXXXX.bin");
632
633             fmt_u32_pad(&mut filename[20..], recording_id as u32, 5, b'0');
634
635             let mut yenc = Yencode::new(tx_buf);
636
637             yenc.start(&filename);
638
639             let format_version = 1u8;
640             yenc.data(&[format_version]);
641
642             let mut next_sector = found_index as usize;
643
644             for _ in 0..NUM_SECTORS {
645                 let address = next_sector * SECTOR_SIZE;
646                 let mut buf = [0u8; SECTOR_SIZE];
647
648                 self.storage.read(address, &mut buf);
649
650                 // Skip flags and recording ID.
651                 yenc.data(&buf[4..]);
652
653                 next_sector += 1;
654                 next_sector &= NUM_SECTORS - 1;
655
656                 if !self.sector_header[next_sector].belongs_to(recording_id) {
657                     break;
658                 }
659             }
660
661             yenc.finish();
662
663             tx_buf.flush();
664
665             Ok(())
666         } else {
667             Err(Error::NoSuchRecording)
668         }
669     }
670
671     ///
672     /// Remove recording @p recording_id.
673     pub fn remove_recording(&mut self, recording_id: u16) -> Result<(), Error> {
674         if let Some(found_index) = (0..NUM_SECTORS).find(|&index| {
675             let sector_header = &self.sector_header[index as usize];
676
677             sector_header.recording_id == recording_id &&
678             sector_header.starts_recording()
679         }) {
680             let mut next_sector = found_index as usize;
681
682             for _ in 0..NUM_SECTORS {
683                 let address = next_sector * SECTOR_SIZE;
684
685                 if let Err(_) = self.storage.erase(address) {
686                     return Err(Error::StorageError);
687                 }
688
689                 // Mark this sector as eligible for the next recording
690                 // and ensure it won't be picked up by list_recordings().
691                 self.read_sector_header(next_sector);
692
693                 next_sector += 1;
694                 next_sector &= NUM_SECTORS - 1;
695
696                 if !self.sector_header[next_sector].belongs_to(recording_id) {
697                     break;
698                 }
699             }
700
701             Ok(())
702         } else {
703             Err(Error::NoSuchRecording)
704         }
705     }
706 }