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
mod comms;
use clap::{Parser, Subcommand};
use comms::{BlotPacket, PacketState};
use confy;
use crossterm::{
event::{self, DisableMouseCapture, Event as CEvent, KeyCode, KeyModifiers},
execute,
terminal::{disable_raw_mode, enable_raw_mode, LeaveAlternateScreen},
};
use futures::{task::noop_waker_ref, FutureExt};
use inquire::{self, Confirm, Select};
use ringbuffer::{AllocRingBuffer, RingBuffer};
use serde::{Deserialize, Serialize};
use serialport::{self, SerialPortType};
use std::{
future::Future,
io::{self, Stdout},
panic,
pin::Pin,
process,
sync::{mpsc, Arc},
task::{Context, Poll},
thread,
time::{Duration, Instant},
};
use tokio::{self, sync::Mutex};
use tui::{
backend::CrosstermBackend,
layout::{Alignment, Constraint, Direction, Layout},
style::{Color, Modifier, Style},
text::{Span, Spans},
widgets::{Block, BorderType, Borders, Paragraph, Tabs},
Terminal,
};
use uuid::Uuid;
#[derive(Serialize, Deserialize)]
struct BlotConfig {
port: Option<String>,
interactive: InteractiveConfig,
}
#[derive(Serialize, Deserialize)]
struct InteractiveConfig {
step: f32,
}
impl ::std::default::Default for BlotConfig {
fn default() -> Self {
Self {
port: None,
interactive: InteractiveConfig { step: 5_f32 },
}
}
}
/// CLI for the Hack Club Blot
#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
#[arg(short, long)]
port: Option<String>,
}
#[derive(Subcommand)]
enum Commands {
/// Move the pen to the specified coordinates
Go {
/// X coordinate
x: f32,
/// Y coordinate
y: f32,
},
/// Manage the Blot's stepper motors
Motors {
#[command(subcommand)]
cmd: MotorsSubcommands,
},
/// Manage the Blot's origin
Origin {
#[command(subcommand)]
cmd: OriginSubcommands,
},
/// Manage the Blot's pen
Pen {
#[command(subcommand)]
cmd: PenSubcommands,
},
/// Enter interactive mode
Interactive,
}
#[derive(Subcommand)]
enum OriginSubcommands {
/// Moves the pen towards the stored origin
Move,
/// Stores the current pen location as the Blot's origin
Set,
}
#[derive(Subcommand)]
enum MotorsSubcommands {
/// Turn the stepper motors on
On,
/// Turn the stepper motors off
Off,
}
#[derive(Subcommand)]
enum PenSubcommands {
/// Move the pen up
Up,
/// Move the pen down
Down,
}
enum Event<I> {
Input(I),
Tick,
}
#[derive(PartialEq)]
enum InteractiveDestination {
Coordinates(InteractiveCoordinates),
Direction(InteractiveDirection),
}
#[derive(PartialEq)]
struct InteractiveCoordinates {
x: f32,
y: f32,
}
#[derive(PartialEq)]
enum InteractiveDirection {
Forward,
Back,
Left,
Right,
}
#[derive(PartialEq)]
enum InteractivePosStatus {
Initializing,
Moving(InteractiveDestination),
Stopped,
}
enum InteractivePenStatus {
Up,
Down,
}
#[derive(PartialEq)]
enum InteractiveEditStatus {
StepSize,
GoCoordinates,
None,
}
#[tokio::main]
async fn main() {
let cli = Cli::parse();
let cfg: Result<BlotConfig, confy::ConfyError> = confy::load("blot-cli", "blot");
let cfg_port = match cfg {
Ok(config) => config.port,
Err(_) => None,
};
let port = match cfg_port {
Some(p) => p,
None => match cli.port {
Some(p) => p,
None => {
let ports = serialport::available_ports().unwrap_or(vec![]);
let filtered = ports
.iter()
.filter(|p| match p.port_type {
SerialPortType::UsbPort(_) => true,
_ => false,
})
.collect::<Vec<_>>();
if filtered.len() == 0 {
println!("No USB serial ports available on system. Make sure the Blot is powered on and plugged in via USB.");
process::exit(1);
}
let options = filtered
.iter()
.map(|p| p.port_name.clone())
.collect::<Vec<_>>();
let ans = Select::new("Choose a serial port", options).prompt();
match ans {
Ok(choice) => {
let path = confy::get_configuration_file_path("blot-cli", "blot");
let config_path = match path {
Ok(p) => {
let path_str = p.clone();
path_str.to_str().unwrap_or("the config file").to_string()
}
Err(_) => "the config file".to_string(),
};
let ans = Confirm::new(&format!(
"Would you like to save this port in {config_path}?"
))
.with_default(true)
.prompt();
match ans {
Ok(save) => {
if save {
let current_cfg: BlotConfig =
confy::load("blot-cli", "blot").unwrap_or_default();
let save_result = confy::store(
"blot-cli",
"blot",
BlotConfig {
port: Some(choice.clone()),
interactive: current_cfg.interactive,
},
);
if save_result.is_err() {
println!(
"Unable to save config: {}",
save_result.unwrap_err()
);
}
};
}
Err(_) => (),
}
choice
}
Err(_) => {
println!("Could not determine port to use");
process::exit(1);
}
}
}
},
};
let packet_queue = Arc::new(Mutex::new(AllocRingBuffer::new(10)));
let comms_thread = tokio::spawn(comms::initialize(port, packet_queue.clone()));
// Exit main thread if comms thread panics
let orig_hook = panic::take_hook();
panic::set_hook(Box::new(move |panic_info| {
orig_hook(panic_info);
process::exit(1);
}));
match &cli.command {
Commands::Go { x, y } => {
println!("Going to: ({}, {})", x, y);
send_command(
packet_queue,
"go",
[x.to_le_bytes(), y.to_le_bytes()].concat(),
)
.await;
}
Commands::Motors { cmd } => match cmd {
MotorsSubcommands::On => {
println!("Turning stepper motors on");
send_command(packet_queue.clone(), "motorsOn", vec![]).await;
send_command(packet_queue.clone(), "motorsOn", vec![]).await;
send_command(packet_queue.clone(), "motorsOn", vec![]).await;
send_command(packet_queue.clone(), "motorsOn", vec![]).await;
send_command(packet_queue.clone(), "motorsOn", vec![]).await;
send_command(packet_queue.clone(), "motorsOn", vec![]).await;
send_command(packet_queue.clone(), "motorsOn", vec![]).await;
send_command(packet_queue.clone(), "motorsOn", vec![]).await;
send_command(packet_queue.clone(), "motorsOn", vec![]).await;
send_command(packet_queue.clone(), "motorsOn", vec![]).await;
}
MotorsSubcommands::Off => {
println!("Turning stepper motors off");
send_command(packet_queue, "motorsOff", vec![]).await;
}
},
Commands::Origin { cmd } => match cmd {
OriginSubcommands::Move => {
println!("Moving towards origin");
send_command(packet_queue, "moveTowardsOrigin", vec![]).await;
}
OriginSubcommands::Set => {
println!("Setting origin");
send_command(packet_queue, "setOrigin", vec![]).await;
}
},
Commands::Pen { cmd } => match cmd {
PenSubcommands::Up => {
println!("Moving pen up");
send_command(packet_queue, "servo", 1000_u32.to_le_bytes().to_vec()).await;
}
PenSubcommands::Down => {
println!("Moving pen down");
send_command(packet_queue, "servo", 1700_u32.to_le_bytes().to_vec()).await;
}
},
Commands::Interactive => {
let orig_hook = panic::take_hook();
panic::set_hook(Box::new(move |panic_info| {
let stdout = io::stdout();
let backend = CrosstermBackend::new(stdout);
let terminal = Terminal::new(backend).expect("Failed to initialize tui backend");
restore_terminal(terminal);
orig_hook(panic_info);
}));
let (tx, rx) = mpsc::channel();
let tick_rate = Duration::from_millis(200);
thread::spawn(move || {
let mut last_tick = Instant::now();
loop {
let timeout = tick_rate
.checked_sub(last_tick.elapsed())
.unwrap_or_else(|| Duration::from_secs(0));
if event::poll(timeout).expect("poll works") {
if let CEvent::Key(key) = event::read().expect("can read events") {
tx.send(Event::Input(key)).expect("can send events");
}
}
if last_tick.elapsed() >= tick_rate {
if let Ok(_) = tx.send(Event::Tick) {
last_tick = Instant::now();
}
}
}
});
let stdout = io::stdout();
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend).expect("Failed to initialize tui backend");
terminal.clear().expect("Failed to clear terminal");
enable_raw_mode().expect("failed to enable raw mode");
let menu_titles = vec![
"Go",
"Forward",
"Back",
"Left",
"Right",
"Up",
"Pen down",
"Change Step",
"Quit",
];
let mut interactive_pos_status = InteractivePosStatus::Initializing;
let mut interactive_pen_status = InteractivePenStatus::Up;
let mut interactive_coordinates = InteractiveCoordinates { x: 0.0, y: 0.0 };
let mut interactive_edit_status = InteractiveEditStatus::None;
let mut edit_text = "".to_string();
let current_cfg: BlotConfig = confy::load("blot-cli", "blot").unwrap_or_default();
let mut step_size = current_cfg.interactive.step;
let mut pending_futures: Vec<Pin<Box<dyn Future<Output = BlotPacket>>>> = vec![];
let mut ctx = Context::from_waker(noop_waker_ref());
loop {
pending_futures = pending_futures
.into_iter()
.filter_map(|mut future| {
let res = (&mut future).poll_unpin(&mut ctx);
match res {
Poll::Ready(p) => match p.msg.as_str() {
"go" => {
interactive_pos_status = InteractivePosStatus::Stopped;
interactive_coordinates = InteractiveCoordinates {
x: f32::from_le_bytes(p.payload[0..4].try_into().unwrap()),
y: f32::from_le_bytes(p.payload[4..8].try_into().unwrap()),
};
None
}
"servo" => {
let servo_position =
u32::from_le_bytes(p.payload[0..4].try_into().unwrap());
interactive_pen_status = if servo_position == 1700 {
InteractivePenStatus::Down
} else {
InteractivePenStatus::Up
};
None
}
_ => None,
},
Poll::Pending => Some(future),
}
})
.collect();
terminal
.draw(|f| {
let main_chunks = Layout::default()
.direction(Direction::Vertical)
.margin(2)
.constraints(
[
Constraint::Length(3),
Constraint::Length(4),
Constraint::Min(2),
Constraint::Length(3),
]
.as_ref(),
)
.split(f.size());
let status_chunks = Layout::default()
.direction(Direction::Horizontal)
.margin(0)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
.split(main_chunks[1]);
let info =
Paragraph::new("Blot CLI - made by Samuel Fernandez (@polypixeldev)")
.style(Style::default().fg(Color::LightCyan))
.alignment(Alignment::Center)
.block(
Block::default()
.borders(Borders::ALL)
.style(Style::default().fg(Color::White))
.border_type(BorderType::Plain),
);
let menu: Vec<_> = menu_titles
.iter()
.map(|t| {
let (first, rest) = t.split_at(1);
Spans::from(vec![
Span::styled(
first,
Style::default()
.fg(Color::Yellow)
.add_modifier(Modifier::UNDERLINED),
),
Span::styled(rest, Style::default().fg(Color::White)),
])
})
.collect();
let tabs = Tabs::new(menu)
.block(Block::default().title("Controls").borders(Borders::ALL))
.style(Style::default().fg(Color::White))
.highlight_style(Style::default().fg(Color::Yellow))
.divider(Span::raw("|"));
let pos_text = match &interactive_pos_status {
InteractivePosStatus::Initializing => {
"Initializating Blot interactive mode"
}
InteractivePosStatus::Moving(destination) => {
let destination_text = match &destination {
InteractiveDestination::Direction(dir) => match &dir {
InteractiveDirection::Forward => "forwards",
InteractiveDirection::Back => "backwards",
InteractiveDirection::Left => "left",
InteractiveDirection::Right => "right",
},
InteractiveDestination::Coordinates(coordinates) => {
&format!("to ({}, {})", coordinates.x, coordinates.y)
}
};
&format!("Blot is moving {destination_text}")
}
InteractivePosStatus::Stopped => &format!(
"Blot is stopped at ({}, {})",
interactive_coordinates.x, interactive_coordinates.y
),
};
let pen_text = match &interactive_pen_status {
InteractivePenStatus::Down => "Pen is DOWN",
InteractivePenStatus::Up => "Pen is UP",
};
let status_text = format!("{pos_text}\n{pen_text}");
let blot_status = Paragraph::new(status_text)
.style(Style::default().fg(Color::LightGreen))
.alignment(Alignment::Left)
.block(
Block::default()
.borders(Borders::all().difference(Borders::RIGHT))
.style(Style::default().fg(Color::White))
.title("Status")
.border_type(BorderType::Plain),
);
let edit_type_text = match &interactive_edit_status {
InteractiveEditStatus::GoCoordinates => "Coordinates (x,y): ",
InteractiveEditStatus::StepSize => "Step size: ",
InteractiveEditStatus::None => "",
};
let edit_text = format!("{edit_type_text}{edit_text}");
let input_box = Paragraph::new(edit_text)
.style(Style::default().fg(Color::Yellow))
.alignment(Alignment::Right)
.block(
Block::default()
.borders(Borders::all().difference(Borders::LEFT))
.style(Style::default().fg(Color::White))
.border_type(BorderType::Plain),
);
f.render_widget(info, main_chunks[0]);
f.render_widget(blot_status, status_chunks[0]);
f.render_widget(input_box, status_chunks[1]);
f.render_widget(tabs, main_chunks[3]);
})
.expect("Failed to draw tui");
if interactive_pos_status == InteractivePosStatus::Initializing {
send_command(
packet_queue.clone(),
"servo",
1000_u32.to_le_bytes().to_vec(),
)
.await;
send_command(packet_queue.clone(), "motorsOn", vec![]).await;
send_command(packet_queue.clone(), "go", vec![0, 0, 0, 0, 0, 0, 0, 0]).await;
interactive_pos_status = InteractivePosStatus::Stopped;
}
if interactive_edit_status != InteractiveEditStatus::None {
match rx.recv() {
Ok(Event::Input(event)) => {
match event.code {
KeyCode::Char('c') => {
if event.modifiers.contains(KeyModifiers::CONTROL) {
restore_terminal(terminal);
break;
}
}
KeyCode::Char(c) => {
let num_parse = c.to_string().parse::<f32>();
if num_parse.is_err() && c != '.' && c != ',' {
continue;
}
let new_edit_text = format!("{edit_text}{c}");
edit_text = new_edit_text;
}
KeyCode::Backspace | KeyCode::Delete => {
edit_text = edit_text[0..(edit_text.len() - 1)].to_string();
}
KeyCode::Enter => {
match &interactive_edit_status {
InteractiveEditStatus::GoCoordinates => {
let split = edit_text.split(",").collect::<Vec<_>>();
let x_parse = split[0].trim().parse::<f32>();
let y_parse = split[1].trim().parse::<f32>();
if x_parse.is_err() | y_parse.is_err() {
continue;
}
let mut new_x = x_parse.unwrap();
let mut new_y = y_parse.unwrap();
if new_y < 0.0 {
new_y = 0.0;
}
if new_y > 125.0 {
new_y = 125.0;
}
if new_x < 0.0 {
new_x = 0.0;
}
if new_x > 125.0 {
new_x = 125.0;
}
let command_future = send_command(
packet_queue.clone(),
"go",
[new_x.to_le_bytes(), new_y.to_le_bytes()].concat(),
);
interactive_pos_status = InteractivePosStatus::Moving(
InteractiveDestination::Coordinates(
InteractiveCoordinates { x: new_x, y: new_y },
),
);
pending_futures.push(Box::pin(command_future));
}
InteractiveEditStatus::StepSize => {
let step_parse = edit_text.trim().parse::<f32>();
if step_parse.is_err() {
continue;
}
let new_step_size = step_parse.unwrap();
if (new_step_size <= 0.0) | (new_step_size >= 125.0) {
continue;
}
step_size = new_step_size;
let current_cfg: BlotConfig =
confy::load("blot-cli", "blot").unwrap_or_default();
let _ = confy::store(
"blot-cli",
"blot",
BlotConfig {
port: current_cfg.port,
interactive: InteractiveConfig {
step: step_size,
},
},
);
}
_ => {}
}
interactive_edit_status = InteractiveEditStatus::None;
edit_text = "".to_string();
}
_ => {}
};
}
Ok(Event::Tick) => {}
Err(_) => {}
}
} else {
match rx.recv() {
Ok(Event::Input(event)) => match event.code {
KeyCode::Char('q') => {
restore_terminal(terminal);
break;
}
KeyCode::Char('g') => {
interactive_edit_status = InteractiveEditStatus::GoCoordinates;
}
KeyCode::Char('c') => {
if event.modifiers.contains(KeyModifiers::CONTROL) {
restore_terminal(terminal);
break;
}
interactive_edit_status = InteractiveEditStatus::StepSize;
}
KeyCode::Char('f') | KeyCode::Char('w') => {
let mut new_y = interactive_coordinates.y + step_size;
if new_y < 0.0 {
new_y = 0.0;
}
if new_y > 125.0 {
new_y = 125.0;
}
let command_future = send_command(
packet_queue.clone(),
"go",
[interactive_coordinates.x.to_le_bytes(), new_y.to_le_bytes()]
.concat(),
);
interactive_pos_status = InteractivePosStatus::Moving(
InteractiveDestination::Direction(
InteractiveDirection::Forward,
),
);
pending_futures.push(Box::pin(command_future));
}
KeyCode::Char('a') | KeyCode::Char('l') => {
let mut new_x = interactive_coordinates.x - step_size;
if new_x < 0.0 {
new_x = 0.0;
}
if new_x > 125.0 {
new_x = 125.0;
}
let command_future = send_command(
packet_queue.clone(),
"go",
[new_x.to_le_bytes(), interactive_coordinates.y.to_le_bytes()]
.concat(),
);
interactive_pos_status = InteractivePosStatus::Moving(
InteractiveDestination::Direction(InteractiveDirection::Left),
);
pending_futures.push(Box::pin(command_future));
}
KeyCode::Char('b') | KeyCode::Char('s') => {
let mut new_y = interactive_coordinates.y - step_size;
if new_y < 0.0 {
new_y = 0.0;
}
if new_y > 125.0 {
new_y = 125.0;
}
let command_future = send_command(
packet_queue.clone(),
"go",
[interactive_coordinates.x.to_le_bytes(), new_y.to_le_bytes()]
.concat(),
);
interactive_pos_status = InteractivePosStatus::Moving(
InteractiveDestination::Direction(InteractiveDirection::Back),
);
pending_futures.push(Box::pin(command_future));
}
KeyCode::Char('r') | KeyCode::Char('d') => {
let mut new_x = interactive_coordinates.x + step_size;
if new_x < 0.0 {
new_x = 0.0;
}
if new_x > 125.0 {
new_x = 125.0;
}
let command_future = send_command(
packet_queue.clone(),
"go",
[new_x.to_le_bytes(), interactive_coordinates.y.to_le_bytes()]
.concat(),
);
interactive_pos_status = InteractivePosStatus::Moving(
InteractiveDestination::Direction(InteractiveDirection::Right),
);
pending_futures.push(Box::pin(command_future));
}
KeyCode::Char('u') | KeyCode::Up => {
let command_future = send_command(
packet_queue.clone(),
"servo",
1000_u32.to_le_bytes().to_vec(),
);
interactive_pen_status = InteractivePenStatus::Up;
pending_futures.push(Box::pin(command_future));
}
KeyCode::Char('p') | KeyCode::Down => {
let command_future = send_command(
packet_queue.clone(),
"servo",
1700_u32.to_le_bytes().to_vec(),
);
interactive_pen_status = InteractivePenStatus::Down;
pending_futures.push(Box::pin(command_future));
}
_ => {}
},
Ok(Event::Tick) => {}
Err(_) => {}
}
}
}
}
}
comms_thread.abort();
}
fn restore_terminal(mut terminal: Terminal<CrosstermBackend<Stdout>>) {
disable_raw_mode().expect("Failed to restore terminal");
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)
.expect("Failed to restore terminal");
terminal.clear().expect("Failed to clear terminal");
terminal.show_cursor().expect("Failed to restore terminal");
}
async fn send_command(
packet_queue: Arc<Mutex<AllocRingBuffer<BlotPacket>>>,
msg: &str,
payload: Vec<u8>,
) -> BlotPacket {
let mut packets = packet_queue.lock().await;
let id = Uuid::new_v4();
let packet = BlotPacket {
id,
msg: msg.to_string(),
payload,
index: None,
state: comms::PacketState::Queued,
};
packets.push(packet.clone());
// Drop mutex so comms thread can gain a lock
std::mem::drop(packets);
wait_for_ack(packet_queue, id).await;
packet
}
async fn wait_for_ack(packet_queue: Arc<Mutex<AllocRingBuffer<BlotPacket>>>, id: Uuid) {
loop {
let packets = packet_queue.lock().await;
let packet_result = packets.iter().find(|p| p.id == id);
if let Some(packet) = packet_result {
if packet.state == PacketState::Resolved {
break;
}
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
}