diff --git a/angular-client/src/app/context/app-context.component.ts b/angular-client/src/app/context/app-context.component.ts index c4591bb72..527d898b7 100644 --- a/angular-client/src/app/context/app-context.component.ts +++ b/angular-client/src/app/context/app-context.component.ts @@ -1,5 +1,4 @@ import { Component, OnInit, inject, ChangeDetectionStrategy } from '@angular/core'; -import { CellService } from 'src/services/cell.service'; import { FaultService } from 'src/services/fault.service'; import SocketService from 'src/services/socket.service'; import Storage from 'src/services/storage.service'; @@ -62,7 +61,6 @@ const SVG_ICONS: Record = { }) export default class AppContextComponent implements OnInit { private storage = inject(Storage); - private cellService = inject(CellService); private faultService = inject(FaultService); private notificationLogService = inject(NotificationLogService); socketService = inject(SocketService); @@ -72,7 +70,6 @@ export default class AppContextComponent implements OnInit { } ngOnInit(): void { - this.cellService.updateCellInfo(); this.socketService.receiveData(this.storage, this.faultService, this.notificationLogService); } } diff --git a/angular-client/src/pages/bms-debug-page/components/cell-view/cell-view.component.spec.ts b/angular-client/src/pages/bms-debug-page/components/cell-view/cell-view.component.spec.ts index 6688c298d..3736ef15b 100644 --- a/angular-client/src/pages/bms-debug-page/components/cell-view/cell-view.component.spec.ts +++ b/angular-client/src/pages/bms-debug-page/components/cell-view/cell-view.component.spec.ts @@ -2,6 +2,10 @@ import { DIALOG_DATA } from '@angular/cdk/dialog'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { SelectedCellInfo } from 'src/services/heat-map.service'; +import { CellService } from 'src/services/cell.service'; +import Storage from 'src/services/storage.service'; +import { DataValue } from 'src/utils/socket.utils'; +import { topics } from 'src/utils/topic.utils'; import { CellViewComponent } from './cell-view.component'; describe('CellViewComponent', () => { @@ -33,4 +37,15 @@ describe('CellViewComponent', () => { expect(classOf('Balancing')).toBe('text-warn'); expect(classOf('CvS Failure')).toBe('text-success'); }); + + /** The panel stays open across navigation, so it keeps its cells live even off the BMS pages. */ + it('keeps the selected cells live while open', () => { + const storage = TestBed.inject(Storage); + const [reading] = TestBed.inject(CellService).getAlphaCellsBySegment(0); + storage.addValue(topics.alphaVolt(0, 0), { values: ['3.70'], time: '0', unit: 'V' } as DataValue); + expect(reading.voltage).toBeCloseTo(3.7); + + fixture.destroy(); + expect(reading.voltage).toBeUndefined(); + }); }); diff --git a/angular-client/src/pages/bms-debug-page/components/cell-view/cell-view.component.ts b/angular-client/src/pages/bms-debug-page/components/cell-view/cell-view.component.ts index 1b01f5318..01b800de5 100644 --- a/angular-client/src/pages/bms-debug-page/components/cell-view/cell-view.component.ts +++ b/angular-client/src/pages/bms-debug-page/components/cell-view/cell-view.component.ts @@ -1,7 +1,7 @@ import { DIALOG_DATA } from '@angular/cdk/dialog'; -import { ChangeDetectorRef, Component, inject, OnDestroy, ChangeDetectionStrategy } from '@angular/core'; +import { ChangeDetectorRef, Component, DestroyRef, inject, OnDestroy, ChangeDetectionStrategy } from '@angular/core'; import { SelectedCellInfo } from 'src/services/heat-map.service'; -import { CellReading } from 'src/services/cell.service'; +import { CellReading, CellService } from 'src/services/cell.service'; import { chipToString } from 'src/utils/bms.utils'; import { ConfigTableComponent, TableRowConfig, TableColumnConfig } from 'src/components/config-table/config-table.component'; import { tw } from 'src/ui/recipes/tw'; @@ -67,6 +67,8 @@ export class CellViewComponent implements OnDestroy { } constructor() { + // The panel stays open across navigation, so it keeps the cell topics subscribed itself. + inject(DestroyRef).onDestroy(inject(CellService).retain()); this.cellsMap = this.dialogData.cells; // Poll for MQTT value changes and selection array changes. this.refreshInterval = setInterval(() => this.cdr.detectChanges(), 50); diff --git a/angular-client/src/pages/bms-debug-page/components/segment-heatmap/segment-heatmap.component.spec.ts b/angular-client/src/pages/bms-debug-page/components/segment-heatmap/segment-heatmap.component.spec.ts index e70d04c78..d4610575d 100644 --- a/angular-client/src/pages/bms-debug-page/components/segment-heatmap/segment-heatmap.component.spec.ts +++ b/angular-client/src/pages/bms-debug-page/components/segment-heatmap/segment-heatmap.component.spec.ts @@ -3,7 +3,7 @@ import { ChangeDetectorRef } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; -import Storage from 'src/services/storage.service'; +import Storage, { TOPIC_LINGER_MS } from 'src/services/storage.service'; import { CellService } from 'src/services/cell.service'; import { HeatMapService, HeatMapView } from 'src/services/heat-map.service'; import { DataValue } from 'src/utils/socket.utils'; @@ -62,7 +62,6 @@ describe('SegmentHeatmapComponent (storage seam)', () => { storage = TestBed.inject(Storage); cellService = TestBed.inject(CellService); heatMap = TestBed.inject(HeatMapService); - cellService.updateCellInfo(); // wire the per-cell storage subscriptions fixture = TestBed.createComponent(SegmentHeatmapComponent); component = fixture.componentInstance; @@ -76,6 +75,23 @@ describe('SegmentHeatmapComponent (storage seam)', () => { expect(component).toBeTruthy(); }); + it('holds the BMS cell topics while shown, and releases them once destroyed and the linger elapses', async () => { + vi.useFakeTimers(); + try { + const cellTopics = () => storage.getTopics().filter((topic) => topic.startsWith('BMS/PerCell/')); + await Promise.resolve(); + expect(cellTopics()).toContain(topics.alphaVolt(SEGMENT, CELL)); + + fixture.destroy(); + vi.advanceTimersByTime(TOPIC_LINGER_MS); + await Promise.resolve(); + expect(cellTopics()).toEqual([]); + expect(cellService.getAlphaCellsBySegment(SEGMENT)[CELL].voltage).toBeUndefined(); + } finally { + vi.useRealTimers(); + } + }); + it('fills the flag views from theme tokens, each under black text at AA', () => { for (const fill of Object.values(HEAT_FILLS)) { expect(tokenValue(fill)).toMatch(/^#[0-9a-f]{6}$/i); diff --git a/angular-client/src/pages/bms-debug-page/components/segment-heatmap/segment-heatmap.component.ts b/angular-client/src/pages/bms-debug-page/components/segment-heatmap/segment-heatmap.component.ts index ba31bea59..b4be4c020 100644 --- a/angular-client/src/pages/bms-debug-page/components/segment-heatmap/segment-heatmap.component.ts +++ b/angular-client/src/pages/bms-debug-page/components/segment-heatmap/segment-heatmap.component.ts @@ -70,6 +70,9 @@ export class SegmentHeatmapComponent implements OnInit { view!: HeatMapView; constructor() { + // The cell topics stay subscribed while any heatmap is on screen. + this.destroyRef.onDestroy(this.cellService.retain()); + effect(() => { this.alphaCells = this.cellService.getAlphaCellsBySegment(this.segment()); this.betaCells = this.cellService.getBetaCellsBySegment(this.segment()); diff --git a/angular-client/src/services/cell.service.spec.ts b/angular-client/src/services/cell.service.spec.ts new file mode 100644 index 000000000..ba2f57697 --- /dev/null +++ b/angular-client/src/services/cell.service.spec.ts @@ -0,0 +1,136 @@ +import { TestBed } from '@angular/core/testing'; +import { CellService } from './cell.service'; +import Storage, { TOPIC_LINGER_MS } from './storage.service'; +import { DataValue } from 'src/utils/socket.utils'; +import { topics } from 'src/utils/topic.utils'; + +/** Lets the microtask that batches a task's topic changes run. */ +const flush = () => Promise.resolve(); + +const push = (storage: Storage, key: string, value: string): void => { + storage.addValue(key, { values: [value], time: '0', unit: '' } as DataValue); +}; + +const isCellTopic = (topic: string) => topic.startsWith('BMS/PerCell/'); + +/** 5 segments x 2 chips x (7 therms + 13 each of volts, S volts, burns, CvS and open wire). */ +const CELL_TOPIC_COUNT = 720; + +describe('CellService', () => { + let storage: Storage; + let cells: CellService; + const releases: (() => void)[] = []; + + const retain = () => { + const release = cells.retain(); + releases.push(release); + return release; + }; + + const cellTopics = () => storage.getTopics().filter(isCellTopic); + const alphaCell = (segment: number, cell: number) => cells.getAlphaCellsBySegment(segment)[cell]; + const betaCell = (segment: number, cell: number) => cells.getBetaCellsBySegment(segment)[cell]; + + beforeEach(() => { + vi.useFakeTimers(); + TestBed.configureTestingModule({ providers: [Storage, CellService] }); + storage = TestBed.inject(Storage); + cells = TestBed.inject(CellService); + }); + + afterEach(() => { + releases.splice(0).forEach((release) => release()); + vi.useRealTimers(); + }); + + it('subscribes no cell topics until something retains it', async () => { + await flush(); + expect(cellTopics()).toEqual([]); + }); + + it('subscribes every cell topic while retained', async () => { + retain(); + await flush(); + expect(cellTopics()).toHaveLength(CELL_TOPIC_COUNT); + expect(cellTopics()).toContain(topics.alphaVolt(0, 0)); + expect(cellTopics()).toContain(topics.betaOw(4, 12)); + }); + + it('keeps the topics while any reader holds them, and drops them after the last releases and the linger', async () => { + const first = retain(); + const second = retain(); + await flush(); + + first(); + vi.advanceTimersByTime(TOPIC_LINGER_MS * 2); + await flush(); + expect(cellTopics()).toHaveLength(CELL_TOPIC_COUNT); + + second(); + vi.advanceTimersByTime(TOPIC_LINGER_MS - 1); + await flush(); + expect(cellTopics()).toHaveLength(CELL_TOPIC_COUNT); + + vi.advanceTimersByTime(1); + await flush(); + expect(cellTopics()).toEqual([]); + }); + + it('counts a repeated release once', async () => { + const first = retain(); + retain(); + first(); + first(); + vi.advanceTimersByTime(TOPIC_LINGER_MS * 2); + await flush(); + expect(cellTopics()).toHaveLength(CELL_TOPIC_COUNT); + }); + + it('fills cell readings from their topics while retained', () => { + retain(); + push(storage, topics.alphaVolt(1, 3), '3.61'); + push(storage, topics.betaSVolt(2, 4), '3.52'); + push(storage, topics.alphaTemp(0, 2), '31.5'); // therm 2 covers cells 2 and 3 + push(storage, topics.betaBurning(3, 5), '1'); + push(storage, topics.alphaCvs(4, 6), '0'); + push(storage, topics.betaOw(0, 7), '1'); + + expect(alphaCell(1, 3).voltage).toBeCloseTo(3.61); + expect(betaCell(2, 4).svolts).toBeCloseTo(3.52); + expect(alphaCell(0, 2).temp).toBeCloseTo(31.5); + expect(alphaCell(0, 3).temp).toBeCloseTo(31.5); + expect(betaCell(3, 5).balancing).toBe(true); + expect(alphaCell(4, 6).cvs).toBe(false); + expect(betaCell(0, 7).ow).toBe(true); + }); + + it('keeps the latest values through a quick release and retain, such as a page switch', () => { + const release = retain(); + push(storage, topics.alphaVolt(0, 0), '3.40'); + + release(); + expect(alphaCell(0, 0).voltage).toBeUndefined(); // nothing reads the cells now + + vi.advanceTimersByTime(TOPIC_LINGER_MS - 1); + retain(); + expect(alphaCell(0, 0).voltage).toBeCloseTo(3.4); // replayed from the lingering topic + }); + + it('shows no stale readings once the topics were released for longer than the linger', () => { + const release = retain(); + push(storage, topics.alphaVolt(0, 0), '3.40'); + release(); + vi.advanceTimersByTime(TOPIC_LINGER_MS); + + retain(); + expect(alphaCell(0, 0).voltage).toBeUndefined(); + push(storage, topics.alphaVolt(0, 0), '3.45'); + expect(alphaCell(0, 0).voltage).toBeCloseTo(3.45); + }); + + it('ignores values that arrive while nothing retains it', () => { + push(storage, topics.alphaVolt(0, 0), '3.40'); + retain(); + expect(alphaCell(0, 0).voltage).toBeUndefined(); + }); +}); diff --git a/angular-client/src/services/cell.service.ts b/angular-client/src/services/cell.service.ts index 90353235f..8f7a968c7 100644 --- a/angular-client/src/services/cell.service.ts +++ b/angular-client/src/services/cell.service.ts @@ -1,4 +1,5 @@ import { Injectable, inject } from '@angular/core'; +import { Subscription } from 'rxjs'; import { ALPHA_THERM_CELL_MAP, BETA_THERM_CELL_MAP, BMS_CONFIG } from 'src/utils/bms.config'; import { Chip, numToSegmentType, Segment } from 'src/utils/bms.utils'; import Storage from './storage.service'; @@ -62,19 +63,51 @@ export class CellService { private perSegmentAlphaCells: CellReading[][] = startingPerSegmentAlphaCells; private perSegmentBetaCells: CellReading[][] = startingPerSegmentBetaCells; - updateCellInfo = () => { - this.subscribeToAlphaCellInfo(); - this.subscribeToBetaCellInfo(); + private subscriptions = new Subscription(); + private readers = 0; + + /** + * Keeps the ~720 BMS cell topics subscribed until the returned release is called, so a + * client reads them only while something shows cell data. The first reader subscribes them + * (Storage replays each topic's latest value, so a quick page switch keeps the readings); the + * last release drops them and clears the readings, which would otherwise go stale. + */ + retain = (): (() => void) => { + if (this.readers++ === 0) { + this.subscribeToAlphaCellInfo(); + this.subscribeToBetaCellInfo(); + } + let released = false; + return () => { + if (released) return; + released = true; + if (--this.readers > 0) return; + this.subscriptions.unsubscribe(); + this.subscriptions = new Subscription(); + this.clearReadings(); + }; + }; + + /** Applies each value of a topic to the cells while retained. */ + private read = (topic: string, apply: (value: string) => void) => { + this.subscriptions.add(this.storageService.get(topic).subscribe((data) => apply(data.values[0]))); + }; + + private clearReadings = () => { + for (const cell of [...this.perSegmentAlphaCells, ...this.perSegmentBetaCells].flat()) { + cell.temp = cell.voltage = cell.svolts = undefined; + cell.balancing = cell.cvs = cell.ow = undefined; + } }; private subscribeToAlphaCellInfo = () => { - this.perSegmentAlphaCells.map((segmentAlphaCells, index) => { + this.perSegmentAlphaCells.forEach((segmentAlphaCells, index) => { const segmentNumber = numToSegmentType(index); // Therms: apply temperature to cells defined in ALPHA_THERM_CELL_MAP allAlphaThermValues.forEach((therm, thermIndex) => { - this.storageService.get(topics.alphaTemp(segmentNumber, therm)).subscribe((data) => { - const temp = parseFloat(data.values[0]); + this.read(topics.alphaTemp(segmentNumber, therm), (value) => { + const temp = parseFloat(value); const cellIndices = ALPHA_THERM_CELL_MAP[thermIndex] ?? []; for (const cellIdx of cellIndices) { if (cellIdx < segmentAlphaCells.length) { @@ -86,49 +119,49 @@ export class CellService { // Volts: one per cell (C-ADC voltage) allAlphaVoltValues.forEach((volt, voltIndex) => { - this.storageService.get(topics.alphaVolt(segmentNumber, volt)).subscribe((data) => { - segmentAlphaCells[voltIndex].voltage = parseFloat(data.values[0]); + this.read(topics.alphaVolt(segmentNumber, volt), (value) => { + segmentAlphaCells[voltIndex].voltage = parseFloat(value); }); }); // S Volts: one per cell (S-ADC voltage, mirrors Volts) allAlphaSVoltValues.forEach((sVolt, sVoltIndex) => { - this.storageService.get(topics.alphaSVolt(segmentNumber, sVolt)).subscribe((data) => { - segmentAlphaCells[sVoltIndex].svolts = parseFloat(data.values[0]); + this.read(topics.alphaSVolt(segmentNumber, sVolt), (value) => { + segmentAlphaCells[sVoltIndex].svolts = parseFloat(value); }); }); // Burns: one per cell allAlphaBurnValues.forEach((burn, burnIndex) => { - this.storageService.get(topics.alphaBurning(segmentNumber, burn)).subscribe((data) => { - segmentAlphaCells[burnIndex].balancing = parseInt(data.values[0]) === 1; + this.read(topics.alphaBurning(segmentNumber, burn), (value) => { + segmentAlphaCells[burnIndex].balancing = parseInt(value) === 1; }); }); // CvS: one per cell allAlphaCvsValues.forEach((cvs, cvsIndex) => { - this.storageService.get(topics.alphaCvs(segmentNumber, cvs)).subscribe((data) => { - segmentAlphaCells[cvsIndex].cvs = parseInt(data.values[0]) === 1; + this.read(topics.alphaCvs(segmentNumber, cvs), (value) => { + segmentAlphaCells[cvsIndex].cvs = parseInt(value) === 1; }); }); // Open Wire: one per cell (mirrors CvS) allAlphaOwValues.forEach((ow, owIndex) => { - this.storageService.get(topics.alphaOw(segmentNumber, ow)).subscribe((data) => { - segmentAlphaCells[owIndex].ow = parseInt(data.values[0]) === 1; + this.read(topics.alphaOw(segmentNumber, ow), (value) => { + segmentAlphaCells[owIndex].ow = parseInt(value) === 1; }); }); }); }; private subscribeToBetaCellInfo = () => { - this.perSegmentBetaCells.map((segmentBetaCells, index) => { + this.perSegmentBetaCells.forEach((segmentBetaCells, index) => { const segmentNumber = numToSegmentType(index); // Therms: apply temperature to cells defined in BETA_THERM_CELL_MAP - allBetaThermValues.map((therm, thermIndex) => { - this.storageService.get(topics.betaTemp(segmentNumber, therm)).subscribe((data) => { - const temp = parseFloat(data.values[0]); + allBetaThermValues.forEach((therm, thermIndex) => { + this.read(topics.betaTemp(segmentNumber, therm), (value) => { + const temp = parseFloat(value); const cellIndices = BETA_THERM_CELL_MAP[thermIndex] ?? []; for (const cellIdx of cellIndices) { if (cellIdx < segmentBetaCells.length) { @@ -139,37 +172,37 @@ export class CellService { }); // Volts: one per cell (C-ADC voltage) - allBetaVoltValues.map((volt, voltIndex) => { - this.storageService.get(topics.betaVolt(segmentNumber, volt)).subscribe((data) => { - segmentBetaCells[voltIndex].voltage = parseFloat(data.values[0]); + allBetaVoltValues.forEach((volt, voltIndex) => { + this.read(topics.betaVolt(segmentNumber, volt), (value) => { + segmentBetaCells[voltIndex].voltage = parseFloat(value); }); }); // S Volts: one per cell (S-ADC voltage, mirrors Volts) - allBetaSVoltValues.map((sVolt, sVoltIndex) => { - this.storageService.get(topics.betaSVolt(segmentNumber, sVolt)).subscribe((data) => { - segmentBetaCells[sVoltIndex].svolts = parseFloat(data.values[0]); + allBetaSVoltValues.forEach((sVolt, sVoltIndex) => { + this.read(topics.betaSVolt(segmentNumber, sVolt), (value) => { + segmentBetaCells[sVoltIndex].svolts = parseFloat(value); }); }); // Burns: one per cell - allBetaBurnValues.map((burn, burnIndex) => { - this.storageService.get(topics.betaBurning(segmentNumber, burn)).subscribe((data) => { - segmentBetaCells[burnIndex].balancing = parseInt(data.values[0]) === 1; + allBetaBurnValues.forEach((burn, burnIndex) => { + this.read(topics.betaBurning(segmentNumber, burn), (value) => { + segmentBetaCells[burnIndex].balancing = parseInt(value) === 1; }); }); // CvS: one per cell allBetaCvsValues.forEach((cvs, cvsIndex) => { - this.storageService.get(topics.betaCvs(segmentNumber, cvs)).subscribe((data) => { - segmentBetaCells[cvsIndex].cvs = parseInt(data.values[0]) === 1; + this.read(topics.betaCvs(segmentNumber, cvs), (value) => { + segmentBetaCells[cvsIndex].cvs = parseInt(value) === 1; }); }); // Open Wire: one per cell (mirrors CvS) allBetaOwValues.forEach((ow, owIndex) => { - this.storageService.get(topics.betaOw(segmentNumber, ow)).subscribe((data) => { - segmentBetaCells[owIndex].ow = parseInt(data.values[0]) === 1; + this.read(topics.betaOw(segmentNumber, ow), (value) => { + segmentBetaCells[owIndex].ow = parseInt(value) === 1; }); }); });