forked from flosse/go-modbus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdu.go
37 lines (29 loc) · 739 Bytes
/
pdu.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Copyright (C) 2014 - 2015, Markus Kohlhase <[email protected]>
*/
package modbus
import (
"fmt"
)
type Pdu struct {
// Function Code
Function uint8
// PDU data
Data []byte
}
const pduLength = 253
func (pdu *Pdu) pack() (bin []byte, err error) {
if pdu.Function < 1 {
return nil, fmt.Errorf("Invalid function code %d", pdu.Function)
}
if l := len(pdu.Data); l > pduLength-1 {
return nil, fmt.Errorf("Invalid length of data (%d instead of max. %d bytes)", l, pduLength-1)
}
return append([]byte{pdu.Function}, pdu.Data...), nil
}
func unpackPdu(data []byte) (*Pdu, error) {
if l := len(data); l < 1 {
return nil, fmt.Errorf("Invalid PDU length (%d bytes)", l)
}
return &Pdu{data[0], data[1:]}, nil
}