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;
32 pub const MEMORY_SIZE: usize = 2 << 20;
33 const SECTOR_SIZE: usize = 4 << 10;
35 const NUM_SECTORS: usize = MEMORY_SIZE / SECTOR_SIZE;
37 #[derive(Clone, Copy, PartialEq, Debug)]
46 // Overrides InUse. The idea is to have erased flash sectors
47 // (0xff..ff) be detected as not in use.
52 #[derive(Clone, Copy)]
54 flags: u16, // Combination of SectorFlag items.
55 recording_id: u16, // Zero is considered invalid.
56 start_time: u32, // UNIX time. Only present if flag DataRecord isn't set.
60 fn new() -> SectorHeader {
68 fn is_in_use(&self) -> bool {
69 let mask = (SectorFlag::InUse as u16) | (SectorFlag::NotInUse as u16);
70 let value = SectorFlag::InUse as u16;
72 (self.flags & mask) == value
75 fn starts_recording(&self) -> bool {
76 let mask = (SectorFlag::InUse as u16)
77 | (SectorFlag::DataRecord as u16)
78 | (SectorFlag::NotInUse as u16);
79 let value = SectorFlag::InUse as u16;
81 (self.flags & mask) == value
84 fn belongs_to(&self, recording_id: u16) -> bool {
85 self.is_in_use() && self.recording_id == recording_id
89 #[derive(Clone, Copy)]
97 fn new() -> InFlight {
106 pub struct Logger<'a> {
107 pub storage: &'a mut dyn Storage,
109 recording_id: u16, // Zero is considered invalid.
111 // The index of the first sector of the currently running recording.
112 // Only written in logger_start_recording.
115 recording_started: u32,
117 // The number of slots filled in num_flight.
118 num_in_flight: usize,
120 // Deltas not yet written out to write_buffer.
122 // Limiting ourselves to 7 items here means we can use
123 // 0xff as a padding byte.
124 in_flight: [InFlight; 7],
126 sector_header: [SectorHeader; NUM_SECTORS],
128 sectors_written: u16,
130 write_buffer_offset: usize,
131 write_buffer: [u8; SECTOR_SIZE],
134 struct SectorHeaderIter<'a> {
135 sector_header: &'a [SectorHeader; NUM_SECTORS],
138 indices: [u16; NUM_SECTORS],
141 fn cmp_sector_header_indices(a: u16, b: u16,
142 sector_header: &[SectorHeader]) -> i32 {
143 let header_a = §or_header[a as usize];
144 let header_b = §or_header[b as usize];
146 // Latest entries come first.
147 if header_a.start_time > header_b.start_time {
149 } else if header_a.start_time < header_b.start_time {
156 fn downheap(heap: &mut [u16], mut index: usize, num_elts: usize,
157 sector_header: &[SectorHeader]) {
158 let orig = heap[index];
161 let mut worker = index * 2;
163 if worker < num_elts &&
164 cmp_sector_header_indices(heap[worker], heap[worker + 1], sector_header) < 0 {
168 if worker > num_elts ||
169 cmp_sector_header_indices(orig, heap[worker], sector_header) >= 0 {
173 heap[index] = heap[worker];
180 impl<'a> SectorHeaderIter<'a> {
181 fn new(logger: &'a Logger) -> SectorHeaderIter<'a> {
182 let mut iter = SectorHeaderIter {
183 sector_header: &logger.sector_header,
185 it_back: NUM_SECTORS,
186 indices: [0; NUM_SECTORS]
189 let mut num_used = 0;
191 // Put the indices of the used directory entries at the beginning
192 // of the array. Ignore the unused ones since we are not going
193 // to sort them anyway.
194 for i in 0..NUM_SECTORS {
195 let sector_header = &iter.sector_header[i];
197 if sector_header.starts_recording() {
198 iter.indices[num_used] = i as u16;
203 let num_elts_to_sort = num_used;
205 if num_elts_to_sort != 0 {
206 // Sort the used directory entries.
207 for i in (1..((num_elts_to_sort + 1) / 2) + 1).rev() {
208 downheap(&mut iter.indices, i - 1, num_elts_to_sort - 1,
212 for i in (1..num_elts_to_sort).rev() {
213 let t = iter.indices[0];
214 iter.indices[0] = iter.indices[i];
217 downheap(&mut iter.indices, 0, i - 1, iter.sector_header);
221 // Now put the indices of the unused directory entries in the array.
223 for i in 0..NUM_SECTORS {
224 iter.indices[i] = i as u16;
227 let latest_used = iter.indices[0] as usize;
228 let mut offset_unused = num_used;
230 // First put the entries that come after the latest one in use...
231 for i in (latest_used + 1)..NUM_SECTORS {
232 let sector_header = &iter.sector_header[i];
234 if !sector_header.is_in_use() {
235 iter.indices[offset_unused] = i as u16;
240 // ... then wrap around if necessary.
241 for i in 0..latest_used {
242 let sector_header = &iter.sector_header[i];
244 if !sector_header.is_in_use() {
245 iter.indices[offset_unused] = i as u16;
252 // Need to handle those sectors that don't start recordings
253 // but that are still used.
259 impl<'a> Iterator for SectorHeaderIter<'a> {
262 fn next(&mut self) -> Option<usize> {
263 if self.it_front == self.it_back {
266 let next_index = self.indices[self.it_front] as usize;
275 impl<'a> DoubleEndedIterator for SectorHeaderIter<'a> {
276 fn next_back(&mut self) -> Option<usize> {
277 if self.it_back == self.it_front {
282 let next_index = self.indices[self.it_back] as usize;
289 fn normalize_angle(mut angle: i32) -> i32 {
290 let deg90 = 90 * 60 * 10000;
291 let deg180 = deg90 << 1;
292 let deg360 = deg180 << 1;
294 while angle >= deg180 {
298 while angle <= -deg180 {
305 fn max<T>(a: T, b: T) -> T
306 where T: PartialOrd {
314 impl<'a> Logger<'a> {
315 pub fn new(storage: &'a mut dyn Storage) -> Logger {
321 recording_started: 0,
324 in_flight: [InFlight::new(); 7],
325 sector_header: [SectorHeader::new(); NUM_SECTORS],
329 write_buffer_offset: 0,
330 write_buffer: [0xff; SECTOR_SIZE],
334 pub fn init(&mut self) {
335 // Reading the directory entries one by one means
336 // we won't need an as large buffer on the stack.
337 for i in 0..NUM_SECTORS {
338 self.read_sector_header(i);
342 fn read_sector_header(&mut self, sector_index: usize) {
343 let address = sector_index * SECTOR_SIZE;
344 let mut chunk = [0u8; 4];
346 self.storage.read(address, &mut chunk);
348 let sector_header_ptr: *mut SectorHeader =
349 &mut self.sector_header[sector_index];
352 core::ptr::copy(chunk.as_ptr(),
353 sector_header_ptr as *mut u8,
358 fn prepare_write_buffer(&mut self, is_initial: bool) {
359 self.write_buffer = [0xff; SECTOR_SIZE];
361 let flags = if is_initial {
362 (SectorFlag::InUse as u16)
364 (SectorFlag::InUse as u16) | (SectorFlag::DataRecord as u16)
367 // Write sector header.
368 self.write_buffer[0..2].copy_from_slice(&flags.to_le_bytes());
369 self.write_buffer[2..4].copy_from_slice(&self.recording_id.to_le_bytes());
371 self.write_buffer_offset = 4;
374 let start = self.write_buffer_offset;
377 self.write_buffer[start..end].copy_from_slice(
378 &self.recording_started.to_le_bytes());
380 self.write_buffer_offset += 4;
384 pub fn start_recording(&mut self, tap: &TimeAndPos) -> u16 {
385 self.find_next_record_slot();
387 self.sectors_written = 0;
388 self.recording_started = tap.unix_time;
389 self.num_in_flight = 0;
391 self.prepare_write_buffer(true);
393 self.write_packet(0, tap.latitude, tap.longitude);
398 pub fn log(&mut self, prev_tap: &TimeAndPos, tap: &TimeAndPos) {
399 let d_time_ms = elapsed_ms(tap.system_time, prev_tap.system_time);
401 // We know that our hardware cannot deliver updates more often
402 // than once a second. However when there's a delay in evaluating
403 // the hardware's messages, we will end up with intervals like
404 // 1050ms and 950ms (the latter will "make up" for the slowness
405 // in the former). To avoid logging deltas of 0 seconds, we round
406 // the intervals to full seconds.
407 let d_time_s = (d_time_ms + 500) / 1000;
409 let d_lat = tap.latitude - prev_tap.latitude;
410 let d_lon = tap.longitude - prev_tap.longitude;
412 if self.write_packet(d_time_s, d_lat, d_lon) {
413 self.flush_in_flight(false);
417 pub fn stop_recording(&mut self, tap: &TimeAndPos) -> u16 {
418 // Mark the end of the points stream.
419 self.write_packet(0xffffffff, 0, 0);
420 self.flush_in_flight(true);
423 let duration = (tap.unix_time - self.recording_started) as u16;
425 let start = self.write_buffer_offset;
427 let dst = &mut self.write_buffer[start..end];
429 dst.copy_from_slice(&duration.to_le_bytes());
431 let this_sector = self.first_sector + self.sectors_written;
433 self.storage.write(this_sector as usize * SECTOR_SIZE,
436 self.sectors_written += 1;
438 for i in 0..self.sectors_written {
439 self.read_sector_header((self.first_sector + i) as usize);
445 fn sector_header_iter(&self) -> SectorHeaderIter {
446 SectorHeaderIter::new(self)
449 fn find_next_record_slot(&mut self) {
450 let mut candidate_index = 0;
451 let mut max_recording_id = 0;
453 for index in self.sector_header_iter() {
454 candidate_index = index;
456 let sector_header = &self.sector_header[index];
458 if !sector_header.is_in_use() {
459 // Due to our sorting we know that there will be no more
460 // used directory entries following. At this point
461 // we aren't interested in unused ones, so break the loop.
466 max(max_recording_id, sector_header.recording_id);
469 self.first_sector = candidate_index as u16;
470 self.recording_id = max_recording_id.wrapping_add(1);
473 fn write_packet(&mut self, d_time_s: u32, d_lat: i32, d_lon: i32) -> bool {
475 let in_flight = &mut self.in_flight[self.num_in_flight];
477 in_flight.d_time_s = d_time_s;
478 in_flight.d_lat = normalize_angle(d_lat);
479 in_flight.d_lon = normalize_angle(d_lon);
482 self.num_in_flight += 1;
484 self.num_in_flight == self.in_flight.len()
487 // Flushes the "in flight" items to the write buffer.
489 // @param is_final @c true iff this is the final flush in this recording.
491 // @note May only be called if logger.num_in_flight is greater than zero.
492 fn flush_in_flight(&mut self, is_final: bool) {
495 // Normally our items will have a time delta of one second.
496 // Mark the ones that differ from that.
497 for i in 0..self.num_in_flight {
498 if self.in_flight[i].d_time_s != 1 {
503 let mut buffer = [0u8; 128];
506 buffer[offset] = flags;
509 for i in 0..(self.num_in_flight - 1) {
510 let in_flight = &self.in_flight[i];
512 // Only write the time delta for the atypical cases.
513 if (flags & (1 << i)) != 0 {
515 varint::write_u32(&mut buffer[offset..], in_flight.d_time_s);
519 varint::write_s32(&mut buffer[offset..], in_flight.d_lat);
522 varint::write_s32(&mut buffer[offset..], in_flight.d_lon);
525 let i = self.num_in_flight - 1;
526 let in_flight = &self.in_flight[i];
528 // Only write the time delta for the atypical cases.
529 if (flags & (1 << i)) != 0 {
531 varint::write_u32(&mut buffer[offset..], in_flight.d_time_s);
534 // The final point is an end-of-stream marker and doesn't store
538 varint::write_s32(&mut buffer[offset..], in_flight.d_lat);
541 varint::write_s32(&mut buffer[offset..], in_flight.d_lon);
544 self.num_in_flight = 0;
546 let num_bytes_written = offset;
548 let remaining = self.write_buffer.len() - self.write_buffer_offset;
550 if remaining < num_bytes_written {
551 // We may use 0xff as padding bytes, since 0xff isn't a valid
552 // first byte in a points batch. prepare_write_buffer() fills
553 // our buffer with 0xff, so we don't need to do anything here.
554 let this_sector = self.first_sector + self.sectors_written;
556 self.storage.write(this_sector as usize * SECTOR_SIZE,
559 self.sectors_written += 1;
561 self.prepare_write_buffer(false);
564 let start = self.write_buffer_offset;
565 let end = start + num_bytes_written;
566 let dst = &mut self.write_buffer[start..end];
568 dst.copy_from_slice(&buffer[0..num_bytes_written]);
570 self.write_buffer_offset += num_bytes_written;
574 /// Check whether or not recording @p recording_id exists.
575 pub fn has_recording(&mut self, recording_id: u16) -> bool {
576 if recording_id == 0 {
580 self.sector_header_iter().find(|&index| {
581 let sector_header = &self.sector_header[index as usize];
583 sector_header.recording_id == recording_id &&
584 sector_header.starts_recording()
589 /// Retrieve recording @p recording_id and
590 /// write it to @p tx_buf in yencoded form.
591 pub fn get_recording(&mut self, recording_id: u16,
592 tx_buf: &mut Buffer) -> Result<(), Error> {
593 if recording_id == 0 {
594 return Err(Error::NoSuchRecording);
597 if let Some(found_index) = self.sector_header_iter().find(|&index| {
598 let sector_header = &self.sector_header[index as usize];
600 sector_header.recording_id == recording_id &&
601 sector_header.starts_recording()
603 let mut filename = [b' '; 29];
605 filename[0..].copy_from_slice(b"gps-watch-recording-XXXXX.bin");
607 fmt_u32_pad(&mut filename[20..], recording_id as u32, 5, b'0');
609 let mut yenc = Yencode::new(tx_buf);
611 yenc.start(&filename);
613 let format_version = 1u8;
614 yenc.data(&[format_version]);
616 let mut next_sector = found_index as usize;
618 for _ in 0..NUM_SECTORS {
619 let address = next_sector * SECTOR_SIZE;
620 let mut buf = [0u8; SECTOR_SIZE];
622 self.storage.read(address, &mut buf);
624 // Skip flags and recording ID.
625 yenc.data(&buf[4..]);
628 next_sector &= NUM_SECTORS - 1;
630 if !self.sector_header[next_sector].belongs_to(recording_id) {
641 Err(Error::NoSuchRecording)