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
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
//! Configuration module.
//!
//! One of the main features of OpenStratos is that it's almost 100% configurable. Apart from the
//! features above, the package contains a `config.toml` file, written in
//! [TOML](https://en.wikipedia.org/wiki/TOML) that enables the configuration of the setup without
//! requiring a recompilation of the software. Things like the picture/video options, alert phone
//! number, debug mode, pin numbers and many more can be modified with that file.
//!
//! Some documentation can be found in the file itself, thank to its comments, but main options are
//! explained here:
//!
//! * **Debug mode** (`debug = bool`): Turns the debug mode on or off, it's off by default. The
//! debug mode will print all serial communication in logs, and it will add more insightful logs,
//! that enable debugging system malfunction. This mode will consume more resources than
//! non-debugging mode, and it's not recommended for normal balloon operation. Also, debug logs will
//! be full of silly comments that might not provide anything useful in a real flight.
//! * **Camera rotation** (`camera_rotation = 0-359`): Sets the rotation of the camera for videos
//! and pictures, in degrees. This is useful if the probe, by design, requires the camera to be in a
//! non-vertical position.
//! * **Data directory** (`data_dir = "/path/to/data"`): Sets the path to the main data output
//! directory. Logs, images, videos and current state file will be stored in this path. Make sure
//! it's a reliable path between reboots.
//! * **Picture section** (`[picture]`): Sets the configuration for pictures. Dimensions, quality,
//! brightness, contrast, ISO, exposure and many more can be configured. Two configuration options
//! are a bit different from the rest actually. The `exif` parameter sets if GPS data should be
//! added to images, so that the final image has position metadata, for example. The `raw` option
//! controls if the raw sensor data should be added to images as JPEG metadata. This will add about
//! 8MiB of information to the images, at least.
//! * **Video section** (`[video]`): Sets the configuration for videos. Dimensions, frames per
//! second, bitrate, and many more, most of them also available for pictures.
//!
//! You can also check the [`Config`](struct.Config.html) structure for further implementation
//! details.

#![allow(missing_debug_implementations)]

use std::{
    fs::File,
    io::{BufReader, Read},
    path::{Path, PathBuf},
    result::Result,
    u8,
};

// Only required for raspicam
#[cfg(feature = "raspicam")]
use std::{ffi::OsStr, i8, u16};

// Only required for GPS, FONA or telemetry
#[cfg(any(feature = "gps", feature = "fona"))]
use std::fmt;

use colored::Colorize;
use failure::{Error, ResultExt};
use lazy_static::lazy_static;
use serde::Deserialize;
use toml;

// Only required for GPS, FONA or telemetry
#[cfg(any(feature = "gps", feature = "fona"))]
use serde::de::{self, Deserializer, Visitor};

// Only required for GPS or FONA
#[cfg(any(feature = "gps", feature = "fona"))]
use sysfs_gpio::Pin;

use crate::{error, generate_error_string, CONFIG_FILE};

lazy_static! {
    /// Configuration object.
    pub static ref CONFIG: Config = match Config::from_file(CONFIG_FILE) {
        Err(e) => {
            panic!("{}", generate_error_string(&e, "error loading configuration").red());
        },
        Ok(c) => c,
    };
}

/// Configuration object.
#[derive(Debug, Deserialize)]
pub struct Config {
    /// Wether the application should run in debug mode or not.
    debug: Option<bool>,
    /// The data directory.
    data_dir: PathBuf,
    /// Flight configuration.
    flight: Flight,
    /// Battery configuration.
    #[cfg(feature = "fona")]
    battery: Battery,
    /// Video configuration.
    #[cfg(feature = "raspicam")]
    video: Video,
    /// Picture configuration.
    #[cfg(feature = "raspicam")]
    picture: Picture,
    /// GPS configuration.
    #[cfg(feature = "gps")]
    gps: Gps,
    /// FONA module configuration.
    #[cfg(feature = "fona")]
    fona: Fona,
    ///Telemetry configuration.
    #[cfg(feature = "telemetry")]
    telemetry: Telemetry,
}

impl Config {
    /// Creates a new configuration object from a path.
    fn from_file<P: AsRef<Path>>(path: P) -> Result<Config, Error> {
        let file = File::open(path.as_ref()).context(error::Config::Open {
            path: path.as_ref().to_owned(),
        })?;
        let mut reader = BufReader::new(file);
        let mut contents = String::new();

        let _ = reader
            .read_to_string(&mut contents)
            .context(error::Config::Read {
                path: path.as_ref().to_owned(),
            })?;

        let config: Config = toml::from_str(&contents).context(error::Config::InvalidToml {
            path: path.as_ref().to_owned(),
        })?;

        if let (false, errors) = config.verify() {
            Err(error::Config::Invalid { errors }.into())
        } else {
            Ok(config)
        }
    }

