summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 9ec26d852098d1ed83d731d95885aeaa9fb16cf7 (plain)
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
// © 2022 cos <https://www.netizen.se/>. Please see LICENSE file for details.
//
//! lctns-edit is a quickly prototyped tool to edit name, latitude and longitude in LCTNS.FIT as
//! found on Garmin watches. works for me, but no guarantees are given. if it bricks your device
//! you're responsible, not me.

use {
    anyhow::{
        Context,
        Result,
        anyhow,
    },
    getopts::Options,
    std::{
        env::args,
        error::Error,
        fmt::{
            Display,
            Error as FmtError,
            Formatter,
            Result as FmtResult,
        },
        io::prelude::*,
        iter::repeat,
        fs::File,
        path::Path,
        str::FromStr,
    },
};

/* LCTNS.FIT seems to start with 109 bytes, which we do not know how to parse. After those initial
 * bytes follows the location data in entries of 37 bytes each. One example of such an entry reads
 * as follows:
 *
 * 0     |3                               |19      |23      |27  |29  |31  |33    36|
 * ffffff|4761726d696e2054616977616e000000|c25bd211|4def7f56|0200|e101|820a|ffff02ff|
 *        G a r m i n   T a i w a n        25°3.70' 121°38.'
 *
 * We do not know know how to interpret all of those, but the name and the position are the
 * important ones which this tool cares about.
 */

const MAGIC_INITIAL_BYTES: usize = 109;
const MAGIC_ENTRY_LEN: usize = 37;
const MAGIC_INDEX_NAME: usize = 3;
const MAGIC_LEN_NAME: usize = 16;
const MAGIC_INDEX_LAT: usize = MAGIC_INDEX_NAME + MAGIC_LEN_NAME;
const MAGIC_LEN_LAT: usize = 4;
const MAGIC_INDEX_LONG: usize = MAGIC_INDEX_LAT + MAGIC_LEN_LAT;
const MAGIC_LEN_LONG: usize = 4;
// 29-30 is likely the icon and 31-32 might be the altitude, but those are merely my guesses.

// TODO Latitude and Longitude are almost identical. It would be a good idea to refactor them to
//      reuse the common code.
struct Latitude {
    inner: i32,
}

impl Latitude {
    /// Creates a [Latitude] using `val` in the format used in the FIT file.
    fn from_fit(val: i32) -> Self {
        Self {
            inner: val,
        }
    }
}

impl Display for Latitude {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
        // TODO Output localized strings.
        let div = ((1i64 << 32) as f32) / 360f32;
        let deg = self.inner as f32 / div;
        let min = deg.fract()*60f32;
        let sec = min.fract()*60f32;

        if deg >= 0f32 {
            write!(f, "N {}°{}'{:.3}\"", deg.trunc(), min.trunc(), sec)
        } else {
            write!(f, "S {}°{}'{:.3}\"", -deg.trunc(), -min.trunc(), -sec)
        }
    }
}

#[derive(Debug)]
struct ParseError { }

impl Error for ParseError { }

impl Display for ParseError {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "Parse error")
    }
}

// FIXME This function gets the parsing done, but it is horribly written and lacking in e.g. error
//       checking. There is a latlon crate which claims to do this kind of parsing but with
//       datatypes generally used for geo. Any attempt to interface with the greater eco-system
//       pulls in quite some heavy dependences though.
impl TryFrom<&str> for Latitude {
    type Error = ParseError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        let mul = ((1i64 << 32) as f32) / 360f32;

        let mut degrees = None;
        let mut minutes = None;
        let mut seconds = None;
        let mut index = 0;

        let sign = if s.contains('N') {
            1f32
        } else if s.contains('S') {
            -1f32
        } else {
            return Err(ParseError { });
        };

        if let Some(deg_sign_pos) = s.find('°') {
            while index < deg_sign_pos {
                if let Ok(val) = f32::from_str(&s[index..deg_sign_pos]) {
                    degrees = Some(val);
                    index = deg_sign_pos;
                    break;
                }
                index += 1;
            }
        }
        index += 2; // Degree character is dual-byte.
        if let Some(min_sign) = s.find('\'') {
            while index < min_sign {
                if let Ok(val) = f32::from_str(&s[index..min_sign]) {
                    minutes = Some(val);
                    index = min_sign;
                    break;
                }
                index += 1;
            }
        }
        if let Some(sec_sign) = s.find('"') {
            while index < sec_sign {
                if let Ok(val) = f32::from_str(&s[index..sec_sign]) {
                    seconds = Some(val);
                    break;
                }
                index += 1;
            }
        }
        match (degrees, minutes, seconds) {
            (Some(deg), None, None) => Ok(Latitude { inner: (sign * mul * deg) as i32 }),
            (Some(deg), Some(min), None) =>
                Ok(Latitude { inner: (sign * mul * (deg + min / 60f32)) as i32 }),
            (Some(deg), Some(min), Some(sec)) =>
                Ok(Latitude { inner: (sign * mul * (deg + min / 60f32 + sec / 3600f32)) as i32 }),
            _ => Err(ParseError { }),
        }
    }
}

