From baae1428bdda10839cd8b8640449d875f081edb1 Mon Sep 17 00:00:00 2001 From: Niklas Kapelle Date: Sat, 13 Apr 2024 12:08:02 +0200 Subject: [PATCH] added exporter service --- src/bin/exporter/Exporter.hx | 67 ++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/bin/exporter/Exporter.hx diff --git a/src/bin/exporter/Exporter.hx b/src/bin/exporter/Exporter.hx new file mode 100644 index 0000000..666dfbe --- /dev/null +++ b/src/bin/exporter/Exporter.hx @@ -0,0 +1,67 @@ +package bin.exporter; + +import kernel.net.Package.GenericPackage; +import kernel.peripherals.exports.RedstoneExport; +import kernel.peripherals.Peripherals.Peripheral; +import kernel.ps.ProcessHandle; +import kernel.ps.IProcess; + +/** + A service to expose local peripherals to the network. +**/ +@:build(macros.Binstore.includeBin("Exporter", ["exporter"])) +class Exporter implements IProcess { + public function new() {} + + public function run(handle:ProcessHandle) { + if (handle.args.length < 2) { + handle.writeLine("Not enough args: "); + handle.close(false); + } + + var addr = handle.args[0]; + var expectedType = handle.args[1]; + + // Check if peripheral is present. Not the case for redstone. + if (expectedType != kernel.peripherals.Redstone.TYPE_NAME && !Peripheral.isPresent(addr)) { + handle.writeLine('Address: $addr not present'); + handle.close(false); + } + + var types = Peripheral.getTypes(addr); + + // Check if the correct type is present. Not the case for redstone. + if (expectedType != kernel.peripherals.Redstone.TYPE_NAME && !types.contains(expectedType)) { + handle.writeLine('Expected type not machted on address: $addr. Wanted $expectedType got $types'); + handle.close(false); + } + + var peri = Peripheral.getFromType(addr, expectedType); + + if (peri == null) { + handle.writeLine('Failed to create peripheral for address: $addr'); + handle.close(false); + } + + var handePackFunc:(GenericPackage) -> Bool = null; + + // Cast to RPC class + // TODO: There must be a smarter way to do this. + switch expectedType { + case kernel.peripherals.Redstone.TYPE_NAME: + handePackFunc = (p) -> { + return RedstoneExport.handlePackage(cast peri, p); + }; + // TODO: More peripherals + } + + handle.writeLine('Listening on export:$addr with type $expectedType'); + + // Listen for packages + kernel.net.Net.registerProto('export:$addr', (p) -> { + if (!handePackFunc(p)) { + handle.writeLine("Failed handle package on export"); + } + }); + } +}