sensor management page

This commit is contained in:
rafaeldpsilva
2025-09-02 15:39:45 +01:00
parent 42f9fa5aed
commit 1522f70f08
8 changed files with 1159 additions and 14 deletions

View File

@@ -0,0 +1,310 @@
<template>
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
<!-- Sensor Header -->
<div class="p-4 border-b border-gray-100">
<div class="flex items-start justify-between">
<div class="flex items-center gap-3">
<div class="p-2 rounded-lg" :class="getSensorTypeStyle(sensor.type).bg">
<span class="text-lg">{{ getSensorTypeIcon(sensor.type) }}</span>
</div>
<div>
<h3 class="font-medium text-gray-900">{{ sensor.name }}</h3>
<p class="text-sm text-gray-500">{{ sensor.id }}</p>
</div>
</div>
<div class="flex items-center gap-2">
<div
class="w-2 h-2 rounded-full"
:class="getSensorStatusColor(sensor.status)"
></div>
<span class="text-xs text-gray-500 capitalize">{{ sensor.status }}</span>
</div>
</div>
</div>
<!-- Sensor Details -->
<div class="p-4 space-y-4">
<!-- Room Assignment -->
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Room Assignment</label>
<select
:value="sensor.room"
@change="$emit('updateRoom', sensor.id, ($event.target as HTMLSelectElement).value)"
class="w-full px-3 py-2 border border-gray-200 rounded-lg bg-white text-sm"
>
<option value="">Unassigned</option>
<option v-for="room in availableRooms" :key="room" :value="room">
{{ room }}
</option>
</select>
</div>
<!-- Tags -->
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">Tags</label>
<div class="flex flex-wrap gap-1 mb-2">
<span
v-for="tag in sensor.tags || getDefaultTags(sensor)"
:key="tag"
class="px-2 py-1 bg-gray-100 text-gray-700 rounded-full text-xs font-medium"
>
{{ tag }}
</span>
</div>
</div>
<!-- Monitoring Capabilities -->
<div>
<div class="text-sm font-medium text-gray-700 mb-2">Monitoring Capabilities</div>
<div class="flex flex-wrap gap-1">
<span
v-for="capability in sensor.capabilities.monitoring"
:key="capability"
class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs font-medium"
>
{{ capability }}
</span>
</div>
</div>
<!-- Current Values -->
<div>
<div class="text-sm font-medium text-gray-700 mb-2">Current Values</div>
<div class="grid grid-cols-2 gap-2 text-xs">
<div v-for="metric in getSensorValues(sensor)" :key="metric.type"
class="bg-gray-50 rounded p-2">
<div class="text-gray-600 mb-1">{{ metric.label }}</div>
<div class="font-medium text-gray-900">
{{ metric.value }} <span class="text-gray-500">{{ metric.unit }}</span>
</div>
</div>
</div>
</div>
<!-- Device Technical Info -->
<div>
<div class="text-sm font-medium text-gray-700 mb-2">Device Information</div>
<div class="grid grid-cols-2 gap-2 text-xs text-gray-600">
<div>
<span class="font-medium">Model:</span>
<div>{{ sensor.metadata.model || 'N/A' }}</div>
</div>
<div>
<span class="font-medium">Firmware:</span>
<div>{{ sensor.metadata.firmware || 'N/A' }}</div>
</div>
<div>
<span class="font-medium">Location:</span>
<div>{{ sensor.metadata.location }}</div>
</div>
<div>
<span class="font-medium">Last Seen:</span>
<div>{{ formatTime(sensor.lastSeen) }}</div>
</div>
<div v-if="sensor.metadata.battery">
<span class="font-medium">Battery:</span>
<div class="flex items-center gap-1">
<span>{{ sensor.metadata.battery }}%</span>
<div class="w-3 h-1 bg-gray-200 rounded-full">
<div
class="h-full rounded-full transition-all"
:class="getBatteryColor(sensor.metadata.battery)"
:style="{ width: sensor.metadata.battery + '%' }"
></div>
</div>
</div>
</div>
<div v-if="sensor.metadata.signalStrength">
<span class="font-medium">Signal:</span>
<div class="flex items-center gap-1">
<span>{{ sensor.metadata.signalStrength }}%</span>
<div class="flex gap-0.5">
<div
v-for="i in 4"
:key="i"
class="w-1 h-2 bg-gray-200 rounded-sm"
:class="{ 'bg-green-500': (sensor.metadata.signalStrength / 25) >= i }"
></div>
</div>
</div>
</div>
</div>
</div>
<!-- Actions -->
<div v-if="sensor.capabilities.actions.length > 0">
<div class="text-sm font-medium text-gray-700 mb-3">Available Actions</div>
<div class="grid grid-cols-2 gap-2">
<button
v-for="action in sensor.capabilities.actions"
:key="action.id"
@click="$emit('executeAction', sensor, action)"
:disabled="isExecutingAction"
class="flex items-center justify-center gap-2 px-3 py-2 bg-gray-50 hover:bg-gray-100 disabled:bg-gray-100 disabled:cursor-not-allowed border border-gray-200 rounded-lg text-sm font-medium text-gray-700 transition-colors"
:class="{ 'opacity-50': isExecutingAction }"
>
<span>{{ action.icon }}</span>
<span class="truncate">{{ action.name }}</span>
</button>
</div>
</div>
<!-- No Actions State -->
<div v-else>
<div class="text-sm font-medium text-gray-700 mb-2">Device Actions</div>
<div class="text-xs text-gray-500 text-center py-3 bg-gray-50 rounded border-2 border-dashed border-gray-200">
This device is monitor-only and has no available actions
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
const props = defineProps<{
sensor: any
availableRooms: string[]
isExecutingAction?: boolean
}>()
const emit = defineEmits<{
updateRoom: [sensorId: string, newRoom: string]
executeAction: [sensor: any, action: any]
}>()
const getSensorValues = (sensor: any) => {
// Mock sensor values based on sensor type and capabilities
const values = []
if (sensor.capabilities.monitoring.includes('energy')) {
values.push({
type: 'energy',
label: 'Energy Consumption',
value: (Math.random() * 5 + 0.5).toFixed(2),
unit: 'kWh'
})
}
if (sensor.capabilities.monitoring.includes('co2')) {
values.push({
type: 'co2',
label: 'CO2 Level',
value: Math.floor(Math.random() * 800 + 350),
unit: 'ppm'
})
}
if (sensor.capabilities.monitoring.includes('temperature')) {
values.push({
type: 'temperature',
label: 'Temperature',
value: (Math.random() * 8 + 18).toFixed(1),
unit: '°C'
})
}
if (sensor.capabilities.monitoring.includes('humidity')) {
values.push({
type: 'humidity',
label: 'Humidity',
value: Math.floor(Math.random() * 40 + 30),
unit: '%'
})
}
if (sensor.capabilities.monitoring.includes('motion')) {
values.push({
type: 'motion',
label: 'Motion Status',
value: Math.random() > 0.7 ? 'Detected' : 'Clear',
unit: ''
})
}
// Add device uptime
values.push({
type: 'uptime',
label: 'Uptime',
value: Math.floor(Math.random() * 30 + 1),
unit: 'days'
})
return values
}
const getDefaultTags = (sensor: any) => {
const tags = [sensor.type]
if (sensor.metadata.battery) {
tags.push('wireless')
} else {
tags.push('wired')
}
if (sensor.capabilities.actions.length > 0) {
tags.push('controllable')
} else {
tags.push('monitor-only')
}
return tags
}
const getSensorTypeIcon = (type: string) => {
const icons = {
energy: '⚡',
co2: '💨',
temperature: '🌡️',
humidity: '💧',
hvac: '❄️',
lighting: '💡',
security: '🔒'
}
return icons[type as keyof typeof icons] || '📱'
}
const getSensorTypeStyle = (type: string) => {
const styles = {
energy: { bg: 'bg-yellow-100', text: 'text-yellow-700' },
co2: { bg: 'bg-green-100', text: 'text-green-700' },
temperature: { bg: 'bg-red-100', text: 'text-red-700' },
humidity: { bg: 'bg-blue-100', text: 'text-blue-700' },
hvac: { bg: 'bg-cyan-100', text: 'text-cyan-700' },
lighting: { bg: 'bg-amber-100', text: 'text-amber-700' },
security: { bg: 'bg-purple-100', text: 'text-purple-700' }
}
return styles[type as keyof typeof styles] || { bg: 'bg-gray-100', text: 'text-gray-700' }
}
const getSensorStatusColor = (status: string) => {
switch (status) {
case 'online': return 'bg-green-500'
case 'offline': return 'bg-gray-400'
case 'error': return 'bg-red-500'
default: return 'bg-gray-400'
}
}
const getBatteryColor = (battery: number) => {
if (battery > 50) return 'bg-green-400'
if (battery > 20) return 'bg-yellow-400'
return 'bg-red-400'
}
const formatTime = (timestamp: number) => {
const date = new Date(timestamp * 1000)
const now = new Date()
const diffMs = now.getTime() - date.getTime()
const diffSecs = Math.floor(diffMs / 1000)
if (diffSecs < 60) {
return `${diffSecs}s ago`
} else if (diffSecs < 3600) {
return `${Math.floor(diffSecs / 60)}m ago`
} else if (diffSecs < 86400) {
return `${Math.floor(diffSecs / 3600)}h ago`
} else {
return date.toLocaleDateString()
}
}
</script>

