2 * Copyright (c) 2017-2020 Tilman Sauerbeck (tilman at code-monkey de)
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:
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
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.
27 use systick::elapsed_ms;
33 pub const MEMORY_SIZE: usize = 2 << 20;
34 const SECTOR_SIZE: usize = 4 << 10;
36 const NUM_SECTORS: usize = MEMORY_SIZE / SECTOR_SIZE;
38 #[derive(Clone, Copy, PartialEq, Debug)]
48 // Overrides InUse. The idea is to have erased flash sectors
49 // (0xff..ff) be detected as not in use.
54 #[derive(Clone, Copy)]
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.
62 fn new() -> SectorHeader {
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;
74 (self.flags & mask) == value
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;
83 (self.flags & mask) == value
86 fn belongs_to(&self, recording_id: u16) -> bool {
87 self.is_in_use() && self.recording_id == recording_id
91 #[derive(Clone, Copy)]
99 fn new() -> InFlight {
108 pub struct Logger<'a> {
109 pub storage: &'a mut dyn Storage,
111 recording_id: u16, // Zero is considered invalid.
113 // The index of the first sector of the currently running recording.
114 // Only written in logger_start_recording.
117 recording_started: u32,
119 // The number of slots filled in num_flight.
120 num_in_flight: usize,
122 // Deltas not yet written out to write_buffer.
124 // Limiting ourselves to 7 items here means we can use
125 // 0xff as a padding byte.
126 in_flight: [InFlight; 7],
128 sector_header: [SectorHeader; NUM_SECTORS],
130 sectors_written: u16,
132 write_buffer_offset: usize,
133 write_buffer: [u8; SECTOR_SIZE],
136 struct SectorHeaderIter<'a> {
137 sector_header: &'a [SectorHeader; NUM_SECTORS],
140 indices: [u16; NUM_SECTORS],
143 fn cmp_sector_header_indices(a: u16, b: u16,
144 sector_header: &[SectorHeader]) -> i32 {
145 let header_a = §or_header[a as usize];
146 let header_b = §or_header[b as usize];
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 {
152 } else if header_a.start_time < header_b.start_time {
157 } else if header_a.starts_recording() {
159 } else if header_b.starts_recording() {
170 fn downheap(heap: &mut [u16], mut index: usize, num_elts: usize,
171 sector_header: &[SectorHeader]) {
172 let orig = heap[index];
175 let mut worker = index * 2;
177 if worker < num_elts &&
178 cmp_sector_header_indices(heap[worker], heap[worker + 1], sector_header) < 0 {
182 if worker > num_elts ||
183 cmp_sector_header_indices(orig, heap[worker], sector_header) >= 0 {
187 heap[index] = heap[worker];
194 impl<'a> SectorHeaderIter<'a> {
195 fn new(logger: &'a Logger) -> SectorHeaderIter<'a> {
196 let mut iter = SectorHeaderIter {
197 sector_header: &logger.sector_header,
199 it_back: NUM_SECTORS,
200 indices: [0; NUM_SECTORS]
203 for i in 0..NUM_SECTORS {
204 iter.indices[i] = i as u16;
207 iter.sort(NUM_SECTORS);
210 // Need to handle those sectors that don't start recordings
211 // but that are still used.
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,
222 for i in (1..num_elts_to_sort).rev() {
223 self.indices.swap(0, i);
225 downheap(&mut self.indices, 0, i - 1, self.sector_header);
230 impl<'a> Iterator for SectorHeaderIter<'a> {
233 fn next(&mut self) -> Option<usize> {
234 if self.it_front == self.it_back {
237 let next_index = self.indices[self.it_front] as usize;
246 impl<'a> DoubleEndedIterator for SectorHeaderIter<'a> {
247 fn next_back(&mut self) -> Option<usize> {
248 if self.it_back == self.it_front {
253 let next_index = self.indices[self.it_back] as usize;
260 fn normalize_angle(mut angle: i32) -> i32 {
261 let deg90 = 90 * 60 * 10000;
262 let deg180 = deg90 << 1;
263 let deg360 = deg180 << 1;
265 while angle >= deg180 {
269 while angle <= -deg180 {
276 fn max<T>(a: T, b: T) -> T
277 where T: PartialOrd {
285 impl<'a> Logger<'a> {
286 pub fn new(storage: &'a mut dyn Storage) -> Logger {
292 recording_started: 0,
295 in_flight: [InFlight::new(); 7],
296 sector_header: [SectorHeader::new(); NUM_SECTORS],
300 write_buffer_offset: 0,
301 write_buffer: [0xff; SECTOR_SIZE],
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);
313 fn read_sector_header(&mut self, sector_index: usize) {
314 let address = sector_index * SECTOR_SIZE;
315 let mut chunk = [0u8; 8];
317 self.storage.read(address, &mut chunk);
319 let sector_header_ptr: *mut SectorHeader =
320 &mut self.sector_header[sector_index];
323 core::ptr::copy(chunk.as_ptr(),
324 sector_header_ptr as *mut u8,
329 fn prepare_write_buffer(&mut self, is_initial: bool) {
330 self.write_buffer = [0xff; SECTOR_SIZE];
332 let flags = if is_initial {
333 (SectorFlag::InUse as u16)
335 (SectorFlag::InUse as u16) | (SectorFlag::DataRecord as u16)
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());
342 self.write_buffer_offset = 4;
345 let start = self.write_buffer_offset;
348 self.write_buffer[start..end].copy_from_slice(
349 &self.recording_started.to_le_bytes());
351 self.write_buffer_offset += 4;
355 pub fn start_recording(&mut self, tap: &TimeAndPos) -> u16 {
356 self.find_next_record_slot();
358 self.sectors_written = 0;
359 self.recording_started = tap.unix_time;
360 self.num_in_flight = 0;
362 self.prepare_write_buffer(true);
364 self.write_packet(0, tap.latitude_deg, tap.longitude_deg);
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);
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;
380 let d_lat = tap.latitude_deg - prev_tap.latitude_deg;
381 let d_lon = tap.longitude_deg - prev_tap.longitude_deg;
383 if self.write_packet(d_time_s, d_lat, d_lon) {
384 self.flush_in_flight(false);
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);
394 let duration = (tap.unix_time - self.recording_started) as u16;
396 let start = self.write_buffer_offset;
398 let dst = &mut self.write_buffer[start..end];
400 dst.copy_from_slice(&duration.to_le_bytes());
402 let this_sector = self.first_sector + self.sectors_written;
404 if self.storage.write(this_sector as usize * SECTOR_SIZE,
405 &self.write_buffer).is_err() {
409 self.sectors_written += 1;
411 for i in 0..self.sectors_written {
412 self.read_sector_header((self.first_sector + i) as usize);
418 fn sector_header_iter(&self) -> SectorHeaderIter {
419 SectorHeaderIter::new(self)
422 fn find_next_record_slot(&mut self) {
423 let mut candidate_index = 0;
424 let mut max_recording_id = 0;
426 for index in self.sector_header_iter() {
427 candidate_index = index;
429 let sector_header = &self.sector_header[index];
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.
439 max(max_recording_id, sector_header.recording_id);
442 self.first_sector = candidate_index as u16;
443 self.recording_id = max_recording_id.wrapping_add(1);
446 fn write_packet(&mut self, d_time_s: u32, d_lat: i32, d_lon: i32) -> bool {
448 let in_flight = &mut self.in_flight[self.num_in_flight];
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);
455 self.num_in_flight += 1;
457 self.num_in_flight == self.in_flight.len()
460 // Flushes the "in flight" items to the write buffer.
462 // @param is_final @c true iff this is the final flush in this recording.
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) {
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 {
476 let mut buffer = [0u8; 128];
479 buffer[offset] = flags;
482 for i in 0..(self.num_in_flight - 1) {
483 let in_flight = &self.in_flight[i];
485 // Only write the time delta for the atypical cases.
486 if (flags & (1 << i)) != 0 {
488 varint::write_u32(&mut buffer[offset..], in_flight.d_time_s);
492 varint::write_s32(&mut buffer[offset..], in_flight.d_lat);
495 varint::write_s32(&mut buffer[offset..], in_flight.d_lon);
498 let i = self.num_in_flight - 1;
499 let in_flight = &self.in_flight[i];
501 // Only write the time delta for the atypical cases.
502 if (flags & (1 << i)) != 0 {
504 varint::write_u32(&mut buffer[offset..], in_flight.d_time_s);
507 // The final point is an end-of-stream marker and doesn't store
511 varint::write_s32(&mut buffer[offset..], in_flight.d_lat);
514 varint::write_s32(&mut buffer[offset..], in_flight.d_lon);
517 self.num_in_flight = 0;
519 let num_bytes_written = offset;
521 let remaining = self.write_buffer.len() - self.write_buffer_offset;
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;
529 if self.storage.write(this_sector as usize * SECTOR_SIZE,
530 &self.write_buffer).is_err() {
534 self.sectors_written += 1;
536 self.prepare_write_buffer(false);
539 let start = self.write_buffer_offset;
540 let end = start + num_bytes_written;
541 let dst = &mut self.write_buffer[start..end];
543 dst.copy_from_slice(&buffer[0..num_bytes_written]);
545 self.write_buffer_offset += num_bytes_written;
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];
554 if !sector_header.starts_recording() {
558 let mut num_data_sectors = 0;
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];
564 if other_sector_header.belongs_to(sector_header.recording_id) {
565 num_data_sectors += 1;
569 let mut date_time_s = [b' '; 19];
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..]);
576 let recording_size = (num_data_sectors + 1) * (SECTOR_SIZE >> 10);
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,
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,
589 tx_buf.write(&date_time_s);
590 tx_buf.write(&recording_size_s[0..recording_size_s_len]);
592 tx_buf.write(&recording_id_s[0..recording_id_s_len]);
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 {
606 self.sector_header_iter().find(|&index| {
607 let sector_header = &self.sector_header[index as usize];
609 sector_header.recording_id == recording_id &&
610 sector_header.starts_recording()
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);
623 if let Some(found_index) = self.sector_header_iter().find(|&index| {
624 let sector_header = &self.sector_header[index as usize];
626 sector_header.recording_id == recording_id &&
627 sector_header.starts_recording()
629 let mut filename = [b' '; 29];
631 filename[0..].copy_from_slice(b"gps-watch-recording-XXXXX.bin");
633 fmt_u32_pad(&mut filename[20..], recording_id as u32, 5, b'0');
635 let mut yenc = Yencode::new(tx_buf);
637 yenc.start(&filename);
639 let format_version = 1u8;
640 yenc.data(&[format_version]);
642 let mut next_sector = found_index as usize;
644 for _ in 0..NUM_SECTORS {
645 let address = next_sector * SECTOR_SIZE;
646 let mut buf = [0u8; SECTOR_SIZE];
648 self.storage.read(address, &mut buf);
650 // Skip flags and recording ID.
651 yenc.data(&buf[4..]);
654 next_sector &= NUM_SECTORS - 1;
656 if !self.sector_header[next_sector].belongs_to(recording_id) {
667 Err(Error::NoSuchRecording)
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];
677 sector_header.recording_id == recording_id &&
678 sector_header.starts_recording()
680 let mut next_sector = found_index as usize;
682 for _ in 0..NUM_SECTORS {
683 let address = next_sector * SECTOR_SIZE;
685 if let Err(_) = self.storage.erase(address) {
686 return Err(Error::StorageError);
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);
694 next_sector &= NUM_SECTORS - 1;
696 if !self.sector_header[next_sector].belongs_to(recording_id) {
703 Err(Error::NoSuchRecording)