♻️ Makes IMU store handle data subscription

This commit is contained in:
Rune Harlyk
2026-01-03 17:45:31 +01:00
committed by nikguin04
parent a31e001eb5
commit b96ea51bd8
4 changed files with 25 additions and 33 deletions
+22 -6
View File
@@ -1,18 +1,34 @@
import { writable } from 'svelte/store'
import { IMUData } from '$lib/platform_shared/message'
import { socket } from './socket'
const imu_data: IMUData[] = []
const maxIMUData = 100
export const imu = (() => {
const { subscribe, update } = writable(imu_data)
const { subscribe, update } = writable<IMUData[]>([])
let unsubscribe: (() => void) | null = null
let listenerCount = 0
const addData = (content: IMUData) => {
update(data => [...data, content].slice(-maxIMUData))
}
return {
subscribe,
addData: (content: IMUData) => {
update(imu_data => {
return [...imu_data, content].slice(-maxIMUData)
})
addData,
listen: () => {
listenerCount++
if (!unsubscribe) {
unsubscribe = socket.on(IMUData, addData)
}
},
stop: () => {
listenerCount = Math.max(0, listenerCount - 1)
if (listenerCount === 0 && unsubscribe) {
unsubscribe()
unsubscribe = null
}
}
}
})()
-16
View File
@@ -8,21 +8,5 @@ export const servoAngles: Writable<AnglesData> = writable(
AnglesData.create({ angles: [0, 45, -90, 0, 45, -90, 0, 45, -90, 0, 45, -90] })
)
export const logs = writable([] as string[])
export const mpu = writable({ heading: 0 })
export const sonar = writable([0, 0])
export const distances = writable({})
export interface socketDataCollection {
angles: Writable<AnglesData>
logs: Writable<string[]>
mpu: Writable<unknown>
distances: Writable<unknown>
}
export const socketData = {
angles: servoAngles,
logs,
mpu,
distances
}