All files triggerManager.ts

90.16% Statements 266/295
87.23% Branches 41/47
85.71% Functions 12/14
90.16% Lines 266/295

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 2961x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 24x 24x 24x 24x 24x 1x 1x 1x 24x 24x 24x 24x 24x 24x 24x 192x 192x 24x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 3x 3x 3x 3x 24x 24x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 4x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 236x 236x 2x 2x 234x 234x 236x 2x 2x 232x 232x 232x 232x 232x 236x 101x 101x 232x 232x 232x 232x 236x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 218x 218x 218x 218x 1x 1x 1x 1x 1x 232x     232x 232x 232x 220x 232x 232x 2x 232x 232x 1x 232x 232x 9x 232x 232x   232x 232x 1x 1x 1x 1x 1x 223x     223x 223x 223x 220x 223x 223x 3x 223x 223x   223x 223x 1x 1x 1x 1x 1x 9x 9x 9x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 9x 4x 9x 9x 4x 9x 9x   9x 9x 1x 1x 1x 1x 1x                                       1x  
/**
 * @fileoverview Trigger Manager \u2014 Renesas Power Profiler
 *
 * Provides the `TriggerManager` class, which implements a flexible hardware-
 * style trigger system for data-acquisition sessions.
 *
 * Trigger modes:
 *  - **NONE**    \u2014 All data is passed through without filtering.
 *  - **CURRENT** \u2014 Fires when the measured current crosses a threshold.
 *  - **VOLTAGE1/VOLTAGE2** \u2014 Fires on a voltage-channel threshold crossing.
 *  - **DIGITAL** \u2014 Fires on a rising or falling edge of a selected digital channel.
 *
 * Once the trigger fires:
 *  1. The circular pre-trigger buffer (sized by `preTriggerDuration`) is returned
 *     together with the triggering data point so the frontend graph shows the
 *     context before the event.
 *  2. If `autoStopEnabled` is set, acquisition stops automatically after
 *     `postTriggerDuration` milliseconds have elapsed since the trigger.
 *
 * The `TriggerManager` is stateful and must be `reset()` before each new
 * acquisition run to clear buffered samples and the fired-flag.
 */
 
export enum TriggerType {
    NONE = 'none',
    CURRENT = 'current',
    VOLTAGE1 = 'voltage1',
    VOLTAGE2 = 'voltage2',
    DIGITAL = 'digital'
}
 
export enum TriggerCondition {
    ABOVE = 'above',
    BELOW = 'below',
    RISING_EDGE = 'rising',  // For digital: 0->1
    FALLING_EDGE = 'falling' // For digital: 1->0
}
 
export interface TriggerConfig {
    enabled: boolean;
    type: TriggerType;
    condition: TriggerCondition;
    threshold?: number;           // For analog channels (current, voltage)
    digitalChannel?: number;      // For digital triggers (0-7)
    preTriggerDuration: number;   // In milliseconds (up to 1000ms)
    postTriggerDuration: number;  // In milliseconds (up to 10000ms) - stop acquisition after this duration post-trigger
    autoStopEnabled: boolean;     // Whether to automatically stop after post-trigger duration
}
 
export interface DataPoint {
    x: number;    // time
    c: number;    // current
    q: number;    // charge
    ch1: number;  // voltage1
    ch2: number;  // voltage2
    d0: number;   // digital channels
    d1: number;
    d2: number;
    d3: number;
    d4: number;
    d5: number;
    d6: number;
    d7: number;
}
 
export class TriggerManager {
    private config: TriggerConfig;
    private preBuffer: DataPoint[] = [];
    private triggered: boolean = false;
    private triggerTime: number | null = null;
    private lastDigitalStates: Record<number, number> = {};
    private sampleRate: number = 1000; // samples per second
    private maxBufferSamples: number;
 
    constructor(config: TriggerConfig, sampleRate: number = 1000) {
        this.config = config;
        this.sampleRate = sampleRate;
        // Calculate max buffer size based on pre-trigger duration
        this.maxBufferSamples = Math.ceil((config.preTriggerDuration / 1000) * sampleRate);
        
        // Initialize digital states
        for (let i = 0; i < 8; i++) {
            this.lastDigitalStates[i] = 0;
        }
    }
 
    /**
     * Update trigger configuration
     */
    public updateConfig(config: TriggerConfig): void {
        this.config = config;
        this.maxBufferSamples = Math.ceil((config.preTriggerDuration / 1000) * this.sampleRate);
        this.reset();
    }
 
    /**
     * Update sample rate
     */
    public updateSampleRate(sampleRate: number): void {
        this.sampleRate = sampleRate;
        this.maxBufferSamples = Math.ceil((this.config.preTriggerDuration / 1000) * sampleRate);
    }
 
    /**
     * Reset trigger state
     */
    public reset(): void {
        this.triggered = false;
        this.triggerTime = null;
        this.preBuffer = [];
        for (let i = 0; i < 8; i++) {
            this.lastDigitalStates[i] = 0;
        }
    }
 
