Add computed sensor stats and refactor AnalyticsView to use stores

This commit is contained in:
rafaeldpsilva
2025-10-01 12:41:12 +01:00
parent b9348140b8
commit 06f7537422
2 changed files with 90 additions and 47 deletions

View File

@@ -1,5 +1,5 @@
import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import { ref, reactive, computed } from 'vue'
import {
sensorsApi,
SensorType,
@@ -14,9 +14,19 @@ export const useSensorStore = defineStore('sensor', () => {
const latestReadings = reactive<Map<string, SensorReading>>(new Map())
const sensorsData = reactive<Map<string, any>>(new Map()) // Legacy support
const recentlyUpdatedSensors = reactive<Set<string>>(new Set()) // Track recently updated sensors
const totalReadings = ref(0) // Total number of readings across all sensors
const apiLoading = ref(false)
const apiError = ref<string | null>(null)
// Computed properties
const totalSensors = computed(() => sensorDevices.size)
const activeSensors = computed(() => {
return Array.from(sensorDevices.values()).filter(
sensor => sensor.status === 'active' || sensor.status === 'online'
).length
})
// Actions
function updateSensorRoom(sensorId: string, newRoom: string) {
const sensor = sensorDevices.get(sensorId)
@@ -56,6 +66,9 @@ export const useSensorStore = defineStore('sensor', () => {
function updateLatestReading(reading: SensorReading) {
latestReadings.set(reading.sensor_id, reading)
// Increment total readings count
totalReadings.value++
// Mark sensor as recently updated
recentlyUpdatedSensors.add(reading.sensor_id)
// Remove from recently updated after 2 seconds
@@ -178,11 +191,18 @@ export const useSensorStore = defineStore('sensor', () => {
console.log(result)
// Check if result has a sensors property (common API pattern)
if (result.sensors && Array.isArray(result.sensors)) {
let totalReadingsCount = 0
result.sensors.forEach((sensor) => {
const sensorKey = sensor._id || sensor.sensor_id
const sensorType = sensor.sensor_type || sensor.type
const sensorName = sensor.name || ''
// Accumulate total readings
if (sensor.total_readings) {
totalReadingsCount += sensor.total_readings
}
const normalizedSensor = {
...sensor,
id: sensorKey,
@@ -207,6 +227,9 @@ export const useSensorStore = defineStore('sensor', () => {
sensorDevices.set(sensorKey, normalizedSensor)
})
// Update total readings
totalReadings.value = totalReadingsCount
} else {
console.warn('Unexpected result format:', typeof result, result)
}
@@ -247,9 +270,14 @@ export const useSensorStore = defineStore('sensor', () => {
latestReadings,
sensorsData,
recentlyUpdatedSensors,
totalReadings,
apiLoading,
apiError,
// Computed
totalSensors,
activeSensors,
// Actions
updateEnergySensors,
updateSensorRoom,