Documentation
¶
Overview ¶
Package hdlc is our IEC 62056-46 (Ed 1.1, 2002+A1:2006) data link layer for DLMS/COSEM, the 3-layer connection-oriented profile of IEC 62056-7-6 (Ed 1.0, 2013): HDLC frame format type 3, extended addressing with upper (logical device) and lower (physical device) server addresses, the UNC repertoire with UI frames, SNRM/UA parameter negotiation, segmentation, windows of up to seven frames, and the 8802-2 LLC header COSEM uses. Outside that profile, for ISO/IEC 13239 peers, a link can be numbered modulo 128 (SNRME, two-octet control fields, windows up to 127), and UI frames can be sent segmented; both are off unless configured.
Client is a gosem transport (gdlms.Transport) for the DLMS client; Station is the secondary station the meter simulator runs. Both are built from the clauses, not from another implementation; clause numbers are those of IEC 62056-46 unless stated.
Index ¶
- Constants
- Variables
- func AllStationFor(size int) int
- func CallingFor(size int) int
- func EncodeUserData(userData []byte) []byte
- func FCS(b []byte) uint16
- func GoodFCS(b []byte) bool
- type Address
- type Bus
- type Client
- func (c *Client) Close()
- func (c *Client) Connect() error
- func (c *Client) Disconnect() error
- func (c *Client) Expired() int
- func (c *Client) IsConnected() bool
- func (c *Client) Modulo() int
- func (c *Client) Params() Params
- func (c *Client) PeerUserData() []byte
- func (c *Client) Send(apdu []byte) error
- func (c *Client) SendBroadcast(apdu []byte) error
- func (c *Client) SetAddress(client, server int)
- func (c *Client) SetInactivity(d time.Duration)
- func (c *Client) SetLogger(l *log.Logger)
- func (c *Client) SetReception(dc gdlms.DataChannel)
- func (c *Client) Trigger() error
- type Config
- type Control
- type Frame
- type FrameReject
- type Kind
- type Line
- type Params
- type RejectError
- type Scanner
- type Station
Examples ¶
Constants ¶
const ( Modulo8 = 8 Modulo128 = 128 // MaxWindow128 is the largest window under modulo 128 numbering. MaxWindow128 = 127 )
Sequence numbering moduli. DLMS (IEC 62056-46) numbers I frames modulo 8 and so does everything here by default; modulo 128 (ISO/IEC 13239's extended numbering, a two-octet control field on I and S frames) is for ISO/IEC 13239 peers outside the DLMS profile, set up with SNRME.
const ( DefaultMaxInfo = 128 DefaultWindow = 1 MaxWindow = 7 // modulo 8 numbering (6.4.4.4.3.5) )
DefaultMaxInfo and DefaultWindow are the parameter defaults (6.4.4.4.3.2, 6.4.4.10.5, 6.4.4.10.6).
const ( NoStation = 0x00 // client, upper and lower ClientManagement = 0x01 // client management process (Table 3) PublicClient = 0x10 // public client, lowest security (Table 3) ManagementDevice = 0x01 // management logical device, upper (Table 4) AllStation = 0x7F // one-byte all-station (broadcast) AllStation2 = 0x3FFF Calling = 0x7E // CALLING physical device, lower (Table 4, 6.4.2.4) Calling2 = 0x3FFE )
Reserved addresses (Tables 3 and 4), without the extension bit. One-byte values apply to one-octet address parts, two-byte values to the two-octet parts of a four-octet server address.
const Flag = 0x7E
Flag opens and closes every frame (6.4.1.2).
const MaxFrameLength = 0x7FF
MaxFrameLength is the largest value of the 11-bit frame length sub-field.
const MaxInfo = 2030
MaxInfo is the largest information field (6.4.3.3 NOTE 2).
Variables ¶
var ( ErrNoLink = errors.New("no HDLC link (send SNRM first)") ErrRefused = errors.New("the server answered DM: it cannot enter normal response mode") ErrLinkLost = errors.New("the HDLC link was lost") ErrRejected = errors.New("the server rejected a frame (FRMR)") ErrTimeout = errors.New("no HDLC response after the retries") )
Errors a Client returns.
var ( LLCCommand = []byte{0xE6, 0xE6, 0x00} LLCResponse = []byte{0xE6, 0xE7, 0x00} )
LLC headers (5.3.2, Figure 5): destination LSAP 0xE6, source LSAP 0xE6 for a command (client to server) or 0xE7 for a response, quality 0x00. Destination LSAP 0xFF is the broadcast LSAP, never sent but accepted.
var ( ErrHCS = errors.New("the HDLC header check sequence is wrong") ErrFCS = errors.New("the HDLC frame check sequence is wrong") ErrInvalid = errors.New("not a valid HDLC frame") )
Errors of Decode. ErrHCS tells the reader to drop what follows the frame (6.4.4.9.2: its length cannot be trusted).
var ErrFRMRField = errors.New("the FRMR information field is too short")
ErrFRMRField is returned for an FRMR information field too short for its modulo.
var ErrParams = errors.New("incorrect parameter list in the information field")
ErrParams is returned for an information field that is not a parameter list this profile allows; an SNRM carrying one is answered with DM (6.4.4.4.3.2).
Functions ¶
func AllStationFor ¶
AllStationFor is the all-station value of an address part in an address field of size octets (1, 2 or 4).
func CallingFor ¶
CallingFor is the CALLING physical device address for the size.
func EncodeUserData ¶
EncodeUserData is an information field of the format identifier and the user data subfield only, as a DISC carries it (ISO/IEC 13239 5.5.3.1.4 Table 9: DISC has no data link layer subfield); nil without user data.
Types ¶
type Address ¶
Address is an HDLC address field (6.4.2.2): a client address is one octet (Upper only); a server address is one octet (upper only), two (upper and lower, seven bits each) or four (upper and lower, fourteen bits each).
func DecodeAddress ¶
DecodeAddress reads an address field from b and returns it with the octets it took. Only 1, 2 and 4 octet fields are valid (6.4.2.2); a longer or unterminated one is refused.
func ServerAddress ¶
ServerAddress is a server address of the given size.
func (Address) Encode ¶
Encode is the address field (6.4.2.1): seven bits per octet, most significant octet first, the low-order bit 0 on every octet but the last, which has it set.
func (Address) LowerAllStation ¶
LowerAllStation reports an all-station lower part (6.4.2.3).
func (Address) NoStationPart ¶
NoStationPart reports the NO_STATION address in either part.
func (Address) UpperAllStation ¶
UpperAllStation reports an all-station upper part (6.4.2.3).
type Bus ¶
type Bus struct {
// contains filtered or unexported fields
}
Bus is one physical line shared by several servers: a multi-drop arrangement behind one converter (IEC 62056-7-6 9.6, IEC 62056-46 6.4.2.2), each meter a physical device with its own lower HDLC address. It gives every client a Port on the one lower transport, hands them all the octets received (each client keeps the frames addressed to it and from its server), and runs one exchange at a time: a client holds the bus from its command with P until the final frame of the answer, so only one secondary has the right to talk (the master/slave rule of 9.6).
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the primary station of an unbalanced connection-mode link (6.1) over a lower transport that carries octets (TCP to a converter, a serial port). It is a gosem Transport: Connect sends SNRM, Send moves one APDU in I frames and delivers the whole answer, Disconnect sends DISC. SendBroadcast sends an unconfirmed APDU in a UI frame (IEC 62056-7-6 9.1).
func (*Client) Close ¶
func (c *Client) Close()
Close stops the client and closes the lower transport.
func (*Client) Connect ¶
Connect opens the lower transport and sets up the link: SNRM, then UA with the negotiation result or DM (6.4.4.4.3.1). SNRM is repeated after each response time-out, up to the retries. With Modulo 128 the command is SNRME (ISO/IEC 13239 extended numbering), followed by SNRM when ModuloFallback is set and the server does not take SNRME.
func (*Client) Disconnect ¶
Disconnect sends DISC and waits for UA or DM (6.4.4.4.3.3), then closes the lower transport.
func (*Client) IsConnected ¶
IsConnected reports a link in normal response mode on a connected lower transport, not past the server's inactivity time-out.
func (*Client) Modulo ¶ added in v0.3.0
Modulo is the numbering of the link set up last: 8, or 128 after SNRME was accepted.
func (*Client) PeerUserData ¶
PeerUserData is the user data subfield of the server's last UA to our SNRM (ISO/IEC 13239 5.5.3.2.3), nil when it sent none.
func (*Client) Send ¶
Send moves one APDU to the server in I frames and waits for its answer, which it delivers whole to the reception channel. Segments are sent windowed (6.4.4.4.3.4 to 6.4.4.4.3.6); every window ends with P 1 and the server's RR acknowledges it. The answer arrives in windows ending with F 1; while its last frame has the segmentation bit set we poll for more with RR (this also covers the long MSDU transfer of 6.4.4.5). A response time-out after an I frame is recovered with an RR poll, never by repeating the I frame (6.4.4.9.1).
func (*Client) SendBroadcast ¶
SendBroadcast sends an unconfirmed APDU in one UI frame with P 0 to the server address (IEC 62056-7-6 9.1). The UI frame needs no link; its data must fit one frame (6.4.4.4.3.4) unless SegmentUI is set: then a longer APDU goes in UI frames of up to the negotiated information field, each with P 0, all but the last with the segmentation bit.
func (*Client) SetAddress ¶
SetAddress changes the client and logical device (upper) addresses.
func (*Client) SetInactivity ¶
SetInactivity sets the server's inactivity time-out (0: not tracked), for instance once read from its HDLC setup object.
func (*Client) SetReception ¶
func (c *Client) SetReception(dc gdlms.DataChannel)
SetReception sets where whole APDUs go.
type Config ¶
type Config struct {
// Client is our one-octet client address (6.4.2.2).
Client int
// Server is the destination: upper (logical device) and lower
// (physical device) address in a 1, 2 or 4 octet field.
Server Address
// Propose, when set, is sent in the SNRM for negotiation; without it
// the SNRM has no information field and the defaults apply. Windows
// above 7 need Modulo 128.
Propose *Params
// Modulo is the sequence numbering: 0 or 8 for modulo 8, the only one
// IEC 62056-46 (and so DLMS) uses; 128 sets the link up with SNRME for
// ISO/IEC 13239 extended numbering (two-octet control fields on I and
// S frames, windows up to 127).
Modulo int
// ModuloFallback, with Modulo 128, sets the link up with SNRM (modulo
// 8) when the server answers SNRME with DM or FRMR or not at all, so
// the numbering is negotiated rather than required.
ModuloFallback bool
// SegmentUI lets SendBroadcast send an APDU longer than one UI frame
// as UI frames with the segmentation bit set on all but the last. IEC
// 62056-46 6.4.4.4.3.4 keeps a UI frame's data to one frame (F-233),
// so this is off by default; servers that join segmented UI frames,
// such as our Station, take them.
SegmentUI bool
// UserData goes in the SNRM's user data subfield (IEC 62056-7-6 9.3;
// ISO/IEC 13239 5.5.3.2.3).
UserData []byte
// DISCUserData goes in the DISC's user data subfield (IEC 62056-7-6
// 9.3; ISO/IEC 13239 Table 9).
DISCUserData []byte
// ResponseTimeout is TO_WAIT_RESP (6.4.4.10.1), default 3 s.
ResponseTimeout time.Duration
// Retries is MAX_NB_OF_RETRIES (6.4.4.10.2), default 3.
Retries int
// InterOctet is the inter-octet time-out (6.4.4.10.4), default 100 ms
// (the medium here is TCP through a converter or a serial port).
InterOctet time.Duration
// Bus, when set, is the multi-drop line this client shares (lower must
// be one of its ports): every exchange holds the bus.
Bus *Bus
// Inactivity is the server's inactivity time-out (6.4.4.10.3; the
// inactivity_time_out of its HDLC setup object). The server drops the
// link after that long without an octet, so we take the link as gone a
// little before (a tenth, at most 2 s) and set it up again instead of
// sending into a dead link and waiting for DM. 0: not tracked.
Inactivity time.Duration
// OnUI receives the APDU of every UI frame the server sends (event
// notifications, IEC 62056-7-6 9.4), LLC header removed. It runs on the
// reading goroutine and must not block.
OnUI func(from Address, apdu []byte)
}
Config sets up a Client, the primary station.
type Control ¶
Control is a decoded control field.
func ParseControl ¶
ParseControl decodes a control field (Table 7).
func ParseControlModulo ¶ added in v0.3.0
ParseControlModulo decodes a control field under the numbering of modulo (8 or 128). Under modulo 128 an I or S frame has two octets (ISO/IEC 13239 extended control field): the first holds N(S), or the S bits, from bit 2; the second holds P/F in bit 1 and N(R) in bits 2 to 8. Unnumbered frames have one octet in either mode.
type Frame ¶
type Frame struct {
Segmented bool // segmentation bit: more of the MSDU follows
Dest, Src Address
Control byte
Info []byte // nil: no information field (only an FCS)
// Extended marks a two-octet control field (an I or S frame under
// modulo 128 numbering); Control2 is its second octet.
Extended bool
Control2 byte
}
Frame is an HDLC frame of format type 3 (6.4.1).
Example ¶
An SNRM from client 16 to a meter at upper address 1, lower address 17, with two-octet server addresses; the frame is decoded back.
package main
import (
"fmt"
"github.com/cB-Sigma/dlms/hdlc"
)
func main() {
f := hdlc.Frame{Dest: hdlc.ServerAddress(1, 17, 2), Src: hdlc.ClientAddress(16), Control: 0x93}
b, err := f.Encode()
if err != nil {
panic(err)
}
fmt.Printf("% X\n", b)
g, err := hdlc.Decode(b)
fmt.Println(g.Control == 0x93, g.Src == f.Src, err)
}
Output: 7E A0 08 02 23 21 93 BD 64 7E true true <nil>
func Decode ¶
Decode reads a frame from flag to flag. It checks the format type, the length, the address fields, the HCS and FCS, and refuses a frame whose source is the all-station or no-station address (6.4.2.4, 6.4.4.2.3). The control field is one octet (modulo 8 numbering).
func DecodeModulo ¶ added in v0.3.0
DecodeModulo is Decode for a link numbered modulo 8 or 128; under modulo 128 an I or S frame has a two-octet control field (Frame.Extended).
func (Frame) ControlField ¶ added in v0.3.0
ControlField decodes the frame's control field (one octet, or two when Extended).
type FrameReject ¶
type FrameReject struct {
Modulo int // 8 or 128
Control uint16 // the rejected control field (second octet in the high byte, modulo 128)
VS, VR int // the sender's send and receive state variables
Response bool // C/R: the rejected frame was a response
// W: control field undefined or not implemented; X: an information
// field the frame may not carry (W is set with it); Y: information
// field longer than the sender takes; Z: invalid N(R).
W, X, Y, Z bool
}
FrameReject is the information field of an FRMR response (IEC 62056-46 6.4.3.10 refers to ISO/IEC 13239 5.5.3.4.2). Bit numbers below are the transmission order of 13239 Figures 18a and 18b: bit 1 is the first bit sent, the lowest order bit of the first octet.
Modulo 8 (Figure 18a, 20 bits padded with zeros to three octets):
octet 1 bits 1-8 the rejected control field octet 2 bit 0 bit 9 0 octet 2 bits 1-3 bits 10-12 V(S) of the sender, bit 10 lowest octet 2 bit 4 bit 13 C/R: 1 when the rejected frame was a response octet 2 bits 5-7 bits 14-16 V(R) of the sender, bit 14 lowest octet 3 bits 0-3 bits 17-20 W, X, Y, Z
Modulo 128 (Figure 18b, 36 bits padded to five octets): the rejected control field in octets 1 and 2 (an unnumbered one in octet 1, octet 2 zero), octet 3 bit 0 zero and bits 1-7 V(S), octet 4 bit 0 C/R and bits 1-7 V(R), octet 5 bits 0-3 W, X, Y, Z. The 2002 edition has no V bit.
func DecodeFrameReject ¶
func DecodeFrameReject(info []byte, modulo int) (FrameReject, error)
DecodeFrameReject reads an FRMR information field of the given modulo (8 or 128). Octets past the layout are padding (5.5.3.4.2) and are ignored.
func (FrameReject) Encode ¶
func (r FrameReject) Encode() []byte
Encode is the information field: three octets modulo 8, five modulo 128.
func (FrameReject) Reason ¶
func (r FrameReject) Reason() string
Reason names the conditions reported, or says the rejection is unspecified when no reason bit is set (5.5.3.4.2).
func (FrameReject) String ¶
func (r FrameReject) String() string
String gives the reason and the rejected frame's control field and counts.
type Kind ¶
type Kind int
Kind is a frame type of the UNC repertoire extended with UI (6.4.3.1, Table 6).
type Line ¶
type Line struct {
Stations []*Station
// contains filtered or unexported fields
}
Line runs several secondary stations on one physical line (a multi-drop bus behind a converter, IEC 62056-7-6 9.6): each station sees every octet and keeps the frames addressed to it; their answers share the line. It also watches the master/slave rule: a primary that polls one station while another still has the right to talk (no frame with the final bit yet) is counted in Violations.
func (*Line) Serve ¶
func (l *Line) Serve(rw io.ReadWriter) error
Serve runs the stations on rw until it ends.
func (*Line) Violations ¶
Violations is how many polls came while another station had the right to talk.
type Params ¶
Params are the negotiable HDLC parameters (6.4.4.4.3.2), each from the point of view of the station that sends them: MaxInfoTX is the longest information field it sends, MaxInfoRX the longest it receives, WindowTX and WindowRX the frames it sends or takes before an acknowledgement.
func DecodeParams ¶
DecodeParams reads an SNRM, UA or DISC information field. An empty field, an absent parameter or a parameter of value 0 means the default. Parameters other than 05 to 08 and groups other than the HDLC parameters are refused (F-1491). The user data subfield (identifier 0xFF, running to the end of the field) is returned; a field of the format identifier and user data only is accepted, the parameters then being the defaults (ISO/IEC 13239 5.5.3.2).
func Negotiate ¶
Negotiate is the secondary station's result (6.4.4.4.3.2, Table 8): proposed are the primary's values from the SNRM, own the secondary's capabilities. Each result is the smaller of the proposal and the secondary's value for the opposite direction, from the secondary's point of view, as the UA carries it.
func (Params) Check ¶
Check reports values outside the protocol's range: information fields of 1 to 2030 octets, windows of 1 to 7 frames.
func (Params) CheckModulo ¶ added in v0.3.0
CheckModulo is Check for a link numbered modulo 8 or 128: under modulo 128 windows may be up to 127 frames.
func (Params) Encode ¶
Encode is the information field of an SNRM or UA carrying all four parameters: the information field lengths on one octet when both fit, on two otherwise (the two layouts of 6.4.4.4.3.2), the windows on four. userData, when given, follows as the user data subfield (IEC 62056-7-6 9.3): the identifier 0xFF and the data, with no length octet, always the last subfield (ISO/IEC 13239 5.5.3.1.3, 5.5.3.2, 5.5.3.2.3).
type RejectError ¶
type RejectError struct {
FrameReject
Raw []byte // the information field as received
}
RejectError is the error for an FRMR from the server: it names the reason and matches ErrRejected.
type Scanner ¶
type Scanner struct {
// InterOctet is the inter-octet (inter-frame) time-out; 0 turns it off.
InterOctet time.Duration
// contains filtered or unexported fields
}
Scanner finds frames in a byte stream (6.4.1.2, 6.4.4.3.3): a frame runs from an opening flag over the octets its length field counts to a closing flag, which may also open the next frame (Figure 11). A gap longer than the inter-octet time-out ends a frame being received: what was gathered is dropped and the stream is scanned for the next opening flag.
type Station ¶
type Station struct {
// Upper and Lower are our logical and physical device addresses in an
// address scheme of Size octets (1, 2 or 4).
Upper, Lower, Size int
// Own are our capabilities for negotiation; zero means the defaults.
Own Params
// Inactivity drops the link after this long without an octet; 0 never.
Inactivity time.Duration
// InterOctet is the inter-octet time-out; 0 turns it off.
InterOctet time.Duration
// Calling is the CALLING DEVICE layer parameter (6.4.4.8): set while
// we have called the client, it makes us answer the CALLING address.
Calling bool
// Handle takes an APDU (LLC removed) from a client and returns the
// answer, or nil for none. unconfirmed is true for a UI frame, whose
// answer is never sent.
Handle func(client int, apdu []byte, unconfirmed bool) []byte
// Log, when set, reports frames refused and events.
Log func(event string)
// OnLink, when set, learns of each link set up (SNRM accepted) or
// ended (DISC, FRMR, inactivity).
OnLink func(client int, up bool)
// UserData, when set, goes in the user data subfield of our UA to an
// SNRM (IEC 62056-7-6 9.3; ISO/IEC 13239 5.5.3.2.3).
UserData []byte
// OnUserData, when set, receives the user data subfield of an SNRM or
// DISC from a client (kind KindSNRM or KindDISC).
OnUserData func(client int, kind Kind, data []byte)
// StopAfterDISC makes Serve return after answering a DISC: the session
// was handed over for one link (IEC 62056-21 mode E).
StopAfterDISC bool
// Modulo128 makes the station take SNRME (ISO/IEC 13239 extended
// numbering, windows up to 127 as Own allows); without it SNRME is
// answered with DM and the client falls back to SNRM. IEC 62056-46
// uses modulo 8 only.
Modulo128 bool
// SegmentUI sends a pending UI APDU longer than the information field
// as several UI frames, the segmentation bit on all but the last (F-233:
// off by default, as IEC 62056-46 keeps UI data to one frame).
SegmentUI bool
// contains filtered or unexported fields
}
Station is a secondary station (a meter's data link layer) for the simulator and tests: it answers SNRM with UA and the negotiation result, takes windowed and segmented I frames, answers in windows and segments that respect the client's parameters, keeps pending UI frames until it has the right to talk (6.4.4.7), rejects what it cannot take with FRMR, answers DM while disconnected, and falls back to disconnected mode after the inactivity time-out (6.4.4.10.3).
func (*Station) Queue ¶
Queue adds an APDU to be sent in a UI frame from the management logical device at the next opportunity (IEC 62056-7-6 9.4).