    /// Verify the correctness of the configuration, and return a list of errors if invalid.
    #[allow(clippy::replace_consts)]
    fn verify(&self) -> (bool, String) {
        // Only required for Raspicam
        #[cfg(feature = "raspicam")]
        let mut errors = String::new();
        #[cfg(feature = "raspicam")]
        let mut ok = true;

        #[cfg(feature = "raspicam")]
        {
            // Check for picture configuration errors.
            if self.picture.width > 3280 {
                ok = false;
                errors.push_str(&format!(
                    "picture width must be below or equal to 3280px, found {}px\n",
                    self.picture.width
                ));
            }
            if self.picture.height > 2464 {
                ok = false;
                errors.push_str(&format!(
                    "picture height must be below or equal to 2464px, found {}px\n",
                    self.picture.height
                ));
            }

            if let Some(r @ 360...u16::MAX) = self.picture.rotation {
                ok = false;
                errors.push_str(&format!(
                    "camera rotation must be between 0 and 359 degrees, found {} degrees\n",
                    r
                ));
            }

            if self.picture.quality > 100 {
                ok = false;
                errors.push_str(&format!(
                    "picture quality must be a number between 0 and 100, found {}px\n",
                    self.picture.quality
                ));
            }

            if let Some(b @ 101...u8::MAX) = self.picture.brightness {
                ok = false;
                errors.push_str(&format!(
                    "picture brightness must be between 0 and 100, found {}\n",
                    b
                ));
            }

            match self.picture.contrast {
                Some(c @ i8::MIN...-101) | Some(c @ 101...i8::MAX) => {
                    ok = false;
                    errors.push_str(&format!(
                        "picture contrast must be between -100 and 100, found {}\n",
                        c
                    ));
                }
                _ => {}
            }

            match self.picture.sharpness {
                Some(s @ i8::MIN...-101) | Some(s @ 101...i8::MAX) => {
                    ok = false;
                    errors.push_str(&format!(
                        "picture sharpness must be between -100 and 100, found {}\n",
                        s
                    ));
                }
                _ => {}
            }

            match self.picture.saturation {
                Some(s @ i8::MIN...-101) | Some(s @ 101...i8::MAX) => {
                    ok = false;
                    errors.push_str(&format!(
                        "picture saturation must be between -100 and 100, found {}\n",
                        s
                    ));
                }
                _ => {}
            }

            match self.picture.iso {
                Some(i @ 0...99) | Some(i @ 801...u16::MAX) => {
                    ok = false;
                    errors.push_str(&format!(
                        "picture ISO must be between 100 and 800, found {}\n",
                        i
                    ));
                }
                _ => {}
            }

            match self.picture.ev {
                Some(e @ i8::MIN...-11) | Some(e @ 11...i8::MAX) => {
                    ok = false;
                    errors.push_str(&format!(
                        "picture EV compensation must be between -10 and 10, found {}\n",
                        e
                    ));
                }
                _ => {}
            }

            // Check for video configuration errors.
            if self.video.width > 2592 {
                ok = false;
                errors.push_str(&format!(
                    "video width must be below or equal to 2592px, found {}px\n",
                    self.video.width
                ));
            }
            if self.video.height > 1944 {
                ok = false;
                errors.push_str(&format!(
                    "video height must be below or equal to 1944px, found {}px\n",
                    self.video.height
                ));
            }

            if let Some(r @ 360...u16::MAX) = self.video.rotation {
                ok = false;
                errors.push_str(&format!(
                    "camera rotation must be between 0 and 359 degrees, found {} degrees\n",
                    r
                ));
            }

            if self.video.fps > 90 {
                ok = false;
                errors.push_str(&format!(
                    "video framerate must be below or equal to 90fps, found {}fps\n",
                    self.video.fps
                ));
            }

            if let Some(b @ 101...u8::MAX) = self.video.brightness {
                ok = false;
                errors.push_str(&format!(
                    "video brightness must be between 0 and 100, found {}\n",
                    b
                ));
            }

            match self.video.contrast {
                Some(c @ i8::MIN...-101) | Some(c @ 101...i8::MAX) => {
                    ok = false;
                    errors.push_str(&format!(
                        "video contrast must be between -100 and 100, found {}\n",
                        c
                    ));
                }
                _ => {}
            }

            match self.video.sharpness {
                Some(s @ i8::MIN...-101) | Some(s @ 101...i8::MAX) => {
                    ok = false;
                    errors.push_str(&format!(
                        "video sharpness must be between -100 and 100, found \
                         {}\n",
                        s
                    ));
                }
                _ => {}
            }

            match self.video.saturation {
                Some(s @ i8::MIN...-101) | Some(s @ 101...i8::MAX) => {
                    ok = false;
                    errors.push_str(&format!(
                        "video saturation must be between -100 and 100, found {}\n",
                        s
                    ));
                }
                _ => {}
            }

            match self.video.iso {
                Some(i @ 0...99) | Some(i @ 801...u16::MAX) => {
                    ok = false;
                    errors.push_str(&format!(
                        "video ISO must be between 100 and 800, found {}\n",
                        i
                    ));
                }
                _ => {}
            }

            match self.video.ev {
                Some(e @ i8::MIN...-11) | Some(e @ 11...i8::MAX) => {
                    ok = false;
                    errors.push_str(&format!(
                        "video EV compensation must be between -10 and 10, found {}\n",
                        e
                    ));
                }
                _ => {}
            }

            // Video modes.
            match (self.video.width, self.video.height, self.video.fps) {
                (2592, 1944, 1...15)
                | (1920, 1080, 1...30)
                | (1296, 972, 1...42)
                | (1296, 730, 1...49)
                | (640, 480, 1...90) => {}
                (w, h, f) => {
                    ok = false;
                    errors.push_str(&format!(
                        "video mode must be one of 2592\u{d7}1944 1-15fps, 1920\u{d7}1080 \
                         1-30fps, 1296\u{d7}972 1-42fps, 1296\u{d7}730 1-49fps, 640\u{d7}480 \
                         1-60fps, found {}x{} {}fps\n",
                        w, h, f
                    ));
                }
            }
        }

        // TODO check GPS configuration

        // Only required for Raspicam
        #[cfg(feature = "raspicam")]
        {
            (ok, errors)
        }

        #[cfg(not(feature = "raspicam"))]
        {
            (true, String::new())
        }
    }

