cc-haxe/src/bin/Net.hx
2022-12-19 21:06:23 +01:00

109 lines
2.3 KiB
Haxe

package bin;
import kernel.peripherals.Peripherals.Peripheral;
import kernel.net.Routing;
import haxe.ds.ReadOnlyArray;
import lib.cli.TermHandle;
import lib.cli.CLIBase;
using tink.CoreApi;
class Net extends CLIBase {
private var handle:TermHandle;
public function invoke(handle:TermHandle):Future<Bool> {
this.handle = handle;
var subcommand = handle.args[0];
var subcommand_args = handle.args.slice(1);
switch (subcommand) {
case "route":
return Future.sync(route(subcommand_args));
case "iface":
return Future.sync(iface(subcommand_args));
case "help":
printHelp();
return Future.sync(true);
case "ping":
return ping(subcommand_args);
case "proto":
return Future.sync(protos());
default:
handle.writeLn("Unknown subcommand: " + subcommand);
printHelp();
return Future.sync(false);
}
}
private function printHelp() {
handle.writeLn("net route");
handle.writeLn("net iface");
handle.writeLn("net help");
handle.writeLn("net proto");
}
private function route(args:ReadOnlyArray<String>):Bool {
var routes = Routing.instance.getRouteTable();
for(k => v in routes) {
handle.writeLn('${k} => ${v.interf.name()}(${v.cost})');
}
return true;
}
private function iface(args:ReadOnlyArray<String>):Bool {
var modems = Peripheral.instance.getModems();
for (modem in modems) {
handle.writeLn(modem.name());
}
return true;
}
function ping(args:ReadOnlyArray<String>): Future<Bool> {
return new Future<Bool>(trigger -> {
if (args.length != 1) {
handle.writeLn("Usage: net ping id");
trigger(false);
return null;
}
var toID:Null<Int> = Std.parseInt(args[0]);
if (toID == null) {
handle.writeLn("Invalid ID");
trigger(false);
return null;
}
kernel.net.Net.instance.ping(toID).handle(result -> {
switch (result){
case Success(acc):
if (acc) {
handle.writeLn("Ping succeeded");
trigger(true);
} else {
handle.writeLn("Ping failed");
trigger(false);
}
case Failure(failure):
handle.writeLn("Ping failed: " + failure);
trigger(false);
}
});
});
}
function protos():Bool {
var protos = kernel.net.Net.instance.getActiveProtocols();
for (proto in protos) {
handle.writeLn(proto);
}
return true;
}
}