-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
649 lines (569 loc) · 23.2 KB
/
Copy pathmain.rs
File metadata and controls
649 lines (569 loc) · 23.2 KB
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
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: MIT
slint::include_modules!();
mod cashcode;
mod cctalk;
mod config;
mod donation;
mod error;
mod funds;
mod home_assistant;
mod sound;
use cashcode::{BillEvent, CashCode};
use config::Config;
use log::{error, info, warn};
use slint::Model;
use std::sync::mpsc::Sender;
use std::thread;
use std::time::Duration;
pub fn main() {
// Initialize logger
env_logger::Builder::from_default_env()
.filter_level(log::LevelFilter::Info)
.init();
info!("Starting :3");
sound::init();
// Test
for _ in 0..5 {
sound::play_yippee();
}
// Load config
let config = match Config::load() {
Ok(config) => config,
Err(e) => {
error!(
"Failed to load configuration, falling back to defaults: {}",
e
);
Config::default()
}
};
let main_window = MainWindow::new().unwrap();
// Enable fullscreen mode for kiosk deployment
main_window.window().set_fullscreen(true);
virtual_keyboard::init(&main_window);
autocomplete_handler::init(&main_window);
let cashcode_tx = bill_acceptor::init(&main_window, &config);
let cctalk_tx = coin_acceptor::init(&main_window, &config, cashcode_tx.clone());
fund_fetcher::init(&main_window, &config);
donation_handler::init(&main_window, &config, cashcode_tx, cctalk_tx);
home_assistant_handler::init(&main_window, &config);
main_window.run().unwrap();
}
mod bill_acceptor {
use super::*;
use slint::*;
use std::sync::mpsc::channel;
/// Commands to control the CashCode bill acceptor
#[derive(Debug, Clone)]
pub enum CashCodeCommand {
Enable,
Disable,
}
pub fn init(app: &MainWindow, config: &Config) -> Sender<CashCodeCommand> {
let weak = app.as_weak();
// Create a channel for bill events (from CashCode to UI)
let (event_tx, event_rx) = channel::<BillEvent>();
// Create a channel for control commands (from UI to CashCode)
let (cmd_tx, cmd_rx) = channel::<CashCodeCommand>();
// Start CashCode driver in a separate thread
thread::spawn({
let config = config.clone();
move || match init_cashcode(&config, event_tx, cmd_rx) {
Ok(_) => info!("CashCode driver stopped"),
Err(e) => error!("CashCode driver error: {}", e),
}
});
// Set up callbacks for page transitions
let cmd_tx_start = cmd_tx.clone();
app.on_start_accepting_money(move || {
info!("📥 UI: Start accepting money");
if cmd_tx_start.send(CashCodeCommand::Enable).is_err() {
error!("Failed to send enable command to CashCode");
}
});
let cmd_tx_stop = cmd_tx.clone();
app.on_stop_accepting_money(move || {
info!("📤 UI: Stop accepting money");
if cmd_tx_stop.send(CashCodeCommand::Disable).is_err() {
error!("Failed to send disable command to CashCode");
}
});
// Poll for bill events and update UI
let timer = Timer::default();
timer.start(
TimerMode::Repeated,
std::time::Duration::from_millis(100),
move || {
if let Some(window) = weak.upgrade() {
// Process all pending events
while let Ok(event) = event_rx.try_recv() {
match event {
BillEvent::Accepted(nominal) => {
info!("💵 Bill accepted in UI: {} dram", nominal as i32);
let current = window.get_session_amount();
window.set_session_amount(current + nominal as i32);
window.set_last_added_amount(nominal as i32);
}
BillEvent::Rejected(reason) => {
info!("❌ Bill rejected: {}", reason);
}
BillEvent::StackerRemoved => {
error!("⚠️ Stacker removed!");
}
BillEvent::StackerReplaced => {
info!("✅ Stacker replaced");
}
BillEvent::Jam(msg) => {
error!("🚫 Jam: {}", msg);
}
BillEvent::Error(msg) => {
error!("⚠️ Error: {}", msg);
}
}
}
}
},
);
// Keep the timer alive for the lifetime of the application
// Otherwise the timer is dropped, the closure is dropped, and the channel receiver is dropped
std::mem::forget(timer);
cmd_tx
}
}
fn init_cashcode(
config: &Config,
tx: Sender<BillEvent>,
cmd_rx: std::sync::mpsc::Receiver<bill_acceptor::CashCodeCommand>,
) -> Result<(), cashcode::CashCodeError> {
use bill_acceptor::CashCodeCommand;
info!("Initializing CashCode driver...");
let mut cashcode = CashCode::new(&config.cashcode_serial_port, &config.stats_db_path)?;
info!("Resetting bill acceptor...");
cashcode.reset()?;
thread::sleep(Duration::from_secs(5));
info!("Polling for initializing status...");
cashcode.poll()?;
thread::sleep(Duration::from_millis(200));
info!("Polling for disabled status...");
cashcode.poll()?;
thread::sleep(Duration::from_millis(200));
// Keep bill acceptor disabled until UI requests to enable it
info!("Bill acceptor initialized, waiting for enable command...");
info!("Starting polling loop...");
loop {
// Check for enable/disable commands from UI
while let Ok(cmd) = cmd_rx.try_recv() {
match cmd {
CashCodeCommand::Enable => {
info!("📥 Enabling bill acceptor...");
if let Err(e) = cashcode.enable() {
error!("Failed to enable bill acceptor: {}", e);
} else {
info!("✅ Bill acceptor enabled");
}
}
CashCodeCommand::Disable => {
info!("📤 Disabling bill acceptor...");
if let Err(e) = cashcode.disable() {
error!("Failed to disable bill acceptor: {}", e);
} else {
info!("✅ Bill acceptor disabled");
}
}
}
}
match cashcode.poll() {
Ok(Some(event)) => {
// Send event to UI thread
if tx.send(event.clone()).is_err() {
error!("Failed to send event to UI thread");
break;
}
// Also log for debugging
if let BillEvent::Accepted(_nominal) = event
&& let Ok(total) = cashcode.get_total_amount()
{
info!("Total collected in DB: {} dram", total);
}
}
Ok(_none) => {
// No event, continue polling
}
Err(e) => {
error!("poll error: {}", e);
thread::sleep(Duration::from_secs(1));
}
}
thread::sleep(Duration::from_millis(400));
}
Ok(())
}
mod coin_acceptor {
use super::*;
use crate::cctalk::{CoinAcceptorCommand, CoinAcceptorEvent};
use slint::*;
use std::sync::mpsc::channel;
pub fn init(
app: &MainWindow,
config: &Config,
cashcode_tx: Sender<bill_acceptor::CashCodeCommand>,
) -> Sender<CoinAcceptorCommand> {
let weak = app.as_weak();
let (event_tx, event_rx) = channel::<CoinAcceptorEvent>();
let (cmd_tx, cmd_rx) = channel::<CoinAcceptorCommand>();
thread::spawn({
let serial_port = config.cctalk_serial_port.clone();
let coin_overrides = config.cctalk_coin_overrides.clone();
move || cctalk::run(serial_port, event_tx, cmd_rx, coin_overrides)
});
// Override start/stop callbacks to drive both bill and coin acceptors.
let cmd_tx_start = cmd_tx.clone();
let cashcode_tx_start = cashcode_tx.clone();
app.on_start_accepting_money(move || {
info!("📥 UI: Start accepting money (bills + coins)");
if cashcode_tx_start
.send(bill_acceptor::CashCodeCommand::Enable)
.is_err()
{
error!("Failed to send enable command to CashCode");
}
if cmd_tx_start.send(CoinAcceptorCommand::Enable).is_err() {
error!("Failed to send enable command to ccTalk coin acceptor");
}
});
let cmd_tx_stop = cmd_tx.clone();
let cashcode_tx_stop = cashcode_tx;
app.on_stop_accepting_money(move || {
info!("📤 UI: Stop accepting money (bills + coins)");
if cashcode_tx_stop
.send(bill_acceptor::CashCodeCommand::Disable)
.is_err()
{
error!("Failed to send disable command to CashCode");
}
if cmd_tx_stop.send(CoinAcceptorCommand::Disable).is_err() {
error!("Failed to send disable command to ccTalk coin acceptor");
}
});
// Poll for coin events on the slint timer and add to session amount.
let timer = Timer::default();
timer.start(
TimerMode::Repeated,
std::time::Duration::from_millis(100),
move || {
if let Some(window) = weak.upgrade() {
while let Ok(event) = event_rx.try_recv() {
match event {
CoinAcceptorEvent::Accepted(value) => {
info!("🪙 Coin accepted in UI: {} AMD", value);
let current = window.get_session_amount();
window.set_session_amount(current + value);
window.set_last_added_amount(value);
}
CoinAcceptorEvent::Error(msg) => {
error!("⚠️ {}", msg);
}
}
}
}
},
);
std::mem::forget(timer);
cmd_tx
}
}
mod virtual_keyboard {
use super::*;
use slint::platform::Key;
use slint::*;
pub fn init(app: &MainWindow) {
let weak = app.as_weak();
app.global::<VirtualKeyboardHandler>().on_key_pressed({
move |key| {
let window = weak.unwrap();
// Check if the right arrow was pressed - trigger autocomplete
if key == SharedString::from(Key::RightArrow) {
let handler = window.global::<AutocompleteHandler>();
let current = handler.get_trigger_autocomplete_toggle();
handler.set_trigger_autocomplete_toggle(!current);
}
window
.window()
.dispatch_event(slint::platform::WindowEvent::KeyPressed { text: key.clone() });
window
.window()
.dispatch_event(slint::platform::WindowEvent::KeyReleased { text: key });
}
});
}
}
mod autocomplete_handler {
use super::*;
pub fn init(app: &MainWindow) {
app.global::<AutocompleteHandler>()
.on_find_suggestion(|input, suggestions| {
if input.is_empty() {
return slint::SharedString::default();
}
let input_lower = input.to_lowercase();
// Find the first suggestion that starts with the input (case-insensitive)
for suggestion in suggestions.iter() {
let suggestion_lower = suggestion.to_lowercase();
if suggestion_lower.starts_with(&input_lower) && suggestion_lower != input_lower
{
return suggestion;
}
}
slint::SharedString::default()
});
app.global::<AutocompleteHandler>()
.on_get_suggestion_suffix(|typed, suggestion| {
if suggestion.is_empty() || typed.is_empty() {
return slint::SharedString::default();
}
// Get the suffix after the typed text
let typed_len = typed.chars().count();
let suffix: String = suggestion.chars().skip(typed_len).collect();
slint::SharedString::from(suffix)
});
app.global::<AutocompleteHandler>()
.on_is_valid_input(|input, suggestions| {
if input.is_empty() {
return false;
}
let input_lower = input.to_lowercase();
// Check if input exactly matches any suggestion (case-insensitive)
suggestions.iter().any(|s| s.to_lowercase() == input_lower)
});
}
}
mod fund_fetcher {
use super::*;
use crate::funds;
use slint::*;
pub fn init(app: &MainWindow, config: &Config) {
let app_handle = app.clone_strong();
let Some(ref token) = config.token else {
warn!("⚠️ No token loaded, donation functions unavailable");
app_handle.set_available_funds(slint::ModelRc::new(slint::VecModel::<
slint::SharedString,
>::default()));
app_handle
.set_available_fund_ids(slint::ModelRc::new(slint::VecModel::<i32>::default()));
return;
};
let token = token.clone();
let token_usernames = token.clone();
app.on_fetch_funds(move || {
info!("🔍 Fetching funds from API...");
let app = app_handle.clone_strong();
let token = token.clone();
slint::spawn_local(async move {
match funds::fetch_funds(&token).await {
Ok(value) => {
info!("✅ Fetched {} funds", value.len());
// Convert funds to string array for ComboBox
let model_data: Vec<slint::SharedString> = value
.iter()
.map(|fund| {
slint::SharedString::from(std::format!(
"{} (ID: {})",
fund.name,
fund.id
))
})
.collect();
// Also store fund IDs separately for lookup
let fund_ids: Vec<i32> = value.iter().map(|f| f.id).collect();
// Set the properties on MainWindow
app.set_available_funds(slint::ModelRc::new(slint::VecModel::from(
model_data,
)));
app.set_available_fund_ids(slint::ModelRc::new(slint::VecModel::from(
fund_ids,
)));
}
Err(e) => {
error!("❌ Failed to fetch funds: {}", e);
app.set_available_funds(slint::ModelRc::new(slint::VecModel::<
slint::SharedString,
>::default(
)));
app.set_available_fund_ids(slint::ModelRc::new(
slint::VecModel::<i32>::default(),
));
}
}
})
.unwrap();
});
let app_handle = app.clone_strong();
app.on_fetch_usernames(move || {
info!("🔍 Fetching usernames from API...");
let app = app_handle.clone_strong();
let token = token_usernames.clone();
slint::spawn_local(async move {
match donation::fetch_usernames(&token).await {
Ok(value) => {
info!("✅ Fetched {} usernames", value.len());
// Convert usernames to string array for the input autocomplete
let model_data: Vec<slint::SharedString> = value
.iter()
.map(|username| slint::SharedString::from(username.to_string()))
.collect();
// Set the properties on MainWindow
app.set_usernames(slint::ModelRc::new(slint::VecModel::from(model_data)));
}
Err(e) => {
error!("❌ Failed to fetch usernames: {}", e);
app.set_available_funds(slint::ModelRc::new(slint::VecModel::<
slint::SharedString,
>::default(
)));
}
}
})
.unwrap();
});
}
}
mod donation_handler {
use super::*;
pub fn init(
app: &MainWindow,
config: &Config,
cashcode_tx: Sender<bill_acceptor::CashCodeCommand>,
cctalk_tx: Sender<cctalk::CoinAcceptorCommand>,
) {
app.on_done_clicked({
let cashcode_tx = cashcode_tx.clone();
let cctalk_tx = cctalk_tx.clone();
let token = config.token.clone();
move |username, fund_id, amount| {
info!(
"💰 Processing donation: {} AMD from {} to fund {}",
amount, username, fund_id
);
// Stop accepting money immediately
if cashcode_tx
.send(bill_acceptor::CashCodeCommand::Disable)
.is_err()
{
error!("Failed to send disable command to CashCode on done click");
}
if cctalk_tx
.send(cctalk::CoinAcceptorCommand::Disable)
.is_err()
{
error!("Failed to send disable command to ccTalk coin acceptor on done click");
}
if let Some(ref token) = token {
// Send donation asynchronously using slint::spawn_local
let token = token.clone();
let username_str = username.to_string();
slint::spawn_local(async move {
match donation::send_donation(&token, fund_id, &username_str, amount).await
{
Ok(_) => {
sound::play_yippee();
info!("✅ Donation sent successfully!");
}
Err(e) => error!("❌ Failed to send donation: {}", e),
}
})
.unwrap();
} else {
warn!("⚠️ No token loaded, donation not sent to server");
}
}
});
// Drive confetti animation from Rust with a two-step approach:
// 1. show-confetti is already set to true by the Slint side (overlay is created)
// 2. After a brief delay, set confetti-falling = true (triggers the animations)
// 3. After animation completes, reset both properties
let weak = app.as_weak();
app.on_confetti_started(move || {
crate::sound::play_yippee();
// Step 1: trigger falling after a short delay so the component is fully rendered
let weak_fall = weak.clone();
slint::Timer::single_shot(std::time::Duration::from_millis(50), move || {
if let Some(window) = weak_fall.upgrade() {
window.set_confetti_falling(true);
}
});
// Step 2: dismiss everything after animations complete
let weak_dismiss = weak.clone();
slint::Timer::single_shot(std::time::Duration::from_millis(2500), move || {
if let Some(window) = weak_dismiss.upgrade() {
window.set_confetti_falling(false);
window.set_show_confetti(false);
}
});
});
// Warmup: run the animation once at startup (no sound) so all SVGs are
// rasterized and cached before the first real donation triggers it.
let weak_warmup = app.as_weak();
slint::Timer::single_shot(std::time::Duration::from_millis(500), move || {
if let Some(window) = weak_warmup.upgrade() {
info!("🎉 Warming up confetti cache...");
window.set_show_confetti(true);
window.set_confetti_falling(true);
let weak_done = weak_warmup.clone();
slint::Timer::single_shot(std::time::Duration::from_millis(1000), move || {
if let Some(window) = weak_done.upgrade() {
window.set_confetti_falling(false);
window.set_show_confetti(false);
}
});
}
});
}
}
mod home_assistant_handler {
use super::*;
use crate::home_assistant::ChromiumManager;
use std::sync::Arc;
pub fn init(app: &MainWindow, config: &Config) {
let chromium = Arc::new(ChromiumManager::new());
info!(
"Home Assistant URL configured: {}",
config.home_assistant_url
);
// Launch Chromium when showing Home Assistant page
let chromium_show = chromium.clone();
let url_for_launch = config.home_assistant_url.clone();
app.on_show_home_assistant(move || {
info!("Showing Home Assistant page, launching Chromium");
if let Err(e) = chromium_show.launch(&url_for_launch) {
error!("Failed to launch Chromium: {}", e);
}
});
// Close Chromium when hiding Home Assistant page
let chromium_hide = chromium.clone();
app.on_hide_home_assistant(move || {
info!("Hiding Home Assistant page, closing Chromium");
chromium_hide.close();
});
// HTTP listener so HASS can POST /close-hass to dismiss its own page
let (tx, rx) = std::sync::mpsc::channel::<()>();
let port = config.hass_api_port;
thread::spawn(move || {
home_assistant::start_close_listener(port, tx);
});
let weak = app.as_weak();
let timer = slint::Timer::default();
timer.start(
slint::TimerMode::Repeated,
std::time::Duration::from_millis(200),
move || {
if rx.try_recv().is_ok()
&& let Some(window) = weak.upgrade()
{
window.invoke_close_hass_remote();
}
},
);
std::mem::forget(timer);
}
}