    /// Gets wether OpenStratos should run in debug mode.
    pub fn debug(&self) -> bool {
        self.debug == Some(true)
    }

    /// Gets the flight information.
    pub fn flight(&self) -> Flight {
        self.flight
    }

    /// Gets battery configuration
    #[cfg(feature = "fona")]
    pub fn battery(&self) -> Battery {
        self.battery
    }

    /// Gets the configuration for video.
    #[cfg(feature = "raspicam")]
    pub fn video(&self) -> &Video {
        &self.video
    }

    /// Gets the configuration for pictures.
    #[cfg(feature = "raspicam")]
    pub fn picture(&self) -> &Picture {
        &self.picture
    }

    /// Gets the GPS configuration.
    #[cfg(feature = "gps")]
    pub fn gps(&self) -> &Gps {
        &self.gps
    }

    /// Gets the FONA module configuration.
    #[cfg(feature = "fona")]
    pub fn fona(&self) -> &Fona {
        &self.fona
    }

    /// Gets the telemetry configuration.
    #[cfg(feature = "telemetry")]
    pub fn telemetry(&self) -> &Telemetry {
        &self.telemetry
    }

    /// Gets the configured data directory.
    pub fn data_dir(&self) -> &Path {
        self.data_dir.as_path()
    }
}

/// Flight configuration structure.
#[derive(Debug, Clone, Copy, Deserialize)]
pub struct Flight {
    /// Approximate expected flight length, in minutes.
    length: u32,
    /// Approximate expected maximum height, in meters.
    expected_max_height: u32,
}

impl Flight {
    /// Gets the approximate expected flight length, in minutes.
    pub fn length(self) -> u32 {
        self.length
    }

    /// Gets the approximate expected maximum height, in meters.
    pub fn expected_max_height(self) -> u32 {
        self.expected_max_height
    }
}

/// Battery configuration structure.
#[cfg(feature = "fona")]
#[derive(Debug, Clone, Copy, Deserialize)]
pub struct Battery {
    /// Minimum voltage for the main battery when empty, at 0%, in volts (`V`).
    main_min: f32,
    /// Maximum voltage for the main battery when full, at 100%, in volts (`V`).
    main_max: f32,
    /// Minimum voltage for the FONA battery when empty, at 0%, in volts (`V`).
    fona_min: f32,
    /// Maximum voltage for the FONA battery when full, at 100%, in volts (`V`).
    fona_max: f32,
    /// Minimum admissible percentage for main battery for the launch.
    main_min_percent: f32,
    /// Minimum admissible percentage for FONA battery for the launch.
    fona_min_percent: f32,
}

