定义设备状态池
This commit is contained in:
67
internal/service/device_status.go
Normal file
67
internal/service/device_status.go
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
// Package service 提供各种业务服务功能
|
||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DeviceStatus 设备状态信息
|
||||||
|
type DeviceStatus struct {
|
||||||
|
// Active 设备是否启动
|
||||||
|
Active bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeviceStatusPool 设备状态池,用于管理所有设备的当前状态
|
||||||
|
type DeviceStatusPool struct {
|
||||||
|
// statuses 设备状态映射 设备ID:状态
|
||||||
|
statuses map[string]*DeviceStatus
|
||||||
|
|
||||||
|
// mutex 读写锁,保证并发安全
|
||||||
|
mutex sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDeviceStatusPool 创建设备状态池实例
|
||||||
|
func NewDeviceStatusPool() *DeviceStatusPool {
|
||||||
|
return &DeviceStatusPool{
|
||||||
|
statuses: make(map[string]*DeviceStatus),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetStatus 设置设备状态
|
||||||
|
func (dsp *DeviceStatusPool) SetStatus(deviceID string, status *DeviceStatus) {
|
||||||
|
dsp.mutex.Lock()
|
||||||
|
defer dsp.mutex.Unlock()
|
||||||
|
|
||||||
|
dsp.statuses[deviceID] = status
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetStatus 获取设备状态
|
||||||
|
func (dsp *DeviceStatusPool) GetStatus(deviceID string) (*DeviceStatus, bool) {
|
||||||
|
dsp.mutex.RLock()
|
||||||
|
defer dsp.mutex.RUnlock()
|
||||||
|
|
||||||
|
status, exists := dsp.statuses[deviceID]
|
||||||
|
return status, exists
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteStatus 删除设备状态
|
||||||
|
func (dsp *DeviceStatusPool) DeleteStatus(deviceID string) {
|
||||||
|
dsp.mutex.Lock()
|
||||||
|
defer dsp.mutex.Unlock()
|
||||||
|
|
||||||
|
delete(dsp.statuses, deviceID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAllStatuses 获取所有设备状态
|
||||||
|
func (dsp *DeviceStatusPool) GetAllStatuses() map[string]*DeviceStatus {
|
||||||
|
dsp.mutex.RLock()
|
||||||
|
defer dsp.mutex.RUnlock()
|
||||||
|
|
||||||
|
// 创建副本以避免外部修改
|
||||||
|
result := make(map[string]*DeviceStatus)
|
||||||
|
for id, status := range dsp.statuses {
|
||||||
|
result[id] = status
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user