modbus

package
v0.40.0 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

Modbus Service

The Modbus service manages Modbus TCP polling clients for things and groups. Each client connects to a Modbus TCP device on a schedule, reads the configured registers or coils using the specified function code, and publishes the result as a JSON message to the platform on behalf of the associated thing.

Modbus Clients

A Modbus client defines the connection parameters, poll schedule, and data fields to read from a Modbus TCP device.

Field Description
id Unique client identifier (UUID)
group_id ID of the group the client belongs to
thing_id ID of the thing the client is associated with
name Human-readable client name
ip_address IP address of the Modbus TCP device
port TCP port of the Modbus device (default Modbus port is 502)
slave_id Modbus slave/unit ID (0–255)
function_code Modbus read function code (see below)
scheduler Poll schedule configuration (see below)
data_fields List of registers or coils to read (see below)
metadata Arbitrary key-value pairs for custom attributes
Function Codes
Value Modbus Code Description
ReadCoils 0x01 Read output coils (digital output)
ReadDiscreteInputs 0x02 Read discrete inputs (digital input)
ReadHoldingRegisters 0x03 Read holding registers (read/write analog)
ReadInputRegisters 0x04 Read input registers (read-only analog)
Scheduler

The scheduler object controls when the client polls the device.

Field Description
frequency Poll frequency: once, minutely, hourly, daily, or weekly
time_zone IANA timezone name (e.g. Europe/Berlin, UTC)
date_time Date and time in YYYY-MM-DD HH:MM format (e.g. 2026-03-25 14:30). Required when frequency is once; ignored otherwise. Must be at least 1 minute in the future.
minute Minute interval (1–59). Used with minutely frequency
hour Hour interval (1–23). Used with hourly frequency
day_time Time of day in HH:MM format. Used with daily frequency
week Weekly schedule: { days: [...], time: "HH:MM" }. Days must be from SUN, MON, TUE, WED, THU, FRI, SAT. Used with weekly frequency
Data Fields

Each entry in data_fields describes a single register or coil to read.

Field Description
name Field name used as the JSON key in the published message
type Data type: bool, int16, uint16, int32, uint32, float32, or string
unit Optional unit label (e.g. °C, %)
scale Optional multiplier applied to the raw numeric value before publishing
byte_order Multi-byte word order: ABCD (big-endian), DCBA (little-endian), CDAB (PDP/middle-endian), BADC (byte-swapped)
address Starting register or coil address
length Register count. For numeric types this is calculated automatically from type; set manually for string fields only

The poll result is published as a JSON object keyed by field name, for example:

{"temperature": 23.5, "humidity": 61}

Configuration

The service is configured using the environment variables presented in the following table. Note that any unset variables will be replaced with their default values.

Variable Description Default
MF_MODBUS_LOG_LEVEL Log level for the Modbus service (debug, info, warn, error) error
MF_BROKER_URL Message broker instance URL nats://localhost:4222
MF_MODBUS_HTTP_PORT Modbus service HTTP port 9028
MF_JAEGER_URL Jaeger server URL for distributed tracing. Leave empty to disable tracing.
MF_MODBUS_DB_HOST Database host address localhost
MF_MODBUS_DB_PORT Database host port 5432
MF_MODBUS_DB_USER Database user mainflux
MF_MODBUS_DB_PASS Database password mainflux
MF_MODBUS_DB Name of the database used by the service modbus
MF_MODBUS_DB_SSL_MODE Database connection SSL mode (disable, require, verify-ca, verify-full) disable
MF_MODBUS_DB_SSL_CERT Path to the PEM encoded certificate file
MF_MODBUS_DB_SSL_KEY Path to the PEM encoded key file
MF_MODBUS_DB_SSL_ROOT_CERT Path to the PEM encoded root certificate file
MF_MODBUS_CLIENT_TLS Flag that indicates if TLS should be turned on false
MF_MODBUS_CA_CERTS Path to trusted CAs in PEM format
MF_MODBUS_SERVER_CERT Path to server certificate in PEM format
MF_MODBUS_SERVER_KEY Path to server key in PEM format
MF_THINGS_AUTH_GRPC_URL Things service Auth gRPC URL localhost:8183
MF_THINGS_AUTH_GRPC_TIMEOUT Things service Auth gRPC request timeout in seconds 1s
MF_MODBUS_ES_URL Event store URL redis://localhost:6379/0
MF_MODBUS_EVENT_CONSUMER Event store consumer name modbus

Deployment

The service itself is distributed as Docker container. Check the modbus service section in docker-compose to see how service is deployed.

To start the service, execute the following shell script:

# Download the latest version of the service
git clone https://github.com/MainfluxLabs/mainflux

cd mainflux

# compile the modbus service
make modbus

# Copy binary to bin
make install

# Set the environment variables and run the service
MF_MODBUS_LOG_LEVEL=[Modbus log level] \
MF_BROKER_URL=[Message broker instance URL] \
MF_MODBUS_HTTP_PORT=[Modbus service HTTP port] \
MF_MODBUS_DB_HOST=[Database host address] \
MF_MODBUS_DB_PORT=[Database host port] \
MF_MODBUS_DB_USER=[Database user] \
MF_MODBUS_DB_PASS=[Database password] \
MF_MODBUS_DB=[Modbus database name] \
MF_THINGS_AUTH_GRPC_URL=[Things service Auth gRPC URL] \
MF_THINGS_AUTH_GRPC_TIMEOUT=[Things service Auth gRPC request timeout] \
$GOBIN/mainfluxlabs-modbus

Usage

For the full HTTP API reference, see the OpenAPI specification.

Documentation

Index

Constants

