| | |
| | | // MakeReadProtocol 创建读取数据的协议 |
| | | MakeReadProtocol(addr string) []byte |
| | | |
| | | // MakeReadProtocolBits 创建读取数据的协议 |
| | | MakeReadProtocolBits(bits int, addr string) []byte |
| | | |
| | | // MakeWriteProtocol 创建写入数据的协议 |
| | | MakeWriteProtocol(addr string, value int) []byte |
| | | |
| | | MakeWriteProtocolBits(bits int, addr string, ival int) []byte |
| | | |
| | | // ParseReadValue 解析从设备读取的值 |
| | | ParseReadValue(data []byte) int |
| | | |
| | | ParseReadValueBits(data []byte) int |
| | | |
| | | // ParseWriteValue 解析写入设备的结果,并返回结果和是否成功 |
| | | ParseWriteValue(data []byte) (int, bool) |
| | |
| | | return protocol, nil |
| | | } |
| | | |
| | | func ReadPLC(deviceType, url, label string) (val int, err error) { |
| | | func ReadPLC(deviceType, url, label string, length int) (val int, err error) { |
| | | protocol, err := LoadProtocol(deviceType) |
| | | if err != nil { |
| | | return 0, err |
| | | } |
| | | addr := protocol.ConvertLabelToAddress(label) |
| | | proto := protocol.MakeReadProtocol(addr) |
| | | var proto []byte |
| | | if length == 1 { |
| | | proto = protocol.MakeReadProtocol(addr) |
| | | } else { |
| | | proto = protocol.MakeReadProtocolBits(length*16, addr) |
| | | } |
| | | |
| | | bp := base64.StdEncoding.EncodeToString(proto) |
| | | fullUrl := fmt.Sprintf("%v?proto=%v", url, bp) |
| | | resp, err := http.Get(fullUrl) |
| | |
| | | logx.Errorf("ReadPLC base64.StdEncoding.DecodeString failed: %v, data: %v", err, string(body)) |
| | | return 0, err |
| | | } |
| | | if length == 1 { |
| | | val = protocol.ParseReadValue(data) |
| | | } else { |
| | | val = protocol.ParseReadValueBits(data) |
| | | } |
| | | |
| | | fmt.Println("read PLC:", val) |
| | | return val, nil |
| | | |
| | |
| | | return err |
| | | } |
| | | addr := protocol.ConvertLabelToAddress(label) |
| | | proto := protocol.MakeWriteProtocol(addr, val) |
| | | var proto []byte |
| | | if val < 65536 { |
| | | proto = protocol.MakeWriteProtocol(addr, val) |
| | | } else { |
| | | proto = protocol.MakeWriteProtocolBits(32, addr, val) |
| | | } |
| | | |
| | | bp := base64.StdEncoding.EncodeToString(proto) |
| | | resp, err := http.Post(url, "text/plain", strings.NewReader(bp)) |
| | | if err != nil { |