View File

@@ -35,7 +35,6 @@ const trendData = computed(() => props.trendData || defaultTrendData)
const trendDir = computed(() => { const trendDir = computed(() => {
const dir = trendData.value[trendData.value.length - 1] - trendData.value[0] const dir = trendData.value[trendData.value.length - 1] - trendData.value[0]
console.log(dir)
if (dir > 0) return 'up' if (dir > 0) return 'up'
if (dir < 0) return 'down' if (dir < 0) return 'down'
return 'neutral' return 'neutral'

View File

@@ -0,0 +1,181 @@
<template>
<div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
<!-- Header -->
<div class="flex items-center justify-between mb-3">
<div class="flex items-center gap-2">
<div class="p-1.5 rounded-lg" :class="getSensorTypeStyle(sensor.type).bg">
<span class="text-sm">{{ getSensorTypeIcon(sensor.type) }}</span>
</div>
<div>
<h3 class="font-medium text-gray-900 text-sm">{{ sensor.name }}</h3>
<p class="text-xs text-gray-500">{{ sensor.room || 'Unassigned' }}</p>
</div>
</div>
<!-- Status Indicator -->
<div class="flex items-center gap-1">
<div
class="w-2 h-2 rounded-full"
:class="getSensorStatusColor(sensor.status)"
></div>
<span class="text-xs text-gray-500 capitalize">{{ sensor.status }}</span>
</div>
</div>
<!-- Sensor Values -->
<div class="mb-3">
<div class="grid grid-cols-2 gap-2 text-xs">
<div v-for="metric in getSensorValues(sensor)" :key="metric.type"
class="bg-gray-50 rounded p-2">
<div class="text-gray-600 mb-1">{{ metric.label }}</div>
<div class="font-medium text-gray-900">
{{ metric.value }} <span class="text-gray-500">{{ metric.unit }}</span>
</div>
</div>
</div>
</div>
<!-- Quick Actions -->
<div v-if="sensor.capabilities.actions.length > 0" class="space-y-2">
<div class="text-xs font-medium text-gray-600 mb-2">Quick Actions</div>
<div class="flex gap-1 flex-wrap">
<button
v-for="action in sensor.capabilities.actions.slice(0, 3)"
:key="action.id"
@click="$emit('executeAction', sensor, action)"
:disabled="isExecutingAction"
class="flex items-center gap-1 px-2 py-1 bg-gray-100 hover:bg-gray-200 disabled:bg-gray-100 disabled:cursor-not-allowed text-gray-700 rounded text-xs font-medium transition-colors"
:class="{ 'opacity-50': isExecutingAction }"
>
<span class="text-xs">{{ action.icon }}</span>
<span class="truncate">{{ action.name }}</span>
</button>
<!-- Show more actions if there are more than 3 -->
<button
v-if="sensor.capabilities.actions.length > 3"
@click="$emit('showMore', sensor)"
class="px-2 py-1 bg-blue-100 hover:bg-blue-200 text-blue-700 rounded text-xs font-medium transition-colors"
>
+{{ sensor.capabilities.actions.length - 3 }}
</button>
</div>
</div>
<!-- No Actions State -->
<div v-else class="text-xs text-gray-500 text-center py-2 bg-gray-50 rounded">
Monitor Only
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{
sensor: any
isExecutingAction?: boolean
}>()
const emit = defineEmits<{
executeAction: [sensor: any, action: any]
showMore: [sensor: any]
}>()
const getSensorValues = (sensor: any) => {
// Mock sensor values based on sensor type and capabilities
const values = []
if (sensor.capabilities.monitoring.includes('energy')) {
values.push({
type: 'energy',
label: 'Energy',
value: (Math.random() * 5 + 0.5).toFixed(2),
unit: 'kWh'
})
}
if (sensor.capabilities.monitoring.includes('co2')) {
values.push({
type: 'co2',
label: 'CO2',
value: Math.floor(Math.random() * 800 + 350),
unit: 'ppm'
})
}
if (sensor.capabilities.monitoring.includes('temperature')) {
values.push({
type: 'temperature',
label: 'Temperature',
value: (Math.random() * 8 + 18).toFixed(1),
unit: '°C'
})
}
if (sensor.capabilities.monitoring.includes('humidity')) {
values.push({
type: 'humidity',
label: 'Humidity',
value: Math.floor(Math.random() * 40 + 30),
unit: '%'
})
}
if (sensor.capabilities.monitoring.includes('motion')) {
values.push({
type: 'motion',
label: 'Motion',
value: Math.random() > 0.7 ? 'Detected' : 'Clear',
unit: ''
})
}
// If no monitoring capabilities, show generic status
if (values.length === 0) {
values.push({
type: 'status',
label: 'Status',
value: sensor.status === 'online' ? 'Active' : 'Inactive',
unit: ''
})
}
return values
}
const getSensorTypeIcon = (type: string) => {
const icons = {
energy: '⚡',
co2: '💨',
temperature: '🌡️',
humidity: '💧',
hvac: '❄️',
lighting: '💡',
security: '🔒'
}
return icons[type as keyof typeof icons] || '📱'
}
const getSensorTypeStyle = (type: string) => {
const styles = {
energy: { bg: 'bg-yellow-100', text: 'text-yellow-700' },
co2: { bg: 'bg-green-100', text: 'text-green-700' },
temperature: { bg: 'bg-red-100', text: 'text-red-700' },
humidity: { bg: 'bg-blue-100', text: 'text-blue-700' },
hvac: { bg: 'bg-cyan-100', text: 'text-cyan-700' },
lighting: { bg: 'bg-amber-100', text: 'text-amber-700' },
security: { bg: 'bg-purple-100', text: 'text-purple-700' }
}
return styles[type as keyof typeof styles] || { bg: 'bg-gray-100', text: 'text-gray-700' }
}
const getSensorStatusColor = (status: string) => {
switch (status) {
case 'online': return 'bg-green-500'
case 'offline': return 'bg-gray-400'
case 'error': return 'bg-red-500'
default: return 'bg-gray-400'
}
}
</script>

View File

@@ -5,14 +5,22 @@
<!-- Navigation bar --> <!-- Navigation bar -->
<nav class="absolute bottom-0 left-0 right-0 transform-none md:transform md:translate-y-full md:group-hover:translate-y-0 md:transition-transform md:duration-300 md:ease-in-out bg-white md:bg-transparent border-t md:border-t-0 border-gray-200 md:shadow-none shadow-lg"> <nav class="absolute bottom-0 left-0 right-0 transform-none md:transform md:translate-y-full md:group-hover:translate-y-0 md:transition-transform md:duration-300 md:ease-in-out bg-white md:bg-transparent border-t md:border-t-0 border-gray-200 md:shadow-none shadow-lg">
<div class="flex justify-center md:pb-4 pb-2"> <div class="flex justify-center md:pb-4 pb-2">
<ul class="flex space-x-8 md:bg-white md:rounded-lg md:shadow-md px-6 py-3 w-full md:w-auto justify-around md:justify-center"> <ul class="flex space-x-4 md:space-x-8 md:bg-white md:rounded-lg md:shadow-md px-6 py-3 w-full md:w-auto justify-around md:justify-center">
<li> <li>
<a class="flex flex-col items-center text-blue-600 font-medium" aria-current="page" href="#"> <router-link to="/" class="flex flex-col items-center font-medium" :class="$route.name === 'home' ? 'text-blue-600' : 'text-gray-600 hover:text-blue-600'">
<svg class="w-6 h-6 mb-1" fill="currentColor" viewBox="0 0 24 24"> <svg class="w-6 h-6 mb-1" fill="currentColor" viewBox="0 0 24 24">
<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/> <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
</svg> </svg>
<span class="text-xs">Home</span> <span class="text-xs">Dashboard</span>
</a> </router-link>
</li>
<li>
<router-link to="/sensors" class="flex flex-col items-center font-medium" :class="$route.name === 'sensors' ? 'text-blue-600' : 'text-gray-600 hover:text-blue-600'">
<svg class="w-6 h-6 mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z"/>
</svg>
<span class="text-xs">Sensors</span>
</router-link>
</li> </li>
<li> <li>
<a class="flex flex-col items-center text-gray-600 hover:text-blue-600" href="#"> <a class="flex flex-col items-center text-gray-600 hover:text-blue-600" href="#">
@@ -22,14 +30,6 @@
<span class="text-xs">Analytics</span> <span class="text-xs">Analytics</span>
</a> </a>
</li> </li>
<li>
<a class="flex flex-col items-center text-gray-600 hover:text-blue-600" href="#">
<svg class="w-6 h-6 mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
</svg>
<span class="text-xs">Users</span>
</a>
</li>
<li> <li>
<a class="flex flex-col items-center text-gray-400 cursor-not-allowed" aria-disabled="true"> <a class="flex flex-col items-center text-gray-400 cursor-not-allowed" aria-disabled="true">
<svg class="w-6 h-6 mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg class="w-6 h-6 mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">

View File

@@ -0,0 +1,228 @@
<template>
<div class="fixed inset-0 z-50 flex items-center justify-center">
<!-- Backdrop -->
<div class="absolute inset-0 bg-black bg-opacity-50" @click="$emit('close')"></div>
<!-- Modal -->
<div
class="relative bg-white rounded-2xl shadow-xl max-w-md w-full mx-4 max-h-[90vh] overflow-y-auto"
>
<!-- Header -->
<div class="p-6 border-b border-gray-100">
<div class="flex items-center justify-between">
<div>
<h3 class="text-lg font-medium text-gray-900">{{ action.name }}</h3>
<p class="text-sm text-gray-600">{{ sensor.name }} {{ sensor.room }}</p>
</div>
<button
@click="$emit('close')"
class="p-2 hover:bg-gray-100 rounded-full transition-colors"
>
<svg class="w-5 h-5 text-gray-400" fill="currentColor" viewBox="0 0 24 24">
<path
d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
/>
</svg>
</button>
</div>
</div>
<!-- Content -->
<div class="p-6">
<div class="space-y-4">
<!-- Range Input (for numeric parameters) -->
<div v-if="action.type === 'adjust' && hasNumericRange">
<label class="block text-sm font-medium text-gray-700 mb-2">
{{ action.name }}
</label>
<div class="space-y-3">
<input
v-model.number="numericValue"
type="range"
:min="action.parameters.min"
:max="action.parameters.max"
:step="action.parameters.step"
class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer slider"
/>
<div class="flex justify-between text-sm text-gray-600">
<span>{{ action.parameters.min }}</span>
<span class="font-medium">{{ numericValue }}{{ getUnit() }}</span>
<span>{{ action.parameters.max }}</span>
</div>
</div>
</div>
<!-- Option Selection -->
<div v-if="action.type === 'adjust' && action.parameters?.options">
<label class="block text-sm font-medium text-gray-700 mb-2">
{{ action.name }}
</label>
<div class="grid grid-cols-2 gap-2">
<button
v-for="option in action.parameters.options"
:key="option"
@click="selectedOption = option"
class="px-3 py-2 border rounded-lg text-sm font-medium transition-colors"
:class="
selectedOption === option
? 'bg-blue-500 text-white border-blue-500'
: 'bg-white text-gray-700 border-gray-200 hover:bg-gray-50'
"
>
{{ option }}
</button>
</div>
</div>
<!-- Toggle Action -->
<div v-if="action.type === 'toggle'">
<div class="flex items-center justify-between">
<span class="text-sm font-medium text-gray-700">{{ action.name }}</span>
<button
@click="toggleValue = !toggleValue"
class="relative inline-flex h-6 w-11 items-center rounded-full transition-colors"
:class="toggleValue ? 'bg-blue-600' : 'bg-gray-200'"
>
<span
class="inline-block h-4 w-4 transform rounded-full bg-white transition-transform"
:class="toggleValue ? 'translate-x-6' : 'translate-x-1'"
/>
</button>
</div>
<p class="text-sm text-gray-500 mt-1">
Current state: {{ toggleValue ? 'ON' : 'OFF' }}
</p>
</div>
<!-- Trigger Action -->
<div v-if="action.type === 'trigger'">
<div class="bg-gray-50 rounded-lg p-4">
<div class="flex items-center gap-3">
<span class="text-2xl">{{ action.icon }}</span>
<div>
<div class="font-medium text-gray-900">{{ action.name }}</div>
<div class="text-sm text-gray-600">Click execute to perform this action</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Footer -->
<div class="px-6 py-4 bg-gray-50 rounded-b-2xl flex gap-3">
<button
@click="$emit('close')"
class="flex-1 px-4 py-2 border border-gray-200 rounded-lg text-gray-700 font-medium hover:bg-gray-100 transition-colors"
>
Cancel
</button>
<button
@click="executeAction"
:disabled="isExecuting"
class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 disabled:bg-blue-400 disabled:cursor-not-allowed transition-colors"
>
{{ isExecuting ? 'Executing...' : 'Execute' }}
</button>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
const props = defineProps<{
sensor: any
action: any
}>()
const emit = defineEmits<{
execute: [sensorId: string, actionId: string, parameters: any]
close: []
}>()
const isExecuting = ref(false)
const numericValue = ref(0)
const selectedOption = ref('')
const toggleValue = ref(false)
// Initialize default values
watch(
() => props.action,
(action) => {
if (action) {
if (action.parameters?.min !== undefined) {
numericValue.value = action.parameters.min
}
if (action.parameters?.options?.length > 0) {
selectedOption.value = action.parameters.options[0]
}
toggleValue.value = false
}
},
{ immediate: true },
)
const hasNumericRange = computed(() => {
return (
props.action.parameters?.min !== undefined &&
props.action.parameters?.max !== undefined &&
!props.action.parameters?.options
)
})
const getUnit = () => {
if (props.action.id === 'temp_adjust') return '°C'
if (props.action.id === 'brightness') return '%'
if (props.action.id === 'fan_speed') return ''
return ''
}
const executeAction = async () => {
isExecuting.value = true
let parameters: any = {}
if (props.action.type === 'adjust') {
if (hasNumericRange.value) {
parameters.value = numericValue.value
} else if (props.action.parameters?.options) {
parameters.value = selectedOption.value
}
} else if (props.action.type === 'toggle') {
parameters.enabled = toggleValue.value
}
try {
emit('execute', props.sensor.id, props.action.id, parameters)
} catch (error) {
console.error('Failed to execute action:', error)
} finally {
isExecuting.value = false
}
}
</script>
<style scoped>
/* Custom slider styling */
.slider::-webkit-slider-thumb {
appearance: none;
height: 20px;
width: 20px;
border-radius: 50%;
background: #3b82f6;
cursor: pointer;
box-shadow: 0 0 2px 0 rgba(0, 0, 0, 0.2);
}
.slider::-moz-range-thumb {
height: 20px;
width: 20px;
border-radius: 50%;
background: #3b82f6;
cursor: pointer;
border: none;
box-shadow: 0 0 2px 0 rgba(0, 0, 0, 0.2);
}
</style>

View File

@@ -1,5 +1,6 @@
import { createRouter, createWebHistory } from 'vue-router' import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue' import HomeView from '../views/HomeView.vue'
import SensorManagementView from '../views/SensorManagementView.vue'
const router = createRouter({ const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
@@ -9,6 +10,11 @@ const router = createRouter({
name: 'home', name: 'home',
component: HomeView, component: HomeView,
}, },
{
path: '/sensors',
name: 'sensors',
component: SensorManagementView,
},
], ],
}) })

