From f8aa2138ab5f53fab70c7b811861eab61ee58f9f Mon Sep 17 00:00:00 2001 From: Eli Yip Date: Wed, 4 Jun 2025 09:27:14 +0800 Subject: [PATCH] refactor: keep legacy sensor data --- api/legacy/handlers.go | 61 +++++------------------ api/router.go | 3 +- api/sensor_handlers.go | 93 ++---------------------------------- component/pressure_sensor.go | 78 ------------------------------ component/sensor.go | 62 +++++++++++++++++------- device/device.go | 14 +++--- device/models/l10.go | 20 +++----- 7 files changed, 76 insertions(+), 255 deletions(-) delete mode 100644 component/pressure_sensor.go diff --git a/api/legacy/handlers.go b/api/legacy/handlers.go index 6fd1993..77556f7 100644 --- a/api/legacy/handlers.go +++ b/api/legacy/handlers.go @@ -7,7 +7,6 @@ import ( "hands/config" "hands/define" - "hands/device" "github.com/gin-gonic/gin" ) @@ -430,7 +429,6 @@ func (s *LegacyServer) handleAnimation(c *gin.Context) { } // handleSensors 获取传感器数据处理函数 -// TODO: 现在的传感器数据都是模拟的,先不进行严格定义,等到有文档了之后修改设备层和这里 func (s *LegacyServer) handleSensors(c *gin.Context) { // 从查询参数获取接口名称 ifName := c.Query("interface") @@ -455,32 +453,17 @@ func (s *LegacyServer) handleSensors(c *gin.Context) { return } - // 获取设备的传感器组件 - sensorComponents := dev.GetComponents(device.SensorComponent) - - // 构建传感器数据响应 - sensorData := make(map[string]any) - for _, component := range sensorComponents { - sensorId := component.GetID() - data, err := dev.ReadSensorData(sensorId) - if err != nil { - // 如果读取失败,记录错误状态 - sensorData[sensorId] = map[string]any{ - "error": err.Error(), - "timestamp": time.Now(), - } - continue - } - - sensorData[sensorId] = map[string]any{ - "values": data.Values(), - "timestamp": data.Timestamp(), - } + sensorData, err := dev.ReadSensorData() + if err != nil { + c.JSON(http.StatusInternalServerError, define.ApiResponse{ + Status: "error", + Error: "获取传感器数据失败:" + err.Error(), + }) } c.JSON(http.StatusOK, define.ApiResponse{ Status: "success", - Data: sensorData, + Data: sensorData.Values(), }) } else { // 返回所有接口的传感器数据 @@ -490,35 +473,17 @@ func (s *LegacyServer) handleSensors(c *gin.Context) { // 获取对应的设备 dev, err := s.mapper.GetDeviceForInterface(ifName) if err != nil { - allSensorData[ifName] = map[string]any{ - "error": "设备不可用:" + err.Error(), - } + allSensorData[ifName] = map[string]any{"error": "设备不可用:" + err.Error()} continue } - // 获取设备的传感器组件 - sensorComponents := dev.GetComponents(device.SensorComponent) - - // 构建传感器数据响应 - sensorData := make(map[string]any) - for _, component := range sensorComponents { - sensorId := component.GetID() - data, err := dev.ReadSensorData(sensorId) - if err != nil { - sensorData[sensorId] = map[string]any{ - "error": err.Error(), - "timestamp": time.Now(), - } - continue - } - - sensorData[sensorId] = map[string]any{ - "values": data.Values(), - "timestamp": data.Timestamp(), - } + sensorData, err := dev.ReadSensorData() + if err != nil { + allSensorData[ifName] = map[string]any{"error": "设备不可用:" + err.Error()} + continue } - allSensorData[ifName] = sensorData + allSensorData[ifName] = sensorData.Values() } c.JSON(http.StatusOK, define.ApiResponse{ diff --git a/api/router.go b/api/router.go index 5ad18ea..9ae9d38 100644 --- a/api/router.go +++ b/api/router.go @@ -67,8 +67,7 @@ func (s *Server) SetupRoutes(r *gin.Engine) { // 传感器数据路由 sensors := deviceRoutes.Group("/sensors") { - sensors.GET("", s.handleGetSensors) // 获取所有传感器数据 - sensors.GET("/:sensorId", s.handleGetSensorData) // 获取特定传感器数据 + sensors.GET("", s.handleGetSensors) // 获取所有传感器数据 } // 设备状态路由 diff --git a/api/sensor_handlers.go b/api/sensor_handlers.go index 67a35f8..dfb1365 100644 --- a/api/sensor_handlers.go +++ b/api/sensor_handlers.go @@ -3,7 +3,6 @@ package api import ( "fmt" "net/http" - "time" "hands/device" @@ -24,103 +23,17 @@ func (s *Server) handleGetSensors(c *gin.Context) { return } - // 获取设备的传感器组件 - sensorComponents := dev.GetComponents(device.SensorComponent) - - sensors := make([]SensorDataResponse, 0, len(sensorComponents)) - - // 遍历所有传感器组件,读取数据 - for _, component := range sensorComponents { - sensorId := component.GetID() - - // 读取传感器数据 - sensorData, err := dev.ReadSensorData(sensorId) - if err != nil { - // 如果读取失败,创建一个错误状态的传感器数据 - sensors = append(sensors, SensorDataResponse{ - SensorID: sensorId, - Timestamp: time.Now(), - Values: map[string]any{ - "error": err.Error(), - "status": "error", - }, - }) - continue - } - - // 转换为响应格式 - sensorResponse := SensorDataResponse{ - SensorID: sensorData.SensorID(), - Timestamp: sensorData.Timestamp(), - Values: sensorData.Values(), - } - sensors = append(sensors, sensorResponse) - } - - response := SensorListResponse{ - Sensors: sensors, - Total: len(sensors), - } - - c.JSON(http.StatusOK, ApiResponse{ - Status: "success", - Data: response, - }) -} - -// handleGetSensorData 获取特定传感器数据 -func (s *Server) handleGetSensorData(c *gin.Context) { - deviceId := c.Param("deviceId") - sensorId := c.Param("sensorId") - - // 获取设备 - dev, err := s.deviceManager.GetDevice(deviceId) - if err != nil { - c.JSON(http.StatusNotFound, ApiResponse{ - Status: "error", - Error: fmt.Sprintf("设备 %s 不存在", deviceId), - }) - return - } - - // 验证传感器是否存在 - sensorComponents := dev.GetComponents(device.SensorComponent) - sensorExists := false - for _, component := range sensorComponents { - if component.GetID() == sensorId { - sensorExists = true - break - } - } - - if !sensorExists { - c.JSON(http.StatusNotFound, ApiResponse{ - Status: "error", - Error: fmt.Sprintf("设备 %s 上不存在传感器 %s", deviceId, sensorId), - }) - return - } - - // 读取传感器数据 - sensorData, err := dev.ReadSensorData(sensorId) + sensorData, err := dev.ReadSensorData() if err != nil { c.JSON(http.StatusInternalServerError, ApiResponse{ Status: "error", - Error: fmt.Sprintf("读取传感器 %s 数据失败:%v", sensorId, err), + Error: fmt.Sprintf("读取传感器数据失败:%v", err), }) - return - } - - // 转换为响应格式 - response := SensorDataResponse{ - SensorID: sensorData.SensorID(), - Timestamp: sensorData.Timestamp(), - Values: sensorData.Values(), } c.JSON(http.StatusOK, ApiResponse{ Status: "success", - Data: response, + Data: sensorData.Values(), }) } diff --git a/component/pressure_sensor.go b/component/pressure_sensor.go deleted file mode 100644 index 1c74a69..0000000 --- a/component/pressure_sensor.go +++ /dev/null @@ -1,78 +0,0 @@ -package component - -import ( - "fmt" - "hands/device" - "math/rand/v2" - "time" -) - -// PressureSensor 压力传感器实现 -type PressureSensor struct { - id string - config map[string]any - isActive bool - samplingRate int - lastReading time.Time -} - -func NewPressureSensor(id string, config map[string]any) *PressureSensor { - return &PressureSensor{ - id: id, - config: config, - isActive: true, - samplingRate: 100, - lastReading: time.Now(), - } -} - -func (p *PressureSensor) GetID() string { - return p.id -} - -func (p *PressureSensor) GetType() device.ComponentType { - return device.SensorComponent -} - -func (p *PressureSensor) GetConfiguration() map[string]any { - return p.config -} - -func (p *PressureSensor) IsActive() bool { - return p.isActive -} - -func (p *PressureSensor) ReadData() (device.SensorData, error) { - if !p.isActive { - return nil, fmt.Errorf("传感器 %s 未激活", p.id) - } - - // 模拟压力数据读取 - // 在实际实现中,这里应该从 can-bridge 或其他数据源读取真实数据 - pressure := rand.Float64() * 100 // 0-100 的随机压力值 - - values := map[string]any{ - "pressure": pressure, - "unit": "kPa", - "location": p.config["location"], - } - - p.lastReading = time.Now() - return NewSensorData(p.id, values), nil -} - -func (p *PressureSensor) GetDataType() string { - return "pressure" -} - -func (p *PressureSensor) GetSamplingRate() int { - return p.samplingRate -} - -func (p *PressureSensor) SetSamplingRate(rate int) error { - if rate <= 0 || rate > 1000 { - return fmt.Errorf("采样率必须在 1-1000Hz 之间") - } - p.samplingRate = rate - return nil -} diff --git a/component/sensor.go b/component/sensor.go index 66b9265..7ed7aa9 100644 --- a/component/sensor.go +++ b/component/sensor.go @@ -2,41 +2,69 @@ package component import ( "hands/device" + "math/rand/v2" "time" ) // Sensor 传感器组件接口 type Sensor interface { - device.Component + // device.Component ReadData() (device.SensorData, error) - GetDataType() string - GetSamplingRate() int - SetSamplingRate(rate int) error + // GetDataType() string + // GetSamplingRate() int + // SetSamplingRate(rate int) error + MockData() } // SensorDataImpl 传感器数据的具体实现 type SensorDataImpl struct { - timestamp time.Time - values map[string]any - sensorID string + Interface string `json:"interface"` + Thumb int `json:"thumb"` + Index int `json:"index"` + Middle int `json:"middle"` + Ring int `json:"ring"` + Pinky int `json:"pinky"` + PalmPosition []byte `json:"palmPosition"` + LastUpdate time.Time `json:"lastUpdate"` } -func NewSensorData(sensorID string, values map[string]any) *SensorDataImpl { +func NewSensorData(ifName string) *SensorDataImpl { return &SensorDataImpl{ - timestamp: time.Now(), - values: values, - sensorID: sensorID, + Interface: ifName, + Thumb: 0, + Index: 0, + Middle: 0, + Ring: 0, + Pinky: 0, + PalmPosition: []byte{128, 128, 128, 128}, + LastUpdate: time.Now(), } } -func (s *SensorDataImpl) Timestamp() time.Time { - return s.timestamp +func (s *SensorDataImpl) MockData() { + go func() { + for { + s.Thumb = rand.IntN(101) + s.Index = rand.IntN(101) + s.Middle = rand.IntN(101) + s.Ring = rand.IntN(101) + s.Pinky = rand.IntN(101) + s.LastUpdate = time.Now() + time.Sleep(500 * time.Millisecond) + } + }() } func (s *SensorDataImpl) Values() map[string]any { - return s.values + return map[string]any{ + "thumb": s.Thumb, + "index": s.Index, + "middle": s.Middle, + "ring": s.Ring, + "pinky": s.Pinky, + "palmPosition": s.PalmPosition, + "lastUpdate": s.LastUpdate, + } } -func (s *SensorDataImpl) SensorID() string { - return s.sensorID -} +func (s *SensorDataImpl) ReadData() (device.SensorData, error) { return s, nil } diff --git a/device/device.go b/device/device.go index 64296d6..6b69425 100644 --- a/device/device.go +++ b/device/device.go @@ -12,7 +12,7 @@ type Device interface { GetHandType() define.HandType // 获取设备手型 SetHandType(handType define.HandType) error // 设置设备手型 ExecuteCommand(cmd Command) error // 执行一个通用指令 - ReadSensorData(sensorID string) (SensorData, error) // 读取特定传感器数据 + ReadSensorData() (SensorData, error) // 读取特定传感器数据 GetComponents(componentType ComponentType) []Component // 获取指定类型的组件 GetStatus() (DeviceStatus, error) // 获取设备状态 Connect() error // 连接设备 @@ -37,9 +37,9 @@ type Command interface { // SensorData 代表从传感器读取的数据 type SensorData interface { - Timestamp() time.Time + // Timestamp() time.Time Values() map[string]any // 例如 {"pressure": 100, "angle": 30.5} - SensorID() string + // SensorID() string } // ComponentType 定义组件类型 @@ -53,10 +53,10 @@ const ( // Component 代表设备的一个可插拔组件 type Component interface { - GetID() string - GetType() ComponentType - GetConfiguration() map[string]interface{} // 组件的特定配置 - IsActive() bool + // GetID() string + // GetType() ComponentType + // GetConfiguration() map[string]interface{} // 组件的特定配置 + // IsActive() bool } // DeviceStatus 代表设备状态 diff --git a/device/models/l10.go b/device/models/l10.go index 83d6628..280816d 100644 --- a/device/models/l10.go +++ b/device/models/l10.go @@ -263,13 +263,9 @@ func (h *L10Hand) ExecuteCommand(cmd device.Command) error { func (h *L10Hand) initializeComponents(_ map[string]any) error { // 初始化传感器组件 - sensors := []device.Component{ - component.NewPressureSensor("pressure_thumb", map[string]any{"location": "thumb"}), - component.NewPressureSensor("pressure_index", map[string]any{"location": "index"}), - component.NewPressureSensor("pressure_middle", map[string]any{"location": "middle"}), - component.NewPressureSensor("pressure_ring", map[string]any{"location": "ring"}), - component.NewPressureSensor("pressure_pinky", map[string]any{"location": "pinky"}), - } + defaultSensor := component.NewSensorData(h.canInterface) + defaultSensor.MockData() + sensors := []device.Component{defaultSensor} h.components[device.SensorComponent] = sensors return nil } @@ -282,19 +278,17 @@ func (h *L10Hand) GetModel() string { return h.model } -func (h *L10Hand) ReadSensorData(sensorID string) (device.SensorData, error) { +func (h *L10Hand) ReadSensorData() (device.SensorData, error) { h.mutex.RLock() defer h.mutex.RUnlock() sensors := h.components[device.SensorComponent] for _, comp := range sensors { - if comp.GetID() == sensorID { - if sensor, ok := comp.(component.Sensor); ok { - return sensor.ReadData() - } + if sensor, ok := comp.(component.Sensor); ok { + return sensor.ReadData() } } - return nil, fmt.Errorf("传感器 %s 不存在", sensorID) + return nil, fmt.Errorf("传感器不存在") } func (h *L10Hand) GetComponents(componentType device.ComponentType) []device.Component {