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
//
// Copyright (C) 2019 Kubos Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

//!
//! Hardware service to allow for communications over a NSL Duplex D2 Radio.
//! This service starts up a communication service to allow transfer of UDP
//! packets over a serial link to and from the radio.
//!
//! # Configuration
//!
//! The service can be configured in the `config.toml` with the following fields:
//!
//! ```toml
//! [nsl-duplex-comms-service]
//! bus = "/dev/ttyUSB0"
//! ping_freq = 10
//!
//! [nsl-duplex-comms-service.comms]
//! max_num_handlers = 10
//! downlink_ports = [15001]
//! timeout = 15000
//! ip = "127.0.0.2"
//!
//! [nsl-duplex-comms-service.addr]
//! ip = "127.0.0.1"
//! port = 8089
//! ```
//!
//! The configuration of this service is split into three parts:
//!   - Service Specific
//!
//!     This section is found under `[nsl-duplex-comms-service]`
//!     - `bus` - Specifies which UART bus the Duplex is on
//!     - `ping_freq` - Specifies how frequently the service sends ping packets when the downlink queue is empty (seconds)
//!   - Communications Service Configs
//!
//!     This section is found under `[nsl-duplex-comms-service.comms]`
//!     - `max_num_handlers` - Maximum number of concurrent message handlers
//!     - `downlink_ports` - Optional list of downlink endpoints
//!     - `timeout` - Timeout for completion of GraphQL requests
//!     - `ip` - Local IP of satellite
//!   - GraphQL Server Configs
//!
//!     This section is found under `[nsl-duplex-comms-service.addr]`
//!     - `ip` - The service's IP address, used for its GraphQL interface
//!     - `port` - The service's port, used for its GraphQL interface
//!
//! Where `bus` specifies the UART bus the Duplex is on, `ping_freq` specifies how often
//! the downlink queue should be checked for queueing up pings, `ip` specifies the
//! service's IP address, and `port` specifies the port on which the service will be
//! listening for UDP packets.
//!
//! # Running the Service
//!
//! The service should be started automatically by its init script, but may also be started manually:
//!
//! ```bash
//! $ nsl-duplex-d2-comms-service
//! NSL Duplex Communications Service starting on /dev/ttyUSB0
//! ```
//!
//! If no config file is specified, then the service will look at `/home/system/etc/config.toml`.
//! An alternative config file may be specified on the command line at run time:
//!
//! ```bash
//! $ nsl-duplex-d2-comms-service -c config.toml
//! ```
//!
//! # Panics
//!
//! This service will panic on start if no config sections are found for the service or
//! if the `bus` parameter is not provided.
//!
//! # GraphQL Schema
//!
//! ## Queries
//!
//! ### Failed Packets Up
//!
//! Request number of bad uplink packets
//!
//! ```
//! {
//!     failedPacketsUp: Int!
//! }
//! ```
//!
//! ### Failed Packets Down
//!
//! Request number of bad downlink packets
//!
//! ```
//! {
//!     failedPacketsDown: Int!
//! }
//! ```
//!
//! ### Packets Up
//!
//! Request number of packets successfully uplinked
//!
//! ```
//! {
//!     packetsUp: Int!
//! }
//! ```
//!
//! ### Packets Down
//!
//! Request number of packets successfully downlinked
//!
//! ```
//! {
//!     packetsDown: Int!
//! }
//! ```
//!
//! ### Errors
//!
//! Request errors that have occurred
//!
//! ```
//! {
//!     errors: [String]
//! }
//! ```
//!
//! ### Modem Health
//!
//! Request current modem health information
//!
//! ```json
//! {
//!     modemHealth {
//!         resetCount: Int!
//!         currentTime: Int!
//!         currentRssi: Int!
//!         connectionStatus: Int!
//!         globalstarGateway: Int!
//!         lastContactTime: Int!
//!         lastAttemptTime: Int!
//!         callAttemptsSinceReset: Int!
//!         successfulConnectsSinceReset: Int!
//!         averageConnectionDuration: Int!
//!         connectionDurationStdDev: Int!
//!     }
//! }
//! ```
//!
//! ### Geolocation
//!
//! Request current geolocation data
//!
//! ```jso
//! {
//!     geolocation {
//!         lon: Float!
//!         lat: Float!
//!         time: Int!
//!         maxError: Int!
//!     }
//! }
//! ```
//!
//! ### Downlink Queue Count
//!
//! Request number of files in the downlink queue
//!
//! ```json
//! {
//!     downlink_queue_count: Int!
//! }
//! ```
//!
//! ### Is Alive
//!
//! Queries the modem's 'is_alive' status
//!
//! ```json
//! {
//!     alive: Boolean!
//! }
//! ```
//!
//! ## Mutations
//!
//! ### NoOp
//!
//! Execute a trivial command against the system
//!
//! ```json
//! mutation {
//!     noop: Boolean!
//! }
//! ```
//!

#![deny(warnings)]
#![deny(missing_docs)]

extern crate comms_service;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate juniper;
extern crate kubos_service;
#[macro_use]
extern crate log;
extern crate nsl_duplex_d2;

mod comms;
mod model;
mod schema;

use crate::comms::*;
use crate::model::Subsystem;
use crate::schema::{MutationRoot, QueryRoot};
use comms_service::*;
use failure::Error;
use kubos_service::{Config, Service};
use std::sync::{Arc, Mutex};
use syslog::Facility;

// Generic return type
type NslDuplexCommsResult<T> = Result<T, Error>;

fn main() -> NslDuplexCommsResult<()> {
    syslog::init(
        Facility::LOG_DAEMON,
        log::LevelFilter::Debug,
        Some("nsl-duplex-comms-service"),
    )
    .unwrap();

    let service_config = Config::new("nsl-duplex-comms-service").map_err(|err| {
        error!("Failed to load service config: {:?}", err);
        err
    })?;

    let bus = service_config
        .get("bus")
        .ok_or_else(|| {
            error!("Failed to load 'bus' config value");
            "Failed to load 'bus' config value"
        })
        .unwrap()
        .as_str()
        .ok_or_else(|| {
            error!("Failed to parse 'bus' config value");
            "Failed to parse 'bus' config value"
        })
        .unwrap()
        .to_owned();

    let ping_freq = if let Some(ping_freq) = service_config.get("ping_freq") {
        ping_freq.as_integer().unwrap_or(DEFAULT_PING_FREQ as i64) as u64
    } else {
        DEFAULT_PING_FREQ
    };

    // Read configuration from config file.
    let comms_config = CommsConfig::new(service_config.clone())?;

    // Open radio serial connection
    let duplex_comms = Arc::new(Mutex::new(DuplexComms::new(&bus, ping_freq)));

    // Start keep alive loop
    let radio = duplex_comms.clone();
    std::thread::spawn(|| ping_loop(radio));

    // Control block to configure communication service.
    let controls = CommsControlBlock::new(
        Some(Arc::new(read)),
        vec![Arc::new(write)],
        duplex_comms.clone(),
        duplex_comms.clone(),
        comms_config,
    )?;

    // Initialize new `CommsTelemetry` object.
    let telem = Arc::new(Mutex::new(CommsTelemetry::default()));

    // Start communication service.
    info!("NSL Duplex Communications Service starting on {}", bus);
    CommsService::start::<Arc<Mutex<DuplexComms>>, SpacePacket>(controls, &telem.clone())?;

    // Start up graphql server
    let subsystem = Subsystem::new(telem, duplex_comms);
    Service::new(service_config, subsystem, QueryRoot, MutationRoot).start();

    Ok(())
}