struct Longitude {
    inner: i32,
}

impl Longitude {
    fn from_fit(val: i32) -> Self {
        Self {
            inner: val,
        }
    }
}

impl Display for Longitude {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
        let div = ((1i64 << 32) as f32) / 360f32;
        let deg = self.inner as f32 / div;
        let min = deg.fract()*60f32;
        let sec = min.fract()*60f32;

        if deg >= 0f32 {
            write!(f, "E {}°{}'{:.3}\"", deg.trunc(), min.trunc(), sec)
        } else {
            write!(f, "W {}°{}'{:.3}\"", -deg.trunc(), -min.trunc(), -sec)
        }
    }
}

impl TryFrom<&str> for Longitude {
    type Error = ParseError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        let mul = ((1i64 << 32) as f32) / 360f32;

        let mut degrees = None;
        let mut minutes = None;
        let mut seconds = None;
        let mut index = 0;

        let sign = if s.contains('E') {
            1f32
        } else if s.contains('W') {
            -1f32
        } else {
            return Err(ParseError { });
        };

        if let Some(deg_sign_pos) = s.find('°') {
            while index < deg_sign_pos {
                if let Ok(val) = f32::from_str(&s[index..deg_sign_pos]) {
                    degrees = Some(val);
                    index = deg_sign_pos;
                    break;
                }
                index += 1;
            }
        }
        index += 2; // Degree character is dual-byte.
        if let Some(min_sign) = s.find('\'') {
            while index < min_sign {
                if let Ok(val) = f32::from_str(&s[index..min_sign]) {
                    minutes = Some(val);
                    index = min_sign;
                    break;
                }
                index += 1;
            }
        }
        if let Some(sec_sign) = s.find('"') {
            while index < sec_sign {
                if let Ok(val) = f32::from_str(&s[index..sec_sign]) {
                    seconds = Some(val);
                    break;
                }
                index += 1;
            }
        }
        match (degrees, minutes, seconds) {
            (Some(deg), None, None) => Ok(Longitude { inner: (sign * mul * deg) as i32 }),
            (Some(deg), Some(min), None) =>
                Ok(Longitude { inner: (sign * mul * (deg + min / 60f32)) as i32 }),
            (Some(deg), Some(min), Some(sec)) =>
                Ok(Longitude { inner: (sign * mul * (deg + min / 60f32 + sec / 3600f32)) as i32 }),
            _ => Err(ParseError { }),
        }
    }
}

struct LctnEntry<'lctns> {
    raw_slice: &'lctns [u8],
}

impl<'lctns> LctnEntry<'lctns> {
    fn new(raw_slice: &'lctns [u8]) -> Self {
        Self {
            raw_slice,
        }
    }

    fn name(&self) -> String {
        let slice = &self.raw_slice[MAGIC_INDEX_NAME..MAGIC_INDEX_NAME + MAGIC_LEN_NAME];
        String::from_utf8_lossy(slice).to_string()
    }

    fn lat(&self) -> i32 {
        let slice = &self.raw_slice[MAGIC_INDEX_LAT..MAGIC_INDEX_LAT + MAGIC_LEN_LAT];
        i32::from_le_bytes(slice.try_into().expect("Latitude error"))
    }

    fn long(&self) -> i32 {
        let slice = &self.raw_slice[MAGIC_INDEX_LONG..MAGIC_INDEX_LONG + MAGIC_LEN_LONG];
        i32::from_le_bytes(slice.try_into().expect("Longitude error"))
    }
}

impl Display for LctnEntry<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
        let latitude = Latitude::from_fit(self.lat());
        let longitude = Longitude::from_fit(self.long());
        write!(f, "{} ({}, {})", self.name(), latitude, longitude)
    }
}

struct LctnEntryMut<'lctns> {
    raw_slice: &'lctns mut [u8],
}

impl<'lctns> LctnEntryMut<'lctns> {
    fn set_name(&mut self, name: String) {
        let iter = name.as_bytes().iter().chain(repeat(&b'\0')).enumerate();
        for (index, byte) in iter {
            if index > MAGIC_LEN_NAME {
                break;
            }
            self.raw_slice[MAGIC_INDEX_NAME + index] = *byte;
        }
    }

    fn set_lat(&mut self, lat: i32) {
        let slice = i32::to_le_bytes(lat);
        for (index, byte) in slice.into_iter().enumerate() {
            self.raw_slice[MAGIC_INDEX_LAT + index] = byte;
        }
    }

    fn set_long(&mut self, long: i32) {
        let slice = i32::to_le_bytes(long);
        for (index, byte) in slice.into_iter().enumerate() {
            self.raw_slice[MAGIC_INDEX_LONG + index] = byte;
        }
    }
}

impl Display for LctnEntryMut<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
        let entry = LctnEntry::new(self.raw_slice);
        write!(f, "{}", &entry)
    }
}

struct Lctns {
    raw_data: Vec<u8>,
}

