Implement memory map and arithmetic logic

This commit is contained in:
2025-12-21 23:35:08 +09:00
parent a459b81884
commit d459bf4e9f
3 changed files with 220 additions and 19 deletions

86
App.tsx
View File

@@ -9,7 +9,8 @@ import { LadderEditor } from './components/LadderEditor';
import { SystemSetupDialog } from './components/SystemSetupDialog'; import { SystemSetupDialog } from './components/SystemSetupDialog';
import { import {
SimObject, ObjectType, AxisObject, CylinderObject, SwitchObject, LedObject, SimObject, ObjectType, AxisObject, CylinderObject, SwitchObject, LedObject,
IOLogicRule, LogicCondition, LogicAction, ProjectData, AxisData, LogicTriggerType, LogicActionType IOLogicRule, LogicCondition, LogicAction, ProjectData, AxisData, LogicTriggerType, LogicActionType,
LogicMathOp, MEMORY_SIZE, ADDR_AXIS_BASE, ADDR_AXIS_STRIDE, OFF_AXIS_CURRENT_POS, OFF_AXIS_TARGET_POS
} from './types'; } from './types';
import { EditableObject } from './components/SceneObjects'; import { EditableObject } from './components/SceneObjects';
import { Layout as LayoutIcon, Cpu, Play, Pause, Square, Download, Upload, Magnet, Settings } from 'lucide-react'; import { Layout as LayoutIcon, Cpu, Play, Pause, Square, Download, Upload, Magnet, Settings } from 'lucide-react';
@@ -36,7 +37,8 @@ const SimulationLoop = ({
setInputs: (inputs: boolean[]) => void, setInputs: (inputs: boolean[]) => void,
setOutputs: (outputs: boolean[]) => void, setOutputs: (outputs: boolean[]) => void,
axes: AxisData[], axes: AxisData[],
setAxes: React.Dispatch<React.SetStateAction<AxisData[]>> setAxes: React.Dispatch<React.SetStateAction<AxisData[]>>,
memoryView: React.MutableRefObject<DataView>
}) => { }) => {
useFrame((state, delta) => { useFrame((state, delta) => {
@@ -64,6 +66,25 @@ const SimulationLoop = ({
const effectiveInputs = sensorInputs.map((bit, i) => bit || manualInputs[i]); const effectiveInputs = sensorInputs.map((bit, i) => bit || manualInputs[i]);
setInputs(effectiveInputs); setInputs(effectiveInputs);
// --- 1. Memory IO Scan (Axis Global State -> Memory) ---
// Update Memory Mapped Axis Areas (Read Current Pos from App State)
// In a real PLC, this happens at the start of scan.
axes.forEach(axis => {
const base = ADDR_AXIS_BASE + (axis.id * ADDR_AXIS_STRIDE);
// 0: Status (Uint16) - reserved
memoryView.current.setUint16(base, 0, true);
// 2: Current Pos (Float32)
memoryView.current.setFloat32(base + OFF_AXIS_CURRENT_POS, axis.value, true);
// 10: Speed (Float32)
memoryView.current.setFloat32(base + 10, axis.speed, true);
// Sync Target to memory if it wasn't written by logic, or initialize it
// (Optional: In strict PLC, memory drives axis. If we want UI slider to work, UI must write to memory OR axis. Logic takes precedence)
// Here we write the *current* target to memory so logic sees it, unless logic overwrites it.
// Check if we need to sync? For now, let's write it so 'readback' works.
// memoryView.current.setFloat32(base + OFF_AXIS_TARGET_POS, axis.target, true);
});
// --- 2. PLC Logic Execution --- // --- 2. PLC Logic Execution ---
const logicOutputs = new Array(32).fill(false); const logicOutputs = new Array(32).fill(false);
@@ -79,6 +100,7 @@ const SimulationLoop = ({
const inputState = effectiveInputs[rule.inputPort]; const inputState = effectiveInputs[rule.inputPort];
conditionMet = inputState; // Default IS_ON behavior for now conditionMet = inputState; // Default IS_ON behavior for now
} else if (rule.triggerType === LogicTriggerType.AXIS_COMPARE) { } else if (rule.triggerType === LogicTriggerType.AXIS_COMPARE) {
// Legacy Axis Compare
const axis = axes[rule.triggerAxisIndex]; const axis = axes[rule.triggerAxisIndex];
if (axis) { if (axis) {
switch (rule.triggerCompareOp) { switch (rule.triggerCompareOp) {
@@ -87,6 +109,18 @@ const SimulationLoop = ({
case LogicCondition.EQUAL: conditionMet = Math.abs(axis.value - rule.triggerValue) < 0.1; break; case LogicCondition.EQUAL: conditionMet = Math.abs(axis.value - rule.triggerValue) < 0.1; break;
} }
} }
} else if (rule.triggerType === LogicTriggerType.MEM_COMPARE) {
// Memory Compare
// Read 4 bytes at address as Float32 (Standardize on Float for M-registers for now)
const addr = rule.triggerAddress || 0;
if (addr >= 0 && addr < MEMORY_SIZE - 4) {
const val = memoryView.current.getFloat32(addr, true);
switch (rule.triggerCompareOp) {
case LogicCondition.GREATER: conditionMet = val > rule.triggerValue; break;
case LogicCondition.LESS: conditionMet = val < rule.triggerValue; break;
case LogicCondition.EQUAL: conditionMet = Math.abs(val - rule.triggerValue) < 0.001; break;
}
}
} }
// 2. Execute Action if Trigger Met // 2. Execute Action if Trigger Met
@@ -96,7 +130,28 @@ const SimulationLoop = ({
logicOutputs[rule.outputPort] = true; logicOutputs[rule.outputPort] = true;
} }
} else if (rule.actionType === LogicActionType.AXIS_MOVE) { } else if (rule.actionType === LogicActionType.AXIS_MOVE) {
// Legacy Move: Directly set Axis Target
axisUpdates.set(rule.targetAxisIndex, rule.targetAxisValue); axisUpdates.set(rule.targetAxisIndex, rule.targetAxisValue);
// Also update Memory Map for consistency
const base = ADDR_AXIS_BASE + (rule.targetAxisIndex * ADDR_AXIS_STRIDE);
if (base < MEMORY_SIZE) memoryView.current.setFloat32(base + OFF_AXIS_TARGET_POS, rule.targetAxisValue, true);
} else if (rule.actionType === LogicActionType.MEM_OPERATION) {
// Memory Math
const addr = rule.memAddress || 0;
if (addr >= 0 && addr < MEMORY_SIZE - 4) {
let currentVal = memoryView.current.getFloat32(addr, true);
let newVal = currentVal;
switch (rule.memOperation) {
case LogicMathOp.SET: newVal = rule.memOperandValue; break;
case LogicMathOp.ADD: newVal = currentVal + rule.memOperandValue; break;
case LogicMathOp.SUB: newVal = currentVal - rule.memOperandValue; break;
}
memoryView.current.setFloat32(addr, newVal, true);
}
} }
} }
}); });
@@ -105,7 +160,27 @@ const SimulationLoop = ({
const effectiveOutputs = logicOutputs.map((bit, i) => bit || manualOutputs[i]); const effectiveOutputs = logicOutputs.map((bit, i) => bit || manualOutputs[i]);
setOutputs(effectiveOutputs); setOutputs(effectiveOutputs);
// Apply Axis Logic Updates (Only if changed to prevent thrashing) // --- 3. Memory Output Scan (Memory -> Axis Command) ---
// Read Target Position from Memory for each axis and apply to State
axes.forEach(axis => {
const base = ADDR_AXIS_BASE + (axis.id * ADDR_AXIS_STRIDE);
const memTarget = memoryView.current.getFloat32(base + OFF_AXIS_TARGET_POS, true);
// Simple change detection (epsilon) or just overwrite if non-zero?
// Issue: If UI Slider sets axis.target, and memory has 0, memory overwrites UI.
// User Requirement: "write to memory... motor moves".
// So Memory is the source of truth for Target.
// But initially memory is 0. So Axis goes to 0?
// Workaround: If memory target is exactly 0 and axis is not 0, maybe don't force?
// Better: Initialize Memory with Axis Target on startup.
// For now, let's assume Logic drives Memory.
if (memTarget !== axis.target && Math.abs(memTarget - axis.target) > 0.001) {
axisUpdates.set(axis.id, memTarget);
}
});
// Apply Axis Logic Updates
if (axisUpdates.size > 0) { if (axisUpdates.size > 0) {
setAxes(prev => prev.map(a => { setAxes(prev => prev.map(a => {
if (axisUpdates.has(a.id)) { if (axisUpdates.has(a.id)) {
@@ -179,6 +254,10 @@ const SimulationLoop = ({
export default function App() { export default function App() {
const [activeView, setActiveView] = useState<'layout' | 'logic'>('layout'); const [activeView, setActiveView] = useState<'layout' | 'logic'>('layout');
// --- Memory System (Ref-based, high frequency) ---
const memoryBuffer = useRef(new ArrayBuffer(MEMORY_SIZE)); // 10000 bytes
const memoryView = useRef(new DataView(memoryBuffer.current));
const [objects, setObjects] = useState<SimObject[]>([]); const [objects, setObjects] = useState<SimObject[]>([]);
const [logicRules, setLogicRules] = useState<IOLogicRule[]>([]); const [logicRules, setLogicRules] = useState<IOLogicRule[]>([]);
@@ -493,6 +572,7 @@ export default function App() {
setOutputs={setOutputs} setOutputs={setOutputs}
axes={axes} axes={axes}
setAxes={setAxes} setAxes={setAxes}
memoryView={memoryView}
/> />
</Canvas> </Canvas>
</div> </div>

View File

@@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
import { Trash2, PlusCircle, Power, Zap, Gauge, Move } from 'lucide-react'; import { Trash2, PlusCircle, Power, Zap, Gauge, Move, Calculator, Cpu } from 'lucide-react';
import { IOLogicRule, LogicCondition, LogicAction, LogicTriggerType, LogicActionType, AxisData } from '../types'; import { IOLogicRule, LogicCondition, LogicAction, LogicTriggerType, LogicActionType, AxisData, LogicMathOp, ADDR_AXIS_BASE, OFF_AXIS_TARGET_POS, ADDR_AXIS_STRIDE, MEMORY_SIZE } from '../types';
interface LadderEditorProps { interface LadderEditorProps {
logicRules: IOLogicRule[]; logicRules: IOLogicRule[];
@@ -44,11 +44,15 @@ export const LadderEditor: React.FC<LadderEditorProps> = ({
triggerAxisIndex: 0, triggerAxisIndex: 0,
triggerCompareOp: LogicCondition.GREATER, triggerCompareOp: LogicCondition.GREATER,
triggerValue: 0, triggerValue: 0,
triggerAddress: 0,
actionType: LogicActionType.OUTPUT_COIL, actionType: LogicActionType.OUTPUT_COIL,
outputPort: 0, outputPort: 0,
action: LogicAction.SET_ON, action: LogicAction.SET_ON,
targetAxisIndex: 0, targetAxisIndex: 0,
targetAxisValue: 0 targetAxisValue: 0,
memAddress: 0,
memOperation: LogicMathOp.SET,
memOperandValue: 0
})} })}
className="flex items-center gap-2 bg-blue-600 hover:bg-blue-500 text-white px-4 py-1.5 rounded-full text-xs font-bold transition-all transform active:scale-95" className="flex items-center gap-2 bg-blue-600 hover:bg-blue-500 text-white px-4 py-1.5 rounded-full text-xs font-bold transition-all transform active:scale-95"
> >
@@ -67,8 +71,11 @@ export const LadderEditor: React.FC<LadderEditorProps> = ({
{logicRules.map((rule, index) => { {logicRules.map((rule, index) => {
const isInputTrigger = rule.triggerType === LogicTriggerType.INPUT_BIT; const isInputTrigger = rule.triggerType === LogicTriggerType.INPUT_BIT;
const isAxisTrigger = rule.triggerType === LogicTriggerType.AXIS_COMPARE; const isAxisTrigger = rule.triggerType === LogicTriggerType.AXIS_COMPARE;
const isMemTrigger = rule.triggerType === LogicTriggerType.MEM_COMPARE;
const isOutputAction = rule.actionType === LogicActionType.OUTPUT_COIL; const isOutputAction = rule.actionType === LogicActionType.OUTPUT_COIL;
const isAxisAction = rule.actionType === LogicActionType.AXIS_MOVE; const isAxisAction = rule.actionType === LogicActionType.AXIS_MOVE;
const isMemAction = rule.actionType === LogicActionType.MEM_OPERATION;
const inputActive = isInputTrigger && currentInputs[rule.inputPort]; const inputActive = isInputTrigger && currentInputs[rule.inputPort];
const outputActive = isOutputAction && currentOutputs[rule.outputPort]; const outputActive = isOutputAction && currentOutputs[rule.outputPort];
@@ -103,6 +110,12 @@ export const LadderEditor: React.FC<LadderEditorProps> = ({
> >
<Gauge size={10} /> Axis Logic <Gauge size={10} /> Axis Logic
</button> </button>
<button
onClick={() => onUpdateRule(rule.id, { triggerType: LogicTriggerType.MEM_COMPARE })}
className={`flex items-center gap-1 text-[10px] uppercase font-bold px-2 py-0.5 rounded border ${isMemTrigger ? 'bg-purple-500/10 border-purple-500 text-purple-500' : 'border-transparent text-gray-600 hover:bg-gray-800'}`}
>
<Cpu size={10} /> Memory
</button>
</div> </div>
<div className="h-16 bg-gray-950 border border-gray-800 rounded-lg flex items-center justify-center relative p-2"> <div className="h-16 bg-gray-950 border border-gray-800 rounded-lg flex items-center justify-center relative p-2">
@@ -119,7 +132,7 @@ export const LadderEditor: React.FC<LadderEditorProps> = ({
</select> </select>
</div> </div>
</div> </div>
) : ( ) : isAxisTrigger ? (
<div className="flex items-center gap-2 w-full"> <div className="flex items-center gap-2 w-full">
<select <select
className="bg-gray-900 border border-gray-700 rounded text-[10px] text-white px-2 py-1 w-20 outline-none" className="bg-gray-900 border border-gray-700 rounded text-[10px] text-white px-2 py-1 w-20 outline-none"
@@ -144,6 +157,37 @@ export const LadderEditor: React.FC<LadderEditorProps> = ({
onChange={(e) => onUpdateRule(rule.id, { triggerValue: parseFloat(e.target.value) })} onChange={(e) => onUpdateRule(rule.id, { triggerValue: parseFloat(e.target.value) })}
/> />
</div> </div>
) : (
// MEMORY TRIGGER
<div className="flex items-center gap-1 w-full justify-center">
<div className="flex flex-col">
<span className="text-[9px] text-gray-500 font-bold ml-1">ADDR</span>
<input
type="text"
className="bg-gray-900 border border-gray-700 rounded text-[10px] text-purple-400 px-2 py-1 w-16 outline-none font-mono"
value={rule.triggerAddress || 0}
onChange={(e) => onUpdateRule(rule.id, { triggerAddress: parseInt(e.target.value) || 0 })}
/>
</div>
<select
className="bg-gray-900 border border-gray-700 rounded text-[10px] text-white px-1 py-1 w-10 text-center outline-none"
value={rule.triggerCompareOp}
onChange={(e) => onUpdateRule(rule.id, { triggerCompareOp: e.target.value as LogicCondition })}
>
<option value={LogicCondition.GREATER}>&gt;</option>
<option value={LogicCondition.LESS}>&lt;</option>
<option value={LogicCondition.EQUAL}>=</option>
</select>
<div className="flex flex-col">
<span className="text-[9px] text-gray-500 font-bold ml-1">VAL</span>
<input
type="number"
className="bg-gray-900 border border-gray-700 rounded text-[10px] text-white px-2 py-1 w-16 outline-none"
value={rule.triggerValue}
onChange={(e) => onUpdateRule(rule.id, { triggerValue: parseFloat(e.target.value) })}
/>
</div>
</div>
)} )}
</div> </div>
</div> </div>
@@ -166,6 +210,12 @@ export const LadderEditor: React.FC<LadderEditorProps> = ({
> >
<Move size={10} /> Move Axis <Move size={10} /> Move Axis
</button> </button>
<button
onClick={() => onUpdateRule(rule.id, { actionType: LogicActionType.MEM_OPERATION })}
className={`flex items-center gap-1 text-[10px] uppercase font-bold px-2 py-0.5 rounded border ${isMemAction ? 'bg-purple-500/10 border-purple-500 text-purple-500' : 'border-transparent text-gray-600 hover:bg-gray-800'}`}
>
<Calculator size={10} /> Math
</button>
</div> </div>
<div className="h-16 bg-gray-950 border border-gray-800 rounded-lg flex items-center justify-center relative p-2"> <div className="h-16 bg-gray-950 border border-gray-800 rounded-lg flex items-center justify-center relative p-2">
@@ -182,13 +232,17 @@ export const LadderEditor: React.FC<LadderEditorProps> = ({
</select> </select>
</div> </div>
</div> </div>
) : ( ) : isAxisAction ? (
<div className="flex items-center gap-2 w-full"> <div className="flex items-center gap-2 w-full">
<span className="text-[9px] text-gray-500 font-bold">MOVE</span> <span className="text-[9px] text-gray-500 font-bold">MOVE</span>
<select <select
className="bg-gray-900 border border-gray-700 rounded text-[10px] text-white px-2 py-1 w-20 outline-none" className="bg-gray-900 border border-gray-700 rounded text-[10px] text-white px-2 py-1 w-20 outline-none"
value={rule.targetAxisIndex} value={rule.targetAxisIndex}
onChange={(e) => onUpdateRule(rule.id, { targetAxisIndex: parseInt(e.target.value) })} onChange={(e) => {
const axisId = parseInt(e.target.value);
// Use new Memory Write if possible, but keep legacy support in data
onUpdateRule(rule.id, { targetAxisIndex: axisId });
}}
> >
{axes.map(a => <option key={a.id} value={a.id}>CH{a.id}</option>)} {axes.map(a => <option key={a.id} value={a.id}>CH{a.id}</option>)}
</select> </select>
@@ -201,6 +255,37 @@ export const LadderEditor: React.FC<LadderEditorProps> = ({
onChange={(e) => onUpdateRule(rule.id, { targetAxisValue: parseFloat(e.target.value) })} onChange={(e) => onUpdateRule(rule.id, { targetAxisValue: parseFloat(e.target.value) })}
/> />
</div> </div>
) : (
// MEMORY ACTION
<div className="flex items-center gap-1 w-full justify-center">
<div className="flex flex-col">
<span className="text-[9px] text-gray-500 font-bold ml-1">ADDR</span>
<input
type="text"
className="bg-gray-900 border border-gray-700 rounded text-[10px] text-purple-400 px-2 py-1 w-16 outline-none font-mono"
value={rule.memAddress || 0}
onChange={(e) => onUpdateRule(rule.id, { memAddress: parseInt(e.target.value) || 0 })}
/>
</div>
<select
className="bg-gray-900 border border-gray-700 rounded text-[10px] text-white px-1 py-1 w-10 text-center outline-none"
value={rule.memOperation}
onChange={(e) => onUpdateRule(rule.id, { memOperation: e.target.value as LogicMathOp })}
>
<option value={LogicMathOp.SET}>=</option>
<option value={LogicMathOp.ADD}>+</option>
<option value={LogicMathOp.SUB}>-</option>
</select>
<div className="flex flex-col">
<span className="text-[9px] text-gray-500 font-bold ml-1">VAL</span>
<input
type="number"
className="bg-gray-900 border border-gray-700 rounded text-[10px] text-white px-2 py-1 w-16 outline-none"
value={rule.memOperandValue}
onChange={(e) => onUpdateRule(rule.id, { memOperandValue: parseFloat(e.target.value) })}
/>
</div>
</div>
)} )}
</div> </div>
</div> </div>

View File

@@ -67,17 +67,34 @@ export interface LedObject extends BaseObject {
outputPort: number; // Reads this Output bit to turn on outputPort: number; // Reads this Output bit to turn on
} }
// Memory Map Constants
export const MEMORY_SIZE = 10000;
export const ADDR_USER_START = 0;
export const ADDR_USER_END = 7999;
export const ADDR_AXIS_BASE = 8000;
export const ADDR_AXIS_STRIDE = 100;
// Axis Memory Layout (Offsets from Axis Base)
export const OFF_AXIS_STATUS = 0; // Uint16
export const OFF_AXIS_CURRENT_POS = 2; // Float32
export const OFF_AXIS_TARGET_POS = 6; // Float32
export const OFF_AXIS_SPEED = 10; // Float32
export const OFF_AXIS_ACCEL = 14; // Float32
export const OFF_AXIS_DECEL = 18; // Float32
export type SimObject = AxisObject | CylinderObject | SwitchObject | LedObject; export type SimObject = AxisObject | CylinderObject | SwitchObject | LedObject;
// Logic Types // Logic Types
export enum LogicTriggerType { export enum LogicTriggerType {
INPUT_BIT = 'INPUT_BIT', INPUT_BIT = 'INPUT_BIT',
AXIS_COMPARE = 'AXIS_COMPARE', AXIS_COMPARE = 'AXIS_COMPARE', // Deprecated in favor of MEM_COMPARE, but kept for compatibility
MEM_COMPARE = 'MEM_COMPARE',
} }
export enum LogicActionType { export enum LogicActionType {
OUTPUT_COIL = 'OUTPUT_COIL', OUTPUT_COIL = 'OUTPUT_COIL',
AXIS_MOVE = 'AXIS_MOVE', AXIS_MOVE = 'AXIS_MOVE', // Deprecated in favor of Memory Write
MEM_OPERATION = 'MEM_OPERATION',
} }
export enum LogicCondition { export enum LogicCondition {
@@ -90,12 +107,18 @@ export enum LogicCondition {
LESS_EQUAL = '<=', LESS_EQUAL = '<=',
} }
export enum LogicMathOp {
SET = '=',
ADD = '+',
SUB = '-',
}
export enum LogicAction { export enum LogicAction {
SET_ON = 'ON', SET_ON = 'ON',
SET_OFF = 'OFF', SET_OFF = 'OFF',
TOGGLE = 'TOGGLE', TOGGLE = 'TOGGLE',
MOVE_ABS = 'MOVE_ABS', MOVE_ABS = 'MOVE_ABS', // Legacy
MOVE_REL = 'MOVE_REL', MOVE_REL = 'MOVE_REL', // Legacy
} }
export interface IOLogicRule { export interface IOLogicRule {
@@ -105,16 +128,27 @@ export interface IOLogicRule {
// Trigger // Trigger
triggerType: LogicTriggerType; triggerType: LogicTriggerType;
inputPort: number; // For INPUT_BIT inputPort: number; // For INPUT_BIT
triggerAxisIndex: number; // For AXIS_COMPARE
triggerCompareOp: LogicCondition; // For AXIS_COMPARE (>, <, ==) // Axis/Memory Trigger
triggerValue: number; // For AXIS_COMPARE triggerAxisIndex: number; // For AXIS_COMPARE (Legacy)
triggerCompareOp: LogicCondition; // >, <, ==
triggerValue: number; // For AXIS_COMPARE (Legacy) or MEM_COMPARE Constant
triggerAddress: number; // For MEM_COMPARE (Address to check)
// Action // Action
actionType: LogicActionType; actionType: LogicActionType;
outputPort: number; // For OUTPUT_COIL outputPort: number; // For OUTPUT_COIL
action: LogicAction; // For OUTPUT_COIL (ON/OFF) action: LogicAction; // For OUTPUT_COIL
targetAxisIndex: number; // For AXIS_MOVE
targetAxisValue: number; // For AXIS_MOVE // Axis Action (Legacy)
targetAxisIndex: number;
targetAxisValue: number;
// Memory Action
memAddress: number; // Address to write to
memOperation: LogicMathOp; // =, +, -
memOperandValue: number; // Value to add/sub/set
} }
// Full Project Export Type // Full Project Export Type
@@ -125,4 +159,6 @@ export interface ProjectData {
inputNames: string[]; inputNames: string[];
outputNames: string[]; outputNames: string[];
axes: AxisData[]; axes: AxisData[];
// Memory snapshot could be large, maybe store only non-zero or user logic?
// For now, we won't persist full RAM, only config.
} }