#[cfg(feature = "fona")]
impl Battery {
    /// Gets the minimum voltage for the main battery when empty, at 0%, in volts (`V`).
    pub fn main_min(self) -> f32 {
        self.main_min
    }

    /// Gets the maximum voltage for the main battery when full, at 100%, in volts (`V`).
    pub fn main_max(self) -> f32 {
        self.main_max
    }

    /// Gets the minimum voltage for the FONA battery when empty, at 0%, in volts (`V`).
    pub fn fona_min(self) -> f32 {
        self.fona_min
    }

    /// Gets the maximum voltage for the FONA battery when full, at 0%, in volts (`V`).
    pub fn fona_max(self) -> f32 {
        self.fona_min
    }

    /// Gets the minimum admissible percentage for main battery for the launch.
    pub fn main_min_percent(self) -> f32 {
        self.main_min_percent
    }

    /// Gets the minimum admissible percentage for FONA battery for the launch.
    pub fn fona_min_percent(self) -> f32 {
        self.fona_min_percent
    }
}

/// Video configuration structure.
#[cfg(feature = "raspicam")]
#[derive(Debug, Clone, Copy, Deserialize)]
pub struct Video {
    /// Height of the video, in px.
    height: u16,
    /// Width of the video, in px.
    width: u16,
    /// Rotation of the camera, in degrees (°).
    rotation: Option<u16>,
    /// Frames per second (FPS) for the video.
    fps: u8,
    /// Bit rate for the video, in bps (bits per second).
    bitrate: u32,
    /// Exposure configuration.
    exposure: Option<Exposure>,
    /// Brightness correction.
    brightness: Option<u8>,
    /// Contrast correction.
    contrast: Option<i8>,
    /// Sharpness configuration.
    sharpness: Option<i8>,
    /// Saturation configuration.
    saturation: Option<i8>,
    /// ISO for the image.
    iso: Option<u16>,
    /// Video stabilization.
    stabilization: Option<bool>,
    /// EV correction configuration.
    ev: Option<i8>,
    /// White balance configuration.
    white_balance: Option<WhiteBalance>,
}

#[cfg(feature = "raspicam")]
impl Video {
    /// Gets the configured video height for the camera, in pixels.
    pub fn height(self) -> u16 {
        self.height
    }

    /// Gets the configured video width for the camera, in pixels.
    pub fn width(self) -> u16 {
        self.width
    }

    /// Gets the configured picture rotation for the camera, in degrees (°).
    pub fn rotation(self) -> Option<u16> {
        self.rotation
    }

    /// Gets the configured video framerate for the camera, in frames per second.
    pub fn fps(self) -> u8 {
        self.fps
    }

    /// Gets the configured bitrate for videos.
    pub fn bitrate(self) -> u32 {
        self.bitrate
    }

    /// Gets the configured exposure for videos.
    pub fn exposure(self) -> Option<Exposure> {
        self.exposure
    }

    /// Gets the configured brightness for videos.
    pub fn brightness(self) -> Option<u8> {
        self.brightness
    }

    /// Gets the configured contrast for videos.
    pub fn contrast(self) -> Option<i8> {
        self.contrast
    }

    /// Gets the configured sharpness for videos.
    pub fn sharpness(self) -> Option<i8> {
        self.sharpness
    }

    /// Gets the configured saturation for videos.
    pub fn saturation(self) -> Option<i8> {
        self.saturation
    }

    /// Gets the configured ISO for videos.
    pub fn iso(self) -> Option<u16> {
        self.iso
    }

    /// Gets if video stabilization needs to be turned on.
    pub fn stabilization(self) -> bool {
        self.stabilization == Some(true)
    }

    /// Gets the configured EV compensation for videos.
    pub fn ev(self) -> Option<i8> {
        self.ev
    }

    /// Gets the configured automatic white balance for videos.
    pub fn white_balance(self) -> Option<WhiteBalance> {
        self.white_balance
    }
}

