opc meldunge parameter fehler io

This commit is contained in:
marco committed 2026-10-30 15:42:17 +01:00
1 parent ee408475de
commit 3dc1ad623c
115 files changed
+5891 -13

No files matched your search

@@ -0,0 +1,23 @@
import { BadRequestException } from '@nestjs/common';
import { createHash } from 'node:crypto';
import type { StructureField } from './structures.types';
import type { ArrayImportInput } from './structure-array.types';
export function validateArrayInput(input: ArrayImportInput) {
if (!input || typeof input.anlageId !== 'string' || !input.anlageId || typeof input.connectionId !== 'string' || !input.connectionId ||
typeof input.arrayNodeId !== 'string' || !input.arrayNodeId.trim() || input.arrayNodeId.length > 2048 ||
!Number.isSafeInteger(input.start) || !Number.isSafeInteger(input.end) || input.start < 0 || input.end < input.start || input.end > 99999 || input.end - input.start >= 200 ||
typeof input.namePattern !== 'string' || input.namePattern.split('{index}').length !== 2 || !/^[A-Za-z_][A-Za-z0-9_]{0,79}$/.test(input.namePattern.replace('{index}', String(input.end))) ||
typeof input.templateName !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]{0,79}$/.test(input.templateName) || !['read', 'write'].includes(input.direction))
throw new BadRequestException('Array, Vorlage, Namensmuster mit einmal {index} und Indexbereich prüfen (max. 200 pro Übernahme).');
}
export function templateFields(fields: StructureField[]) {
return fields.map(({ name, dataType, unit }) => ({ name, dataType, unit })).sort((a, b) => a.name.localeCompare(b.name, 'en'));
}
export function fieldSignature(fields: StructureField[]) { return createHash('sha256').update(JSON.stringify(templateFields(fields))).digest('hex'); }
export function arrayIndex(browseName: string): number | null {
// Siemens can expose array children as QualifiedNames such as "3:0".
// The importer passes the name part ("0"); accept both numeric and bracketed forms.
const name = browseName.trim().replace(/^\d+:/, '');
const match = /^(\d+)$/.exec(name) ?? /\[(\d+)\]$/.exec(name);
return match && Number.isSafeInteger(Number(match[1])) ? Number(match[1]) : null;
}
@@ -0,0 +1,98 @@
import { BadRequestException, ConflictException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { randomUUID, createHash } from 'node:crypto';
import { BrowseDirection, NodeClass } from 'node-opcua';
import { OpcService } from '../opcua/opcua.service';
import { OpcConfigService } from '../opcua/opcua-config.service';
import { StructuresService } from './structures.service';
import type { OpcStructure } from './structures.types';
import type { StructureTemplate } from './structure-template.schema';
import type { ArrayImportInput, ArrayImportPreview, ArrayImportRow } from './structure-array.types';
import { validateArrayInput, arrayIndex, fieldSignature, templateFields } from './structure-array.helpers';
@Injectable()
export class StructureArrayService {
constructor(@InjectModel('OpcStructure', 'anlagen') private readonly model: Model<OpcStructure>,
@InjectModel('OpcStructureTemplate', 'anlagen') private readonly templates: Model<StructureTemplate>,
private readonly structures: StructuresService, private readonly config: OpcConfigService, private readonly opc: OpcService) {}
async preview(input: ArrayImportInput): Promise<ArrayImportPreview> {
validateArrayInput(input); await this.config.checkPlant(input.anlageId);
const existing = await this.model.find({ anlageId: input.anlageId }).select('name').lean().exec();
const names = new Set(existing.map(r => r.name));
const template = await this.templates.findOne({ anlageId: input.anlageId, name: input.templateName }).lean().exec();
const connection = await this.opc.openStructureSession(input.anlageId, input.connectionId);
try {
const elements = new Map<number, string[]>();
let page = await connection.session.browse({ nodeId: input.arrayNodeId.trim(), referenceTypeId: 'HierarchicalReferences', includeSubtypes: true, browseDirection: BrowseDirection.Forward, nodeClassMask: NodeClass.Object | NodeClass.Variable, resultMask: 63 });
let continuation: Buffer | undefined, count = 0;
try {
while (true) {
continuation = page.continuationPoint?.length ? page.continuationPoint : undefined;
if (!page.statusCode.isGood()) throw new BadRequestException('Array kann nicht durchsucht werden: ' + page.statusCode.toString());
for (const ref of page.references ?? []) {
if (++count > 20000) throw new BadRequestException('Array hat zu viele direkte Knoten. Einen kleineren Teilbereich auswählen.');
const index = arrayIndex(ref.browseName.name ?? '');
if (index !== null && index >= input.start && index <= input.end) elements.set(index, [...(elements.get(index) ?? []), ref.nodeId.toString()]);
}
if (!continuation) break;
page = await connection.session.browseNext(continuation, false);
}
} finally { if (continuation) await connection.session.browseNext(continuation, true).catch(() => undefined); }
const rows: ArrayImportRow[] = [];
let signature = template?.signature;
for (let index = input.start; index <= input.end; index++) {
const name = input.namePattern.replace('{index}', String(index)), targets = elements.get(index) ?? [];
const row: ArrayImportRow = { index, name, rootNodeId: targets[0] ?? '', status: 'error', message: '', fields: [] };
if (names.has(name)) { row.status = 'exists'; row.message = 'Name bereits vorhanden; bleibt unverändert.'; }
else if (targets.length !== 1) row.message = targets.length ? 'Array-Index mehrfach vorhanden.' : 'Array-Index nicht im OPC-Browser gefunden.';
else {
try {
row.fields = await this.structures.inspectFields(connection.session, targets[0]);
if (row.fields.some(f => input.direction === 'read' ? !f.readable : !f.writable)) throw new Error('Zugriffsrichtung nicht für alle Felder erlaubt.');
const current = fieldSignature(row.fields);
if (signature && current !== signature) throw new Error('Felder oder Datentypen passen nicht zur Vorlage.');
signature = current; row.status = 'ready'; row.message = 'Bereit';
} catch (cause) { row.message = cause instanceof Error ? cause.message : 'Struktur nicht lesbar'; }
}
rows.push(row);
}
await connection.assertCurrent();
const token = createHash('sha256').update(JSON.stringify({ input, templateId: template?.id, signature, rows })).digest('hex');
return { token, rows, ready: rows.filter(r => r.status === 'ready').length, existing: rows.filter(r => r.status === 'exists').length, errors: rows.filter(r => r.status === 'error').length, templateName: input.templateName };
} finally { await connection.close(); }
}
async apply(input: ArrayImportInput & { token: string }) {
const { token, ...settings } = input;
const preview = await this.preview(settings);
if (!token || preview.token !== token) throw new ConflictException('Vorschau oder CPU-Daten geändert. Vorschau erneut laden.');
const ready = preview.rows.filter(r => r.status === 'ready');
if (!ready.length) throw new BadRequestException('Keine neuen gültigen Einträge zur Übernahme');
await this.config.checkPlant(input.anlageId);
const signature = fieldSignature(ready[0].fields);
let template = await this.templates.findOne({ anlageId: input.anlageId, name: input.templateName }).lean().exec();
if (!template) {
try { template = (await this.templates.create({ anlageId: input.anlageId, name: input.templateName, id: randomUUID(), signature, fields: templateFields(ready[0].fields) })).toObject(); }
catch (cause) {
if ((cause as { code?: number }).code !== 11000) throw cause;
template = await this.templates.findOne({ anlageId: input.anlageId, name: input.templateName }).lean().exec();
}
}
if (!template || template.signature !== signature) throw new ConflictException('Vorlage inzwischen geändert. Vorschau neu laden.');
let created = 0, skipped = preview.existing;
const failures: { name: string; message: string }[] = [];
for (const row of ready) {
try {
await this.config.checkPlant(input.anlageId);
const result = await this.model.updateOne({ anlageId: input.anlageId, name: row.name }, { $setOnInsert: {
anlageId: input.anlageId, name: row.name, id: randomUUID(), version: 1, connectionId: input.connectionId, rootNodeId: row.rootNodeId, direction: input.direction, templateId: template.id,
bindings: row.fields.map(({ name, nodeId, readable, writable }) => ({ name, nodeId, readable, writable })),
} }, { upsert: true, runValidators: true });
if (result.upsertedCount) created++; else skipped++;
} catch (cause) {
if ((cause as { code?: number }).code === 11000) skipped++;
else { failures.push({ name: row.name, message: 'Nicht gespeichert. Verbindung zur Datenbank und ausgewählte Anlage prüfen.' }); break; }
}
}
return { created, skipped, invalid: preview.errors, failures, notProcessed: ready.length - created - (skipped - preview.existing) - failures.length };
}
}
@@ -0,0 +1,24 @@
import { describe, expect, it } from '@jest/globals';
import { validateArrayInput, arrayIndex, fieldSignature, templateFields } from './structure-array.helpers';
import type { ArrayImportInput } from './structure-array.types';
import type { StructureField } from './structures.types';
const input: ArrayImportInput = { anlageId: 'a', connectionId: 'c', arrayNodeId: 'ns=3;s=Array', start: 0, end: 40, namePattern: 'GrenzwertIst_{index}', templateName: 'DigitalIst', direction: 'read' };
describe('Array structure import', () => {
it('accepts inclusive ranges up to 200 and rejects malformed or unbounded requests', () => {
expect(() => validateArrayInput(input)).not.toThrow(); expect(() => validateArrayInput({ ...input, end: 199 })).not.toThrow();
for (const patch of [{ end: 200 }, { start: -1 }, { start: 0.5 }, { start: 41 }, { end: NaN }, { arrayNodeId: '' }, { namePattern: 'Fixed' }, { namePattern: '{index}' }, { namePattern: 'X_{index}_{index}' }, { templateName: '../bad' }, { direction: 'both' }]) expect(() => validateArrayInput({ ...input, ...patch } as ArrayImportInput)).toThrow();
});
it('extracts real element indices without inventing node addresses', () => {
expect(arrayIndex('GrenzwertIst[0]')).toBe(0); expect(arrayIndex('[40]')).toBe(40); expect(arrayIndex('3:GrenzwertIst[123]')).toBe(123);
expect(arrayIndex('0')).toBe(0); expect(arrayIndex('40')).toBe(40); expect(arrayIndex('3:2')).toBe(2);
expect(arrayIndex('-1')).toBeNull(); expect(arrayIndex('2.Signal')).toBeNull(); expect(arrayIndex('1.5')).toBeNull();
expect(arrayIndex('GrenzwertIst')).toBeNull(); expect(arrayIndex('GrenzwertIst[-1]')).toBeNull(); expect(arrayIndex('GrenzwertIst[0].Signal')).toBeNull();
});
it('shares type definitions independently of addresses, rights and browse order', () => {
const fields: StructureField[] = [{ name: 'Signal', nodeId: 'ns=3;i=1', dataType: 'Boolean', readable: true, writable: false, unit: '' }, { name: 'Delay', nodeId: 'ns=3;i=2', dataType: 'Int32', readable: true, writable: true, unit: 'ms' }];
const other = [...fields].reverse().map(f => ({ ...f, nodeId: 'different:' + f.nodeId, writable: !f.writable }));
expect(fieldSignature(fields)).toBe(fieldSignature(other)); expect(templateFields(fields)[0]).not.toHaveProperty('nodeId');
expect(fieldSignature(fields)).not.toBe(fieldSignature(fields.map(f => ({ ...f, dataType: 'Boolean' }))));
expect(fieldSignature(fields)).not.toBe(fieldSignature(fields.map(f => ({ ...f, unit: '' }))));
});
});
@@ -0,0 +1,4 @@
import type { StructureField } from './structures.types';
export interface ArrayImportInput { anlageId: string; connectionId: string; arrayNodeId: string; start: number; end: number; namePattern: string; templateName: string; direction: 'read' | 'write' }
export interface ArrayImportRow { index: number; name: string; rootNodeId: string; status: 'ready' | 'exists' | 'error'; message: string; fields: StructureField[] }
export interface ArrayImportPreview { token: string; rows: ArrayImportRow[]; ready: number; existing: number; errors: number; templateName: string }
@@ -0,0 +1,6 @@
import { Schema } from 'mongoose';
import type { StructureField } from './structures.types';
export interface StructureTemplate { anlageId: string; id: string; name: string; signature: string; fields: Pick<StructureField, 'name' | 'dataType' | 'unit'>[] }
export const StructureTemplateSchema = new Schema<StructureTemplate>({ anlageId: { type: String, required: true }, id: { type: String, required: true }, name: { type: String, required: true }, signature: { type: String, required: true }, fields: { type: Schema.Types.Mixed, required: true } }, { collection: 'opcua_structure_templates', timestamps: true, strict: 'throw' });
StructureTemplateSchema.index({ anlageId: 1, name: 1 }, { unique: true });
StructureTemplateSchema.index({ anlageId: 1, id: 1 }, { unique: true });
@@ -0,0 +1,63 @@
import { Injectable, OnModuleDestroy } from '@nestjs/common';
import { Observable, type Subscription } from 'rxjs';
import { OpcMonitorManager } from '../opcua/opcua-monitor-manager.service';
import { StructuresService } from './structures.service';
import type { OpcStructure, StructureSnapshot } from './structures.types';
@Injectable()
export class StructuresLiveService implements OnModuleDestroy {
private readonly stops = new Set<() => void>();
constructor(private readonly structures: StructuresService, private readonly monitors: OpcMonitorManager) {}
watch(anlageId: string, name: string, expectedId?: string, checkBinding?: () => Promise<void>): Observable<{ data: StructureSnapshot }> {
return new Observable(subscriber => {
let active = true, cancel: (() => void) | undefined, inner: Subscription | undefined;
const stop = () => { active = false; inner?.unsubscribe(); cancel?.(); };
this.stops.add(stop);
let row: OpcStructure | undefined;
const empty = (status: StructureSnapshot['status'], error?: string): StructureSnapshot => ({ name, status, values: Object.fromEntries((row?.fields ?? []).map(f => [f.name, null])), fields: {}, updatedAt: new Date().toISOString(), error });
const emit = (snapshot: StructureSnapshot) => { if (active) subscriber.next({ data: structuredClone(snapshot) }); };
void (async () => {
try {
while (active) {
try {
row = await this.structures.get(anlageId, name);
if (expectedId && row.id !== expectedId) throw new Error('Struktur wurde ersetzt');
if (row.direction !== 'read') throw new Error('Nur Lesestrukturen können live abonniert werden');
await checkBinding?.(); if (!active) break;
const definition = row;
let snapshot = empty('connecting'); emit(snapshot);
await new Promise<void>(resolve => {
cancel = resolve;
inner = this.monitors.observe(anlageId, definition.connectionId, definition.fields.map(f => f.nodeId), async session => {
const fields = await this.structures.inspectFields(session, definition.rootNodeId);
const canonical = (f: typeof fields) => JSON.stringify([...f].sort((a,b) => a.name.localeCompare(b.name, 'en')));
if (canonical(fields) !== canonical(definition.fields)) throw new Error('CPU-Struktur geändert');
}, async () => { await this.structures.assertCurrent(definition); await checkBinding?.(); }).subscribe({
next: event => {
if (event.status !== 'online') { snapshot = empty(event.status, event.error); emit(snapshot); return; }
if (event.nodeId && event.value) {
for (const field of definition.fields.filter(f => f.nodeId === event.nodeId)) {
const raw = event.value.value.value;
const good = event.value.statusCode.isGood() && (field.dataType === 'Boolean' ? typeof raw === 'boolean' : typeof raw === 'number' && Number.isFinite(raw) && (field.dataType === 'Float' || Number.isInteger(raw)));
snapshot.values[field.name] = good ? raw : null;
snapshot.fields[field.name] = { value: good ? raw : null, good, status: event.value.statusCode.toString(), sourceTimestamp: event.value.sourceTimestamp?.toISOString() ?? null };
}
snapshot.updatedAt = new Date().toISOString();
}
snapshot.status = definition.fields.every(f => snapshot.fields[f.name]?.good) ? 'online' : 'partial';
delete snapshot.error; emit(snapshot);
},
error: () => { emit(empty('offline', 'Struktur oder Zuordnung nicht mehr gültig. Bitte neu laden.')); resolve(); }, complete: resolve,
});
if (!active) { inner.unsubscribe(); resolve(); }
});
} catch { emit(empty('offline', 'Live-Struktur nicht verfügbar. Verbindung und Zuordnung prüfen.')); }
finally { inner?.unsubscribe(); inner = undefined; }
if (active) await new Promise<void>(resolve => { const timer = setTimeout(resolve, 3000); cancel = () => { clearTimeout(timer); resolve(); }; });
}
} finally { this.stops.delete(stop); subscriber.complete(); }
})();
return stop;
});
}
onModuleDestroy() { for (const stop of this.stops) stop(); }
}
@@ -0,0 +1,17 @@
import { Body, Controller, Delete, Get, Param, Post, Query, Sse } from '@nestjs/common';
import { StructuresService, type StructureInput } from './structures.service';
import { StructuresLiveService } from './structures-live.service';
import { StructureArrayService } from './structure-array.service';
import type { ArrayImportInput } from './structure-array.types';
@Controller('rk2/opcua-structures')
export class StructuresController {
constructor(private readonly structures: StructuresService, private readonly live: StructuresLiveService, private readonly arrays: StructureArrayService) {}
@Get() list() { return this.structures.list(); }
@Post('array/preview') previewArray(@Body() dto: ArrayImportInput) { return this.arrays.preview(dto); }
@Post('array/import') importArray(@Body() dto: ArrayImportInput & { token: string }) { return this.arrays.apply(dto); }
@Post('inspect') inspect(@Body() dto: StructureInput) { return this.structures.inspect(dto); }
@Post() create(@Body() dto: StructureInput) { return this.structures.create(dto); }
@Delete(':name') remove(@Param('name') name: string, @Body() dto: { anlageId: string; id: string; version: number }) { return this.structures.remove(dto?.anlageId, name, dto?.id, dto?.version); }
@Post(':name/write') write(@Param('name') name: string, @Body() dto: { anlageId: string; id: string; version: number; values: Record<string, unknown> }) { return this.structures.write(dto?.anlageId, name, dto); }
@Sse(':name/live') watch(@Param('name') name: string, @Query('anlageId') anlageId: string, @Query('expectedId') expectedId?: string) { return this.live.watch(anlageId, name, expectedId); }
}
+11
View File
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { OpcModule } from '../opcua/opcua.module';
import { StructureSchema } from './structures.schema';
import { StructuresService } from './structures.service';
import { StructuresLiveService } from './structures-live.service';
import { StructuresController } from './structures.controller';
import { StructureTemplateSchema } from './structure-template.schema';
import { StructureArrayService } from './structure-array.service';
@Module({ imports: [OpcModule, MongooseModule.forFeature([{ name: 'OpcStructure', schema: StructureSchema }, { name: 'OpcStructureTemplate', schema: StructureTemplateSchema }], 'anlagen')], exports: [StructuresService, StructuresLiveService], providers: [StructureArrayService, StructuresService, StructuresLiveService], controllers: [StructuresController] })
export class StructuresModule {}
@@ -0,0 +1,9 @@
import { Schema } from 'mongoose';
import type { OpcStructure } from './structures.types';
export const StructureSchema = new Schema<OpcStructure>({
anlageId: { type: String, required: true }, id: { type: String, required: true }, version: { type: Number, default: 1 },
name: { type: String, required: true }, connectionId: { type: String, required: true }, rootNodeId: { type: String, required: true },
direction: { type: String, enum: ['read', 'write'], required: true }, fields: { type: Schema.Types.Mixed, default: undefined }, templateId: { type: String }, bindings: { type: Schema.Types.Mixed, default: undefined },
}, { collection: 'opcua_structures', timestamps: true, strict: 'throw' });
StructureSchema.index({ anlageId: 1, name: 1 }, { unique: true });
StructureSchema.index({ anlageId: 1, id: 1 }, { unique: true });
+119
View File
@@ -0,0 +1,119 @@
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { randomUUID } from 'node:crypto';
import { AttributeIds, BrowseDirection, DataType, NodeClass, resolveNodeId, type ClientSession } from 'node-opcua';
import { OpcService } from '../opcua/opcua.service';
import { OpcConfigService } from '../opcua/opcua-config.service';
import type { OpcStructure, StructureField } from './structures.types';
import type { StructureTemplate } from './structure-template.schema';
import { validateStructureInput, validateStructureWrite } from './structures.validation';
export interface StructureInput { anlageId: string; name: string; connectionId: string; rootNodeId: string; direction: 'read' | 'write' }
@Injectable()
export class StructuresService {
constructor(@InjectModel('OpcStructure', 'anlagen') private readonly model: Model<OpcStructure>, private readonly config: OpcConfigService, private readonly opc: OpcService, @InjectModel('OpcStructureTemplate', 'anlagen') private readonly templates?: Model<StructureTemplate>) {}
async list() {
const { anlageId } = await this.config.get();
const rows = await this.model.find({ anlageId }).select('-_id -__v -createdAt -updatedAt').lean().exec();
const templates = this.templates ? await this.templates.find({ anlageId }).select('-_id -__v -createdAt -updatedAt').lean().exec() : [];
return { anlageId, structures: rows.map(row => this.resolveTemplate(row, templates)), templates };
}
async get(anlageId: string, name: string) {
await this.config.checkPlant(anlageId);
const row = await this.model.findOne({ anlageId, name }).lean().exec();
if (!row) throw new NotFoundException('Struktur nicht gefunden');
const templates = row.templateId && this.templates ? await this.templates.find({ anlageId, id: row.templateId }).lean().exec() : [];
return this.resolveTemplate(row, templates);
}
private resolveTemplate(row: OpcStructure, templates: StructureTemplate[]): OpcStructure {
if (!row.templateId) return row;
const template = templates.find(t => t.id === row.templateId);
if (!template) throw new ConflictException('Strukturvorlage fehlt');
const fields = template.fields.map(field => {
const binding = row.bindings?.find(b => b.name === field.name);
if (!binding) throw new ConflictException('Feldzuordnung zur Vorlage fehlt');
return { name: field.name, nodeId: binding.nodeId, dataType: field.dataType, readable: binding.readable, writable: binding.writable, unit: field.unit };
});
return { ...row, fields };
}
async assertCurrent(row: OpcStructure) {
const latest = await this.get(row.anlageId, row.name);
if (latest.id !== row.id || latest.version !== row.version) throw new ConflictException('Struktur inzwischen geändert');
}
async inspectFields(session: ClientSession, rootNodeId: string): Promise<StructureField[]> {
try { resolveNodeId(rootNodeId); } catch { throw new BadRequestException('Ungültige Struktur-NodeId'); }
const page = await session.browse({ nodeId: rootNodeId, referenceTypeId: 'HierarchicalReferences', includeSubtypes: true, browseDirection: BrowseDirection.Forward, nodeClassMask: NodeClass.Variable, resultMask: 63 });
if (page.continuationPoint?.length) { await session.browseNext(page.continuationPoint, true); throw new BadRequestException('Zu viele Felder. Einen einzelnen Struktureintrag auswählen.'); }
if (!page.statusCode.isGood() || (page.references?.length ?? 0) > 30) throw new BadRequestException('Keine kleine, aufklappbare Struktur gefunden (max. 30 direkte Felder).');
const fields: StructureField[] = [];
const refs = (page.references ?? []).map(ref => ({ nodeId: ref.nodeId.toString(), name: ref.browseName.name ?? '' }));
// A scalar array element is exposed as a one-field definition named Value.
if (!refs.length) refs.push({ nodeId: resolveNodeId(rootNodeId).toString(), name: 'Value' });
for (const ref of refs) {
const name = ref.name;
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || ['__proto__', 'constructor', 'prototype'].includes(name) || fields.some(f => f.name === name))
throw new BadRequestException('Feldname nicht unterstützt oder doppelt: ' + name);
const meta = await session.read([AttributeIds.DataType, AttributeIds.ValueRank, AttributeIds.UserAccessLevel].map(attributeId => ({ nodeId: ref.nodeId, attributeId })));
if (meta.some(v => !v.statusCode.isGood()) || meta[1].value.value !== -1) throw new BadRequestException('Nur skalare Bool-/TIME-Felder werden im Beispiel unterstützt: ' + name);
let type = meta[0].value.value;
const typeName = await session.read({ nodeId: type, attributeId: AttributeIds.BrowseName });
let resolved = false;
for (let depth = 0; depth < 12; depth++) {
if (type.namespace === 0 && [1, 4, 6, 10].includes(type.value)) { resolved = true; break; }
const parent = await session.browse({ nodeId: type, referenceTypeId: 'HasSubtype', includeSubtypes: false, browseDirection: BrowseDirection.Inverse, resultMask: 63 });
if (parent.references?.length !== 1) break;
type = parent.references[0].nodeId;
}
if (!resolved) throw new BadRequestException('Im kleinen Beispiel nur Boolean, Int16, Int32/TIME und Float: ' + name);
const access = Number(meta[2].value.value);
const duration = /time/i.test(typeName.value.value?.name ?? '') || /^VerzSignal(Kommt|Geht)$/.test(name);
fields.push({ name, nodeId: ref.nodeId.toString(), dataType: type.value === 1 ? 'Boolean' : type.value === 4 ? 'Int16' : type.value === 10 ? 'Float' : 'Int32', readable: !!(access & 1), writable: !!(access & 2), unit: duration ? 'ms' : '' });
}
return fields;
}
async inspect(input: StructureInput) {
validateStructureInput(input);
const connection = await this.opc.openStructureSession(input.anlageId, input.connectionId);
try {
const fields = await this.inspectFields(connection.session, input.rootNodeId.trim());
if (fields.some(f => input.direction === 'read' ? !f.readable : !f.writable)) throw new BadRequestException('Mindestens ein Feld erlaubt die gewählte Zugriffsrichtung für diesen OPC-Benutzer nicht.');
await connection.assertCurrent();
return fields;
} finally { await connection.close(); }
}
async create(input: StructureInput) {
const fields = await this.inspect(input);
await this.config.checkPlant(input.anlageId);
try {
const row = await this.model.create({ ...input, rootNodeId: input.rootNodeId.trim(), fields, id: randomUUID(), version: 1 });
return { anlageId: row.anlageId, id: row.id, version: row.version, name: row.name, connectionId: row.connectionId, rootNodeId: row.rootNodeId, direction: row.direction, fields: row.fields };
} catch (error) {
if ((error as { code?: number }).code === 11000) throw new ConflictException('Dieser Variablenname ist bereits angelegt');
throw error;
}
}
async remove(anlageId: string, name: string, id: string, version: number) {
const row = await this.get(anlageId, name);
if (id !== row.id || !Number.isSafeInteger(version) || version !== row.version) throw new ConflictException('Struktur geändert');
const result = await this.model.deleteOne({ anlageId, name, id: row.id, version });
if (result.deletedCount !== 1) throw new ConflictException('Struktur geändert');
return { deleted: true };
}
async write(anlageId: string, name: string, input: { id: string; version: number; values: Record<string, unknown> }, beforeWrite?: () => Promise<void>) {
const row = await this.get(anlageId, name), entries = validateStructureWrite(row, input);
const connection = await this.opc.openStructureSession(anlageId, row.connectionId);
try {
const current = await this.inspectFields(connection.session, row.rootNodeId);
if (JSON.stringify([...current].sort((a,b) => a.name.localeCompare(b.name, 'en'))) !== JSON.stringify([...row.fields].sort((a,b) => a.name.localeCompare(b.name, 'en')))) throw new ConflictException('CPU-Struktur oder Zugriffsrechte geändert. Struktur neu einlesen.');
await connection.assertCurrent(); await this.assertCurrent(row);
await beforeWrite?.();
// Exactly one write request; results can be partial. Never retry a write automatically.
const results = await connection.session.write(entries.map(({ field, value }) => ({ nodeId: field.nodeId, attributeId: AttributeIds.Value,
value: { value: { dataType: DataType[field.dataType], value } } })));
return { writtenAt: new Date().toISOString(), results: results.map((status, index) => ({ field: entries[index].field.name, good: status.isGood(), status: status.toString() })) };
} catch (error) {
if (error instanceof BadRequestException || error instanceof ConflictException) throw error;
throw new BadRequestException('Schreibergebnis unbekannt. Keine automatische Wiederholung; CPU-Rückmeldung prüfen.');
} finally { await connection.close(); }
}
}
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from '@jest/globals';
import { validateStructureInput, validateStructureWrite } from './structures.validation';
import type { OpcStructure } from './structures.types';
const row: OpcStructure = { anlageId: 'a', id: 'id', version: 1, name: 'GrenzwertSoll_0', direction: 'write', connectionId: 'cpu', rootNodeId: 'ns=3;s=Soll[0]', fields: [
{ name: 'ErsatzwertValue', nodeId: 'ns=3;s=value', dataType: 'Boolean', readable: false, writable: true, unit: '' },
{ name: 'VerzSignalKommt', nodeId: 'ns=3;s=time', dataType: 'Int32', readable: false, writable: true, unit: 'ms' },
] };
describe('Named OPC structures', () => {
it('accepts finite REAL fractions and rejects nonnumeric or overflowing values',()=>{
const structure={...row,fields:[{...row.fields[0],name:'IstStrom',dataType:'Float' as const}]};
for(const value of [0,3.25,-42.5])expect(validateStructureWrite(structure,{id:row.id,version:1,values:{IstStrom:value}})[0].value).toBe(value);
for(const value of [NaN,Infinity,1e100,'3.25'])expect(()=>validateStructureWrite(structure,{id:row.id,version:1,values:{IstStrom:value}})).toThrow();
});
it('accepts variable names and rejects unsupported directions and missing addresses', () => {
expect(() => validateStructureInput(row)).not.toThrow();
for (const patch of [{ name: '__proto__' }, { name: '0wrong' }, { name: 'a.b' }, { direction: 'both' }, { rootNodeId: '' }, { connectionId: '' }]) expect(() => validateStructureInput({ ...row, ...patch })).toThrow();
});
it('validates Int16 write bounds without coercion',()=>{
const structure = {...row,fields:[{...row.fields[0],name:'M1',dataType:'Int16' as const}]};
for(const value of [-32768,0,32767])expect(validateStructureWrite(structure,{id:row.id,version:1,values:{M1:value}})[0].value).toBe(value);
for(const value of [-32769,32768,0.5,'1'])expect(()=>validateStructureWrite(structure,{id:row.id,version:1,values:{M1:value}})).toThrow();
});
it('preserves explicit false and signed Int32 millisecond values', () => {
const entries = validateStructureWrite(row, { id: row.id, version: 1, values: { ErsatzwertValue: false, VerzSignalKommt: 1500 } });
expect(entries.map(e => e.value)).toEqual([false, 1500]);
expect(validateStructureWrite(row, { id: row.id, version: 1, values: { VerzSignalKommt: -2147483648 } })[0].value).toBe(-2147483648);
});
it('rejects coercion, overflow, unknown fields, stale versions and empty writes', () => {
for (const values of [{ ErsatzwertValue: 'false' }, { VerzSignalKommt: 0.5 }, { VerzSignalKommt: 2147483648 }, { VerzSignalKommt: NaN }, { Unknown: true }, {}])
expect(() => validateStructureWrite(row, { id: row.id, version: 1, values })).toThrow();
expect(() => validateStructureWrite(row, { id: 'recreated', version: 1, values: { ErsatzwertValue: true } })).toThrow();
expect(() => validateStructureWrite(row, { id: row.id, version: 2, values: { ErsatzwertValue: true } })).toThrow();
});
it('never permits writes to read definitions or readonly fields', () => {
expect(() => validateStructureWrite({ ...row, direction: 'read' }, { id: row.id, version: 1, values: { ErsatzwertValue: true } })).toThrow();
expect(() => validateStructureWrite({ ...row, fields: row.fields.map(f => ({ ...f, writable: false })) }, { id: row.id, version: 1, values: { ErsatzwertValue: true } })).toThrow();
});
});
+4
View File
@@ -0,0 +1,4 @@
export interface StructureField { name: string; nodeId: string; dataType: 'Boolean' | 'Int16' | 'Int32' | 'Float'; readable: boolean; writable: boolean; unit: string }
export interface OpcStructure { anlageId: string; id: string; version: number; name: string; connectionId: string; rootNodeId: string; direction: 'read' | 'write'; fields: StructureField[]; templateId?: string; bindings?: Pick<StructureField, 'name' | 'nodeId' | 'readable' | 'writable'>[] }
export interface StructureValue { value: boolean | number | null; good: boolean; status: string; sourceTimestamp: string | null }
export interface StructureSnapshot { name: string; status: 'connecting' | 'online' | 'partial' | 'offline'; values: Record<string, boolean | number | null>; fields: Record<string, StructureValue>; updatedAt: string; error?: string }
@@ -0,0 +1,21 @@
import { BadRequestException } from '@nestjs/common';
import type { OpcStructure } from './structures.types';
export function validateStructureInput(input: { name: string; direction: string; rootNodeId: string; connectionId: string }) {
if (!input || typeof input.name !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]{0,79}$/.test(input.name) || ['__proto__', 'constructor', 'prototype'].includes(input.name) ||
!['read', 'write'].includes(input.direction) || typeof input.rootNodeId !== 'string' || !input.rootNodeId.trim() || input.rootNodeId.length > 2048 ||
typeof input.connectionId !== 'string' || !input.connectionId)
throw new BadRequestException('Name, Richtung, Verbindung und Struktur-NodeId prüfen. Name z. B. GrenzwertIst_0.');
}
export function validateStructureWrite(structure: OpcStructure, input: { id: string; version: number; values: Record<string, unknown> }) {
if (structure.direction !== 'write') throw new BadRequestException('Lesestrukturen sind nicht beschreibbar');
if (!input || input.id !== structure.id || input.version !== structure.version) throw new BadRequestException('Struktur geändert. Neu laden.');
if (!input.values || typeof input.values !== 'object' || Array.isArray(input.values) || !Object.keys(input.values).length || Object.keys(input.values).length > 30)
throw new BadRequestException('Mindestens ein Feld auswählen');
return Object.entries(input.values).map(([name, value]) => {
const field = structure.fields.find(f => f.name === name);
if (!field?.writable) throw new BadRequestException('Feld nicht zum Schreiben freigegeben: ' + name);
if (field.dataType === 'Boolean' ? typeof value !== 'boolean' : typeof value !== 'number' || !Number.isFinite(value) || (field.dataType === 'Float' ? !Number.isFinite(Math.fround(value)) : !Number.isInteger(value) || value < (field.dataType === 'Int16' ? -32768 : -2147483648) || value > (field.dataType === 'Int16' ? 32767 : 2147483647)))
throw new BadRequestException('Ungültiger Wert für ' + name + ': ' + field.dataType + ' im gültigen Wertebereich erwartet');
return { field, value: value as boolean | number };
});
}