View File

@@ -48,6 +48,38 @@ interface LegacyEnergyData {
unit: string unit: string
} }
interface SensorDevice {
id: string
name: string
type: 'energy' | 'co2' | 'temperature' | 'humidity' | 'hvac' | 'lighting' | 'security'
room: string
status: 'online' | 'offline' | 'error'
lastSeen: number
capabilities: {
monitoring: string[] // e.g., ['energy', 'temperature']
actions: SensorAction[] // Available actions
}
metadata: {
location: string
model?: string
firmware?: string
battery?: number
}
}
interface SensorAction {
id: string
name: string
type: 'toggle' | 'adjust' | 'trigger'
icon: string
parameters?: {
min?: number
max?: number
step?: number
options?: string[]
}
}
export const useEnergyStore = defineStore('energy', () => { export const useEnergyStore = defineStore('energy', () => {
// State // State
const isConnected = ref(false) const isConnected = ref(false)
@@ -63,6 +95,19 @@ export const useEnergyStore = defineStore('energy', () => {
const sensorsData = reactive<Map<string, any>>(new Map()) // Legacy support const sensorsData = reactive<Map<string, any>>(new Map()) // Legacy support
const roomsData = reactive<Map<string, RoomMetrics>>(new Map()) const roomsData = reactive<Map<string, RoomMetrics>>(new Map())
const latestReadings = reactive<Map<string, SensorReading>>(new Map()) const latestReadings = reactive<Map<string, SensorReading>>(new Map())
const sensorDevices = reactive<Map<string, SensorDevice>>(new Map())
const availableRooms = ref<string[]>([
'Conference Room A',
'Conference Room B',
'Office Floor 1',
'Office Floor 2',
'Kitchen',
'Lobby',
'Server Room',
'Storage Room',
'Meeting Room 1',
'Meeting Room 2'
])
let socket: WebSocket | null = null let socket: WebSocket | null = null
const newDataBuffer: (LegacyEnergyData | SensorReading)[] = [] const newDataBuffer: (LegacyEnergyData | SensorReading)[] = []
@@ -233,6 +278,156 @@ export const useEnergyStore = defineStore('energy', () => {
return 'critical' return 'critical'
} }
// Initialize mock sensor devices
function initializeMockSensors() {
const mockSensors: SensorDevice[] = [
{
id: 'sensor_1',
name: 'Energy Monitor 1',
type: 'energy',
room: 'Conference Room A',
status: 'online',
lastSeen: Date.now() / 1000,
capabilities: {
monitoring: ['energy'],
actions: []
},
metadata: {
location: 'Wall mounted',
model: 'EM-100',
firmware: '2.1.0'
}
},
{
id: 'sensor_2',
name: 'HVAC Controller 1',
type: 'hvac',
room: 'Conference Room A',
status: 'online',
lastSeen: Date.now() / 1000,
capabilities: {
monitoring: ['temperature', 'co2'],
actions: [
{ id: 'temp_adjust', name: 'Adjust Temperature', type: 'adjust', icon: '🌡️', parameters: { min: 18, max: 28, step: 0.5 } },
{ id: 'fan_speed', name: 'Fan Speed', type: 'adjust', icon: '💨', parameters: { min: 0, max: 5, step: 1 } },
{ id: 'power_toggle', name: 'Power', type: 'toggle', icon: '⚡' }
]
},
metadata: {
location: 'Ceiling mounted',
model: 'HVAC-200',
firmware: '3.2.1'
}
},
{
id: 'sensor_3',
name: 'Smart Light Controller',
type: 'lighting',
room: 'Office Floor 1',
status: 'online',
lastSeen: Date.now() / 1000,
capabilities: {
monitoring: ['energy'],
actions: [
{ id: 'brightness', name: 'Brightness', type: 'adjust', icon: '💡', parameters: { min: 0, max: 100, step: 5 } },
{ id: 'power_toggle', name: 'Power', type: 'toggle', icon: '⚡' },
{ id: 'scene', name: 'Scene', type: 'adjust', icon: '🎨', parameters: { options: ['Work', 'Meeting', 'Presentation', 'Relax'] } }
]
},
metadata: {
location: 'Ceiling grid',
model: 'SL-300',
firmware: '1.5.2'
}
},
{
id: 'sensor_4',
name: 'CO2 Sensor',
type: 'co2',
room: 'Meeting Room 1',
status: 'online',
lastSeen: Date.now() / 1000,
capabilities: {
monitoring: ['co2', 'temperature', 'humidity'],
actions: [
{ id: 'calibrate', name: 'Calibrate', type: 'trigger', icon: '⚙️' }
]
},
metadata: {
location: 'Wall mounted',
model: 'CO2-150',
firmware: '2.0.3',
battery: 85
}
},
{
id: 'sensor_5',
name: 'Security Camera',
type: 'security',
room: 'Lobby',
status: 'online',
lastSeen: Date.now() / 1000,
capabilities: {
monitoring: ['motion'],
actions: [
{ id: 'record_toggle', name: 'Recording', type: 'toggle', icon: '📹' },
{ id: 'ptz_control', name: 'Pan/Tilt/Zoom', type: 'trigger', icon: '🎥' },
{ id: 'night_mode', name: 'Night Mode', type: 'toggle', icon: '🌙' }
]
},
metadata: {
location: 'Corner ceiling',
model: 'SEC-400',
firmware: '4.1.0'
}
}
]
mockSensors.forEach(sensor => {
sensorDevices.set(sensor.id, sensor)
})
}
// Sensor management functions
function updateSensorRoom(sensorId: string, newRoom: string) {
const sensor = sensorDevices.get(sensorId)
if (sensor) {
sensor.room = newRoom
sensorDevices.set(sensorId, { ...sensor })
}
}
async function executeSensorAction(sensorId: string, actionId: string, parameters?: any) {
const sensor = sensorDevices.get(sensorId)
if (!sensor) return false
const action = sensor.capabilities.actions.find(a => a.id === actionId)
if (!action) return false
// Simulate API call to device
console.log(`Executing action ${actionId} on sensor ${sensorId}`, parameters)
// Here you would make the actual API call to control the device
// For now, we'll simulate a successful action
return new Promise((resolve) => {
setTimeout(() => {
console.log(`Action ${action.name} executed successfully on ${sensor.name}`)
resolve(true)
}, 1000)
})
}
function getSensorsByRoom(room: string): SensorDevice[] {
return Array.from(sensorDevices.values()).filter(sensor => sensor.room === room)
}
function getSensorsByType(type: SensorDevice['type']): SensorDevice[] {
return Array.from(sensorDevices.values()).filter(sensor => sensor.type === type)
}
// Initialize mock sensors on store creation
initializeMockSensors()
return { return {
isConnected, isConnected,
latestMessage, latestMessage,
@@ -240,8 +435,14 @@ export const useEnergyStore = defineStore('energy', () => {
sensorsData, sensorsData,
roomsData, roomsData,
latestReadings, latestReadings,
sensorDevices,
availableRooms,
connect, connect,
disconnect, disconnect,
getCO2Status getCO2Status,
updateSensorRoom,
executeSensorAction,
getSensorsByRoom,
getSensorsByType
} }
}) })

View File

@@ -0,0 +1,220 @@
<template>
<div class="space-y-6">
<!-- Header -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 class="text-2xl font-bold text-gray-900">Sensor & IoT Management</h1>
<p class="text-gray-600">Manage sensors, assign rooms, and control device actions</p>
</div>
<div class="mt-4 sm:mt-0">
<div class="flex items-center gap-2 text-sm text-gray-600">
<div
class="w-3 h-3 rounded-full"
:class="energyStore.isConnected ? 'bg-green-500' : 'bg-red-500'"
></div>
<span>{{ energyStore.isConnected ? 'Connected' : 'Disconnected' }}</span>
<span class="mx-2"></span>
<span>{{ sensorList.length }} sensors</span>
</div>
</div>
</div>
<!-- Filters and View Toggle -->
<div class="flex flex-col lg:flex-row gap-4">
<!-- Filters -->
<div class="flex flex-col sm:flex-row gap-4 flex-1">
<select
v-model="selectedRoom"
class="px-4 py-2 border border-gray-200 rounded-lg bg-white"
>
<option value="">All Rooms</option>
<option v-for="room in energyStore.availableRooms" :key="room" :value="room">
{{ room }}
</option>
</select>
<select
v-model="selectedType"
class="px-4 py-2 border border-gray-200 rounded-lg bg-white"
>
<option value="">All Types</option>
<option value="energy">Energy</option>
<option value="co2">CO2</option>
<option value="temperature">Temperature</option>
<option value="hvac">HVAC</option>
<option value="lighting">Lighting</option>
<option value="security">Security</option>
</select>
<select
v-model="selectedStatus"
class="px-4 py-2 border border-gray-200 rounded-lg bg-white"
>
<option value="">All Status</option>
<option value="online">Online</option>
<option value="offline">Offline</option>
<option value="error">Error</option>
</select>
</div>
<!-- View Toggle -->
<div class="flex items-center gap-2 bg-gray-100 rounded-lg p-1">
<button
@click="viewMode = 'simple'"
class="px-3 py-1.5 rounded text-sm font-medium transition-colors"
:class="viewMode === 'simple'
? 'bg-white text-gray-900 shadow-sm'
: 'text-gray-600 hover:text-gray-900'"
>
<div class="flex items-center gap-1">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"/>
</svg>
Simple
</div>
</button>
<button
@click="viewMode = 'detailed'"
class="px-3 py-1.5 rounded text-sm font-medium transition-colors"
:class="viewMode === 'detailed'
? 'bg-white text-gray-900 shadow-sm'
: 'text-gray-600 hover:text-gray-900'"
>
<div class="flex items-center gap-1">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
</svg>
Detailed
</div>
</button>
</div>
</div>
<!-- Sensors Grid -->
<div
class="grid gap-4"
:class="viewMode === 'simple'
? 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'
: 'grid-cols-1 lg:grid-cols-2 xl:grid-cols-3'"
>
<!-- Simple Cards -->
<SimpleSensorCard
v-if="viewMode === 'simple'"
v-for="sensor in filteredSensors"
:key="sensor.id"
:sensor="sensor"
:is-executing-action="isExecutingAction"
@execute-action="executeAction"
@show-more="showSensorDetails"
/>
<!-- Detailed Cards -->
<DetailedSensorCard
v-if="viewMode === 'detailed'"
v-for="sensor in filteredSensors"
:key="sensor.id"
:sensor="sensor"
:available-rooms="energyStore.availableRooms"
:is-executing-action="isExecutingAction"
@update-room="updateRoom"
@execute-action="executeAction"
/>
</div>
<!-- Empty State -->
<div v-if="filteredSensors.length === 0" class="text-center py-12">
<div class="text-gray-400 text-6xl mb-4">🔍</div>
<h3 class="text-lg font-medium text-gray-900 mb-2">No sensors found</h3>
<p class="text-gray-600">Try adjusting your filters or check if sensors are connected.</p>
</div>
<!-- Action Modal -->
<ActionModal
v-if="showActionModal"
:sensor="selectedSensor"
:action="selectedAction"
@execute="handleActionExecute"
@close="closeActionModal"
/>
</div>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'
import { useEnergyStore } from '@/stores/energy'
import ActionModal from '@/components/modals/ActionModal.vue'
import SimpleSensorCard from '@/components/cards/SimpleSensorCard.vue'
import DetailedSensorCard from '@/components/cards/DetailedSensorCard.vue'
const energyStore = useEnergyStore()
// View mode
const viewMode = ref<'simple' | 'detailed'>('simple')
// Filters
const selectedRoom = ref('')
const selectedType = ref('')
const selectedStatus = ref('')
// Action modal
const showActionModal = ref(false)
const selectedSensor = ref<any>(null)
const selectedAction = ref<any>(null)
const isExecutingAction = ref(false)
const sensorList = computed(() => {
return Array.from(energyStore.sensorDevices.values()).sort((a, b) =>
a.name.localeCompare(b.name)
)
})
const filteredSensors = computed(() => {
return sensorList.value.filter(sensor => {
const matchesRoom = !selectedRoom.value || sensor.room === selectedRoom.value
const matchesType = !selectedType.value || sensor.type === selectedType.value
const matchesStatus = !selectedStatus.value || sensor.status === selectedStatus.value
return matchesRoom && matchesType && matchesStatus
})
})
const updateRoom = (sensorId: string, newRoom: string) => {
energyStore.updateSensorRoom(sensorId, newRoom)
}
const executeAction = (sensor: any, action: any) => {
if (action.parameters) {
// Show modal for actions with parameters
selectedSensor.value = sensor
selectedAction.value = action
showActionModal.value = true
} else {
// Execute simple actions directly
handleActionExecute(sensor.id, action.id, {})
}
}
const handleActionExecute = async (sensorId: string, actionId: string, parameters: any) => {
isExecutingAction.value = true
try {
await energyStore.executeSensorAction(sensorId, actionId, parameters)
} catch (error) {
console.error('Action execution failed:', error)
} finally {
isExecutingAction.value = false
closeActionModal()
}
}
const closeActionModal = () => {
showActionModal.value = false
selectedSensor.value = null
selectedAction.value = null
}
const showSensorDetails = (sensor: any) => {
// Switch to detailed view when user wants to see more actions
viewMode.value = 'detailed'
// Optionally scroll to the sensor or highlight it
}
</script>