/// Picture configuration structure.
#[cfg(feature = "raspicam")]
#[derive(Debug, Clone, Copy, Deserialize)]
pub struct Picture {
    /// Height of the picture, in px.
    height: u16,
    /// Width of the picture, in px.
    width: u16,
    /// Rotation of the camera, in degrees (°).
    rotation: Option<u16>,
    /// Quality of the picture, in px.
    quality: u8,
    /// Wether to add EXIF data to pictures or not.
    #[cfg(feature = "gps")]
    exif: Option<bool>,
    /// Wether to save the raw sensor data as JPG metadata.
    raw: Option<bool>,
    /// Exposure configuration.
    exposure: Option<Exposure>,
    /// Brightness correction.
    brightness: Option<u8>,
    /// Contrast correction.
    contrast: Option<i8>,
    /// Sharpness configuration.
    sharpness: Option<i8>,
    /// Saturation configuration.
    saturation: Option<i8>,
    /// ISO for the image.
    iso: Option<u16>,
    /// EV correction configuration.
    ev: Option<i8>,
    /// White balance configuration.
    white_balance: Option<WhiteBalance>,
    /// Interval between pictures during flight.
    interval: u32,
    /// Repeat each picture after these seconds (for issues with probe movement).
    repeat: Option<u32>,
    /// Timeout for first picture after launch, in seconds.
    first_timeout: u32,
}

#[cfg(feature = "raspicam")]
impl Picture {
    /// Gets the configured picture height for the camera, in pixels.
    pub fn height(self) -> u16 {
        self.height
    }

    /// Gets the configured picture width for the camera, in pixels.
    pub fn width(self) -> u16 {
        self.width
    }

    /// Gets the configured picture rotation for the camera, in degrees (°).
    pub fn rotation(self) -> Option<u16> {
        self.rotation
    }

    /// Gets the configured picture quality for the camera.
    pub fn quality(self) -> u8 {
        self.quality
    }

    /// Gets wether the camera should add available EXIF information to pictures.
    #[cfg(feature = "gps")]
    pub fn exif(self) -> bool {
        self.exif == Some(true)
    }

    /// Gets wether the camera should add raw sensor data to pictures as JPEG metadata.
    pub fn raw(self) -> bool {
        self.raw == Some(true)
    }

    /// Gets the configured exposure for pictures.
    pub fn exposure(self) -> Option<Exposure> {
        self.exposure
    }

    /// Gets the configured brightness for pictures.
    pub fn brightness(self) -> Option<u8> {
        self.brightness
    }

    /// Gets the configured contrast for pictures.
    pub fn contrast(self) -> Option<i8> {
        self.contrast
    }

    /// Gets the configured sharpness for pictures.
    pub fn sharpness(self) -> Option<i8> {
        self.sharpness
    }

    /// Gets the configured saturation for pictures.
    pub fn saturation(self) -> Option<i8> {
        self.saturation
    }

    /// Gets the configured ISO for pictures.
    pub fn iso(self) -> Option<u16> {
        self.iso
    }

    /// Gets the configured EV compensation for pictures.
    pub fn ev(self) -> Option<i8> {
        self.ev
    }

    /// Gets the configured automatic white balance for pictures.
    pub fn white_balance(self) -> Option<WhiteBalance> {
        self.white_balance
    }

    /// Gets the interval between pictures during flight.
    pub fn interval(self) -> u32 {
        self.interval
    }

    /// Gets the timeout for repeated picture.
    ///
    /// Repeat each picture after these seconds (for issues with probe movement).
    pub fn repeat(self) -> Option<u32> {
        self.repeat
    }

    /// Gets the timeout for first picture after launch, in seconds.
    pub fn first_timeout(self) -> u32 {
        self.first_timeout
    }
}

/// Exposure setting.
#[cfg(feature = "raspicam")]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
pub enum Exposure {
    /// Turns off exposure control.
    Off,
    /// Use automatic exposure mode.
    Auto,
    /// Select setting for night shooting.
    Night,
    /// Night preview mode.
    NightPreview,
    /// Select setting for back-lit subject.
    BackLight,
    /// Spot light mode.
    SpotLight,
    /// Select setting for sports (fast shutter etc.).
    Sports,
    /// Select setting optimized for snowy scenery.
    Snow,
    /// Select setting optimized for beach.
    Beach,
    /// Select setting for long exposures.
    VeryLong,
    /// Constrain fps to a fixed value.
    FixedFps,
    /// Anti-shake mode.
    AntiShake,
    /// Select setting optimized for fireworks.
    Fireworks,
}

#[cfg(feature = "raspicam")]
impl AsRef<OsStr> for Exposure {
    fn as_ref(&self) -> &OsStr {
        OsStr::new(match *self {
            Exposure::Off => "off",
            Exposure::Auto => "auto",
            Exposure::Night => "night",
            Exposure::NightPreview => "nightpreview",
            Exposure::BackLight => "backlight",
            Exposure::SpotLight => "spotlight",
            Exposure::Sports => "sports",
            Exposure::Snow => "snow",
            Exposure::Beach => "beach",
            Exposure::VeryLong => "verylong",
            Exposure::FixedFps => "fixedfps",
            Exposure::AntiShake => "antishake",
            Exposure::Fireworks => "fireworks",
        })
    }
}

