Documentation
¶
Overview ¶
Package enip is an EtherNet/IP client with CIP explicit messaging, in pure Go: the encapsulation layer (sessions, SendRRData, SendUnitData, ListIdentity over TCP and UDP), CIP requests and replies with paths, routes and Multiple Service Packets, Unconnected Send, Forward Open and Large Forward Open (class 3 connections), the Logix tag services with fragmentation, the attribute services, and the Logix atomic, STRING and structure type encodings.
The simulator in package sim behaves like a Logix controller and is used by the tests.
Index ¶
- Constants
- func AtomicTypeCode(name string) (code uint16, ok bool)
- func Decode(t Type, data []byte, elements int, members []Member) (any, error)
- func DecodeAtomic(code uint16, b []byte) (any, error)
- func DecodeString(b []byte) (string, error)
- func Element(b []byte, i uint32) []byte
- func EncapStatusText(s uint32) string
- func Encode(t Type, v any, elements int) ([]byte, error)
- func EncodeAtomic(code uint16, v any) ([]byte, error)
- func EncodeString(s string) ([]byte, error)
- func ExtStatusText(general byte, ext uint16) string
- func IdentityItem(id Identity, major, minor uint8, serial uint32) []byte
- func IsCIP(err error) bool
- func Logical(class, instance uint16, attr int) []byte
- func MarshalCPF(items ...Item) []byte
- func MarshalResponse(service, status byte, ext []uint16, data []byte) []byte
- func MultipleService(reqs [][]byte) []byte
- func ParseRequest(b []byte) (service byte, path, data []byte, err error)
- func ParseUnconnectedSend(b []byte) (msg, route []byte, err error)
- func PortSegment(b []byte, port uint16, link string) ([]byte, error)
- func RRData(timeout uint16, items ...Item) []byte
- func RegisterSessionData() []byte
- func Request(service byte, path, data []byte) []byte
- func Route(s string) ([]byte, error)
- func SplitMultiple(b []byte) ([][]byte, error)
- func StatusText(s byte) string
- func Symbolic(b []byte, name string) []byte
- func TagPath(tag string) ([]byte, error)
- type Client
- func (c *Client) Close()
- func (c *Client) Do(ctx context.Context, service byte, path, data []byte) (*Response, error)
- func (c *Client) GetAttribute(ctx context.Context, class, instance uint16, attr int) ([]byte, error)
- func (c *Client) Identity() *Identity
- func (c *Client) ListIdentity(ctx context.Context) (*Identity, error)
- func (c *Client) MaxMessage() int
- func (c *Client) Mode() (string, error)
- func (c *Client) ReadTag(ctx context.Context, tag string, elements int) (Type, []byte, error)
- func (c *Client) ReadTags(ctx context.Context, reads []*TagRead) error
- func (c *Client) SetAttribute(ctx context.Context, class, instance uint16, attr int, data []byte) error
- func (c *Client) WriteTag(ctx context.Context, tag string, t Type, elements int, data []byte) error
- type Error
- type Header
- type Identity
- type Item
- type Member
- type Response
- type TagRead
- type Type
Examples ¶
Constants ¶
const ( SvcGetAttributesAll byte = 0x01 SvcMultipleService byte = 0x0A SvcGetAttributeSingle byte = 0x0E SvcSetAttributeSingle byte = 0x10 SvcForwardClose byte = 0x4E SvcReadTag byte = 0x4C SvcWriteTag byte = 0x4D SvcReadTagFragmented byte = 0x52 // to a symbol SvcUnconnectedSend byte = 0x52 // to the connection manager SvcWriteTagFragmented byte = 0x53 SvcForwardOpen byte = 0x54 SvcLargeForwardOpen byte = 0x5B ReplyBit byte = 0x80 ClassIdentity uint16 = 0x01 ClassMessageRouter uint16 = 0x02 ClassConnectionManager uint16 = 0x06 )
CIP service codes used here.
const ( StatusSuccess byte = 0x00 StatusConnFailure byte = 0x01 StatusPathSegment byte = 0x04 StatusPathUnknown byte = 0x05 StatusPartial byte = 0x06 StatusServiceNotSup byte = 0x08 StatusNotSettable byte = 0x0E StatusReplyTooLarge byte = 0x11 StatusNotEnoughData byte = 0x13 StatusAttrNotSupported byte = 0x14 StatusTooMuchData byte = 0x15 StatusObjectMissing byte = 0x16 StatusEmbeddedError byte = 0x1E StatusVendor byte = 0xFF )
General status codes this package acts on.
const ( CmdNOP uint16 = 0x0000 CmdListServices uint16 = 0x0004 CmdListIdentity uint16 = 0x0063 CmdListInterfaces uint16 = 0x0064 CmdRegisterSession uint16 = 0x0065 CmdUnRegisterSession uint16 = 0x0066 CmdSendRRData uint16 = 0x006F CmdSendUnitData uint16 = 0x0070 )
Encapsulation commands (the 16-bit command field of the 24-byte header).
const ( ItemNullAddress uint16 = 0x0000 ItemIdentity uint16 = 0x000C ItemConnectedAddress uint16 = 0x00A1 ItemConnectedData uint16 = 0x00B1 ItemUnconnectedData uint16 = 0x00B2 ItemSockaddrOT uint16 = 0x8000 ItemSockaddrTO uint16 = 0x8001 )
Common packet format item type IDs.
const ( TypeBOOL uint16 = 0xC1 TypeSINT uint16 = 0xC2 TypeINT uint16 = 0xC3 TypeDINT uint16 = 0xC4 TypeLINT uint16 = 0xC5 TypeUSINT uint16 = 0xC6 TypeUINT uint16 = 0xC7 TypeUDINT uint16 = 0xC8 TypeULINT uint16 = 0xC9 TypeREAL uint16 = 0xCA TypeLREAL uint16 = 0xCB TypeBYTE uint16 = 0xD1 TypeWORD uint16 = 0xD2 TypeDWORD uint16 = 0xD3 TypeLWORD uint16 = 0xD4 TypeStruct uint16 = 0x02A0 // followed by a structure handle // HandleSTRING is the structure handle of the built-in Logix STRING // (LEN DINT + DATA SINT[82], 88 bytes with padding). HandleSTRING uint16 = 0x0FCE // StringSize is the Logix STRING's size in bytes and StringChars its // character capacity. StringSize = 88 StringChars = 82 )
Atomic data type codes (the Logix tag type word).
const DefaultConnSize = 500
DefaultConnSize is the class 3 connection size, in bytes, used when a Client does not set one.
const DefaultPort = 44818
DefaultPort is the EtherNet/IP explicit messaging port (TCP and UDP).
const HeaderLen = 24
HeaderLen is the size of the encapsulation header.
Variables ¶
This section is empty.
Functions ¶
func AtomicTypeCode ¶
AtomicTypeCode returns the code of the atomic type with exactly this name (upper case: "DINT", "REAL" …); ok is false otherwise, including for STRING.
func Decode ¶
Decode turns a read reply's data into a JSON-able value: one element is a scalar, several an array. A structure without members is {"handle": "0x…", "hex": "…"}.
func DecodeAtomic ¶
DecodeAtomic reads one atomic value; BOOL gives a bool, integers and reals a float64 (LINT/ULINT beyond 2^53 lose precision).
func DecodeString ¶
DecodeString reads a Logix STRING (LEN then characters).
func EncapStatusText ¶
EncapStatusText names encapsulation status codes.
func Encode ¶
Encode turns a JSON value into tag data for elements elements of type t: numbers/booleans for atomics, text for STRING, arrays for several elements, {"hex": "…"} or a hex string for structures.
func EncodeAtomic ¶
EncodeAtomic writes one atomic value (bool or number), refusing values out of the type's range.
func EncodeString ¶
EncodeString writes a Logix STRING of StringSize bytes.
Example ¶
Encode a string for a write and decode it again.
package main
import (
"fmt"
"github.com/cB-Sigma/enip"
)
func main() {
b, _ := enip.EncodeString("Pump 7")
s, _ := enip.DecodeString(b)
fmt.Println(s)
}
Output: Pump 7
func ExtStatusText ¶
ExtStatusText names the extended status of connection manager errors (general 0x01) and Logix tag errors (general 0xFF).
func IdentityItem ¶
IdentityItem encodes an identity item's data (socket address fields are big-endian, the rest little-endian).
func Logical ¶
Logical appends class, instance and (when attr >= 0) attribute segments, each 8-bit when it fits and 16-bit otherwise.
func MarshalCPF ¶
MarshalCPF encodes an item count followed by the items.
func MarshalResponse ¶
MarshalResponse encodes a CIP reply.
func MultipleService ¶
MultipleService packs requests into one Multiple Service Packet body.
func ParseRequest ¶
ParseRequest splits a CIP request.
func ParseUnconnectedSend ¶
ParseUnconnectedSend splits an Unconnected Send body (for simulators).
func PortSegment ¶
PortSegment appends one port segment.
func RRData ¶
RRData builds the body of SendRRData or SendUnitData: interface handle 0, a timeout in seconds and the items.
func RegisterSessionData ¶
func RegisterSessionData() []byte
RegisterSessionData is the request/reply body of RegisterSession: protocol version 1, options 0.
func Route ¶
Route parses a route such as "1,0" (backplane port 1, slot 0) or "1,0,2,10.0.0.9,1,2" into port segments. Links that are IP addresses (or above 255) use the extended link address form.
Example ¶
The route to the CPU in slot 2 of a ControlLogix chassis (backplane port 1), and the symbolic path of a program-scoped tag.
package main
import (
"fmt"
"github.com/cB-Sigma/enip"
)
func main() {
route, _ := enip.Route("1,2")
path, _ := enip.TagPath("Program:Main.Count")
fmt.Printf("% x\n% x\n", route, path)
}
Output: 01 02 91 0c 50 72 6f 67 72 61 6d 3a 4d 61 69 6e 91 05 43 6f 75 6e 74 00
func SplitMultiple ¶
SplitMultiple splits a Multiple Service Packet body (request or reply) into its embedded messages.
Types ¶
type Client ¶
type Client struct {
Addr string // host:port
Route []byte // port segments to the CPU; nil talks to the target itself
Timeout time.Duration // per exchange
Connected bool // try a Forward Open
ConnSize int // connection size; above 511 uses Large Forward Open
// KeepAlive is how long the connection must survive without traffic
// (it sets the RPI × multiplier timeout); default 1 minute.
KeepAlive time.Duration
// contains filtered or unexported fields
}
Client is one EtherNet/IP session with a target, optionally with a class 3 connection. It is safe for concurrent use; requests are serialised.
func (*Client) Do ¶
Do sends one CIP request and returns the reply. A transport failure closes the session (the next call reconnects); a CIP error status comes back in the reply, not as the error.
func (*Client) GetAttribute ¶
func (c *Client) GetAttribute(ctx context.Context, class, instance uint16, attr int) ([]byte, error)
GetAttribute reads one attribute (Get_Attribute_Single), or every attribute of the instance when attr < 0 (Get_Attribute_All).
func (*Client) ListIdentity ¶
ListIdentity asks the target for its identity over TCP.
func (*Client) MaxMessage ¶
MaxMessage is the largest CIP message (request or reply) the current transport carries.
func (*Client) Mode ¶
Mode reports "connected", "unconnected" or "" when not connected, and why connected messaging was refused, if it was.
func (*Client) ReadTag ¶
ReadTag reads elements elements of a tag, continuing with Read Tag Fragmented when the value does not fit in one reply.
func (*Client) ReadTags ¶
ReadTags reads several tags in one Multiple Service Packet (the caller keeps the batch within MaxMessage); replies that were cut short are completed with fragmented reads. The error is for the whole batch.
type Header ¶
type Header struct {
Command uint16
Length uint16 // bytes of data after the header
Session uint32
Status uint32
Context [8]byte
Options uint32
}
Header is the encapsulation header; every field is little-endian.
func ParseHeader ¶
ParseHeader decodes the first 24 bytes of b.
func ReadPacket ¶
ReadPacket reads one encapsulation packet from a stream.
type Identity ¶
type Identity struct {
Protocol uint16 `json:"protocol"`
IP string `json:"ip"`
Port uint16 `json:"port"`
Vendor uint16 `json:"vendor"`
DeviceType uint16 `json:"deviceType"`
ProductCode uint16 `json:"productCode"`
Revision string `json:"revision"`
Status uint16 `json:"status"`
Serial string `json:"serial"`
ProductName string `json:"productName"`
State uint8 `json:"state"`
}
Identity is a ListIdentity reply item (the identity object's key attributes plus the device's socket address).
func Discover ¶
Discover sends ListIdentity over UDP to addr (a broadcast or unicast host:port) and collects replies for wait.
func ParseIdentity ¶
ParseIdentity decodes an identity item.
func ParseListIdentity ¶
ParseListIdentity decodes a ListIdentity reply body.
type Item ¶
Item is one common packet format item.
func ParseRRData ¶
ParseRRData splits the body of SendRRData/SendUnitData into its items.
type Member ¶
type Member struct {
Name string `json:"name"`
Offset int `json:"offset"`
Type string `json:"type"`
Bit int `json:"bit,omitempty"` // for BOOL members packed in a host word
}
Member is a structure member the configuration names, for decoding a structure's bytes without the controller's template.
type Response ¶
Response is a decoded CIP reply.
func ParseResponse ¶
ParseResponse decodes a CIP reply.
type Type ¶
Type is a tag's data type: an atomic code, or TypeStruct and a handle.
func ParseTypeName ¶
ParseTypeName turns "DINT", "REAL", "STRING" … into a Type. ok is false for unknown names.