modbus

package
v0.37.0 Latest Latest
Warning

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

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

README

Modbus

Modbus service manages Modbus TCP clients for things and groups, polling registers or coils on a schedule and publishing the results as messages to the platform.

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
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

Starting the service will load all persisted Modbus clients and begin scheduling polls according to each client's configured frequency (repeating cron or one-time). Each poll reads the specified registers or coils from the Modbus TCP device using the configured function code, formats the result as a JSON payload, and publishes it as a platform message scoped to the associated thing. Supported data types are bool, int16, uint16, int32, uint32, float32, and string. Byte order (ABCD, DCBA, CDAB, BADC) can be configured per data field.

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

This section is empty.

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 apiutil.PageMetadata) (ClientsPage, error)

	// RetrieveByGroup retrieves Modbus clients related to
	// a certain group identified by a given ID.
	RetrieveByGroup(ctx context.Context, groupID string, pm apiutil.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 {
	apiutil.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 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 apiutil.PageMetadata) (ClientsPage, error)

	// ListClientsByGroup retrieves data about a subset of clients
	// related to a certain group.
	ListClientsByGroup(ctx context.Context, token, groupID string, pm apiutil.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.

Directories

Path Synopsis
api

Jump to

Keyboard shortcuts

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