Split lib from modules

This commit is contained in:
Daniel Kluge
2023-11-01 21:41:10 +01:00
parent cab50cda6a
commit 71ef5f32c0
16 changed files with 1721 additions and 2460 deletions
+13
View File
@@ -0,0 +1,13 @@
import { MultiMessageBroker, FileImporter } from "prototyp";
import HTTPInterfaceServer from "./modules/httpInterfaceServer";
import MQTTConnector from "./modules/mqttConnector";
const aas = FileImporter.readAASByPath("../owntest.json");
const broker = new MultiMessageBroker();
broker.registerInterfaceConnection({ interfaceConnection: MQTTConnector, config: { reconnectPeriod: 1000 }})
broker.registerAAS({ aas, serverInterfaces: { serverInterface: HTTPInterfaceServer, config: { bindPort: 3000, bindAddress: "0.0.0.0" } } });
broker.prepare();
broker.start();
+216
View File
@@ -0,0 +1,216 @@
import express from "express";
import { AbstractInterfaceServer, Types, Traverser, AASCoreJsonization, AASCoreTypes } from "prototyp";
export type Config = {
bindAddress: string,
bindPort: number,
}
export default class HTTPInterfaceServer extends AbstractInterfaceServer<Config> {
public static serverInterfaceName: string = "HTTPInterfaceServer";
public static supportsSubscriptions: boolean = false; // TODO, longpolling?
private app: express.Express = express();
private server: any = null;
private observers: any[] = [];
public prepare(): void {
this.app.use(express.json());
this.createRoutes();
}
public run(): void {
this.server = this.app.listen(this.config.bindPort, this.config.bindAddress, () => {
console.log(`Listening on ${this.config.bindAddress}:${this.config.bindPort}`);
});
}
public stop(): void {
if (this.server && this.server.close) this.server.close();
}
public notify(event: any): void {
this.observers.forEach(observer => {
// TODO
// Notify long pollers
});
}
private createRoutes(): void {
const NOT_IMPLEMENTED = (_req: express.Request, res: express.Response) => res.status(501).end();
const getSM = (id: string) => {
if (!id) return null;
try {
// This is what the specification says
const decoded = Buffer.from(id, "base64").toString("utf-8");
let sm = Traverser.findSMById(this.aas, decoded);
if (sm === null) {
// Normally, at least in BaSyx just the shortId is used, so just test if we find something like this
sm = Traverser.findSMByIdShort(this.aas, id);
}
return sm;
} catch {
return null;
}
}
// /aas
this.app.get("/aas", (_, res) => res.json(AASCoreJsonization.toJsonable(this.aas)).end());
this.app.put("/aas", NOT_IMPLEMENTED);
this.app.delete("/aas", NOT_IMPLEMENTED);
// /aas/$reference
this.app.get("/aas/$reference", NOT_IMPLEMENTED);
// /aas/asset-information
this.app.get("/aas/asset-information", NOT_IMPLEMENTED);
this.app.put("/aas/asset-information", NOT_IMPLEMENTED);
this.app.get("/aas/asset-information/thumbnail", NOT_IMPLEMENTED);
this.app.put("/aas/asset-information/thumbnail", NOT_IMPLEMENTED);
this.app.delete("/aas/asset-information/thumbnail", NOT_IMPLEMENTED);
// /aas/submodel-refs
this.app.get("/aas/submodel-refs", NOT_IMPLEMENTED);
this.app.post("/aas/submodel-refs", NOT_IMPLEMENTED);
this.app.delete("/aas/submodel-refs/:submodelIdentifier", NOT_IMPLEMENTED);
// /aas/submodels
this.app.get("/aas/submodels/:smId", (req, res) => {
const sm = getSM(req.params.smId);
if (sm === null) return res.status(404).end();
return res.json(AASCoreJsonization.toJsonable(sm)).end()
});
this.app.put("/aas/submodels/:smId", NOT_IMPLEMENTED);
this.app.patch("/aas/submodels/:smId", NOT_IMPLEMENTED);
this.app.delete("/aas/submodels/:smId", NOT_IMPLEMENTED);
// /aas/submodels/:smId/submodel-elements
this.app.use("/aas/submodels/:smId/submodel-elements", (req, res, next) => {
if (req.path !== "/") return next();
if (req.method !== "GET") return res.status(501).end();
const sm = getSM(req.params.smId);
if (sm === null || sm.submodelElements === null) return res.status(404).end();
return res.json(sm.submodelElements.map(element => AASCoreJsonization.toJsonable(element))).end();
});
// Main function
this.app.use("/aas/submodels/:smId/submodel-elements/*", (req, res) => {
const idShortPathString = (req.params as any)[0];
if (idShortPathString.endsWith("/")) res.status(400).end();
const sm = getSM(req.params.smId);
if (sm === null || sm.submodelElements === null) return res.status(404).end();
if (idShortPathString === "") {
if (req.method === "GET") {
const json = sm.submodelElements.map(element => AASCoreJsonization.toJsonable(element));
return res.json(json).end();
}
}
// Currently we don't support these operations
if (idShortPathString.endsWith("$value") ||
idShortPathString.endsWith("$reference") ||
idShortPathString.endsWith("$metadata") ||
idShortPathString.endsWith("$path")) return res.status(501).end();
// If operation ids are changed, you can change the format here
const endingMatchSearch = idShortPathString.match(/(\/value$|\/attachment$|\/invoke$|\/invoke-async$|\/operation-status\/[a-zA-Z0-9\-]+$|\/operation-result\/[a-zA-Z0-9\-]+$)/)
const endingMatch = endingMatchSearch?.[0];
const idShortPath = endingMatch ? idShortPathString.replace(new RegExp(`${endingMatch}$`), "").split("/") : idShortPathString.split("/");
switch (endingMatch) {
case undefined: {
if (req.method !== "GET") return res.status(501).end();
const prop = Traverser.getElementByIdPath(this.aas, sm, idShortPath);
if (prop === null || !AASCoreTypes.isProperty(prop)) return res.status(404).end();
return res.json(AASCoreJsonization.toJsonable(prop)).end();
}
case "/value":
if (req.method !== "GET" && req.method !== "PUT") return res.status(501).end();
const prop = Traverser.getElementByIdPath(this.aas, sm, idShortPath);
console.log((prop as AASCoreTypes.Property).constructor.name)
if (prop === null || !AASCoreTypes.isProperty(prop)) {
// @ts-ignore
console.log(prop === null, !AASCoreTypes.isProperty(prop))
return res.status(404).end();
}
const request: Types.RequestTypes.Request = req.method === "GET" ? { type: "READ", target: prop } : { type: "WRITE", target: prop, extraData: { value: req.body } };
const value = this.onRequestCallback(request);
if (req.method === "PUT") res.status(204).end();
if (value === null) return res.status(500).end();
return res.json(value).end();
case "/attachment":
return res.status(501).end();
case "/invoke": {
if (req.method !== "POST") return res.status(405).end();
const op = Traverser.getElementByIdPath(this.aas, sm, idShortPath);
if (op === null || !AASCoreTypes.isOperation(op)) return res.status(404).end();
// TODO
// Parameter?
const success = this.onRequestCallback({ type: "CALL", target: op, extraData: { args: req.body } });
return res.send(success ? 204 : 500).end();
}
case "/invoke-async": {
if (req.method !== "POST") return res.status(405).end();
const op = Traverser.getElementByIdPath(this.aas, sm, idShortPath);
if (op === null || !AASCoreTypes.isOperation(op)) return res.status(404).end();
// TODO
// Invoke operation and get handle
const request: Types.RequestTypes.Request = { type: "CALL-ASYNC", target: op, extraData: { args: req.body } };
const handle = this.onRequestCallback(request);
const operationPaths = [`${idShortPath.join("/")}/operation-status/${handle}`, `${idShortPath.join("/")}/operation-result/${handle}`];
return res.status(202).header("Location", operationPaths).end();
}
default: {
// operation-status, operation-result or anything else
const [_, operation, handle] = endingMatch.split("/");
switch (operation) {
case "operation-status": {
if (req.method !== "GET") return res.status(405).end();
const state = this.onRequestCallback({ type: "GET-OP-STATE", target: handle });
if (state === undefined) return res.status(404).end();
return res.json({
finished: state,
handle
}).end();
}
case "operation-result": {
if (req.method !== "GET") return res.status(405).end();
const result = this.onRequestCallback({ type: "GET-OP-RESULT", target: handle });
if (result === null) return res.status(404).end();
return res.json({
result,
handle
}).end();
}
default: {
return res.status(404).end();
}
}
}
}
})
}
}
+114
View File
@@ -0,0 +1,114 @@
import * as mqtt from "mqtt";
import { AbstractConnectionObject } from "prototyp";
import type { AASCoreTypes } from "prototyp";
export default class MQTTConnector extends AbstractConnectionObject<mqtt.IClientOptions> {
public static readonly connectorName: string = "MQTT Connector";
public static readonly uriProtocol: string[] = ["mqtt", "mqtts"];
public static readonly connectionType: "ON_DEMAND" | "PERMANENT" = "PERMANENT";
public static readonly supportsSubscriptions: boolean = true;
private client: mqtt.MqttClient|null = null;
private readonly messageStore: Record<string, any> = {};
public connect(): boolean {
if (!this.client) this.client = mqtt.connect(this.endpointMetadata.base, this.connectionParameter);
this.client.on("message", (topic, message) => {
//console.log(`${topic}: ${message.toString("utf-8")}`)
// If json is expected you could parse it here
this.messageStore[topic] = message.toString("utf-8");
// Notify observers
if (this.observerStore[topic] !== undefined) {
this.observerStore[topic].forEach(cb => cb(message.toString("utf-8")));
}
});
this.client.subscribe("#");
return this.client.connected;
}
public disconnect(): void {
if (this.client) this.client.end();
this.client = null;
}
public readProperty(prop: AASCoreTypes.Property): any {
console.log(prop);
const cc = this.mapper.get(prop);
console.log(cc);
if (cc === undefined) return null;
const errorReturn = cc.default ?? null;
if (!this.client || !this.client.connected) return errorReturn;
console.log(this.messageStore)
const value = this.messageStore[cc.forms.href.substring(1)];
console.log(value)
if (value === undefined) return errorReturn;
switch (cc.type) {
case "integer":
return Number.parseInt(value);
case "float":
return Number.parseFloat(value);
case "boolean":
return !!value;
case "string":
default:
return value;
}
}
public writeProperty(prop: AASCoreTypes.Property, value: any): boolean {
const cc = this.mapper.get(prop);
if (cc === undefined || !this.client || !this.client.connected) return false;
const topic = cc.forms.href.substring(1);
if (topic === undefined) return false;
this.client.publish(topic, value.toString());
return true;
}
public observeProperty(prop: AASCoreTypes.Property, callback: (value: any) => void): boolean {
const cc = this.mapper.get(prop);
if (cc === undefined || !cc.observable || !this.client || !this.client.connected) return false;
const topic = cc.forms.href.substring(1);
if (this.observerStore[topic] === undefined) this.observerStore[topic] = [callback];
else this.observerStore[topic].push(callback);
return true;
}
public callActionSync(action: AASCoreTypes.Operation, args: Record<string, any>): any {
// TODO
// Vorher mal ne ordentliche Mapping-Definition
throw new Error("Method not implemented.");
}
public callActionAsync(action: AASCoreTypes.Operation, args: Record<string, any>): string | null {
// TODO
// Vorher mal ne ordentliche Mapping-Definition
throw new Error("Method not implemented.");
}
public subscribeEvent(event: AASCoreTypes.BasicEventElement, callback: (event: AASCoreTypes.BasicEventElement) => void): boolean {
// TODO
// Vorher mal ne ordentliche Mapping-Definition
throw new Error("Method not implemented.");
}
public unsubscribeEvent(event: AASCoreTypes.BasicEventElement): void {
// TODO
// Vorher mal ne ordentliche Mapping-Definition
throw new Error("Method not implemented.");
}
}