View Source
const (
	ReadCoilsFunc            = "ReadCoils"            // 0x01
	ReadDiscreteInputsFunc   = "ReadDiscreteInputs"   // 0x02
	ReadHoldingRegistersFunc = "ReadHoldingRegisters" // 0x03
	ReadInputRegistersFunc   = "ReadInputRegisters"   // 0x04

	ByteOrderABCD = "ABCD" // Big-endian (standard network order)
	ByteOrderDCBA = "DCBA" // Little-endian (x86, ARM in little-endian mode)
	ByteOrderCDAB = "CDAB" // Middle-endian (PDP-style)
	ByteOrderBADC = "BADC" // Byte-swapped (less common, but used in some contexts)
)
View Source
const (
	BoolType    = "bool"
	Int16Type   = "int16"
	Int32Type   = "int32"
	Uint16Type  = "uint16"
	Uint32Type  = "uint32"
	Float32Type = "float32"
	StringType  = "string"
)

Variables

View Source
var AllowedOrders = map[string]string{
	"id":   "id",
	"name": "name",
}

Functions

This section is empty.

Types

type Block

type Block struct {
	Start  uint16
	Length uint16
}

type Client

type Client struct {
	ID           string
	GroupID      string
	ThingID      string
	Name         string
	IPAddress    string
	Port         string
	SlaveID      uint8
	FunctionCode string
	Scheduler    cron.Scheduler
	Metadata     map[string]any
	DataFields   []DataField
}

type ClientRepository

type ClientRepository interface {
	// Save persists multiple Modbus clients.
	// Clients are saved using a transaction.
	// If one client fails, then none will be saved.
	// Successful operation is indicated by non-nil error response.
	Save(ctx context.Context, dls ...Client) ([]Client, error)

	// RetrieveByThing retrieves clients related to
	// a certain thing identified by a given ID.
	RetrieveByThing(ctx context.Context, thingID string, pm PageMetadata) (ClientsPage, error)

	// RetrieveByGroup retrieves Modbus clients related to
	// a certain group identified by a given ID.
	RetrieveByGroup(ctx context.Context, groupID string, pm PageMetadata) (ClientsPage, error)

	// RetrieveByID retrieves a client having the provided ID.
	RetrieveByID(ctx context.Context, id string) (Client, error)

	// RetrieveAll retrieves all clients.
	RetrieveAll(ctx context.Context) ([]Client, error)

	// Update performs an update to the existing client.
	// A non-nil error is returned to indicate operation failure.
	Update(ctx context.Context, w Client) error

	// Remove removes Modbus clients having the provided IDs.
	Remove(ctx context.Context, ids ...string) error

	// RemoveByThing removes Modbus clients related to
	// a certain thing identified by a given thing ID.
	RemoveByThing(ctx context.Context, thingID string) error

	// RemoveByGroup removes Modbus clients related to
	// a certain group identified by a given group ID.
	RemoveByGroup(ctx context.Context, groupID string) error
}

type ClientsPage

type ClientsPage struct {
	PageMetadata
	Clients []Client
}

type DataField

type DataField struct {
	Name      string  `json:"name"`
	Type      string  `json:"type"`
	Unit      string  `json:"unit"`
	Scale     float64 `json:"scale"`
	ByteOrder string  `json:"byte_order"`
	Address   uint16  `json:"address"`
	Length    uint16  `json:"length"`
}

type PageMetadata added in v0.39.0

type PageMetadata struct {
	Total  uint64 `json:"total,omitempty"`
	Offset uint64 `json:"offset,omitempty"`
	Limit  uint64 `json:"limit,omitempty"`
	Order  string `json:"order,omitempty"`
	Dir    string `json:"dir,omitempty"`
	Name   string `json:"name,omitempty"`
}

PageMetadata contains page metadata that helps navigation.

func (PageMetadata) Validate added in v0.39.0

func (pm PageMetadata) Validate(maxLimitSize, maxNameSize int) error

Validate validates the page metadata.

type Service

type Service interface {
	// CreateClients creates clients for certain thing identified by the thing ID.
	CreateClients(ctx context.Context, token, thingID string, Clients ...Client) ([]Client, error)

	// ListClientsByThing retrieves data about a subset of clients
	// related to a certain thing.
	ListClientsByThing(ctx context.Context, token, thingID string, pm PageMetadata) (ClientsPage, error)

	// ListClientsByGroup retrieves data about a subset of clients
	// related to a certain group.
	ListClientsByGroup(ctx context.Context, token, groupID string, pm PageMetadata) (ClientsPage, error)

	// ViewClient retrieves data about a client identified with the provided ID.
	ViewClient(ctx context.Context, token, id string) (Client, error)

	// UpdateClient updates client identified by the provided ID.
	UpdateClient(ctx context.Context, token string, client Client) error

	// RemoveClients removes clients identified with the provided IDs.
	RemoveClients(ctx context.Context, token string, id ...string) error

	// RemoveClientsByThing removes clients related to the specified thing,
	// identified by the provided thing ID.
	RemoveClientsByThing(ctx context.Context, thingID string) error

	// RemoveClientsByGroup removes clients related to the specified group,
	// identified by the provided group ID.
	RemoveClientsByGroup(ctx context.Context, groupID string) error

	// RescheduleTasks reschedules all tasks for things related to the specified profile ID.
	RescheduleTasks(ctx context.Context, profileID string, config map[string]any) error

	// LoadAndScheduleTasks loads schedulers and starts them to execute requests based on client configuration.
	LoadAndScheduleTasks(ctx context.Context) error
}

Service specifies an API that must be fulfilled by the domain service implementation, and all of its decorators (e.g. logging & metrics). All methods that accept a token parameter use it to identify and authorize the user performing the operation.

func New

Directories

Path Synopsis
api

Jump to

Keyboard shortcuts

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