All Projects → xiegeo → modbusone

xiegeo / modbusone

Licence: BSD-3-Clause License
A modbus library for Go, with unified client and server APIs. One implementation to rule them all.

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to modbusone

STM32 HAL FREEMODBUS RTU
FreeMODBUS RTU port for STM32 HAL library
Stars: ✭ 111 (+122%)
Mutual labels:  modbus, rtu
docker-mysql-replication
master master & master slave replication in mysql
Stars: ✭ 33 (-34%)
Mutual labels:  master, slave
etherlabmaster
IgH EtherCAT Master Building and Configuration Environment
Stars: ✭ 55 (+10%)
Mutual labels:  master
ioBroker.modbus
Modbus adapter for ioBroker
Stars: ✭ 31 (-38%)
Mutual labels:  modbus
NModbus4.NetCore
Simply NModbus4 but targeting .NET instead of .NET Framework
Stars: ✭ 25 (-50%)
Mutual labels:  modbus
libzbxmodbus
Loadable module to integrate Modbus (RTU, TCP and encapsulated) into Zabbix. Bulk data collection included.
Stars: ✭ 44 (-12%)
Mutual labels:  modbus
growatt-esp8266
Growatt Inverter monitoring via MQTT using ESP8266 modbus interface
Stars: ✭ 34 (-32%)
Mutual labels:  modbus
Arduino-MDB-UART
Atmega1284 PLC as MDB-UART converter/MDB Master/MDB VMC emulator
Stars: ✭ 70 (+40%)
Mutual labels:  master
modbus4mqtt
Modbus TCP <-> MQTT glue. YAML configuration. Robust.
Stars: ✭ 21 (-58%)
Mutual labels:  modbus
go-modbus
modbus write in pure go, support rtu,ascii,tcp master library,also support tcp slave.(WIP new implement<old: https://github.com/thinkgos/gomodbus >)
Stars: ✭ 124 (+148%)
Mutual labels:  modbus
rodbus
Rust implementation of Modbus with idiomatic bindings for C, C++, .NET, and Java
Stars: ✭ 34 (-32%)
Mutual labels:  modbus
crc16
A native node addon to calcalate and verify CRC16 values, adopted by MODBUS agreement
Stars: ✭ 24 (-52%)
Mutual labels:  modbus
LeelaMasterWeight
Leela Master weight is training from leela zero self-play sgf and human sgf file
Stars: ✭ 49 (-2%)
Mutual labels:  master
modbus-rs
Modbus implementation in pure Rust
Stars: ✭ 56 (+12%)
Mutual labels:  modbus
ModbusMechanic
Cross platform GUI MODBUS TCP/RTU simulator & gateway. Interprets data types including ascii float and int.
Stars: ✭ 63 (+26%)
Mutual labels:  modbus
IoT-Technical-Guide
🐝 IoT Technical Guide --- 从零搭建高性能物联网平台及物联网解决方案和Thingsboard源码分析 ✨ ✨ ✨ (IoT Platform, SaaS, MQTT, CoAP, HTTP, Modbus, OPC, WebSocket, 物模型,Protobuf, PostgreSQL, MongoDB, Spring Security, OAuth2, RuleEngine, Kafka, Docker)
Stars: ✭ 2,565 (+5030%)
Mutual labels:  modbus
node-drivers
Industrial protocol drivers in node.js
Stars: ✭ 20 (-60%)
Mutual labels:  modbus
mysql-tarantool-replication
A standalone MySQL -> Tarantool replication daemon
Stars: ✭ 47 (-6%)
Mutual labels:  slave
Process-Simulator-2-OpenSource
Open source code of Process Simulator 2
Stars: ✭ 20 (-60%)
Mutual labels:  modbus
openmuc
OpenMUC is a software framework based on Java and OSGi that simplifies the development of customized monitoring, logging and controlling systems.
Stars: ✭ 12 (-76%)
Mutual labels:  modbus

ModbusOne GoDoc

A Modbus library for Go, with unified client and server APIs. One implementation to rule them all.

Example
// handlerGenerator returns ProtocolHandlers that interact with our application.
// In this example, we are only using Holding Registers.
func handlerGenerator(name string) modbusone.ProtocolHandler {
    return &modbusone.SimpleHandler{
        ReadHoldingRegisters: func(address, quantity uint16) ([]uint16, error) {
            fmt.Printf("%v ReadHoldingRegisters from %v, quantity %v\n",
                name, address, quantity)
            r := make([]uint16, quantity)
            // application code that fills in r here
            return r, nil
        },
        WriteHoldingRegisters: func(address uint16, values []uint16) error {
            fmt.Printf("%v WriteHoldingRegisters from %v, quantity %v\n",
                name, address, len(values))
            // application code here
            return nil
        },
        OnErrorImp: func(req modbusone.PDU, errRep modbusone.PDU) {
            fmt.Printf("%v received error:%x in request:%x", name, errRep, req)
        },
    }
}

func Example_serialPort() {
    // Server id and baudRate, for Modbus over serial port.
    id := byte(1)
    baudRate := int64(19200)

    // Open serial connections:
    clientSerial, serverSerial := newInternalSerial()
    // Normally we want to open a serial connection from serial.OpenPort
    // such as github.com/tarm/serial. modbusone can take any io.ReadWriteCloser,
    // so we created two that talks to each other for demonstration here.

    // SerialContext adds baudRate information to calculate
    // the duration that data transfers should takes.
    // It also records Stats of read and dropped packets.
    clientSerialContext := modbusone.NewSerialContext(clientSerial, baudRate)
    serverSerialContext := modbusone.NewSerialContext(serverSerial, baudRate)

    // You can create either a client or a server from a SerialContext and an id.
    client := modbusone.NewRTUClient(clientSerialContext, id)
    server := modbusone.NewRTUServer(serverSerialContext, id)

    // Create Handler to handle client and server actions.
    handler := handlerGenerator

    termChan := make(chan error)

    // Now we are ready to serve!
    // Serve is blocking until the serial connection has io errors or is closed.
    // So we use a goroutine to start it and continue setting up our demo.
    go client.Serve(handler("client"))
    go func() {
        //A server is Started to same way as a client
        err := server.Serve(handler("server"))
        // Do something with the err here.
        // For a command line app, you probably want to terminate.
        // For a service, you probably want to wait until you can open the serial port again.
        termChan <- err
    }()
    defer client.Close()
    defer server.Close()

    // If you only need to support server side, then you are done.
    // If you need to support client side, then you need to make requests.
    startAddress := uint16(0)
    quantity := uint16(200)
    reqs, err := modbusone.MakePDURequestHeaders(modbusone.FcReadHoldingRegisters,
        startAddress, quantity, nil)
    if err != nil {
        fmt.Println(err) //if what you asked for is not possible.
    }
    // Larger than allowed requests are split to many packets.
    fmt.Println("reqs count:", len(reqs))

    // We can add more requests, even of different types.
    // The last nil is replaced by the reqs to append to.
    startAddress = uint16(1000)
    quantity = uint16(100)
    reqs, err = modbusone.MakePDURequestHeaders(modbusone.FcWriteMultipleRegisters,
        startAddress, quantity, reqs)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("reqs count:", len(reqs))

    // Range over the requests to handle each individually,
    for _, r := range reqs {
        err = client.DoTransaction(r)
        if err != nil {
            fmt.Println(err, "on", r) // The server timed out, or the connection was closed.
        }
    }
    // or just do them all at once. Notice that reqs can be reused.
    n, err := modbusone.DoTransactions(client, id, reqs)
    if err != nil {
        fmt.Println(err, "on", reqs[n])
    }

    // Clean up
    server.Close()
    err = <-termChan
    fmt.Println("serve terminated:", err)

    //Output:
    //reqs count: 2
    //reqs count: 3
    //server ReadHoldingRegisters from 0, quantity 125
    //client WriteHoldingRegisters from 0, quantity 125
    //server ReadHoldingRegisters from 125, quantity 75
    //client WriteHoldingRegisters from 125, quantity 75
    //client ReadHoldingRegisters from 1000, quantity 100
    //server WriteHoldingRegisters from 1000, quantity 100
    //server ReadHoldingRegisters from 0, quantity 125
    //client WriteHoldingRegisters from 0, quantity 125
    //server ReadHoldingRegisters from 125, quantity 75
    //client WriteHoldingRegisters from 125, quantity 75
    //client ReadHoldingRegisters from 1000, quantity 100
    //server WriteHoldingRegisters from 1000, quantity 100
    //serve terminated: io: read/write on closed pipe
} //end readme example
For more usage examples, see examples/memory, which is a command line application that can be used as either a server or a client.

Architecture

modbusone architecture

Why

There exist Modbus libraries for Go, such as goburrow/modbus and flosse/go-modbus. However they do not include any server APIs. Even if server function is implemented, user code will have to be written separately to support running both as client and server.

In my use case, client/server should be interchangeable. User code should worry about how to handle the translation of MODBUS data model to application logic. The only difference is the client also initiate requests.

This means that a remote function call like API, which is effective as a client-side API, is insufficient.

Instead, a callback based API (like http server handler) is used for both server and client.

Implemented

  • Serial RTU
  • Function Codes 1-6,15,16
  • Server and Client API
  • Server and Client Tester (examples/memory)

Development

This project is mostly stable, and I am using it in production.

API stability is best effort. This means:

  • Changes should not break users code unless there is a compelling reason.

  • Code broken by API changes should not compile, new errors to user code should not be introduced silently.

  • API changes will be documented to speed adoption of new versions.

My primary usage is RTU (over RS-485). Others may or may not be implemented in the future.

Contribution to new or existing functionally, or just changing a private identifier public are welcome, as well as documentation, test, example code or any other improvements.

Breaking Changes

2018-09-27 v0.2.0

  • NewRTUPacketReader returns PacketReader interface instead of io.Reader. When a new RTU server or client receives a SerialContext, it will test if it is also a PacketReader, and only create a new NewRTUPacketReader if not.
  • (client/server).Serve() now also closes themselves when returned. This avoids some potentially bad usages. Before, the behavior was undefined.

2017-06-13 pre-v0.1.0

  • Removed dependency on goburrow/serial. All serial connections should be created with NewSerialContext, which can accept any ReadWriteCloser

Challenges

Compatibility with a wide range of serial hardware/drivers. (good)

Compatibility with existing Modbus environments. (good)

Recover from transmission errors and timeouts, to work continuously unattended. (good)

Better test coverage that also tests error conditions. (todo)

Fuzz testing. (todo)

Failover mode

Failover has landed in v0.2.0, but it should be considered less stable than the other parts.

In mission-critical applications, or anywhere hardware redundancy is cheaper than downtime, having a standby system taking over in case of the failure of the primary system is desirable.

Ideally, failover is implemented in the application level, which speaks over two serial ports simultaneously, only acting on the values from one of the ports at a time. However, this may not always be possible. A "foreign" application, which you have no control over, might not have this feature. As such, failover mode attempts to addresses this by allowing two separate hardware devices sharing a single serial bus to appear as a single device. This failover mode is outside the design of the original Modbus protocol.

The basic operation of failover mode is to stay quiet on the port until the primary fails. While staying quiet, it relays all reads and writes to the application side as if it is the primary. This allows the application to stay in sync for a hot switch over when the primary fails. While on standby and in Client (Master) mode, writes may be received by the handler that is not initiated by that Client.

Definitions

Client/Server
Also called Master/Slave in the context of serial communication.
PDU
Protocol data unit, MODBUS application protocol, include function code and data. The same format no matter what the lower level protocol is.
ADU
Application data unit, PDU prepended with Server addresses and postpended with error check, as needed.
RTU
Remote terminal unit, in the context of Modbus, it is a raw wire protocol delimited by a delay. RTU is an example of ADU.

License

This library is distributed under the BSD-style license found in the LICENSE file.

See also licenses folder for origins of large blocks of source code.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].