first commit

This commit is contained in:
jhartworks committed 2026-10-08 10:20:30 +02:00
commit b31e9a7261
38 files changed
+3822

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
[
{
"pname": "Microsoft.Data.Sqlite",
"version": "8.0.31",
"hash": "sha256-8j8RPB1byBT5Whk7PnbCuHDQAmQqkEEH7BsfyILFGqg="
},
{
"pname": "Microsoft.Data.Sqlite.Core",
"version": "8.0.31",
"hash": "sha256-roWfZVlyU6ykSNgscencfYtL9+gTwlIBbHJAv3fGYcE="
},
{
"pname": "MQTTnet",
"version": "5.2.0.1603",
"hash": "sha256-w5T7ekYwVGg+Zs8uolvcWFyY+r9duni0qIigxgHgIdw="
},
{
"pname": "SQLitePCLRaw.bundle_e_sqlite3",
"version": "2.1.12",
"hash": "sha256-qaBua1oxP27zZ1+RmX0BKt7/6KqeH/1p7Uak5oWwVOE="
},
{
"pname": "SQLitePCLRaw.core",
"version": "2.1.12",
"hash": "sha256-rwaQQTj/ptyVpZkTPWTSVHFtb6zHVDprO5EHk9rp3KU="
},
{
"pname": "SQLitePCLRaw.lib.e_sqlite3",
"version": "2.1.12",
"hash": "sha256-SiLAL/z0iXkpA88mPe+fzidzlxaIP5ZfC17v8WN0MKw="
},
{
"pname": "SQLitePCLRaw.provider.e_sqlite3",
"version": "2.1.12",
"hash": "sha256-3ysycZkuXXGRhsRnHjz0+GWAl8FUy81BSUq1lMWZdZU="
},
{
"pname": "System.Memory",
"version": "4.5.3",
"hash": "sha256-Cvl7RbRbRu9qKzeRBWjavUkseT2jhZBUWV1SPipUWFk="
}
]
+25
View File
@@ -0,0 +1,25 @@
{ ... }:
{
imports = [
(builtins.getFlake "path:/etc/nixos/seiugw").nixosModules.default
];
services.seiugw = {
enable = true;
bacnet.interface = "ens18"; # Set this to the VM's BACnet/IP interface.
bacnet.deviceInstance = 23;
bacnet.ipPort = 47808;
webPort = 8088;
openFirewall = true;
trends = {
enable = true;
databaseName = "wago";
};
komari = {
enable = true;
endpoint = "https://komari.cloud.se-inno.de";
# Do not put the enrollment token into this Nix file or Git. See README.
};
};
}
+41
View File
@@ -0,0 +1,41 @@
-- Empty initial schema for the legacy SE-LTD data format.
-- Existing systems expect isp01…isp20 with datum, userlevel and Wert1…Wert200.
DELIMITER //
CREATE PROCEDURE create_legacy_isp_tables()
BEGIN
DECLARE table_index INT DEFAULT 1;
DECLARE value_index INT DEFAULT 1;
DECLARE value_columns LONGTEXT DEFAULT '';
DECLARE statement_sql LONGTEXT;
WHILE value_index <= 200 DO
SET value_columns = CONCAT(value_columns, ', `Wert', value_index, '` TEXT NULL');
SET value_index = value_index + 1;
END WHILE;
WHILE table_index <= 20 DO
SET statement_sql = CONCAT(
'CREATE TABLE IF NOT EXISTS `isp',
LPAD(table_index, 2, '0'),
'` (',
'`id` INT(11) NOT NULL AUTO_INCREMENT,',
'`datum` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'`userlevel` INT(1) DEFAULT NULL',
value_columns,
', PRIMARY KEY (`id`)',
') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'
);
PREPARE statement FROM statement_sql;
EXECUTE statement;
DEALLOCATE PREPARE statement;
SET table_index = table_index + 1;
END WHILE;
END//
CALL create_legacy_isp_tables()//
DROP PROCEDURE create_legacy_isp_tables//
DELIMITER ;
+318
View File
@@ -0,0 +1,318 @@
{ self }:
{ config, lib, pkgs, ... }:
let
inherit (lib) escapeShellArg mkEnableOption mkIf mkOption optionals types;
cfg = config.services.seiugw;
hostProvisioningRequest = "${cfg.dataDir}/provisioning/host.json";
komariInstalledMarker = "${cfg.dataDir}/provisioning/komari-installed";
in
{
options.services.seiugw = {
enable = mkEnableOption "SEIU Gateway";
package = mkOption {
type = types.package;
default = self.packages.${pkgs.stdenv.hostPlatform.system}.default;
description = "SEIU Gateway package to run.";
};
dataDir = mkOption {
type = types.str;
default = "/var/lib/seiugw";
description = "Persistent SQLite database, gateway key and later PKI storage.";
};
listenAddress = mkOption {
type = types.str;
default = "0.0.0.0";
description = "Address for the local web administration service.";
};
webPort = mkOption {
type = types.port;
default = 8088;
description = "TCP port for the local web administration service.";
};
openFirewall = mkOption {
type = types.bool;
default = true;
description = "Open the configured web and BACnet/IP ports in the NixOS firewall.";
};
bacnet = {
interface = mkOption {
type = types.str;
example = "ens18";
description = "Linux interface connected to the BACnet/IP field network.";
};
deviceInstance = mkOption {
type = types.ints.between 0 4194303;
default = 23;
description = "Configurable BACnet device instance. Vendor ID remains fixed at 815.";
};
ipPort = mkOption {
type = types.port;
default = 47808;
description = "BACnet/IP UDP port.";
};
};
opcUa.port = mkOption {
type = types.port;
default = 4840;
description = "Reserved OPC UA TCP port passed to the gateway.";
};
trends = {
enable = mkOption {
type = types.bool;
default = true;
description = "Run the local MariaDB store for long-term and legacy trend data.";
};
databaseName = mkOption {
type = types.str;
default = "wago";
description = "MariaDB database retaining the legacy SE-LTD table format.";
};
};
komari = {
enable = mkOption {
type = types.bool;
default = true;
description = "Register the gateway with a Komari server once the one-time commissioning request and secret token exist.";
};
endpoint = mkOption {
type = types.str;
default = "https://komari.cloud.se-inno.de";
description = "Komari endpoint passed to the agent.";
};
enrollmentTokenFile = mkOption {
type = types.str;
default = "${cfg.dataDir}/komari-enrollment-token";
description = "Root-readable file with the Komari one-time enrollment token. It must not be stored in Nix or Git.";
};
installDir = mkOption {
type = types.str;
default = "/opt/komari";
description = "Mutable location used by the upstream Komari installer for its agent binary.";
};
installerUrl = mkOption {
type = types.str;
default = "https://raw.githubusercontent.com/komari-monitor/komari-agent/refs/heads/main/install.sh";
description = "Upstream Komari installer URL. It is deliberately only fetched during one-time commissioning.";
};
ignoreUnsafeCertificateErrors = mkOption {
type = types.bool;
default = true;
description = "Pass --ignore-unsafe-cert to the Komari agent as requested for the controlled Komari endpoint.";
};
};
};
config = mkIf cfg.enable {
users.groups.seiugw = { };
users.users.seiugw = {
isSystemUser = true;
group = "seiugw";
home = cfg.dataDir;
createHome = true;
};
systemd.tmpfiles.rules = [
"d ${cfg.dataDir} 0750 seiugw seiugw -"
"d ${cfg.dataDir}/provisioning 0750 seiugw seiugw -"
] ++ optionals cfg.komari.enable [
"d ${cfg.komari.installDir} 0750 root root -"
];
networking.firewall = mkIf cfg.openFirewall {
allowedTCPPorts = [ cfg.webPort ];
allowedUDPPorts = [ cfg.bacnet.ipPort ];
};
# Keep MariaDB local. The gateway process receives socket-authenticated access;
# no database password or network-exposed database account is created.
services.mysql = mkIf cfg.trends.enable {
enable = true;
package = pkgs.mariadb;
settings.mysqld.bind-address = "127.0.0.1";
ensureDatabases = [ cfg.trends.databaseName ];
ensureUsers = [
{
name = "seiugw";
ensurePermissions = {
"${cfg.trends.databaseName}.*" = "ALL PRIVILEGES";
};
}
];
initialDatabases = [
{
name = cfg.trends.databaseName;
schema = ./legacy-schema.sql;
}
];
};
systemd.services.seiugw = {
description = "SEIU industrial protocol gateway";
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" ];
after = [ "network-online.target" ] ++ optionals cfg.trends.enable [ "mysql.service" ];
requires = optionals cfg.trends.enable [ "mysql.service" ];
environment = {
ASPNETCORE_URLS = "http://${cfg.listenAddress}:${toString cfg.webPort}";
Gateway__DataDirectory = cfg.dataDir;
Gateway__Bacnet__Interface = cfg.bacnet.interface;
Gateway__Bacnet__DeviceInstance = toString cfg.bacnet.deviceInstance;
Gateway__Bacnet__IpPort = toString cfg.bacnet.ipPort;
Gateway__OpcUa__Port = toString cfg.opcUa.port;
};
serviceConfig = {
ExecStart = "${cfg.package}/bin/Gateway.Api";
User = "seiugw";
Group = "seiugw";
WorkingDirectory = cfg.dataDir;
UMask = "0077";
Restart = "on-failure";
RestartSec = "5s";
NoNewPrivileges = true;
PrivateTmp = true;
ProtectHome = true;
ProtectSystem = "strict";
ReadWritePaths = [ cfg.dataDir ];
};
};
# The web process writes only project number and ISP as JSON after its first
# successful commissioning. This root helper validates both values again
# before applying the runtime hostname. The data is retained so the name is
# re-applied after every later boot without changing NixOS configuration.
systemd.services.seiugw-apply-hostname = {
description = "Apply SEIU Gateway commissioning hostname";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig.Type = "oneshot";
path = [ pkgs.coreutils pkgs.gnugrep pkgs.hostname pkgs.jq ];
script = ''
set -euo pipefail
request=${escapeShellArg hostProvisioningRequest}
[ -s "$request" ] || exit 0
project="$(${pkgs.jq}/bin/jq -er '.projectNumber' "$request")" || exit 0
isp="$(${pkgs.jq}/bin/jq -er '.ispNumber' "$request")" || exit 0
if ! ${pkgs.gnugrep}/bin/grep -Eq '^P[A-Z0-9_-]{1,32}$' <<<"$project"; then
exit 0
fi
case "$isp" in
*[!0-9]*|"") exit 0 ;;
esac
if [ "$isp" -lt 1 ] || [ "$isp" -gt 99 ]; then
exit 0
fi
host_name="SE-UGW-$project-ISP$(printf '%02d' "$isp")"
[ "''${#host_name}" -le 63 ] || exit 0
${pkgs.hostname}/bin/hostname "$host_name"
'';
};
systemd.paths.seiugw-apply-hostname = {
wantedBy = [ "multi-user.target" ];
pathConfig = {
PathExists = hostProvisioningRequest;
PathChanged = hostProvisioningRequest;
Unit = "seiugw-apply-hostname.service";
};
};
systemd.services.seiugw-komari-bootstrap = mkIf cfg.komari.enable {
description = "One-time Komari agent installer for SEIU Gateway";
after = [ "network-online.target" "seiugw-apply-hostname.service" ];
requires = [ "seiugw-apply-hostname.service" ];
wants = [ "network-online.target" ];
serviceConfig = {
Type = "oneshot";
Restart = "on-failure";
RestartSec = "30s";
};
path = [ pkgs.bash pkgs.coreutils pkgs.curl ];
script = ''
set -euo pipefail
marker=${escapeShellArg komariInstalledMarker}
token_file=${escapeShellArg cfg.komari.enrollmentTokenFile}
install_dir=${escapeShellArg cfg.komari.installDir}
agent="$install_dir/agent"
[ -e "$marker" ] && exit 0
[ -s ${escapeShellArg hostProvisioningRequest} ] || exit 0
[ -r "$token_file" ] || exit 0
token="$(${pkgs.coreutils}/bin/cat "$token_file")"
[ -n "$token" ] || exit 0
if [ ! -x "$agent" ]; then
${pkgs.curl}/bin/curl --fail --location --silent --show-error --proto '=https' ${escapeShellArg cfg.komari.installerUrl} \
| ${pkgs.bash}/bin/bash -s -- --install-dir "$install_dir" --install-no-mirror -e ${escapeShellArg cfg.komari.endpoint} --auto-discovery "$token" ${lib.optionalString cfg.komari.ignoreUnsafeCertificateErrors "--ignore-unsafe-cert"}
fi
[ -x "$agent" ]
${pkgs.systemd}/bin/systemctl try-restart seiugw-komari-agent.service || ${pkgs.systemd}/bin/systemctl start seiugw-komari-agent.service
${pkgs.coreutils}/bin/touch "$marker"
${pkgs.coreutils}/bin/chmod 0600 "$marker"
'';
};
systemd.paths.seiugw-komari-request = mkIf cfg.komari.enable {
wantedBy = [ "multi-user.target" ];
pathConfig = {
PathExists = hostProvisioningRequest;
PathChanged = hostProvisioningRequest;
Unit = "seiugw-komari-bootstrap.service";
};
};
systemd.paths.seiugw-komari-token = mkIf cfg.komari.enable {
wantedBy = [ "multi-user.target" ];
pathConfig = {
PathExists = cfg.komari.enrollmentTokenFile;
PathChanged = cfg.komari.enrollmentTokenFile;
Unit = "seiugw-komari-bootstrap.service";
};
};
# The upstream installer deliberately does not create a NixOS unit. NixOS
# owns this unit instead, while the binary remains in the upstream mutable
# install directory. The enrollment token is read at service start and is
# never placed in the Nix store.
systemd.services.seiugw-komari-agent = mkIf cfg.komari.enable {
description = "Komari monitoring agent";
after = [ "network-online.target" "seiugw-apply-hostname.service" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
unitConfig.ConditionPathExists = "${cfg.komari.installDir}/agent";
serviceConfig = {
Type = "simple";
WorkingDirectory = cfg.komari.installDir;
Restart = "always";
RestartSec = "10s";
};
path = [ pkgs.bash pkgs.coreutils ];
script = ''
set -euo pipefail
token="$(${pkgs.coreutils}/bin/cat ${escapeShellArg cfg.komari.enrollmentTokenFile})"
[ -n "$token" ]
exec ${escapeShellArg "${cfg.komari.installDir}/agent"} -e ${escapeShellArg cfg.komari.endpoint} --auto-discovery "$token" ${lib.optionalString cfg.komari.ignoreUnsafeCertificateErrors "--ignore-unsafe-cert"}
'';
};
};
}
+19
View File
@@ -0,0 +1,19 @@
{ lib, buildDotnetModule, dotnetCorePackages }:
buildDotnetModule {
pname = "seiugw";
version = "0.1.0";
src = lib.cleanSource ../.;
projectFile = "src/Gateway.Api/Gateway.Api.csproj";
nugetDeps = ./deps.json;
dotnet-sdk = dotnetCorePackages.sdk_8_0;
dotnet-runtime = dotnetCorePackages.aspnetcore_8_0;
executables = [ "Gateway.Api" ];
meta = {
description = "Industrial protocol gateway for BACnet/IP, OPC UA, Modbus TCP and MQTT";
platforms = lib.platforms.linux;
};
}