driver

package
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package driver connects silk's real-time tag database to industrial field devices over Modbus TCP and Siemens S7. It is UI-agnostic (no gui import): a device configuration — connection + a list of tag points — polls the device and writes each value into a core.TagDB, from where silk's existing bindings, animation, alarms, trends and codegen drive the screen. Read-write points also push tag edits back to the device.

codec.go is the shared value layer: it converts between a device's raw register/byte payload and a Go value, for every common PLC data type and all four register/byte orderings.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Decode

func Decode(raw []byte, dt DataType, order ByteOrder) (interface{}, error)

Decode turns a raw device payload into a Go value of dt, honouring order. The returned concrete types are: bool, int16, uint16, int32, uint32, int64, uint64, float32, float64. It errors if raw is shorter than the type width.

func Encode

func Encode(v interface{}, dt DataType, order ByteOrder) ([]byte, error)

Encode turns a Go value into a raw device payload of dt in order. v is coerced through float64 for numerics (matching how silk tags carry values), so an int32 point fed a tag's float64 value round-trips. Bool accepts bool or any nonzero numeric.

Types

type AccessMode

type AccessMode int

AccessMode is a tag point's read/write capability.

const (
	ReadOnly AccessMode = iota
	ReadWrite
)

func (AccessMode) String

func (a AccessMode) String() string

type ByteOrder

type ByteOrder int

ByteOrder selects how a multi-byte value's bytes are laid out across the device's registers. Modeled as two independent operations — reversing the order of the 16-bit words, and swapping the two bytes within each word — so the four industry orderings compose cleanly and generalise to 16/32/64-bit:

ABCD  BigEndian       高低      words as-is, bytes as-is (Modbus/S7 default)
DCBA  LittleEndian    低高      words reversed, bytes swapped
BADC  BigByteSwap     字节交换   words as-is, bytes swapped
CDAB  LittleByteSwap  字交换     words reversed, bytes as-is (common for 32-bit)
const (
	BigEndian ByteOrder = iota
	LittleEndian
	BigByteSwap
	LittleByteSwap
)

func (ByteOrder) String

func (o ByteOrder) String() string

type DataType

type DataType int

DataType is a PLC variable type. Widths: Bool 1, 16-bit 2, 32-bit 4, 64-bit 8.

const (
	TypeBool DataType = iota
	TypeInt16
	TypeUInt16
	TypeInt32
	TypeUInt32
	TypeInt64
	TypeUInt64
	TypeFloat32
	TypeFloat64
)

func (DataType) ByteWidth

func (dt DataType) ByteWidth() int

ByteWidth is the number of raw bytes a value of this type occupies.

func (DataType) RegisterCount

func (dt DataType) RegisterCount() int

RegisterCount is how many 16-bit Modbus registers the type spans.

func (DataType) String

func (dt DataType) String() string

type Driver

type Driver interface {
	Connect() error
	Close() error
	ReadPoint(p TagPoint) (interface{}, error)
	WritePoint(p TagPoint, v interface{}) error
}

Driver is a live connection to one field device. Implementations (Modbus TCP, S7) handle addressing and the wire protocol; the codec handles value bytes.

type MQTT

type MQTT struct {
	// contains filtered or unexported fields
}

MQTT is a Driver for MQTT brokers. Unlike Modbus/S7 it is push, not poll: the broker delivers messages when they change, so the driver keeps the latest value per topic in a cache and the Poller surfaces that cache on each tick.

A point's Address is an MQTT topic (e.g. "silk/plant/line1/temp"). ReadPoint subscribes to the topic the first time the point is asked for and thereafter returns the cached value — nil until the first message arrives, then whatever the subscribe callback last parsed. WritePoint publishes the value to the topic at QoS 0. Payloads are parsed as a JSON number first, then a plain float, then a bool string, else kept as the raw string.

func NewMQTT

func NewMQTT(broker, clientID string) *MQTT

NewMQTT builds a driver for the broker at broker (form "tcp://host:port") using clientID as the MQTT client identifier.

func (*MQTT) Close

func (m *MQTT) Close() error

Close disconnects from the broker. Safe on a never-connected driver.

func (*MQTT) Connect

func (m *MQTT) Connect() error

Connect dials the broker. Auto-reconnect is on; each (re)connect re-subscribes the tracked topics so the cache stays live across drops.

func (*MQTT) ReadPoint

func (m *MQTT) ReadPoint(p TagPoint) (interface{}, error)

ReadPoint returns the latest cached value for the point's topic, subscribing to it on first use. The value is nil until the first message is received.

func (*MQTT) WritePoint

func (m *MQTT) WritePoint(p TagPoint, v interface{}) error

WritePoint publishes the value to the point's topic at QoS 0.

type ModbusTCP

type ModbusTCP struct {
	URL     string        // e.g. "tcp://127.0.0.1:502"
	UnitID  uint8         // slave/unit id
	Timeout time.Duration // per-request timeout
	// contains filtered or unexported fields
}

