-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
757 lines (644 loc) · 32.6 KB
/
main.cpp
File metadata and controls
757 lines (644 loc) · 32.6 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
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
// ItlwmCLI main.cpp
// Copyright 2026 by Calebh101
//
// This file contains the entire source code for ItlwmCLI.
#include <ftxui/dom/elements.hpp>
#include <ftxui/screen/image.hpp>
#include <ftxui/component/component.hpp>
#include <ftxui/component/screen_interactive.hpp>
#include "Api.h"
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <regex>
#include <fmt/format.h>
#include <fstream>
#include "json.hpp"
#include "filesystem.hpp"
#include <mutex>
#include <atomic>
#define VERSION "1.0.0B" // Version of the app.
#define BETA false // If the app is in beta.
#define CONSTANT_REFRESH_INTERVAL 50 // How many milliseconds the UI should wait to refresh (<= 0 to disable). Must be a factor of 1000.
#define RSSI_RECORD_INTERVAL 5 // How many iterations (CONSTANT_REFRESH_INTERVAL) to wait before the RSSI value should be recorded. The actual interval would be (CONSTANT_REFRESH_INTERVAL * RSSI_RECORD_INTERVAL) milliseconds.
#define RSSI_UNAVAILABLE_THRESHOLD -200 // The RSSI that means unavailable/invalid.
#define MAX_RSSI_RECORD_LENGTH 10000 // The max length of the RSSI list. After this, new values added chop off the old values.
#define HEADER_LINES 2 // How many lines the header is.
#define VISIBLE_LOG_LINES 6 // How many lines are used for the command line widget.
#define VISIBLE_NETWORKS 32 // How many networks should be visible.
#define BAR_WIDTH 2 // How wide the bars for the real-time signal graph should be.
#define TAB_MULTIPLIER 4 // How many spaces a tab is in the command line widget.
#define LOG_INDEX_PADDING 5 // How much to pad the log lines' line numbers with spaces
// Make the script aware if it's running in debug mode
#ifdef __DEBUG
#define DEBUG true
#else
#define DEBUG false
#endif
using namespace ftxui;
using namespace ghc::filesystem;
using json = nlohmann::json;
struct itlwm_snapshot {
bool ssid_ok;
bool bssid_ok;
bool state_ok;
bool power_ok;
bool platform_ok;
bool networks_ok;
bool station_ok;
};
auto screen = ScreenInteractive::TerminalOutput();
std::vector<std::string> output; // Logs
std::deque<int16_t> signalRssis; // Signal strengths recorded (for graphs)
int positionAway = 0; // How far we have scrolled up in the command line widget
int logScrolledLeft = 0; // How far we've scrolled right in the command line
std::atomic<bool> running{true}; // If the UI update thread should run
bool showSaveSettingsPrompt = true; // If we should ask to save a settings file (if it doesn't already exist)
std::thread refresher; // The UI update thread
ghc::filesystem::path exec; // Parent directory of the executable
ghc::filesystem::path settingsfile; // The file path containing our settings (potentially)
json settings; // Our global settings
std::mutex mutex; // Mutex for locking
itlwm_snapshot snapshot{}; // Keeping track of the current snapshot
enum rssi_stage {
rssi_stage_excellent,
rssi_stage_good,
rssi_stage_fair,
rssi_stage_poor,
rssi_stage_unavailable,
};
// RSSI is negative, and the closer it is to 0, the better the signal strength
rssi_stage rssiToRssiStage(bool valid, int rssi) {
if (!valid) return rssi_stage_unavailable;
rssi = abs(rssi);
if (rssi <= 0) return rssi_stage_unavailable;
if (rssi <= 50) return rssi_stage_excellent;
if (rssi <= 60) return rssi_stage_good;
if (rssi <= 70) return rssi_stage_fair;
return rssi_stage_poor;
}
std::string rssiStageToString(rssi_stage stage) {
switch (stage) {
case rssi_stage_excellent: return "excellent";
case rssi_stage_good: return "good";
case rssi_stage_fair: return "fair";
case rssi_stage_poor: return "poor";
case rssi_stage_unavailable: return "unavailable";
}
}
Color rssiStageToColor(rssi_stage stage) {
switch (stage) {
case rssi_stage_excellent: return Color::Green;
case rssi_stage_good: return Color::Yellow;
case rssi_stage_fair: return Color::Orange1;
case rssi_stage_poor: return Color::Red;
case rssi_stage_unavailable: return Color::White;
}
}
std::string itlPhyModeToString(bool valid, itl_phy_mode mode) {
if (!valid) return "Mode Unavailable";
switch (mode) {
case ITL80211_MODE_11A: return "IEEE 802.11a";
case ITL80211_MODE_11B: return "IEEE 802.11b";
case ITL80211_MODE_11G: return "IEEE 802.11g";
case ITL80211_MODE_11N: return "IEEE 802.11n";
case ITL80211_MODE_11AC: return "IEEE 802.11ac";
case ITL80211_MODE_11AX: return "IEEE 802.11ax";
default: return "Unknown Mode";
}
}
std::string parse80211State(bool valid, uint32_t state) {
if (!valid) return "Unavailable";
switch (state) {
case ITL80211_S_INIT: return "Idle (Default)";
case ITL80211_S_SCAN: return "Scanning...";
case ITL80211_S_AUTH: return "Authenticating...";
case ITL80211_S_ASSOC: return "Associating...";
case ITL80211_S_RUN: return "Running";
default: return "Unknown";
}
}
// Custom debug function, it just prints to the terminal. We shouldn't use this when the GUI is running.
template <typename... Args>
void debug(const std::string& input, Args&&... args) {
std::cout << "ItlwmCLI: " << fmt::format(input, std::forward<Args>(args)...) << std::endl;
}
// Add to command line widget logs ('output')
void log(std::string input) {
std::lock_guard<std::mutex> lock(mutex);
if (positionAway != 0) positionAway++; // If we're not following the logs, then scroll even farther away from them to stay where we are now
output.push_back(input);
}
// Same thing as the above, but with an indent
void log(int indent, std::string input) {
std::string spaces(indent * TAB_MULTIPLIER, ' ');
return log(fmt::format("{}{}", spaces, input));
}
json loadSettings() {
if (ghc::filesystem::exists(settingsfile)) {
std::ifstream in(settingsfile);
if (in.is_open()) {
std::string content((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
in.close();
try {
return json::parse(content);
} catch (...) {
debug("Failed to read settings file: invalid JSON (ignoring)");
return json();
}
} else {
debug("Failed to read settings file: {}", settingsfile.string());
exit(1);
}
} else {
return json();
}
}
// Helper function so I don't have to duplicate my code
bool _saveSettings(json& settings) {
std::ofstream out(settingsfile);
if (out.is_open()) {
out << settings.dump();
out.close();
return true;
} else {
log(fmt::format("Failed to write to settings file: {}", settingsfile.string()));
return false;
}
}
bool saveSettings(json& settings) {
if (ghc::filesystem::exists(settingsfile)) {
return _saveSettings(settings);
} else {
if (showSaveSettingsPrompt) {
log("Unable to save to settings file; we don't know if you want to. Do note that all settings are stored in plain text (even passwords).");
log(1, "To allow saving to a settings file, run 'settings file allow'. To hide this message ,run 'settings file deny'.");
}
return false;
}
}
std::vector<std::string> parseCommand(const std::string& input) {
std::vector<std::string> args;
std::regex re(R"((\"[^\"]*\"|'[^']*'|\S+))"); // Double-quoted strings, single-quoted strings, non-whitespace strings
auto begin = std::sregex_iterator(input.begin(), input.end(), re); // First match
auto end = std::sregex_iterator(); // Last iteration
for (auto iterator = begin; iterator != end; ++iterator) {
std::string arg = iterator->str();
if ((arg.front() == '"' && arg.back() == '"') || (arg.front() == '\'' && arg.back() == '\'')) arg = arg.substr(1, arg.length() - 2); // Remove quotes
args.push_back(arg);
}
return args;
}
inline void trim(std::string& s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
return !std::isspace(ch);
})); // Remove leading whitespace
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !std::isspace(ch);
}).base(), s.end()); // Remove trailing whitespace
}
template <typename T>
T atOrDefault(std::vector<T>& input, int i, T _default) {
if (i < input.size()) return input[i];
return _default;
}
template <typename T>
std::optional<T> atOrNull(std::vector<T>& input, int i) {
if (i < input.size()) return input[i];
return std::nullopt;
}
void usage(std::string command = "") {
if (command == "settings") {
log("settings Usage:");
log(1, "settings help Print this help message.");
log(1, "settings clear Delete the app's settings file.");
log(1, "settings file [status] Decide if you want to allow saving a settings file or not. If a settings file already exists, this is not necessary. 'status' can be 'allow' or 'deny'.");
} else if (command == "save" || command == "unsave") {
log("save/unsave Usage:");
log(1, "save/unsave help Print this help message.");
log(1, "save/unsave password [SSID] [password] Save a password for a WiFi network, for use later.");
} else if (command.empty()) {
log("Usage:");
log(1, "help [command] Print this help message, or optionally the help message of a different command.");
log(1, "about Show info about ItlwmCLI.");
log(1, "exit/e Peacefully exit my tool.");
log(1, "power [status] Turn WiFi on or off. 'status' can be 'on' or 'off'.");
log(1, "connect [ssid] [password] Connect to a WiFi network.");
log(1, "associate [ssid] [password] Associate a WiFi network, or make it known to itlwm.");
log(1, "disassociate [ssid] Disassociate a WiFi network.");
log(1, "save/unsave [subcommand] Save something for use later, or \"unsave\" (delete) a saved value.");
log(1, "settings [subcommand] Manage settings.");
} else {
log(fmt::format("Invalid command: {}", command));
log(fmt::format("Tip: Not all commands have a dedicated usage page. Run 'help' for a list of all commands!"));
}
}
bool processCommand(std::string input) {
trim(input);
if (input.empty()) return true;
auto command = parseCommand(input); // The full list of arguments
auto action = command[0]; // The thing the user is trying to do, the first argument
if (action == "help") {
usage(atOrDefault(command, 1, std::string("")));
} else if (action == "about") {
log("ItlwmCLI by Calebh101");
log(1, fmt::format("Version: {}", VERSION));
log(1, fmt::format("{} release, {} mode", BETA ? "Beta" : "Stable", DEBUG ? "debug" : "release"));
} else if (action == "exit" || action == "e") { // 'e' is helpful, so the user doesn't think Ctrl-C is the only efficient way to exit
log("Thanks for stopping by!");
log("Tip: itlwm will still be running even after you exit my program.");
screen.PostEvent(Event::Custom);
running = false;
if (refresher.joinable()) refresher.join(); // Wait to exit (so we don't crash)
screen.Exit();
} else if (action == "echo") { // Debug command, solely for command parsing tests; won't be listed to the user
log(fmt::format("Received command of '{}' with {} extra arguments", action, command.size() - 1));
} else if (action == "power") {
if (command.size() >= 2) {
const std::string status = command[1];
int result;
if (status == "on") {
result = power_on();
} else if (status == "off") {
result = power_off();
} else {
log("State must be 'on' or 'off'.");
return true;
}
log(fmt::format("Power turned {} with status {}.", status, result));
} else {
log("Command 'power' needs 1 argument.");
}
} else if (action == "connect") {
if (command.size() >= 2) {
if (!settings.contains("savedPasswords") || !settings["savedPasswords"].is_object()) settings["savedPasswords"] = json::object();
const std::string ssid = command[1];
const std::string pswd = atOrDefault(command, 2, settings["savedPasswords"].value(ssid, "")); // Try to get the 3rd argument, then try to get the saved password, then default to empty
log(fmt::format("Connecting to network '{}' with password '{}'...", ssid, pswd));
connect_network(ssid.c_str(), pswd.c_str());
} else {
log("Command 'connect' needs 1-2 arguments.");
}
} else if (action == "associate") {
if (command.size() >= 2) {
if (!settings.contains("savedPasswords") || !settings["savedPasswords"].is_object()) settings["savedPasswords"] = json::object();
const std::string ssid = command[1];
const std::string pswd = atOrDefault(command, 2, settings["savedPasswords"].value(ssid, "")); // Try to get the 3rd argument, then try to get the saved password, then default to empty
log(fmt::format("Associating network '{}' with password '{}'...", ssid, pswd));
associate_ssid(ssid.c_str(), pswd.c_str());
} else {
log("Command 'associate' needs 1-2 arguments.");
}
} else if (action == "disassociate") {
if (command.size() >= 2) {
const std::string ssid = command[1];
log(fmt::format("Disassociating network '{}'...", ssid));
dis_associate_ssid(ssid.c_str());
} else {
log("Command 'disassociate' needs 1 argument.");
}
} else if (action == "save") {
std::optional<std::string> subcommand = atOrNull(command, 1);
if (subcommand == "help") {
usage("save");
} else if (subcommand == "password") {
std::optional<std::string> ssid = atOrNull(command, 2);
std::optional<std::string> pswd = atOrNull(command, 3);
if (ssid == std::nullopt || pswd == std::nullopt) {
log("Please provide both an SSID and a password.");
return true;
}
{
std::lock_guard<std::mutex> lock(mutex);
settings["savedPasswords"][*ssid] = pswd;
}
bool saved = saveSettings(settings);
log(fmt::format("Saved SSID '{}' with password '{}'!", ssid.value_or("<unknown>"), pswd.value_or("<unknown>")));
} else if (subcommand == std::nullopt) {
log("A subcommand is required. (Run 'save help' for valid subcommands)");
} else {
log(fmt::format("Invalid subcommand: {} (run 'save help' for valid subcommands)", subcommand.value_or("<unknown>")));
}
} else if (action == "unsave") {
std::optional<std::string> subcommand = atOrNull(command, 1);
if (subcommand == "help") {
usage("unsave");
} else if (subcommand == "password") {
std::optional<std::string> ssid = atOrNull(command, 2);
if (ssid == std::nullopt) {
log("Please provide an SSID.");
return true;
}
if (settings["savedPasswords"].contains(ssid.value_or(""))) {
settings["savedPasswords"].erase(ssid.value_or(""));
bool saved = saveSettings(settings);
log(fmt::format("Unsaved SSID '{}'!", ssid.value_or("<unknown>")));
} else {
log("Provided SSID doesn't have a password saved.");
}
} else if (subcommand == std::nullopt) {
log("A subcommand is required. (Run 'unsave help' for valid subcommands)");
} else {
log(fmt::format("Invalid subcommand: {} (run 'unsave help' for valid subcommands)", subcommand.value_or("<unknown>")));
}
} else if (action == "settings") {
std::optional<std::string> subcommand = atOrNull(command, 1);
if (subcommand == "help") {
usage("settings");
} else if (subcommand == "file") {
std::optional<std::string> status = atOrNull(command, 2);
if (status == "allow") {
showSaveSettingsPrompt = false;
_saveSettings(settings);
log("Saved settings!");
} else if (status == "deny") {
showSaveSettingsPrompt = false;
log("Declined to save settings.");
} else {
log("Please input a valid status.");
}
} else if (subcommand == "clear") {
if (ghc::filesystem::exists(settingsfile) && std::remove(ghc::filesystem::absolute(settingsfile).c_str()) == 0) {
log(fmt::format("Settings file at {} removed.", ghc::filesystem::absolute(settingsfile).string()));
} else {
log(fmt::format("Unable to remove settings file at {}. (Does it exist?)", ghc::filesystem::absolute(settingsfile).string()));
}
} else if (subcommand == std::nullopt) {
log("A subcommand is required. (Run 'settings help' for valid subcommands)");
} else {
log(fmt::format("Invalid subcommand: {} (run 'settings help' for valid subcommands)", subcommand.value_or("<unknown>")));
}
} else if (action == "save/unsave") {
log("No silly, I meant either 'save' or 'unsave'");
} else {
return false;
}
return true; // So we don't have to specify return true in each command, it's just caught in overflow
}
// For sorting networks by RSSI
bool compareNetworkStrength(const ioctl_network_info& a, const ioctl_network_info& b) {
return abs(a.rssi) < abs(b.rssi);
}
int main(int argc, char* argv[]) {
#ifndef __APPLE__
debug("This program requires macOS to run."); // No Timmy, this doesn't work on Windows 11
#endif
auto versionTypeString = DEBUG ? (BETA ? "Beta (Debug)" : "Debug") : (BETA ? "Beta" : "Release");
debug("Starting ItlwmCLI version {} {}", VERSION, versionTypeString);
exec = ghc::filesystem::absolute(argv[0]).parent_path();
settingsfile = exec / "ItlwmCLI.settings.json"; // File for settings, obviously
// We finally get to the good stuff
debug("Loading application...");
settings = loadSettings();
// Initialize all of itlwm's blah
network_info_list_t networks{};
platform_info_t platformInfo{};
station_info_t stationInfo{};
char currentSsid[MAX_SSID_LENGTH] = {0};
char currentBssid[32] = {0};
bool currentPowerState = false;
uint32_t current80211State = 0;
unsigned long iteration = 0; // How many times the refresher thread has iterated
signed long pastIteration = -1; // Keeping track of "have we already recorded for this iteration?"
int minRssi = 0; // Minimum RSSI of the graph
int maxRssi = 0; // Maximum RSSI of the graph
std::string input_str; // What the user has inputted in the command line widget
debug("Loading widgets...");
log("Hello! Welcome to ItlwmCLI! Type 'help' for available commands, 'about' for app info.");
InputOption style = InputOption::Default();
style.transform = [](InputState state) {
state.element |= bgcolor(Color::Default); // FTXUI puts a weird white background on input elements
if (state.is_placeholder) state.element |= color(Color::RGB(128, 128, 128));
return state.element;
};
auto input = Input(&input_str, "Type 'help' for available commands. Use up/down, left/right to scroll.", style); // The input provider for the command line widget
auto renderer = Renderer([&] {
std::vector<std::string> localOutput;
std::deque<int16_t> localSignalRssis;
int localPositionAway;
int localLogScrolledLeft;
unsigned long localIteration;
itlwm_snapshot s;
char localSsid[MAX_SSID_LENGTH];
char localBssid[32];
network_info_list_t localNetworks;
platform_info_t localPlatformInfo;
station_info_t localStationInfo;
{
std::lock_guard<std::mutex> lock(mutex);
s = snapshot;
std::strcpy(localSsid, currentSsid);
std::strcpy(localBssid, currentBssid);
localNetworks = networks;
localPlatformInfo = platformInfo;
localStationInfo = stationInfo;
localSignalRssis = signalRssis;
localOutput = output;
localPositionAway = positionAway;
localLogScrolledLeft = logScrolledLeft;
}
Elements output_elements;
Elements networks_elements;
int start = static_cast<int>(localOutput.size()) - VISIBLE_LOG_LINES; // Where should we start rendering command logs?
bool foundConnected = false; // If one of the networks returned from itlwm is the one we're connected to (it doesn't seem to do this in my testing)
int newStart = start - localPositionAway;
if (newStart < 0) newStart = 0;
int toRender = localOutput.size() - localPositionAway;
if (toRender < 0) toRender = 0;
for (size_t i = newStart; i < toRender; ++i) {
std::string index = std::to_string(i + 1);
std::string spaces = "";
while (index.size() + spaces.size() < LOG_INDEX_PADDING) spaces += " "; // Pad so the line numbers line up correctly
output_elements.push_back(text(fmt::format("{}{}. {}", spaces, index, localOutput[i].size() > localLogScrolledLeft ? localOutput[i].substr(localLogScrolledLeft) : "")));
}
while (output_elements.size() < VISIBLE_LOG_LINES) { // Pad with blanks to keep FTXUI consistent
output_elements.insert(output_elements.begin(), text(""));
}
// So uh, s.station_ok is always false in my experience for some reason, so we're using a different method
s.station_ok = localStationInfo.rssi < 0 && localStationInfo.rssi > RSSI_UNAVAILABLE_THRESHOLD;
bool rssi_available = s.station_ok;
// If the WiFi is off, then everything should be off
if (s.power_ok == false || currentPowerState == false) {
s.ssid_ok = false;
s.bssid_ok = false;
s.state_ok = false;
s.platform_ok = false;
s.networks_ok = false;
s.station_ok = false;
rssi_available = false;
}
if (s.state_ok == false || current80211State != ITL80211_S_RUN) rssi_available = false; // If we're not connected, don't record the signal strength
rssi_stage rssiStage = rssiToRssiStage(rssi_available, localStationInfo.rssi);
if (s.networks_ok) {
std::sort(localNetworks.networks, localNetworks.networks + localNetworks.count, compareNetworkStrength); // Sort
int amount = 0;
for (int i = 0; i < localNetworks.count; i++) {
auto network = localNetworks.networks[i];
bool emptySsid = std::all_of(std::begin(network.ssid), std::end(network.ssid), [](unsigned char c) {
return c == 0;
}); // Is the SSID empty? Let's find out!
if (emptySsid) continue; // If it is, then we skip
bool connected = s.ssid_ok ? strcmp(localSsid, reinterpret_cast<char*>(network.ssid)) == 0 : false; // If our current SSID matches the one we're scanning
if (connected) foundConnected = true;
std::string ssid(reinterpret_cast<const char*>(network.ssid), strnlen(reinterpret_cast<const char*>(network.ssid), 32)); // fmt is stingy
networks_elements.push_back(text(fmt::format("{}. {} (RSSI {}) {} {}", amount + 1, ssid, std::to_string(network.rssi), network.rsn_protos == 0 ? "" : "(locked)", s.ssid_ok && connected ? "(connected)" : "")));
amount++;
}
}
while (networks_elements.size() < VISIBLE_NETWORKS) { // If we don't hit how many we want, pad the widget
networks_elements.push_back(text(""));
}
// Setup stuff for the graph
if (localSignalRssis.empty()) {
minRssi = 0;
maxRssi = 0;
} else {
minRssi = *std::min_element(localSignalRssis.begin(), localSignalRssis.end()); // Minimum graph point (based on the entire dataset)
maxRssi = *std::max_element(localSignalRssis.begin(), localSignalRssis.end()); // Maximum graph point (based on the entire dataset)
if (minRssi == maxRssi) maxRssi = minRssi + 1;
}
// Fancy duplication stuff
int lastIndexLength = localOutput.size();
std::stringstream hashtagStream;
hashtagStream << std::setw(LOG_INDEX_PADDING) << std::setfill(' ') << std::string(std::to_string(localOutput.size()).size(), '#');
// Get average RSSI
long long rssiSum = 0;
for (int n : localSignalRssis) rssiSum += abs(n);
int rssiAverage = localSignalRssis.empty() ? 0 : -static_cast<int>(rssiSum / localSignalRssis.size());
auto makeGraph = [rssi_available, minRssi, maxRssi, localSignalRssis](int width, int height) -> std::vector<int> {
std::vector<int> scaled(width, 0);
if (localSignalRssis.empty()) return scaled; // Empty, we don't have data yet
std::deque<int16_t> data(localSignalRssis); // Duplicate the list
int i;
if (data.size() * BAR_WIDTH > width) { // Truncate the copied list
std::deque<int16_t> subvec(data.end() - width / BAR_WIDTH, data.end());
data = subvec;
}
size_t padSize = 0;
if (data.size() < width) padSize = width - data.size() * BAR_WIDTH; // Padding
for (size_t i = 0; i < data.size(); ++i) {
int rssi = data[i];
int y = (rssi - minRssi) * height / (maxRssi - minRssi); // Make it relative
if (rssi <= RSSI_UNAVAILABLE_THRESHOLD) y = 0;
for (size_t j = 0; j < BAR_WIDTH; ++j) { // Make X points, for however wide we want the bars
if (padSize + i * BAR_WIDTH + j < scaled.size()) {
scaled[padSize + i * BAR_WIDTH + j] = y;
}
}
}
return scaled;
};
return vbox({
// Header
vbox({
text(fmt::format("ItlwmCLI {} {} by Calebh101", VERSION, versionTypeString)) | center, // We tell the user if the program is a beta release, a debug binary, or both
text(fmt::format("Powered by itlwm {}", s.platform_ok ? localPlatformInfo.driver_info_str: "Unknown")) | center,
}) | border | size(HEIGHT, EQUAL, HEADER_LINES + 2),
// Body
hbox({
vbox({
// Stats
vbox({
text(fmt::format("{}, {}", s.power_ok ? (currentPowerState ? "On" : "Off") : "Unavailable", parse80211State(s.state_ok, current80211State))),
text(fmt::format("{} @{} (channel {})", itlPhyModeToString(s.station_ok, localStationInfo.op_mode), s.platform_ok ? localPlatformInfo.device_info_str : "??", s.station_ok ? std::to_string(localStationInfo.channel) : "unavailable")),
text(fmt::format("Current SSID: {}", s.ssid_ok ? localSsid : "Unavailable")),
text(fmt::format("RSSI: {} ({}) (average: {})", rssi_available ? std::to_string(localStationInfo.rssi) : "Unavailable", rssiStageToString(rssiStage), std::to_string(rssiAverage))),
}) | border | size(WIDTH, EQUAL, Terminal::Size().dimx / 2) | size(HEIGHT, EQUAL, 6),
// Graph showing signal strengths
vbox({
text("Graph of your RSSI") | center,
hbox({
vbox({
text(std::to_string(maxRssi)),
filler(),
text(std::to_string(static_cast<int>(std::round((minRssi + maxRssi) / 2.0)))), // Midpoint
filler(),
text(std::to_string(minRssi)),
}) | size(WIDTH, EQUAL, 5),
graph(makeGraph),
}) | flex,
}) | border | flex | size(WIDTH, EQUAL, Terminal::Size().dimx / 2),
}),
// Shows what networks have been found
vbox({
networks_elements,
}) | border | size(WIDTH, EQUAL, Terminal::Size().dimx / 2),
}) | flex | size(HEIGHT, EQUAL, Terminal::Size().dimy - VISIBLE_LOG_LINES - HEADER_LINES - 5), // visible log lines, header lines, then 2 for the header border and 3 for the command line border + input
// Command line
vbox({
vbox(output_elements),
hbox({text(fmt::format("{}. > ", hashtagStream.str())), input->Render()}),
}) | border | size(HEIGHT, EQUAL, VISIBLE_LOG_LINES + 3),
});
});
auto interactive = CatchEvent(renderer, [&](Event event) { // Catch events, like keystrokes
if (event == Event::Return) { // User tried to enter a command
std::string input;
{
std::lock_guard<std::mutex> lock(mutex);
trim(input_str);
if (input_str.empty()) return true;
input = input_str;
input_str.clear();
positionAway = 0;
logScrolledLeft = 0;
}
log("> " + input);
screen.PostEvent(Event::Custom); // Update UI
bool valid = processCommand(input);
if (!valid) log("Invalid command: " + input);
return true;
}
if (event == Event::ArrowUp || event == Event::ArrowDown || event == Event::ArrowRight || event == Event::ArrowLeft) {
std::lock_guard<std::mutex> lock(mutex);
int maxScroll = output.size() > VISIBLE_LOG_LINES ? static_cast<int>(output.size() - VISIBLE_LOG_LINES) : 0;
if (event == Event::ArrowUp && positionAway < maxScroll) positionAway++;
else if (event == Event::ArrowDown && positionAway > 0) positionAway--;
else if (event == Event::ArrowRight) logScrolledLeft++;
else if (event == Event::ArrowLeft && logScrolledLeft > 0) logScrolledLeft--;
return true;
}
if (input->OnEvent(event)) return true;
return false;
});
debug("Starting services...");
running = true;
if (CONSTANT_REFRESH_INTERVAL > 0) {
debug("Allowing constant refresh...");
refresher = std::thread([&] {
while (running) {
std::this_thread::sleep_for(std::chrono::milliseconds(CONSTANT_REFRESH_INTERVAL));
{
std::lock_guard<std::mutex> lock(mutex);
iteration++;
std::memset(currentSsid, 0, sizeof(currentSsid));
std::memset(currentBssid, 0, sizeof(currentBssid));
snapshot.ssid_ok = get_network_ssid(currentSsid);
snapshot.bssid_ok = get_network_bssid(currentBssid);
snapshot.state_ok = get_80211_state(¤t80211State);
snapshot.power_ok = get_power_state(¤tPowerState);
snapshot.platform_ok = get_platform_info(&platformInfo);
snapshot.networks_ok = get_network_list(&networks);
snapshot.station_ok = get_station_info(&stationInfo);
if (iteration % RSSI_RECORD_INTERVAL == 0) {
int16_t rssiCopy = 0;
bool available = stationInfo.rssi < 0 && stationInfo.rssi > RSSI_UNAVAILABLE_THRESHOLD && currentPowerState && current80211State == ITL80211_S_RUN;
if (available) {
rssiCopy = stationInfo.rssi;
signalRssis.push_back(rssiCopy);
if (signalRssis.size() > MAX_RSSI_RECORD_LENGTH) signalRssis.pop_front();
}
}
}
screen.PostEvent(Event::Custom);
}
});
}
debug("Starting application...");
screen.Loop(interactive);
running = false;
if (refresher.joinable()) refresher.join();
api_terminate();
return 0;
}