    /**
     * Check if triggers are enabled
     */
    public isEnabled(): boolean {
        return this.config.enabled && this.config.type !== TriggerType.NONE;
    }
 
    /**
     * Check if already triggered
     */
    public isTriggered(): boolean {
        return this.triggered;
    }
 
    /**
     * Check if post-trigger duration has expired
     * @param currentTime - current time in seconds
     */
    public shouldStopAcquisition(currentTime: number): boolean {
        // Only auto-stop if enabled in config
        if (!this.config.autoStopEnabled) {
            return false;
        }
        if (!this.triggered || this.triggerTime === null) {
            return false;
        }
        // currentTime is in seconds, convert to milliseconds
        const elapsedMs = (currentTime - this.triggerTime) * 1000;
        return elapsedMs >= this.config.postTriggerDuration;
    }
 
    /**
     * Get buffered data (pre-trigger buffer)
     */
    public getPreTriggerBuffer(): DataPoint[] {
        return [...this.preBuffer];
    }
 
    /**
     * Process a single data point and check for trigger condition
     * Returns: { triggered: boolean, shouldSend: boolean, data?: DataPoint[] }
     */
    public processDataPoint(dataPoint: DataPoint): { triggered: boolean; shouldSend: boolean; data?: DataPoint[] } {
        // If triggers are disabled, always send data
        if (!this.config.enabled || this.config.type === TriggerType.NONE) {
            return { triggered: false, shouldSend: true };
        }
 
        // If already triggered, send all subsequent data
        if (this.triggered) {
            return { triggered: true, shouldSend: true };
        }
 
        // Add to pre-trigger buffer
        this.preBuffer.push(dataPoint);
        
        // Maintain buffer size
        if (this.preBuffer.length > this.maxBufferSamples) {
            this.preBuffer.shift();
        }
 
        // Check trigger condition
        const triggerDetected = this.checkTrigger(dataPoint);
 
        if (triggerDetected) {
            this.triggered = true;
            this.triggerTime = dataPoint.x; // Store trigger time
            // Return buffered data + current point
            const bufferToSend = [...this.preBuffer];
            return { 
                triggered: true, 
                shouldSend: true, 
                data: bufferToSend 
            };
        }
 
        // Not triggered yet, don't send data
        return { triggered: false, shouldSend: false };
    }
 
    /**
     * Check if the current data point meets the trigger condition
     */
    private checkTrigger(dataPoint: DataPoint): boolean {
        if (this.config.threshold === undefined && this.config.type !== TriggerType.DIGITAL) {
            return false;
        }
 
        switch (this.config.type) {
            case TriggerType.CURRENT:
                return this.checkAnalogTrigger(dataPoint.c);
 
            case TriggerType.VOLTAGE1:
                return this.checkAnalogTrigger(dataPoint.ch1);
 
            case TriggerType.VOLTAGE2:
                return this.checkAnalogTrigger(dataPoint.ch2);
 
            case TriggerType.DIGITAL:
                return this.checkDigitalTrigger(dataPoint);
 
            default:
                return false;
        }
    }
 
    /**
     * Check analog trigger (current or voltage)
     */
    private checkAnalogTrigger(value: number): boolean {
        if (this.config.threshold === undefined) {
            return false;
        }
 
        switch (this.config.condition) {
            case TriggerCondition.ABOVE:
                return value > this.config.threshold;
 
            case TriggerCondition.BELOW:
                return value < this.config.threshold;
 
            default:
                return false;
        }
    }
 
    /**
     * Check digital trigger (edge detection)
     */
    private checkDigitalTrigger(dataPoint: DataPoint): boolean {
        if (this.config.digitalChannel === undefined || 
            this.config.digitalChannel < 0 || 
            this.config.digitalChannel > 7) {
            return false;
        }
 
        const channelKey = `d${this.config.digitalChannel}` as keyof DataPoint;
        const currentState = dataPoint[channelKey] as number;
        const lastState = this.lastDigitalStates[this.config.digitalChannel];
 
        // Update state
        this.lastDigitalStates[this.config.digitalChannel] = currentState;
 
        // Check edge condition
        switch (this.config.condition) {
            case TriggerCondition.RISING_EDGE:
                return lastState === 0 && currentState === 1;
 
            case TriggerCondition.FALLING_EDGE:
                return lastState === 1 && currentState === 0;
 
            default:
                return false;
        }
    }
 
    /**
     * Process a batch of data points
     */
    public processBatch(dataPoints: DataPoint[]): { triggered: boolean; dataToSend: DataPoint[] } {
        const dataToSend: DataPoint[] = [];
        let batchTriggered = false;

        for (const point of dataPoints) {
            const result = this.processDataPoint(point);
            
            if (result.triggered && !batchTriggered) {
                batchTriggered = true;
                // Add pre-trigger buffer
                if (result.data) {
                    dataToSend.push(...result.data);
                }
            } else if (result.shouldSend) {
                dataToSend.push(point);
            }
        }

        return { triggered: batchTriggered || this.triggered, dataToSend };
    }
}