ModbusTCP is a Driver for Modbus TCP devices (PLCs, gateways, meters).

Point addresses use the scheme "<area>:<offset>", where area is one of

hr    holding register (16-bit, read/write)
ir    input register   (16-bit, read-only)
coil  coil             (1 bit,  read/write)
di    discrete input   (1 bit,  read-only)

and offset is the 0-based register/coil number, e.g. "hr:0", "ir:100", "coil:5". Bool points map to coil/di, numeric points to hr/ir; a type spanning several registers (Int32, Float64, ...) occupies RegisterCount() consecutive registers from offset, laid out per the point's ByteOrder.

func NewModbusTCP

func NewModbusTCP(url string, unitID uint8) *ModbusTCP

NewModbusTCP builds a driver for the device at url (form "tcp://host:port") with the given unit id and a 1s request timeout.

func (*ModbusTCP) Close

func (m *ModbusTCP) Close() error

Close shuts the connection down. Safe on a never-connected driver.

func (*ModbusTCP) Connect

func (m *ModbusTCP) Connect() error

Connect dials the device and selects the unit id.

func (*ModbusTCP) ReadPoint

func (m *ModbusTCP) ReadPoint(p TagPoint) (interface{}, error)

ReadPoint reads one point: coils/discrete inputs as bool, registers decoded through the codec with the point's type and byte order.

func (*ModbusTCP) WritePoint

func (m *ModbusTCP) WritePoint(p TagPoint, v interface{}) error

WritePoint writes one point: bool to a coil, numerics encoded through the codec into holding registers. Input registers and discrete inputs are read-only by the protocol.

type OPCUA

type OPCUA struct {
	// contains filtered or unexported fields
}

OPCUA is a Driver for OPC-UA servers over TCP using gopcua. Unlike Modbus and S7, OPC-UA is self-describing: each node carries its own typed value, so a point's Type and Order are not used to decode the wire bytes — the server hands back an already-typed ua.Variant. A point's Address is an OPC-UA NodeID in the standard textual form:

ns=2;s=Demo.Float   string identifier in namespace 2
ns=3;i=1001         numeric identifier in namespace 3
i=2258              numeric identifier in namespace 0

parsed by ua.ParseNodeID. The read path returns the variant's Go value (float64, bool, int32, string, ...) and the write path wraps the value in a variant; the Poller normalizes numerics/bools to float64/bool.

func NewOPCUA

func NewOPCUA(endpoint string) *OPCUA

NewOPCUA builds a driver for the server at endpoint (form "opc.tcp://host:port").

func (*OPCUA) Close

func (o *OPCUA) Close() error

Close tears the session down. Safe to call when not connected.

func (*OPCUA) Connect

func (o *OPCUA) Connect() error

Connect creates the client and opens the secure channel / session.

func (*OPCUA) ReadPoint

func (o *OPCUA) ReadPoint(p TagPoint) (interface{}, error)

ReadPoint reads the Value attribute of the point's node and returns the variant's Go value. p.Order is ignored — the variant is already typed.

func (*OPCUA) WritePoint

func (o *OPCUA) WritePoint(p TagPoint, v interface{}) error

WritePoint wraps v in a variant and writes it to the Value attribute of the point's node. v is expected to be an OPC-UA builtin type (the Poller carries tag values as float64 or bool).

type Poller

type Poller struct {
	// contains filtered or unexported fields
}

Poller drives a core.TagDB from a device: it periodically reads every point into its tag, and for read-write points pushes user/script tag edits back to the device. Poll-originated tag updates are suppressed from the write path so a read never echoes back as a write.

func NewPoller

func NewPoller(drv Driver, points []TagPoint, tags *core.TagDB, period time.Duration) *Poller

NewPoller builds a poller. period is the read interval.

func (*Poller) PollOnce

func (p *Poller) PollOnce()

PollOnce reads every point once into the tag DB. Exposed for tests and for a synchronous initial refresh; the loop calls it each tick.

func (*Poller) Start

func (p *Poller) Start() error

Start connects the device, wires read-write points to device writes, and launches the poll loop. It errors if the device connection fails.

func (*Poller) Stop

func (p *Poller) Stop()

Stop halts polling, unsubscribes write handlers and closes the device. It is safe to call once.

type Redundant

type Redundant struct {

	// OnFailover, if non-nil, is called with the newly active side ("primary"
	// or "backup") each time traffic flips between the two devices. OnError, if
	// non-nil, is called with the active device's error just before a failover
	// retry. Both are optional status hooks; register them with SetOnFailover /
	// SetOnError before the driver is put into service.
	OnFailover func(active string)
	OnError    func(error)
	// contains filtered or unexported fields
}

Redundant pairs a primary and a backup Driver behind the Driver interface and fails over between them automatically, the way FameView (杰控) runs 百毫秒级 device redundancy: one device carries traffic while the other stands by, and a fault on the active side moves traffic to the standby without the caller noticing.