/// White balance setting.
#[cfg(feature = "raspicam")]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
pub enum WhiteBalance {
    /// Turn off white balance calculation.
    Off,
    /// Automatic mode (default).
    Auto,
    /// Sunny mode.
    Sun,
    /// Cloudy mode.
    CloudShade,
    /// Tungsten lighting mode.
    Tungsten,
    /// Fluorescent lighting mode.
    Fluorescent,
    /// Incandescent lighting mode.
    Incandescent,
    /// Flash mode.
    Flash,
    /// Horizon mode.
    Horizon,
}

#[cfg(feature = "raspicam")]
impl AsRef<OsStr> for WhiteBalance {
    fn as_ref(&self) -> &OsStr {
        OsStr::new(match *self {
            WhiteBalance::Off => "off",
            WhiteBalance::Auto => "auto",
            WhiteBalance::Sun => "sun",
            WhiteBalance::CloudShade => "cloudshade",
            WhiteBalance::Tungsten => "tungsten",
            WhiteBalance::Fluorescent => "fluorescent",
            WhiteBalance::Incandescent => "incandescent",
            WhiteBalance::Flash => "flash",
            WhiteBalance::Horizon => "horizon",
        })
    }
}

/// GPS configuration structure.
#[cfg(feature = "gps")]
#[derive(Debug, Deserialize)]
pub struct Gps {
    /// UART serial console path.
    uart: PathBuf,
    /// Serial console baud rate.
    baud_rate: u32,
    /// Power GPIO pin.
    #[serde(deserialize_with = "deserialize_pin")]
    power_gpio: Pin,
}

#[cfg(feature = "gps")]
impl Gps {
    /// Gets the UART serial console path.
    pub fn uart(&self) -> &Path {
        &self.uart
    }

    /// Gets the serial console baud rate.
    pub fn baud_rate(&self) -> u32 {
        self.baud_rate
    }

    /// Gets the power GPIO pin.
    pub fn power_gpio(&self) -> Pin {
        self.power_gpio
    }
}

/// Fona configuration structure
#[cfg(feature = "fona")]
#[derive(Debug, Deserialize)]
pub struct Fona {
    /// UART serial console path.
    uart: PathBuf,
    /// Serial console baud rate.
    baud_rate: u32,
    /// Power control GPIO pin.
    #[serde(deserialize_with = "deserialize_pin")]
    power_gpio: Pin,
    /// Status GPIO pin.
    #[serde(deserialize_with = "deserialize_pin")]
    status_gpio: Pin,
    /// SMS receiver phone number.
    sms_phone: PhoneNumber,
    /// Operator GSM location service domain.
    location_service: String,
}

#[cfg(feature = "fona")]
impl Fona {
    /// Gets the UART serial console path.
    pub fn uart(&self) -> &Path {
        &self.uart
    }

    /// Gets the serial console baud rate.
    pub fn baud_rate(&self) -> u32 {
        self.baud_rate
    }

    /// Gets the power GPIO pin.
    pub fn power_gpio(&self) -> Pin {
        self.power_gpio
    }

    /// Gets the status GPIO pin.
    pub fn status_gpio(&self) -> Pin {
        self.status_gpio
    }

    /// Gets the phone number for SMSs.
    pub fn sms_phone(&self) -> &PhoneNumber {
        &self.sms_phone
    }

    /// Gets the location service for GSM location retrieval.
    pub fn location_service(&self) -> &str {
        &self.location_service
    }
}

/// Phone number representation.
#[cfg(feature = "fona")]
#[derive(Debug)]
pub struct PhoneNumber(String);

#[cfg(feature = "fona")]
impl PhoneNumber {
    /// Gets the phone number as a string.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[cfg(feature = "fona")]
impl<'de> Deserialize<'de> for PhoneNumber {
    fn deserialize<D>(deserializer: D) -> Result<PhoneNumber, D::Error>
    where
        D: Deserializer<'de>,
    {
        // TODO: better parsing and checking

        /// Visitor for phone numbers.
        struct PhoneNumberVisitor;
        impl<'dev> Visitor<'dev> for PhoneNumberVisitor {
            type Value = PhoneNumber;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a valid phone number")
            }

            fn visit_str<E>(self, value: &str) -> Result<PhoneNumber, E>
            where
                E: de::Error,
            {
                Ok(PhoneNumber(value.to_owned()))
            }
        }

        deserializer.deserialize_str(PhoneNumberVisitor)
    }
}

/// Telemetry configuration structure.
#[cfg(feature = "telemetry")]
#[derive(Debug, Deserialize)]
pub struct Telemetry {
    /// UART serial console path.
    uart: PathBuf,
    /// Serial console baud rate.
    baud_rate: u32,
}

#[cfg(feature = "telemetry")]
impl Telemetry {
    /// Gets the UART serial console path.
    pub fn uart(&self) -> &Path {
        &self.uart
    }

    /// Gets the serial console baud rate.
    pub fn baud_rate(&self) -> u32 {
        self.baud_rate
    }
}

/// Deserializes a Raspberry Pi pin number into a `Pin` structure.
///
/// Note: it will make sure it deserializes a Pin between 2 and 28 (pin numbers for Raspberry Pi).
#[cfg(any(feature = "gps", feature = "fona"))]
fn deserialize_pin<'de, D>(deserializer: D) -> Result<Pin, D::Error>
where
    D: Deserializer<'de>,
{
    /// Visitor for u32 (comparing to usize).
    struct PinVisitor;
    impl<'dev> Visitor<'dev> for PinVisitor {
        type Value = Pin;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("an integer between 2 and 28")
        }

        #[allow(clippy::absurd_extreme_comparisons)]
        fn visit_i64<E>(self, value: i64) -> Result<Pin, E>
        where
            E: de::Error,
        {
            if value >= 2 && value <= 28 {
                #[allow(clippy::cast_sign_loss)]
                {
                    Ok(Pin::new(value as u64))
                }
            } else {
                Err(E::custom(format!("pin out of range: {}", value)))
            }
        }
    }

    deserializer.deserialize_u8(PinVisitor)
}

#[cfg(test)]
mod tests {
    #[cfg(all(feature = "gps", feature = "raspicam"))]
    use super::Gps;
    #[cfg(all(feature = "raspicam", feature = "telemetry"))]
    use super::Telemetry;
    #[cfg(all(feature = "raspicam", feature = "fona"))]
    use super::{Battery, Fona, PhoneNumber};
    use super::{Config, CONFIG};
    #[cfg(feature = "raspicam")]
    use super::{Exposure, Flight, Picture, Video, WhiteBalance};

    #[cfg(all(feature = "raspicam", any(feature = "gps", feature = "fona")))]
    use sysfs_gpio::Pin;

    #[cfg(feature = "gps")]
    use std::path::Path;
    #[cfg(feature = "raspicam")]
    use std::path::PathBuf;

    /// Loads the default configuration and checks it.
    #[test]
    fn load_config() {
        let config = Config::from_file("config.toml").unwrap();

        assert_eq!(config.debug(), true);
        #[cfg(feature = "raspicam")]
        {
            assert_eq!(config.picture().height(), 2464);
            assert_eq!(config.picture().width(), 3280);
            #[cfg(feature = "gps")]
            {
                assert_eq!(config.picture().exif(), true);
            }
            assert_eq!(config.video().height(), 1080);
            assert_eq!(config.video().width(), 1920);
            assert_eq!(config.video().fps(), 30);
        }

        #[cfg(feature = "gps")]
        {
            assert_eq!(config.gps().uart(), Path::new("/dev/ttyAMA0"));
            assert_eq!(config.gps().baud_rate(), 9_600);
            assert_eq!(config.gps().power_gpio().get_pin(), 3)
        }
    }

