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
+1518
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/express": "^4.17.20",
"ts-node": "^10.9.1",
"typescript": "^5.2.2"
},
"dependencies": {
"express": "^4.18.2",
"mqtt": "^5.1.4",
"prototyp": "file:../lib"
}
}
+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.");
}
}
+111
View File
@@ -0,0 +1,111 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
"rootDir": "./src", /* Specify the root folder within your source files. */
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
"baseUrl": "src", /* Specify the base directory to resolve non-relative module names. */
"paths": {
"types/*": ["types/*"],
}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
"noFallthroughCasesInSwitch": false, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}