package connection import ( "sync" "time" "github.com/rs/xid" "go.bug.st/serial" ) // SerialConnection 串口连接包装器 type SerialConnection struct { id string port serial.Port mu sync.RWMutex createdAt time.Time lastActive time.Time attributes map[string]interface{} } // NewSerialConnection 创建串口连接 // 如果id为空,将自动生成唯一的xid func NewSerialConnection(id string, port serial.Port) *SerialConnection { if id == "" { id = xid.New().String() } return &SerialConnection{ id: id, port: port, createdAt: time.Now(), lastActive: time.Now(), attributes: make(map[string]interface{}), } } // ID 获取连接ID func (c *SerialConnection) ID() string { return c.id } // RemoteAddr 获取远程地址(串口使用设备路径作为地址) func (c *SerialConnection) RemoteAddr() string { // 串口没有远程地址的概念,返回设备路径或固定值 return "serial://" + c.id } // LocalAddr 获取本地地址 func (c *SerialConnection) LocalAddr() string { // 串口没有本地地址的概念,返回设备路径或固定值 return "serial://" + c.id } // Write 写入数据 func (c *SerialConnection) Write(data []byte) error { c.mu.Lock() c.lastActive = time.Now() c.mu.Unlock() if c.port != nil { _, err := c.port.Write(data) return err } return nil } // Close 关闭连接 func (c *SerialConnection) Close() error { if c.port != nil { return c.port.Close() } return nil } // SetAttribute 设置属性 func (c *SerialConnection) SetAttribute(key string, value interface{}) { c.mu.Lock() defer c.mu.Unlock() if c.attributes == nil { c.attributes = make(map[string]interface{}) } c.attributes[key] = value } // GetAttribute 获取属性 func (c *SerialConnection) GetAttribute(key string) interface{} { c.mu.RLock() defer c.mu.RUnlock() if c.attributes == nil { return nil } return c.attributes[key] } // LastActive 获取最后活动时间 func (c *SerialConnection) LastActive() time.Time { c.mu.RLock() defer c.mu.RUnlock() return c.lastActive } // UpdateActive 更新活动时间 func (c *SerialConnection) UpdateActive() { c.mu.Lock() defer c.mu.Unlock() c.lastActive = time.Now() }