impl Lctns {
    fn new<F: AsRef<Path>>(filename: F) -> Result<Self> {
        let mut lctns = Lctns {
            raw_data: Vec::new(),
        };

        let mut f = File::open(filename)?;
        lctns.raw_data = Vec::new();
        f.read_to_end(&mut lctns.raw_data)?;
        Ok(lctns)
    }

    fn save<F: AsRef<Path>>(&self, filename: F) -> Result<()> {
        let mut f = File::create(filename)?;
        f.write(&self.raw_data).map(|_| ()).context("Save failed")
    }

    fn len(&self) -> usize {
        (self.raw_data.len() - MAGIC_INITIAL_BYTES) / MAGIC_ENTRY_LEN
    }

    fn get(&self, index: usize) -> Option<LctnEntry> {
        let start = MAGIC_INITIAL_BYTES + index * MAGIC_ENTRY_LEN;
        let end = MAGIC_INITIAL_BYTES + (index + 1) * MAGIC_ENTRY_LEN;
        Some(LctnEntry {
            raw_slice: &self.raw_data[start..end],
        })
    }

    fn get_mut(&mut self, index: usize) -> Option<LctnEntryMut> {
        let start = MAGIC_INITIAL_BYTES + index * MAGIC_ENTRY_LEN;
        let end = MAGIC_INITIAL_BYTES + (index + 1) * MAGIC_ENTRY_LEN;
        Some(LctnEntryMut {
            raw_slice: &mut self.raw_data[start..end],
        })
    }

    fn show_all(&self) -> Result<()> {
        for index in 0..self.len() {
            println!("{:4}: {}", index, self.get(index).unwrap());
        }
        Ok(())
    }

    fn _hexdump(&self) -> Result<()> {
        let mut left = String::default();
        let mut right = String::default();
        let buffer = &self.raw_data[MAGIC_INITIAL_BYTES..]; // Ignore stuff at start of file.

        for (index, byte) in buffer.iter().enumerate() {
            if index % MAGIC_ENTRY_LEN == 0 {
                println!("{left} {right}\n");
                left = format!("{:04}  ", index);
                right = String::default();
                println!("{}", self.get(index/MAGIC_ENTRY_LEN).unwrap());
            }
            left += &format!("{:02x} ", byte);
            if byte > &32 && byte < &127 {
                right += std::str::from_utf8(&buffer[index..index+1]).unwrap();
            } else {
                right += "_";
            }
        }
        println!("{left} {right}");
        Ok(())
    }
}

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Usage: {}", program);
    print!("{}", opts.usage(&brief));
}

fn main() -> Result<()> {
    let args: Vec<String> = args().collect();
    let program = args[0].clone();
    let mut index = None;

    let mut opts = Options::new();
    opts.optopt("i", "input", "FILE", "");
    opts.optopt("o", "output", "FILE", "");
    opts.optopt("e", "entry", "NUM", "");
    opts.optopt("n", "name", "NAME", "");
    // While "λ" and "φ" would be reasonable for "latitude" and "longitude", the getopts crate
    // seems to only allow ascii for the short name. Thus they end up with only their long ones.
    opts.optopt("", "latitude", "N|S deg°[min'sec\"]", "");
    opts.optopt("", "longitude", "E|W deg°[min'sec\"]", "");
    opts.optflag("h", "help", "Print this help text");
    let matches = opts.parse(&args[1..])?;
    if matches.opt_present("help") {
        print_usage(&program, opts);
        return Ok(());
    }

    let mut lctns = Lctns::new(matches.opt_str("input")
        .unwrap_or_else(|| String::from("LCTNS.FIT")))?;
    let output = matches.opt_str("output");
    let mut save = false;
    if let Some(string) = matches.opt_str("entry") {
        let highest = lctns.len();
        let i = string.parse()?;
        if i < highest {
            index = Some(i);
        } else {
            Err(anyhow!("{i} is too large. There are only {highest} number of records in file."))?;
        }
    }
    if let Some(i) = index {
        let mut entry = lctns.get_mut(i).ok_or_else(|| anyhow!("No entry at {i}"))?;
        if let Some(name) = matches.opt_str("name") {
            save = true;
            entry.set_name(name);
        }
        if let Some(lat) = matches.opt_str("latitude") {
            save = true;
            let raw: Latitude = lat.as_str().try_into()?;
            entry.set_lat(raw.inner);
        }
        if let Some(long) = matches.opt_str("longitude") {
            save = true;
            let raw: Longitude = long.as_str().try_into()?;
            entry.set_long(raw.inner);
        }
        println!("{entry}");
    } else if matches.opt_str("name").is_some() || matches.opt_str("latitude") .is_some() ||
            matches.opt_str("longitude").is_some() || matches.opt_str("output").is_some()
    {
        Err(anyhow!("Updates requires selecting an entry. (Using: --entry NUM)"))?;
    } else {
        lctns.show_all()?;
    }

    if save && output.is_some() {
        lctns.save(output.unwrap())?; // Ok to unwrap(), previous line checks for is_some()
    }

    Ok(())
}