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
//! ## WorldView Module
//!
//! This module defines central data structures and helper functions for managing the
//! global state of the elevator network. It contains the `WorldView` struct, which serves as
//! an information packet about the entire system, including all elevators, their tasks, and
//! hall requests. Additionally, it provides serialization, deserialization, and retrieval
//! utilities for handling worldview data efficiently.
//!
//! ### Key Responsibilities:
//! - **Defining Core Structs**: `WorldView` and `ElevatorContainer` store network-wide
//! and per-elevator state, respectively.
//! - **Handling Directions and States**: The `Dirn` and `ElevatorBehaviour` enums define
//! movement direction and current operational state of elevators.
//! - **Data Serialization and Deserialization**: Utility functions facilitate efficient
//! transmission and storage of worldview data.
//! - **Retrieving Elevator Information**: Functions allow querying and modifying elevator
//! state within the network.
//! - **Master Detection**: Determines whether the current system is the master node.
//!
//! ### Overview of Structs & Enums:
//! - [`Dirn`] – Represents the movement direction of an elevator.
//! - [`ElevatorBehaviour`] – Describes the current state of an elevator.
//! - [`ElevatorContainer`] – Holds information about an individual elevator's state, tasks, and requests.
//! - [`WorldView`] – Contains global network state, including all elevators and hall requests.
//!
//! ### Overview of Functions:
//! - [`serialize`] / [`deserialize`] – Convert worldview data to and from binary format.
//! - [`get_wv`] – Retrieves the latest local worldview.
//! - [`update_wv`] – Updates worldview asynchronously if changes are detected.
//! - [`is_master`] – Checks if the current elevator is the master.
//! - [`extract_elevator_container`] / [`extract_self_elevator_container`] – Retrieve elevator state from worldview.
//! - [`get_index_to_container`] – Finds the index of an elevator container by ID.
//!
//! This module is critical for ensuring a synchronized state across networked elevators.
use crateconfig;
use cratenetwork;
use crateprint;
use bincode;
use ;
use HashMap;
use watch;
/// Struct describing direction an elevator is taking calls in.
/// Struct describing the current behaviour of an elevator
/// Represents the state of an elevator, including tasks, status indicators, and movement.
/// Represents the system's current state (WorldView).
///
/// `WorldView` contains an overview of all elevators in the system,
/// the master elevator's ID, and the call buttons pressed outside the elevators.
/// Serialize any `<T>` to `Vec<u8>` if possible
/// Deserialized `&[u8]` to `<T>` if possible
/// Retrieves the index of an `ElevatorContainer` with the specified `id` in the deserialized `WorldView`.
///
/// This function deserializes the provided `WorldView` data and iterates through the elevator containers
/// to find the one that matches the given `id`. If found, it returns the index of the container; otherwise, it returns `None`.
///
/// ## Parameters
/// - `id`: The ID of the elevator whose index is to be retrieved.
/// - `wv`: A serialized `WorldView` as a `Vec<u8>`.
///
/// ## Returns
/// - `Some(usize)`: The index of the `ElevatorContainer` in the `WorldView` if found.
/// - `None`: If no elevator with the given `id` exists.
/// Fetches a clone of the latest local worldview (wv) from the system.
///
/// This function retrieves the most recent worldview stored in the provided `LocalChannels` object.
/// It returns a cloned vector of bytes representing the current serialized worldview.
///
/// # Parameters
/// - `chs`: The `LocalChannels` object, which contains the latest worldview data in `wv`.
///
/// # Return Value
/// Returns a vector of `u8` containing the cloned serialized worldview.
///
/// # Example
/// ```
/// use elevatorpro::utils::get_wv;
/// use elevatorpro::network::local_network::LocalChannels;
///
/// let local_chs = LocalChannels::new();
/// let _ = local_chs.watches.txs.wv.send(vec![1, 2, 3, 4]);
///
/// let fetched_wv = get_wv(local_chs.clone());
/// assert_eq!(fetched_wv, vec![1, 2, 3, 4]);
/// ```
///
/// **Note:** This function clones the current state of `wv`, so any future changes to `wv` will not affect the returned vector.
/// Asynchronously updates the worldview (wv) in the system.
///
/// This function reads the latest worldview data from a specific channel and updates
/// the given `wv` vector with the new data if it has changed. The function operates asynchronously,
/// allowing it to run concurrently with other tasks without blocking.
///
/// ## Parameters
/// - `chs`: The `LocalChannels` object, which holds the channels used for receiving worldview data.
/// - `wv`: A mutable reference to the `Vec<u8>` that will be updated with the latest worldview data.
///
/// ## Returns
/// - `true` if wv was updated, `false` otherwise.
///
/// ## Example
/// ```
/// # use tokio::runtime::Runtime;
/// use elevatorpro::utils::update_wv;
/// use elevatorpro::network::local_network::LocalChannels;
///
/// let chs = LocalChannels::new();
/// let mut wv = vec![1, 2, 3, 4];
///
/// # let rt = Runtime::new().unwrap();
/// # rt.block_on(async {///
/// chs.watches.txs.wv.send(vec![4, 3, 2, 1]);
/// let result = update_wv(chs.clone(), &mut wv).await;
/// assert_eq!(result, true);
/// assert_eq!(wv, vec![4, 3, 2, 1]);
///
/// let result = update_wv(chs.clone(), &mut wv).await;
/// assert_eq!(result, false);
/// assert_eq!(wv, vec![4, 3, 2, 1]);
/// # });
/// ```
///
/// ## Notes
/// - This function is asynchronous and requires an async runtime, such as Tokio, to execute.
/// - The `LocalChannels` channels allow for thread-safe communication across threads.
pub async
/// Checks if the current system is the master based on the latest worldview data.
///
/// This function compares the system's `SELF_ID` with the value at `MASTER_IDX` in the provided worldview (`wv`).
///
/// ## Returns
/// - `true` if the current system's `SELF_ID` matches the value at `MASTER_IDX` in the worldview.
/// - `false` otherwise.
/// Extracts the elevator container with the specified `id` from the given serialized worldview.
///
/// This function deserializes the provided worldview, filters out elevator containers
/// that do not match the given `id`, and returns the first matching result if available.
///
/// ## Parameters
/// - `wv`: A `Vec<u8>` representing the serialized worldview.
/// - `id`: The elevator ID to search for.
///
/// ## Returns
/// - `Some(ElevatorContainer)` if a container with the given `id` is found.
/// - `None` if no matching elevator container exists in the worldview.
///
/// ## Note
/// If multiple containers have the same `id`, only the first match is returned.
/// Retrieves a clone of the `ElevatorContainer` with `SELF_ID` from the latest worldview.
///
/// This function calls `extract_elevator_container` with `SELF_ID` to fetch the elevator container that matches the
/// current `SELF_ID` from the provided worldview (`wv`). The `SELF_ID` is a static identifier loaded from memory,
/// which represents the current elevator's unique identifier.
///
/// ## Parameters
/// - `wv`: The latest worldview in serialized state.
///
/// ## Returns
/// - A clone of the `ElevatorContainer` associated with `SELF_ID`.
///
/// **Note:** This function internally calls `extract_elevator_container` to retrieve the correct elevator container.