opc meldunge parameter fehler io

This commit is contained in:
marco committed 2026-10-30 15:42:23 +01:00
1 parent 58338ee07c
commit 0e7b53e558
87 files changed
+1500 -8

No files matched your search

+70
View File
@@ -0,0 +1,70 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import Modal from '@/components/ui/Modal';
import MotorControl from './motorControl';
import { SensorStatus } from '@/components/sensoren/digitalLiveStatus';
import { api_digitalLiveScene, api_digitalSensorLive } from '@/actions/sensoren/api-digital-opc';
import { liveSceneBounds, liveSceneDraws } from '@/lib/sensoren/live-scene';
import { motorStatus, operatingMode } from '@/lib/sensoren/motor-status';
import type { DigitalLiveScene, DigitalSensorLive } from '@/types/digital-opc';
import type { StructureSnapshot } from '@/types/opcua-structures';
function SensorDialog({ id, anlageId, onClose }: { id: string; anlageId: string; onClose: () => void }) {
const [data,setData] = useState<DigitalSensorLive | null>(null), [error,setError] = useState('');
useEffect(() => { let active = true; api_digitalSensorLive(id,anlageId).then(row => { if(active) setData(row); }).catch(cause => { if(active) setError(cause instanceof Error ? cause.message : 'Sensor nicht erreichbar'); }); return () => { active = false; }; },[id,anlageId]);
return <Modal onClose={onClose}><div role="dialog" aria-label="Sensorstatus und Bedienung" className="max-h-[85dvh] w-[min(54rem,85vw)] overflow-auto pr-5"><h2 className="mb-3 font-semibold">Sensorstatus und Bedienung</h2>{data ? <SensorStatus data={data} /> : <p role={error ? 'alert' : 'status'}>{error || 'Sensor wird geladen …'}</p>}<Button size="sm" variant="secondary" onClick={onClose}>Schließen</Button></div></Modal>;
}
export default function LiveAnlage({ initial }: { initial: DigitalLiveScene }) {
const [scene,setScene] = useState(initial), [snapshots,setSnapshots] = useState<Record<string,StructureSnapshot>>({});
const [viewport,setViewport] = useState(() => liveSceneBounds(initial)), [hand,setHand] = useState(false), [selected,setSelected] = useState('');
const [filter,setFilter] = useState(''), [error,setError] = useState(''), [busy,setBusy] = useState(false);
const svg = useRef<SVGSVGElement>(null), drag = useRef<{ x:number; y:number; box:typeof viewport } | null>(null);
useEffect(() => {
setSnapshots({}); setError(''); if(!scene.sensors.some(s => s.ist)&&!(scene.motors??[]).some(m=>m.structure||m.operatingMode||m.parameters)) return;
let active = true;
const source = new EventSource('/live-anlage/events?anlageId=' + encodeURIComponent(scene.anlageId) + '&token=' + encodeURIComponent(scene.token));
source.onmessage = event => {
if(!active) return;
try { const data = JSON.parse(event.data);
if(data.type === 'reload') { setSnapshots({}); setError(data.error); source.close(); }
else if(['sensor','motor','motorMode','motorParameters'].includes(data.type)) setSnapshots(old => ({ ...old, [(data.type==='sensor'?'':data.type+':')+data.sensorId]:data.snapshot }));
else if(data.type === 'empty') source.close();
} catch { setSnapshots({}); setError('Ungültige Live-Antwort'); }
};
source.onerror = () => { if(active) { setSnapshots({}); setError('Live-Verbindung unterbrochen. Wiederverbindung läuft.'); } };
source.onopen = () => { if(active) setError(''); };
return () => { active = false; source.close(); };
},[scene]);
async function reload() { if(busy) return; setBusy(true); setSelected(''); setSnapshots({}); try { const next = await api_digitalLiveScene(); setScene(next); setViewport(liveSceneBounds(next)); setError(''); } catch(cause) { setError(cause instanceof Error ? cause.message : 'Laden fehlgeschlagen'); } finally { setBusy(false); } }
function zoom(factor:number) { setViewport(v => ({x:v.x+v.width*(1-factor)/2,y:v.y+v.height*(1-factor)/2,width:v.width*factor,height:v.height*factor})); }
const selectedMotor = (scene.motors??[]).find(m=>'motor:'+m.componentId===selected);
const motorSnapshot = selectedMotor ? snapshots[selected] : undefined;
const selectedMotorValue = motorSnapshot?.status==='online'||motorSnapshot?.status==='partial' ? motorSnapshot.values[selectedMotor!.field] : null;
const selectedMotorStatus = motorStatus(selectedMotorValue);
const parameterSnapshot=selectedMotor?snapshots['motorParameters:'+selectedMotor.componentId]:undefined;
const parameterValues=parameterSnapshot?.status==='online'||parameterSnapshot?.status==='partial'?parameterSnapshot.values:{};
const modeSnapshot=selectedMotor?snapshots['motorMode:'+selectedMotor.componentId]:undefined;
const modeValue=modeSnapshot?.status==='online'||modeSnapshot?.status==='partial'?modeSnapshot.values.Value:null;
const draws = liveSceneDraws(scene, snapshots);
const visible = scene.sensors.filter(s => (s.sensor.datenNr+' '+s.sensor.beschreibung).toLowerCase().includes(filter.toLowerCase()));
const online = scene.sensors.filter(s => snapshots[s.sensor.id]?.status === 'online').length;
return <div className="space-y-3"><h1 className="text-xl font-semibold">Live-Anlagenansicht</h1><p className="text-sm">Digitale Sensoren und Motorkomponenten mit projektierten Positionen und echten CPU-Zuständen. Anklicken öffnet die Bedienung.</p>
<div className="flex flex-wrap items-center gap-2"><Button size="sm" variant="secondary" onClick={() => setViewport(liveSceneBounds(scene))}>Alles anzeigen</Button><Button size="sm" variant="secondary" onClick={() => zoom(0.8)}>+</Button><Button size="sm" variant="secondary" onClick={() => zoom(1.25)}>−</Button><Button size="sm" variant={hand ? 'primary':'secondary'} onClick={() => setHand(!hand)}>Hand / Verschieben</Button><Button size="sm" disabled={busy} onClick={() => void reload()}>Anlagenbild neu laden</Button><span className="text-xs">{online} / {scene.sensors.length} Sensoren online · {(scene.motors??[]).filter(m=>snapshots['motor:'+m.componentId]?.status==='online').length} / {(scene.motors??[]).length} Motoren online</span></div>
{error && <p role="alert" className="text-amber-700">{error}</p>}
<div className="grid gap-3 xl:grid-cols-[minmax(0,1fr)_16rem]"><div className="relative rounded border bg-slate-50">
<svg ref={svg} className={'h-[70dvh] w-full touch-none '+(hand?'cursor-grab':'')} role="img" aria-label="Live-Anlagenbild der Sensoren und Motorkomponenten" viewBox={[viewport.x,viewport.y,viewport.width,viewport.height].join(' ')}
onPointerDownCapture={e => { if(hand || e.button===1 || e.target===e.currentTarget) { e.preventDefault(); e.stopPropagation(); drag.current={x:e.clientX,y:e.clientY,box:viewport}; e.currentTarget.setPointerCapture(e.pointerId); } }}
onPointerMove={e => { const d=drag.current, node=svg.current; if(!d || !node) return; const rect=node.getBoundingClientRect(), scale=Math.min(rect.width/d.box.width,rect.height/d.box.height); setViewport({...d.box,x:d.box.x-(e.clientX-d.x)/scale,y:d.box.y-(e.clientY-d.y)/scale}); }}
onPointerUp={e => { drag.current=null; if(e.currentTarget.hasPointerCapture(e.pointerId))e.currentTarget.releasePointerCapture(e.pointerId); }} onPointerCancel={() => { drag.current=null; }}>
<title>Live-Anlagenbild – Sensoren und Motorkomponenten</title>
{draws.map((g,index) => <g key={g.id+':'+index} role="button" tabIndex={hand?-1:0} aria-label={g.name+(g.unknown?' – unbekannt':'')} className={hand?'':'cursor-pointer'} onClick={() => { if(!hand)setSelected(g.id); }} onKeyDown={e => { if(!hand && (e.key==='Enter'||e.key===' ')){e.preventDefault();setSelected(g.id);} }}>
<title>{g.name + (g.unknown ? ' – unbekannt' : '')}</title>{g.unknown ? <><rect x={g.p.x} y={g.p.y} width={g.p.width} height={g.p.height} fill="#fef3c7" fillOpacity={0.4} stroke="#b45309" strokeDasharray="4 3" vectorEffect="non-scaling-stroke"/><text x={g.p.x+g.p.width/2} y={g.p.y+g.p.height/2} textAnchor="middle" dominantBaseline="middle" fontSize={Math.min(g.p.width,g.p.height)*0.5} fill="#92400e">?</text></> : g.text ? <><rect x={g.p.x} y={g.p.y} width={g.p.width} height={g.p.height} fill="#f1f5f9" stroke="#475569" vectorEffect="non-scaling-stroke"/><text x={g.p.x+g.p.width/2} y={g.p.y+g.p.height/2} textAnchor="middle" dominantBaseline="middle" fontSize={Math.min(g.p.height*0.5,g.p.width/(g.text.length*0.65))} fill="#0f172a">{g.text}</text></> : <image x={g.p.x} y={g.p.y} width={g.p.width} height={g.p.height} preserveAspectRatio="none" href={'data:image/svg+xml;charset=utf-8,'+encodeURIComponent(g.svg)} />}
</g>)}
</svg>{!scene.sensors.length && !(scene.motors??[]).length && <p className="absolute left-4 top-4">Noch keine digitalen Sensoren oder Motorkomponenten projektiert.</p>}
</div><aside className="space-y-2 rounded border p-2"><Input placeholder="Sensor suchen" aria-label="Sensor im Anlagenbild suchen" value={filter} onChange={e => setFilter(e.target.value)} /><div className="max-h-[60dvh] overflow-auto">{visible.map(s => <button key={s.sensor.id} className="block w-full rounded p-2 text-left text-xs hover:bg-slate-100" onClick={() => setSelected(s.sensor.id)}>{s.sensor.datenNr} · {s.sensor.beschreibung}<span className="block text-gray-600">{s.issue || snapshots[s.sensor.id]?.status || 'Verbindungsaufbau'}</span></button>)}{(scene.motors??[]).filter(m=>(m.name+' '+m.antriebId).toLowerCase().includes(filter.toLowerCase())).map(m=><button key={m.componentId} className="block w-full rounded p-2 text-left text-xs hover:bg-slate-100" onClick={()=>setSelected('motor:'+m.componentId)}>{m.name}<span className="block text-gray-600">{m.field} · {m.issue||motorStatus(snapshots['motor:'+m.componentId]?.values[m.field])?.label||'Unbekannt'}</span></button>)}</div></aside></div>
<p className="text-xs text-gray-600">? bedeutet unbekannter Zustand oder fehlende Zustandsgrafik. Editor-Ebenen und temporäre Sichtbarkeit werden hier nicht angewendet. Diese Anlagenansicht zeigt digitale Sensoren und Motorkomponenten. Anzeigen und analoge Sensoren folgen separat.</p>
{selectedMotor && <Modal onClose={()=>setSelected('')}><div role="dialog" aria-label="Motorstatus" className="max-h-[80dvh] w-[min(40rem,85vw)] space-y-3 overflow-auto pr-5"><h2 className="font-semibold">{selectedMotor.name}</h2><p>Feld: {selectedMotor.field} · Struktur: {selectedMotor.structure?.name??'Keine Zuordnung'}</p><p>Statuscode: {selectedMotorValue===null||selectedMotorValue===undefined?'Unbekannt':String(selectedMotorValue)}</p><p>{selectedMotorStatus?.label??'Unbekannter oder ungültiger Status'}</p><p className="text-xs">Verbindung: {motorSnapshot?.status??'offline'} · Qualität: {motorSnapshot?.fields[selectedMotor.field]?.status??'Unbekannt'}</p><p>Betriebsart: {operatingMode(modeValue)??'Unbekannt'}</p><p>Restzeit: {typeof parameterValues.Restzeit==='number'?parameterValues.Restzeit+' s':'Unbekannt'}</p><p>Ist-Drehzahl: {parameterValues.IstDrehzahl??'Unbekannt'}</p><p>Ist-Strom: {parameterValues.IstStrom??'Unbekannt'}</p><p className="text-xs">Parameterqualität: {parameterSnapshot?.fields.Restzeit?.status??'Unbekannt'}</p><MotorControl key={selectedMotor.componentId} motor={selectedMotor} anlageId={scene.anlageId} online={!error&&motorSnapshot?.status==='online'} /><Button size="sm" onClick={()=>setSelected('')}>Schließen</Button></div></Modal>}
{selected && !selectedMotor && <SensorDialog key={selected} id={selected} anlageId={scene.anlageId} onClose={() => setSelected('')} />}
</div>;
}