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
#![deny(missing_docs)] //! A module containing data structures for messages that are used //! in the XIO Web API. #[macro_use] extern crate serde_derive; #[cfg(test)] extern crate serde_json; extern crate indexmap; extern crate uuid; extern crate xio_base_datatypes; extern crate xio_hwdb; extern crate xio_jobset; mod may_be_skipped; pub use may_be_skipped::{MayBeSkipped, MustNotBeSkipped}; use indexmap::{IndexMap, IndexSet}; use std::time::Duration; use uuid::Uuid; use xio_base_datatypes as base; use xio_hwdb as hwdb; use xio_jobset as jobset; /// Get the uuid which defines the XIO web API /// /// This is always `82522deb-24b0-444c-a3c7d269b5dfb67d` pub fn api_uuid() -> Uuid { Uuid::from_bytes([ 0x82, 0x52, 0x2d, 0xeb, 0x24, 0xb0, 0x44, 0x4c, 0xa3, 0xc7, 0xd2, 0x69, 0xb5, 0xdf, 0xb6, 0x7d, ]) } /// An enum representing the version of the API. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "lowercase")] pub enum ApiVersion { /// Version 1. V1, } /// A description of the XIO web API. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] pub struct ApiDescription { /// The version of the API. pub version: ApiVersion, /// A human-readable description of the API. pub description: String, /// The uuid of the API. Must be the uuid that can be retrieved from /// the `api_uuid()` function. pub uuid: Uuid, } impl MustNotBeSkipped for ApiDescription {} impl Default for ApiDescription { fn default() -> ApiDescription { ApiDescription { version: ApiVersion::V1, description: "XIO web API".to_string(), uuid: api_uuid(), } } } /// A message wrapping the response of a XIO Web API request. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case", tag = "code")] pub enum Response<T: Default + MayBeSkipped> { /// A success response, optionally containing data. Ok { /// The data embedded in the response. #[serde( default, skip_serializing_if = "MayBeSkipped::may_be_skipped" )] data: T, }, /// An error response. Error { /// A message describing the error. message: String, }, } impl<T: Default + MayBeSkipped> Response<T> { /// Build a successful response. pub fn ok(data: T) -> Self { Response::Ok { data } } /// Build an error response. pub fn error<E>(error: E) -> Self where E: std::fmt::Display, { Response::Error { message: format!("{}", error), } } } /// The state of a XIO module. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case", tag = "state")] pub enum ModuleState { /// The state of the module is unknown (e.g. has not been requested /// from the device yet). Unknown, /// The module is uninitialized. Uninitialized, /// The module is ready to be started. Ready { /// If true, the module has been assigned to a jobset. /// /// In this state, it can not be controlled by requesting a /// `ModuleAction`, because then the job control takes care of /// switching the module state. assigned_to_jobset: bool, }, /// The module is currently running. Running { /// If true, the module has been assigned to a jobset. /// /// In this state, it can not be controlled by requesting a /// `ModuleAction`, because then the job control takes care of /// switching the module state. assigned_to_jobset: bool, }, /// An error has occurred Error, } /// Actions for controlling module state. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case", tag = "action")] pub enum ModuleAction { /// Initialize a module. /// /// Can only be executed when the module is in `Uninitialized` state. Initialize, /// Start a module. /// /// Can only be executed when the module is in `Ready` state /// while not being assigned to a jobset. Start, /// Stop a module. /// /// Can only be executed when the module is in `Running` state /// while not being assigned to a jobset. Stop, /// Uninitialize a module. /// /// Can only be executed when the module is in `Ready` state /// while not being assigned to a jobset. Uninitialize, } impl Default for ModuleAction { fn default() -> Self { ModuleAction::Initialize } } impl MustNotBeSkipped for ModuleAction {} /// Actions for controlling the job execution. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case", tag = "action")] pub enum JobControlAction { /// Start a job. StartJob { /// The identifier string of the job. /// /// The job must be deployed on the board already in order to be /// started. job: String, }, /// Stop the currently running job. StopJob, } impl Default for JobControlAction { fn default() -> Self { JobControlAction::StartJob { job: "".to_string(), } } } impl MustNotBeSkipped for JobControlAction {} #[cfg(test)] mod job_control_action_tests { use {serde_json, JobControlAction}; #[test] fn serialize_start_job() { let msg = JobControlAction::StartJob { job: "init".to_string(), }; let serialized = serde_json::to_string(&msg).unwrap(); assert_eq!( "{\"action\":\"start_job\",\"job\":\"init\"}", serialized ); } #[test] fn serialize_stop_job() { let msg = JobControlAction::StopJob; let serialized = serde_json::to_string(&msg).unwrap(); assert_eq!("{\"action\":\"stop_job\"}", serialized); } } impl Default for ModuleState { fn default() -> ModuleState { ModuleState::Unknown } } /// The current state of a controller. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case", tag = "code")] pub enum ControllerState { /// The controller is uninitialized. /// /// In this state, the controller can not be used. There is no /// information, why it has not been initialized. The reason may /// for example be that the initialization is ongoing, or that the /// controller has no firmware flashed. Uninitialized, /// The controller firmware is currently being flashed. FlashingFirmware, /// The controller has an unsupported XIO frame format version. UnsupportedFrameFormatVersion { /// The frame format version required by the server. required: u8, /// The frame format version found on the controller. /// /// If the controller has answered to frame format version request, /// the result is stored here. Otherwise it is `None. found: Option<u8>, }, /// The controller has an unsupported XIO commandset version. UnsupportedCommandSetVersion { /// The commandset version required by the server. required: u16, /// The commandset version found on the controller. /// /// If the controller has answered to frame format version request, /// the result is stored here. Otherwise it is `None. found: Option<u16>, }, /// The connection to the controller is stale. Stale, /// The controller is ready for use, but has no jobset deployed. Ready, /// A jobset has been deployed, and no job is running. JobSetDeployed { /// The identifiers of the jobs that have been deployed. deployed_jobs: IndexSet<String>, }, /// A jobset has been deployed, and a job is currently running. JobRunning { /// The identifiers of the jobs that have been deployed. deployed_jobs: IndexSet<String>, /// The identifier of the job that is currently running. /// /// It is one of the identifiers stored in the `deployed_jobs` field. running: String, }, } impl Default for ControllerState { fn default() -> Self { ControllerState::Uninitialized } } #[cfg(test)] mod controller_state_tests { use {serde_json, ControllerState}; #[test] fn serialize_uninitialized() { let msg = ControllerState::Uninitialized; let serialized = serde_json::to_string(&msg).unwrap(); assert_eq!("{\"code\":\"uninitialized\"}", serialized); } #[test] fn serialize_unsupported_frame_format_version() { let msg = ControllerState::UnsupportedFrameFormatVersion { required: 3, found: Some(5), }; let serialized = serde_json::to_string(&msg).unwrap(); assert_eq!( "{\"code\":\"unsupported_frame_format_version\",\ \"required\":3,\"found\":5}", serialized ); } } impl ToString for ControllerState { fn to_string(&self) -> std::string::String { format!("{:?}", self) } } /// Description of the status of a controller. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, Default)] pub struct ControllerStatus { /// The unique uuid of the controller (serial number). pub uuid: Uuid, /// The unique uuid of the model. pub model_uuid: Uuid, /// The model identifier string of the controller. pub model_id: String, /// The commandset version supported by the controller. #[serde(default, skip_serializing_if = "Option::is_none")] pub commandset_version: Option<u16>, /// The frame format version supported by the controller. #[serde(default, skip_serializing_if = "Option::is_none")] pub frame_format_version: Option<u8>, /// The firmware version running on the controller. #[serde(default, skip_serializing_if = "Option::is_none")] pub firmware_version: Option<String>, /// The latest firmware version which can be loaded on the controller. #[serde(default, skip_serializing_if = "Option::is_none")] pub firmware_version_available: Option<String>, /// The manufacturer string. #[serde(default, skip_serializing_if = "Option::is_none")] pub manufacturer: Option<String>, /// The current state of the controller. pub state: ControllerState, /// The currently loaded `jobset::JobSet`. #[serde(default, skip_serializing_if = "Option::is_none")] pub job_set: Option<jobset::JobSet>, /// The module states indexed by their identifier string. pub modules: IndexMap<String, ModuleState>, } /// Progress of a process. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] pub struct Progress { /// The current amount of progress (e.g. the percentage). pub current: u64, /// The overall amount of progress to be made (e.g. 100 for percent). pub overall: u64, } impl MustNotBeSkipped for ControllerStatus {} impl ControllerStatus { /// Create a new controller. pub fn new( uuid: Uuid, model_uuid: Uuid, model_id: String, board_description: &hwdb::HardwareBoardDescription, ) -> Self { let modules = board_description .capabilities .keys() .map(|id| (id.to_string(), ModuleState::default())) .collect::<IndexMap<String, ModuleState>>(); ControllerStatus { uuid, model_uuid, model_id, modules, commandset_version: None, frame_format_version: None, firmware_version: None, firmware_version_available: None, manufacturer: None, job_set: None, state: ControllerState::Uninitialized, } } } /// An enum representating device events. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case", tag = "event")] pub enum DeviceEvent { /// The status of the device has been updated. /// /// This also gets used to indicate that a new device has been added. Updated { /// The new status of the device. status: ControllerStatus, }, /// A device was removed. Removed { /// The uuid of the device. uuid: Uuid, }, } /// An enum representating controller events. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case", tag = "event")] pub enum ControllerEvent { /// The state of a module has changed. ModuleStateChanged { /// The id of the module. module_id: String, /// The new state of the module. state: ModuleState, }, /// The controller state has changed. StateChanged { /// The new state of the controller. state: ControllerState, }, /// The controller flashing process outputs progress information. FlashingProgressMessage { /// The progress message. message: String, /// The progress that was made. progress: Option<Progress>, }, /// The controller flashing process outputs error information. FlashingErrorMessage { /// The error message. message: String, }, /// Flashing has finished. FlashingFinished { /// A flag indicating whether the flashing was successful. success: bool, /// A message describing what happened. message: String, }, } #[cfg(test)] mod controller_event_tests { use {serde_json, ControllerEvent, Progress}; #[test] fn serialize_flashing_information_progress() { let msg = ControllerEvent::FlashingProgressMessage { message: "working".to_string(), progress: Some(Progress { current: 45, overall: 1000, }), }; let serialized = serde_json::to_string(&msg).unwrap(); assert_eq!( "{\"event\":\"flashing_progress_message\",\ \"message\":\"working\",\ \"progress\":{\"current\":45,\"overall\":1000}}", serialized ); } #[test] fn serialize_flashing_information_finished() { let msg = ControllerEvent::FlashingFinished { message: "successfully flashed".to_string(), success: true, }; let serialized = serde_json::to_string(&msg).unwrap(); assert_eq!( "{\"event\":\"flashing_finished\",\"success\":true,\"message\":\"successfully flashed\"}", serialized ); } } /// An enum representing events that can occur during job execution. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case", tag = "e")] pub enum JobEvent { /// Execution of a job has started. Started { /// The job identifier string. job: String, /// A definition of the tags and the field names for each tag. tags: IndexMap<String, Vec<String>>, /// The number of milliseconds since the job started. #[serde(rename = "i")] instant: u64, }, /// A data row was recorded. #[serde(rename = "d")] Data { /// The tag of the data. #[serde(rename = "t")] tag: String, /// The data values. /// /// The values are sorted in the same order as the `tags` field /// by the `JobEvent::Started` variant. #[serde(rename = "v")] values: Vec<base::DataValueDescriptive>, /// The number of milliseconds since the job started. #[serde(rename = "i")] instant: u64, }, /// The job execution has reached a new position. Position { /// The command position index. command: u16, /// The message string of the current position. #[serde( rename = "_message", default, skip_serializing_if = "String::is_empty" )] message: String, /// The description string of the current position. description: String, /// The number of milliseconds since the job started. #[serde(rename = "i")] instant: u64, }, /// The currently running job has stopped. Stopped { /// The details about why the job has stopped. details: JobStoppedReason, /// The number of milliseconds since the job started. #[serde(rename = "i")] instant: u64, }, } impl JobEvent { /// Get the instant of the event (in milliseconds since job start). pub fn instant(&self) -> u64 { use JobEvent::*; match *self { Started { instant, .. } => instant, Data { instant, .. } => instant, Position { instant, .. } => instant, Stopped { instant, .. } => instant, } } /// Get the instant of the event (duration since job start). pub fn instant_duration(&self) -> Duration { Duration::from_millis(self.instant()) } } /// A command or condition position inside a job, with its description string. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] pub struct PositionWithDescription { /// The command position index. pub position: u16, /// The message string. #[serde( rename = "_message", default, skip_serializing_if = "String::is_empty" )] pub message: String, /// The description string. pub description: String, } /// The reasons for a job to be stopped. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case", tag = "reason")] pub enum JobStoppedReason { /// The job has reached the end. Finished, /// The job was stopped due to a user request over the XIO protocol. StoppedByUser, /// An exit criterion matched and therefore the execution was stopped. ExitCriterionMatched { /// The command that was executed while the condition matched. command: PositionWithDescription, /// The condition which matched. condition: PositionWithDescription, }, /// The job execution failed due to some reason. Failed { /// The error code indicating the reason for the failure. error: base::ErrorCode, }, } /// A request for flashing the latest firmware. #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub struct FirmwareFlashRequest {}