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
//
// Copyright (C) 2018 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.
//

use crate::model::*;
use crate::objects::*;
use juniper::FieldResult;

type Context = kubos_service::Context<Subsystem>;

pub struct QueryRoot;

// Base GraphQL query model
graphql_object!(QueryRoot: Context as "Query" |&self| {

    // Test query to verify service is running without attempting
    // to communicate with the underlying subsystem
    //
    // {
    //     ping: "pong"
    // }
    field ping() -> FieldResult<String>
    {
        Ok(String::from("pong"))
    }

    //----- Generic Queries -----//

    // Get the last run mutation
    //
    // {
    //     ack: AckCommand
    // }
    field ack(&executor) -> FieldResult<AckCommand>
    {
        let last_cmd = executor.context().subsystem().last_cmd.read()?;
        Ok(*last_cmd)
    }

    // Get all errors encountered since the last time this field was queried
    //
    // {
    //     errors: [String]
    // }
    field errors(&executor) -> FieldResult<Vec<String>>
    {
        executor.context().subsystem().get_errors();

        match executor.context().subsystem().errors.write() {
            Ok(mut master_vec) => {
                let current = master_vec.clone();
                master_vec.clear();
                master_vec.shrink_to_fit();
                Ok(current)
            },
            _ => Ok(vec!["Error: Failed to borrow master errors vector".to_owned()])
        }
    }

    // Get the current power state of the system
    //
    // Note: `uptime` is included as an available field in order to conform to
    //       the Kubos Service Outline, but cannot be implemented for this device,
    //       so the value will be 1 if the device is on and 0 if the device is off
    //
    // {
    //     power {
    //         state: PowerState,
    //         uptime: Int
    //     }
    // }
    field power(&executor) -> FieldResult<GetPowerResponse>
    {
        Ok(executor.context().subsystem().get_power()?)
    }

    // Get the current configuration of the system
    //
    // Stretch goal: implement the LOGLIST command
    //
    // {
    //     config: "Not Implemented"
    // }
    field config(&executor) -> FieldResult<String>
    {
        Ok(String::from("Not Implemented"))
    }

    // Get the test results of the last run test
    //
    // {
    //     testResults{
    //         success,
    //         telemetryNominal{...},
    //         telemetryDebug{...}
    //     }
    // }
    field test_results(&executor) -> FieldResult<IntegrationTestResults> {
        Ok(executor.context().subsystem().get_test_results()?)
    }

    // Get the current system status and errors
    //
    // {
    //     systemStatus {
    //        errors: Vec<String>,
    //        status: Vec<String>
    //     }
    // }
    field system_status(&executor) -> FieldResult<SystemStatus>
    {
        Ok(executor.context().subsystem().get_system_status()?)
    }

    // Get current status of position information gathering
    //
    // {
    //     lockStatus {
    //         positionStatus: SolutionStatus,
    //           positionType: PosVelType,
    //           time {
    //             ms: Int,
    //               week: Int
    //           },
    //         timeStatus: RefTimeStatus,
    //         velocityStatus: SolutionStatus,
    //           velocityType: PosVelType
    //     }
    // }
    field lock_status(&executor) -> FieldResult<LockStatus>
    {
        Ok(executor.context().subsystem().get_lock_status()?)
    }

    // Get the last known good position information
    //
    // {
    //     lockInfo {
    //        position: Vec<Float>,
    //        time {
    //            ms: Int,
    //            week: Int
    //        },
    //        velocity: Vec<Float>
    //     }
    // }
    field lock_info(&executor) -> FieldResult<LockInfo>
    {
        Ok(executor.context().subsystem().get_lock_info()?)
    }

    // Get current telemetry information for the system
    //
    // {
    //     telemetry{
    //         debug {
    //             components: [{
    //                 bootVersion: String,
    //                 compType: Int,
    //                 compileDate: String,
    //                 compileTime: String,
    //                 hwVersion: String,
    //                 model: String,
    //                 serialNum: String,
    //                 swVersion: String,
    //             }],
    //             numComponents: Int
    //         },
    //         nominal{
    //             lockInfo {...},
    //             lockStatus {...},
    //             systemStatus: {
    //                errors: Vec<String>,
    //                status: Vec<String>
    //             }
    //         }
    //     }
    // }
    field telemetry(&executor) -> FieldResult<Telemetry>
    {
        Ok(executor.context().subsystem().get_telemetry()?)
    }
});

pub struct MutationRoot;

