提交 e34b44ca 编写于 作者: J jason

协议小优化

上级 73ad0664
package protocol
import (
"iot-master/base"
)
type Adapter interface {
Name() string
Version() string
Attach(link base.Link)
Read(slave uint8, code uint8, offset uint16, size uint16) ([]byte, error)
Write(slave uint8, code uint8, offset uint16, buf []byte) error
}
......@@ -4,14 +4,14 @@ import (
"errors"
"fmt"
"iot-master/base"
"iot-master/protocol/adapter"
"iot-master/protocol"
"iot-master/protocol/helper"
)
func init() {
adapter.RegisterAdapter(
protocol.RegisterAdapter(
"Modbus RTU",
[]adapter.Code{
[]protocol.Code{
{"线圈", 1},
{"离散量", 2},
{"保持寄存器", 3},
......@@ -30,7 +30,7 @@ type RTU struct {
resp chan response
}
func NewModbusRtu(opts string) (adapter.Adapter, error) {
func NewModbusRtu(opts string) (protocol.Adapter, error) {
return &RTU{
resp: make(chan response, 1),
}, nil
......
package adapter
package protocol
import (
"errors"
"iot-master/base"
"sync"
)
type Adapter interface {
Name() string
Version() string
Attach(link base.Link)
Read(slave uint8, code uint8, offset uint16, size uint16) ([]byte, error)
Write(slave uint8, code uint8, offset uint16, buf []byte) error
}
type Factory func(opts string) (Adapter, error)
//可以改为普通map
var protocols sync.Map //adapters
//功能码
type Code struct {
Name string `json:"name"`
Code uint8 `json:"code"`
}
type adapter struct {
type adapters struct {
Name string `json:"name"`
Codes []Code `json:"codes"`
factory Factory
}
//可以改为普通map
var protocols sync.Map //adapter
type Factory func(opts string) (Adapter, error)
func GetProtocols() []adapter {
ps := make([]adapter, 0)
func GetProtocols() []adapters {
ps := make([]adapters, 0)
protocols.Range(func(key, value interface{}) bool {
ps = append(ps, value.(adapter))
ps = append(ps, value.(adapters))
return true
})
return ps
......@@ -43,14 +33,14 @@ func GetProtocols() []adapter {
func CreateAdapter(name string, opts string) (Adapter, error) {
if v, ok := protocols.Load(name); ok && v != nil {
p := v.(*adapter)
p := v.(*adapters)
return p.factory(opts)
}
return nil, errors.New("找不到协议")
}
func RegisterAdapter(name string, codes []Code, factory Factory) {
protocols.Store(name, &adapter{
protocols.Store(name, &adapters{
Name: name,
Codes: codes,
factory: factory,
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册