    /// Tests an invalid configuration, and the error output.
    #[test]
    #[cfg(feature = "raspicam")]
    fn config_error() {
        let flight = Flight {
            length: 300,
            expected_max_height: 35000,
        };

        #[cfg(feature = "gps")]
        let picture = Picture {
            height: 10_345,
            width: 5_246,
            rotation: Some(180),
            quality: 95,
            raw: Some(true),
            exif: Some(true),
            exposure: Some(Exposure::AntiShake),
            brightness: Some(50),
            contrast: Some(50),
            sharpness: None,
            saturation: None,
            iso: None,
            ev: None,
            white_balance: Some(WhiteBalance::Horizon),
            first_timeout: 120,
            interval: 300,
            repeat: Some(30),
        };

        #[cfg(not(feature = "gps"))]
        let picture = Picture {
            height: 10_345,
            width: 5_246,
            rotation: Some(180),
            quality: 95,
            raw: Some(true),
            exposure: Some(Exposure::AntiShake),
            brightness: Some(50),
            contrast: Some(50),
            sharpness: None,
            saturation: None,
            iso: None,
            ev: None,
            white_balance: Some(WhiteBalance::Horizon),
            first_timeout: 120,
            interval: 300,
            repeat: Some(30),
        };

        let video = Video {
            height: 12_546,
            width: 5_648,
            rotation: Some(180),
            fps: 92,
            bitrate: 20_000_000,
            exposure: Some(Exposure::AntiShake),
            brightness: Some(50),
            contrast: Some(50),
            sharpness: None,
            saturation: None,
            iso: None,
            stabilization: Some(true),
            ev: None,
            white_balance: Some(WhiteBalance::Horizon),
        };

        #[cfg(feature = "fona")]
        let fona = Fona {
            uart: PathBuf::from("/dev/ttyUSB0"),
            baud_rate: 9_600,
            power_gpio: Pin::new(7),
            status_gpio: Pin::new(21),
            sms_phone: PhoneNumber(String::new()),
            location_service: "gprs-service.com".to_owned(),
        };

        #[cfg(feature = "fona")]
        let battery = Battery {
            main_min: 1.952_777_7,
            main_max: 2.216_666_7,
            fona_min: 3.7,
            fona_max: 4.2,
            main_min_percent: 0.8,
            fona_min_percent: 0.75,
        };

        #[cfg(feature = "telemetry")]
        let telemetry = Telemetry {
            uart: PathBuf::from("/dev/ttyUSB0"),
            baud_rate: 230_400,
        };

        #[cfg(feature = "gps")]
        let gps = Gps {
            uart: PathBuf::from("/dev/ttyAMA0"),
            baud_rate: 9_600,
            power_gpio: Pin::new(3),
        };

        #[cfg(all(feature = "gps", feature = "fona", feature = "telemetry"))]
        let config = Config {
            debug: None,
            flight,
            battery,
            data_dir: PathBuf::from("data"),
            picture,
            video,
            gps,
            fona,
            telemetry,
        };

        #[cfg(all(feature = "gps", feature = "fona", not(feature = "telemetry")))]
        let config = Config {
            debug: None,
            flight,
            battery,
            data_dir: PathBuf::from("data"),
            picture,
            video,
            gps,
            fona,
        };

        #[cfg(all(feature = "gps", not(feature = "fona"), feature = "telemetry"))]
        let config = Config {
            debug: None,
            flight,
            data_dir: PathBuf::from("data"),
            picture,
            video,
            gps,
            telemetry,
        };

        #[cfg(all(feature = "gps", not(feature = "fona"), not(feature = "telemetry")))]
        let config = Config {
            debug: None,
            flight,
            data_dir: PathBuf::from("data"),
            picture,
            video,
            gps,
        };

        #[cfg(all(not(feature = "gps"), feature = "fona", feature = "telemetry"))]
        let config = Config {
            debug: None,
            flight,
            battery,
            data_dir: PathBuf::from("data"),
            picture,
            video,
            fona,
            telemetry,
        };

        #[cfg(all(not(feature = "gps"), feature = "fona", not(feature = "telemetry")))]
        let config = Config {
            debug: None,
            flight,
            battery,
            data_dir: PathBuf::from("data"),
            picture,
            video,
            fona,
        };

        #[cfg(all(not(feature = "gps"), not(feature = "fona"), feature = "telemetry"))]
        let config = Config {
            debug: None,
            flight,
            data_dir: PathBuf::from("data"),
            picture,
            video,
            telemetry,
        };

        #[cfg(all(
            not(feature = "gps"),
            not(feature = "fona"),
            not(feature = "telemetry")
        ))]
        let config = Config {
            debug: None,
            flight,
            data_dir: PathBuf::from("data"),
            picture,
            video,
        };

        let (verify, errors) = config.verify();

        assert_eq!(verify, false);
        assert_eq!(
            errors,
            "picture width must be below or equal to 3280px, found 5246px\npicture height \
             must be below or equal to 2464px, found 10345px\nvideo width must be below or \
             equal to 2592px, found 5648px\nvideo height must be below or equal to 1944px, \
             found 12546px\nvideo framerate must be below or equal to 90fps, found 92fps\n\
             video mode must be one of 2592\u{d7}1944 1-15fps, 1920\u{d7}1080 1-30fps, \
             1296\u{d7}972 1-42fps, 1296\u{d7}730 1-49fps, 640\u{d7}480 1-60fps, found 5648x12546 \
             92fps\n"
        );
    }

    /// Tests the default configuration and its loading using the static `CONFIG` constant.
    #[test]
    fn config_static() {
        assert!(CONFIG.debug());
    }
}