♻️ Makes IMU store handle data subscription
This commit is contained in:
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
})()
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user