// Base GraphQL mutation model
graphql_object!(MutationRoot: Context as "Mutation" |&self| {
    // Get all errors encountered while processing this GraphQL request
    //
    // Note: This will only return errors thrown by fields which have
    // already been processed, so it is recommended that this field be specified last.
    //
    // mutation {
    //     errors: [String]
    // }
    field errors(&executor) -> FieldResult<Vec<String>>
    {
        executor.context().subsystem().get_errors();

        match executor.context().subsystem().errors.read() {
            Ok(master_vec) => Ok(master_vec.clone()),
            _ => Ok(vec!["Error: Failed to borrow master errors vector".to_owned()])
        }
    }

    // Execute a trivial command against the system
    //
    // mutation {
    //     noop {
    //         errors: String,
    //         success: Boolean
    //    }
    // }
    field noop(&executor) -> FieldResult<GenericResponse>
    {
        let mut last_cmd = executor.context().subsystem().last_cmd.write()?;
        *last_cmd = AckCommand::Noop;
        Ok(executor.context().subsystem().noop()?)
    }

    // Control the power state of the system
    //
    // Note: Power control of the GPS device will be done by the GPSRM service
    //
    // mutation {
    //     controlPower: "Not Implemented"
    // }
    field control_power(&executor) -> FieldResult<String>
    {
        let mut last_cmd = executor.context().subsystem().last_cmd.write()?;
        *last_cmd = AckCommand::ControlPower;
        Ok(String::from("Not Implemented"))
    }

    // Configure the system
    //
    // config: Vector of configuration requests (ConfigStruct)
    //   - option: Configuration operation which should be performed
    //   - hold: For `LOG_*` requests, specifies whether this request should be excluded
    //           from removal by future 'UNLOG_ALL' requests.
    //           For `UNLOG_ALL` requests, specifies whether the 'hold' value in previous
    //           `LOG_*` requests should be ignored.
    //   - interval: Interval at which log messages should be generated.
    //               Note: Only applies to `LOG_POSITION_DATA` requests. Ignored otherwise
    //   - offset: Offset of interval at which log messages should be generated.
    //             Note: Only applies to `LOG_POSITION_DATA` requests. Ignored otherwise
    //
    // mutation {
    //     configureHardware(config: [{option: ConfigOption, hold: Boolean, interval: Float, offset: Float},...]) {
    //         config: String
    //         errors: String,
    //         success: Boolean,
    //     }
    // }
    field configure_hardware(
        &executor,
        config: Vec<ConfigStruct>,
    ) -> FieldResult<ConfigureHardwareResponse>
    {
        let mut last_cmd = executor.context().subsystem().last_cmd.write()?;
        *last_cmd = AckCommand::ConfigureHardware;
        Ok(executor.context().subsystem().configure_hardware(config)?)
    }

    // Run a system self-test
    //
    // test: Type of self-test to perform
    //
    // mutation {
    //     testHardware(test: TestType) {
    //         ... on IntegrationTestResults {
    //             errors: String,
    //             success: Boolean,
    //             telemetryNominal{...},
    //             telemetryDebug{...}
    //         }
    //         ... on HardwareTestResults {
    //             errors: "Not Implemented",
    //             success: true,
    //             data: Empty
    //         }
    //    }
    // }
    field test_hardware(&executor, test: TestType) -> FieldResult<TestResults>
    {
        let mut last_cmd = executor.context().subsystem().last_cmd.write()?;
        *last_cmd = AckCommand::TestHardware;
        match test {
            TestType::Integration => Ok(TestResults::Integration(executor.context().subsystem()
                    .get_test_results().unwrap())),
            TestType::Hardware => Ok(TestResults::Hardware(HardwareTestResults {
                        errors: "Not Implemented".to_owned(), success: true, data: "".to_owned()}))
        }
    }

    // Pass a custom command through to the system
    //
    // command: String containing the hex values to be sent (ex. "C3")
    //          It will be converted to a byte array before transfer.
    //
    // mutation {
    //     issueRawCommand(command: String) {
    //         errors: String,
    //         success: Boolean,
    //         response: String
    //     }
    // }
    field issue_raw_command(&executor, command: String) -> FieldResult<GenericResponse>
    {
        let mut last_cmd = executor.context().subsystem().last_cmd.write()?;
        *last_cmd = AckCommand::IssueRawCommand;
        Ok(executor.context().subsystem().passthrough(command)?)
    }
});