Failover is driven by operation results, not a background health poll (v1): every ReadPoint/WritePoint tries the currently active driver first and, on error, retries once on the standby. A successful retry promotes the standby to active, so the next call goes straight to the side that is actually working.

func NewRedundant

func NewRedundant(primary, backup Driver) *Redundant

NewRedundant builds a redundant driver over primary and backup. primary is the preferred device; backup takes over on primary failure.

func (*Redundant) Active

func (r *Redundant) Active() string

Active reports which device is currently carrying traffic, "primary" or "backup", for status display.

func (*Redundant) Close

func (r *Redundant) Close() error

Close closes both devices, returning the first error seen (primary before backup); both are always closed regardless of either result.

func (*Redundant) Connect

func (r *Redundant) Connect() error

Connect connects both devices and succeeds if at least one comes up, recording which side is active: primary when it connects, otherwise the backup. It fails only if both devices fail to connect.

func (*Redundant) ReadPoint

func (r *Redundant) ReadPoint(p TagPoint) (interface{}, error)

ReadPoint reads p from the active device; on error it retries once on the standby and, if that succeeds, promotes the standby to active. It returns the value from whichever device answered, or the standby's error if both fail.

func (*Redundant) SetOnError

func (r *Redundant) SetOnError(fn func(error))

SetOnError registers the callback fired with the active device's error just before a failover retry. Passing nil disables it.

func (*Redundant) SetOnFailover

func (r *Redundant) SetOnFailover(fn func(active string))

SetOnFailover registers the callback fired with the newly active side each time traffic flips between the primary and backup. Passing nil disables it.

func (*Redundant) WritePoint

func (r *Redundant) WritePoint(p TagPoint, v interface{}) error

WritePoint writes v to p on the active device; on error it retries once on the standby and, if that succeeds, promotes the standby to active. It returns nil if either device accepted the write, or the standby's error if both fail.

type S7

type S7 struct {
	Host    string        // IP or hostname; port defaults to 102 when omitted
	Rack    int           // CPU rack (S7-300: 0; S7-1200/1500: 0)
	Slot    int           // CPU slot (S7-300: 2; S7-1200/1500: 0 or 1)
	Timeout time.Duration // dial/request timeout
	// contains filtered or unexported fields
}

S7 is a Driver for Siemens S7 PLCs (S7-300/400/1200/1500) over ISO-on-TCP using gos7. Addresses use the classic Siemens syntax:

DB<n>.DBX<byte>.<bit>   bool in data block n         DB1.DBX0.3
DB<n>.DBB<byte>         byte in data block n         DB1.DBB4
DB<n>.DBW<byte>         16-bit word                  DB2.DBW10
DB<n>.DBD<byte>         32-bit dword                 DB3.DBD12
M<byte>.<bit>           merker (flag) bit            M10.1
MB<byte> MW<byte> MD<byte>  merker byte/word/dword   MB5 MW20 MD24
I<byte>.<bit>           input bit (E accepted)       I0.1  E0.1
Q<byte>.<bit>           output bit (A accepted)      Q0.5  A0.5

The mnemonic (DBB/DBW/DBD, MB/MW/MD) only locates the byte offset; the number of bytes actually read or written comes from the point's DataType.ByteWidth(), so a TypeFloat64 point at DB1.DBD0 transfers 8 bytes. Bit addresses (DBX / M x.y / I / Q) require TypeBool; bit 0 is the byte's least significant bit, valid bits are 0-7.

func NewS7

func NewS7(host string, rack, slot int) *S7

NewS7 builds an S7 driver for host (port 102 unless given) with a 2s timeout.

func (*S7) Close

func (s *S7) Close() error

Close shuts the connection down. Safe to call when not connected.

func (*S7) Connect

func (s *S7) Connect() error

Connect dials the PLC and negotiates the ISO-on-TCP / S7 session.

func (*S7) ReadPoint

func (s *S7) ReadPoint(p TagPoint) (interface{}, error)

ReadPoint reads one point. Bit addresses read the containing byte and extract the bit as a bool; numeric addresses read Type.ByteWidth() bytes and decode them with the point's byte order.

func (*S7) WritePoint

func (s *S7) WritePoint(p TagPoint, v interface{}) error

WritePoint writes one point. Numerics are encoded with the point's byte order; a bit is read-modify-written inside its byte so neighbouring bits are preserved (not atomic against concurrent writers of the same byte).

type TagPoint

type TagPoint struct {
	Tag     string    // silk tag name this point drives
	Address string    // protocol address (Modbus "40001"; S7 "DB1.DBD0")
	Type    DataType  // value type
	Order   ByteOrder // register/byte order for multi-byte types
	Access  AccessMode
}

TagPoint maps one device address to one silk tag with its data type, byte order and access mode. It is the unit of device configuration.

func (TagPoint) Writable

func (p TagPoint) Writable() bool

Writable reports whether tag edits are pushed back to the device.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL