70 lines
1.4 KiB
Go

package model
import (
"net"
"sync"
"time"
)
// DeviceType 设备类型枚举
type DeviceType string
const (
DeviceTypeEcowitt DeviceType = "ECOWITT"
DeviceTypeWH65LP DeviceType = "WH65LP"
DeviceTypeUnknown DeviceType = "UNKNOWN"
)
// MemoryDevice 内存中的设备信息
type MemoryDevice struct {
IP string
LastSeen time.Time
StationID string
DeviceType DeviceType
}
var (
devices = make(map[string]*MemoryDevice)
deviceMutex sync.RWMutex
)
// UpdateDeviceInMemory 更新内存中的设备信息
func UpdateDeviceInMemory(stationID string, addr net.Addr, deviceType DeviceType) {
ip, _, _ := net.SplitHostPort(addr.String())
deviceMutex.Lock()
defer deviceMutex.Unlock()
devices[stationID] = &MemoryDevice{
IP: ip,
LastSeen: time.Now(),
StationID: stationID,
DeviceType: deviceType,
}
}
// GetOnlineDevicesFromMemory 获取内存中的在线设备
func GetOnlineDevicesFromMemory() []*MemoryDevice {
deviceMutex.RLock()
defer deviceMutex.RUnlock()
result := make([]*MemoryDevice, 0, len(devices))
for _, device := range devices {
if time.Since(device.LastSeen) < 10*time.Minute {
result = append(result, device)
}
}
return result
}
// GetDeviceTypeFromMemory 从内存中获取设备类型
func GetDeviceTypeFromMemory(stationID string) DeviceType {
deviceMutex.RLock()
defer deviceMutex.RUnlock()
if device, ok := devices[stationID]; ok {
return device.DeviceType
}
return DeviceTypeUnknown
}