GithubHelp home page GithubHelp logo

goburrow / modbus Goto Github PK

View Code? Open in Web Editor NEW
906.0 906.0 352.0 110 KB

Fault-tolerant implementation of modbus protocol in Go (golang)

License: BSD 3-Clause "New" or "Revised" License

Go 96.32% C 3.68%

modbus's People

Contributors

adiclepcea avatar andig avatar nqv avatar xiegeo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

modbus's Issues

How to not loose values or not read values twice (synchronisation)

The Energy meters made by www.janitza.de update their internal modbus registers every 0.2 seconds.
When I poll these values each 0.2 seconds over TCP, I want to:

  • not loose an updated value because in my setup each value is important
  • not read a value twice (or discard a duplicated value an immediately try to catch the next updated value)
    But because afaik modbus does not provide any synchronisation method. I'm not sure how and where to solve this. Does anyone have an idea?

( https://www.janitza.de/betriebsanleitungen.html?file=files/download/manuals/current/UMG96RM/EL/Janitza-Manual-UMG96RM-EL-Modbus-adress-list-and-formulary-en.pdf )

response slave id does not match request

Im not sure if this is an issue with the library or an issue with my modbus device.
I have a raspberry pi with a USB modbus dongle and a ventilation system which i fetch temperatures from modbus registers.

I make the connection like this and then fetch registers every 30 second after that.

func (m *Modbus) Connect() error {
    // Modbus RTU/ASCII
    handler := modbus.NewRTUClientHandler("/dev/ttyUSB0")
    handler.BaudRate = 9600
    handler.DataBits = 8
    handler.Parity = "N"
    handler.StopBits = 2
    handler.SlaveId = 1
    handler.Timeout = 5 * time.Second
    //handler.Logger = log.New(os.Stdout, "test: ", log.LstdFlags)
    m.handler = handler
    if err := handler.Connect(); err != nil {
        return err
    }

    m.client = modbus.NewClient(handler)
    return nil
}

It works fine for a few days then i start getting below errors.
I restart my app and its fine again.
Im thinking of only checking for error and then making the connection again. But this might be a library issue?

2015/07/20 20:31:18 modbus: response slave id '241' does not match request '1'
2015/07/20 20:31:18 modbus: response slave id '35' does not match request '1'
2015/07/20 20:31:18 modbus: response slave id '249' does not match request '1'
2015/07/20 20:31:18 modbus: response slave id '241' does not match request '1'
2015/07/20 20:31:18 modbus: response slave id '143' does not match request '1'
2015/07/20 20:31:19 modbus: response slave id '69' does not match request '1'
2015/07/20 20:31:48 modbus: response slave id '180' does not match request '1'
2015/07/20 20:31:48 modbus: response slave id '48' does not match request '1'
2015/07/20 20:31:48 modbus: response slave id '241' does not match request '1'
2015/07/20 20:31:48 modbus: response slave id '143' does not match request '1'
2015/07/20 20:31:48 modbus: response slave id '154' does not match request '1'
2015/07/20 20:31:49 modbus: response slave id '117' does not match request '1'

Modbus-RTU: Only first byte of answer is read from my device

I'm implementing a client for a Eastron SDM630 electricity meter using your library. The aduRequest ist composed and send correctly, but your library only reads one byte back. I suspect that this relates to the handling of the select call in serial_linux.go, but I'm not sure.

My setup consists of a RS485-USB-dongle that shows up as /dev/ttyUSB0 under my Ubuntu 14.04-box. I can successfully read the device using the minimalmodbus python library and the following script:

#!/usr/bin/env python
import minimalmodbus

instrument = minimalmodbus.Instrument('/dev/ttyUSB0', 1) # port name, slave address (in decimal)
instrument.serial.baudrate = 9600
instrument.serial.bytesize = 8
instrument.serial.parity = minimalmodbus.serial.PARITY_NONE
instrument.serial.stopbits = 1
instrument.serial.timeout = 1
instrument.debug = True
instrument.mode = minimalmodbus.MODE_RTU
print instrument

l1_voltage = instrument.read_float(0, functioncode=4,
    numberOfRegisters=2)
print "L1 voltage: ", l1_voltage

The output of this script looks like this:

$ python test.py
minimalmodbus.Instrument<id=0xb7322b2c, address=1, mode=rtu, close_port_after_each_call=False, precalculate_read_size=True, debug=True, serial=Serial<id=0xb7322b6c, open=True>(port='/dev/ttyUSB0', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=1, xonxoff=False, rtscts=False, dsrdtr=False)>

MinimalModbus debug mode. Writing to instrument (expecting 9 bytes back): '\x01\x04\x00\x00\x00\x02q\xcb'
MinimalModbus debug mode. No sleep required before write. Time since previous read: 1429260650749.2 ms, minimum silent period: 4.01 ms.
MinimalModbus debug mode. Response from instrument: '\x01\x04\x04Cj\xcf\x17\xdb\xe2' (9 bytes), roundtrip time: 31.6 ms. Timeout setting: 1000.0 ms.

L1 voltage:  234.808944702

So, in order to query the SDM630, the library generates the following ADU request (in python syntax):
'\x01\x04\x00\x00\x00\x02q\xcb' and the device responds with '\x01\x04\x04Cj\xcf\x17\xdb\xe2'.

BUT: My program creates the correct ADU request []byte{0x1, 0x4, 0x0, 0x0, 0x0, 0x2, 0x71, 0xcb} (go syntax). It fails to read the answer correctly, it just receives the first byte of the answer: []byte{0x1}. The output of the program is here:

$ go run main.go  
Connecting to RTU via /dev/ttyUSB0
test: 2015/04/17 11:07:40 modbus: connecting '/dev/ttyUSB0'
test: 2015/04/17 11:07:40 modbus: sending []byte{0x1, 0x4, 0x0, 0x0, 0x0, 0x2, 0x71, 0xcb}
test: 2015/04/17 11:07:40 modbus: received []byte{0x1}
Failed to read from SDM630 device modbus: response length '1' does not meet minimum '4'
test: 2015/04/17 11:07:40 modbus: closing '/dev/ttyUSB0'

Any ideas?

Best regards,
-Mathias

How to run?

I'm new in GoLang.
I clone this project, how can I run a simple modbus/TCP holding register with these code files?

Output formatting inconsistent (minor)

It would be nice if send an receive were formatted identically:

RTUClientHandler: 2018/05/12 13:52:47 modbus: received 01 04 04 43 69 0b 7c 38 cd
RTUClientHandler: 2018/05/12 13:52:47 modbus: sending "\x01\x04\x00\x04\x00\x020\n"

Support serial mode on Mac OS

On OS X Yosemite with XCode command line tools and binary installed Golang, go get fails. Here is my command prompt window

image

illegal function

modbus: exception '1' (illegal function), function '131'
Always inform there is a error.
I only used very simple modbus/Tcp example like that.
What's wrong with that? I also used modbus slave and choose 03 holding register.

package main

import (
"fmt"
"github.com/goburrow/modbus"
)

func main() {
cli := modbus.TCPClient("127.0.0.1:502")
res, err := cli.ReadHoldingRegisters(0, 3)
fmt.Println(res)
fmt.Println(err)

}

Read data out of SMA sunnyBoy

Hey, maybe a bit stupid question, but do you think it's possible to use this package to read data out of my sunnyboy inverter? According to the website it supports modbus. I also opened port 502 and by using netcat I indeed see some response on that port. But then what? What is my next approach in finding out what "registers" I should read to get the current generated solar energy?

Idle close of a serial connection is racy and may cause a crash

the crash happens inside Send invoked here and is due to nul dereference of mb.port, which was nulled just as the goroutine was sleeping one line above.
sometimes it's the mb.port.Write that fails as the socket is being closed.
this requires precise timing and happens if the polling interval is the same as idle timeout (60 s).
the function does take steps to reset the idle timer at the beginning, but the implementation is racy and the closeIdle callback may already have been fired. Send does not acquire a mutex to update lastActivity and make sure connection is alive, and so the closeIdle and Send race each other.

Read File Record Implement

In one of my software, I need to use Read File Record command (function code 20). I checked your source code, this command seems to be no implemented.

[SOLVED] Cannot wring single Coil

I've managed to read all data I need. Now I start writing. I use this function

bts2, _ := StringToInt64(task.Val)
var set uint16
if bts2 == 0 {
	set = 0x0000
} else {
	set = 0xFF00
}
result, err = m.Client.WriteSingleCoil(i, set)
i++
if err != nil {
	fmt.Println(err)
}

But I hav EOF error.

What do I do wrong?

i is 0 and 1 2 in a cycle

Wait until timeout on error

Hello. Can not receive proper error message. Trying to read non-existing address from code below. Code is running infinite if no timeout defined. Slave device is freemodbus-1.5.0 driven avr, was successfully tested with this https://sourceforge.net/projects/qmodmaster/

`package main

import (
"github.com/goburrow/modbus"
"fmt"
"time"
)

func main() {
handler := modbus.NewRTUClientHandler("/dev/ttyUSB0")
handler.BaudRate = 115200
handler.DataBits = 8
handler.Parity = "N"
handler.StopBits = 1
handler.SlaveId = 1
handler.Timeout = 10 * time.Second

err := handler.Connect()
fmt.Println(err)

client := modbus.NewClient(handler)
results, err := client.ReadInputRegisters(997, 1)

fmt.Println(err)
fmt.Println(results)

}`

Error : modbus: response unit id '1' does not match request '3'

Hi,
I am new to modbus. When i keep slave id 1 and readCoil on modbus device , everything works perfect but changing the slave id to other then 1 causing below error
Error : modbus: response unit id '1' does not match request '3'
Where as WriteCoil works with no issues either it is slave id 1 or any.

I have only 1 device attached modbus gateway. I am using TCP NewTCPClientHandler.

Any suggestions ?

Thanks,

golang >v.1.16.3 couldn't find package serial

I have a problem with build my tool on golang version 1.16.3. It says that it can't find package github.com/goburrow/serial even I've downloaded via command "go get github.com/goburrow/serial". When I reinstalled golang to version 1.15.11 my tool became build.

How find out what's changed in version 1.16.x?

ValueError: The slave is indicating an error. The response is: '\x01\x83\x02\xc0\xf1'

when i run the program its showing value error

import minimalmodbus
instrument = minimalmodbus.Instrument('COM3', 1) # port name, slave address (in decimal)
instrument.serial.baudrate = 9600
instrument.serial.bytesize = 8
instrument.serial.parity = minimalmodbus.serial.PARITY_EVEN
instrument.serial.stopbits = 1
instrument.serial.timeout = 1
instrument.debug = True
instrument.mode = minimalmodbus.MODE_RTU
print instrument
#l1_voltage = instrument.read_float(3911, functioncode=3, numberOfRegisters=2)
temperature = instrument.read_register(3911 , 2)
print temperature

Traceback (most recent call last):
File "C:/Python27/usbtors485.py", line 12, in
temperature = instrument.read_register(0x3911 , 2)
File "C:\Python27\lib\minimalmodbus.py", line 258, in read_register
return self._genericCommand(functioncode, registeraddress, numberOfDecimals=numberOfDecimals, signed=signed)
File "C:\Python27\lib\minimalmodbus.py", line 697, in _genericCommand
payloadFromSlave = self._performCommand(functioncode, payloadToSlave)
File "C:\Python27\lib\minimalmodbus.py", line 798, in _performCommand
payloadFromSlave = _extractPayload(response, self.address, self.mode, functioncode)
File "C:\Python27\lib\minimalmodbus.py", line 1088, in _extractPayload
raise ValueError('The slave is indicating an error. The response is: {!r}'.format(response))
ValueError: The slave is indicating an error. The response is: '\x01\x83\x02\xc0\xf1'

Found a bug when slave device return error code

Modbus RTU Client:
"panic: runtime error: slice bounds out of range"

This panic occurs when slave device return an error code, and the frame return may be not standard.
source: rtuclient.go, n1
line: err = io.ReadFull(mb.port, data[n:5])

I changed for temporary:
err = fmt.Errorf("modbus: return error code")
n1 = 0

Maybe you could check code for similar problems.
Thank you for your product.

ggenien

Unexpected disconnects from ClientHandlers.

While investigating why one of our server experiences thousands of connections being in TIME_WAIT state I discovered an undocumented and unexpected side effect of modbus.TCPClientHandler.Send()`:

if mb.conn == nil {
		// Establish a new connection and close it when complete
		if err = mb.Connect(); err != nil {
			return
		}
		defer mb.Close()
}

When Send() is called and a connection has not been it established yet, the Send() connects for 1 request and then disconnects. A similar implementation can be found in modbus.ASCIIClientHandler and modbus.RTUClientHandler.Send().

I don't think it's the responsability of the Send() method to connect and disconnect implicitly. This should be done explicitly. Connecting and reconnecting for every request is a waste of resources , especially for embedded devices which we use. It also gives room for errors, because one doesn't has to explicitly call TCPCLientHandler.Connect() before doing a request.

I removed the above code fragment and did a quick tests. And because the connection is now reused properly I saw a major drop the amount of connections in TIME WAIT state. The number dropped from around 2600 to 14.

time_wait

TCP length header included device ID?

I wanted to learn more about the MODBUS TCP protocol and found this library and started reading the sources to get a better understanding. I came across this in the tcpTransporter.Send() method:

modbus/tcpclient.go

Lines 173 to 178 in 606c02f

var data [tcpMaxLength]byte
if _, err = io.ReadFull(mb.conn, data[:tcpHeaderSize]); err != nil {
return
}
// Read length, ignore transaction & protocol id (4 bytes)
length := int(binary.BigEndian.Uint16(data[4:]))

Where:

modbus/tcpclient.go

Lines 22 to 23 in 606c02f

tcpHeaderSize = 7
tcpMaxLength = 260

Unless I'm not seeing it right: After io.ReadFull, data has 7 bytes populated, remaining 253 bytes are 0x00. Decoding it with data[4:] practically passes 3 populated bytes.

This will result in length to contain a larger value if the device ID is non zero. This could then lead to a false positive on the length error check further down the code.

Also, the aduResponse might end up being longer. This wouldn't be a problem if the PDU unpacking takes proper precautions on lengths, haven't checked.

aduResponse = data[:length]

I'm not actually using this project, so I'm not able to confirm if this an actual bug and I might be completely wrong about my assumption. Just trying to learn new things :D.

Data returned by reads

Hi,
I started working on modbus and saw your package. Very well written and works very well. Thanks for doing this. I don't have much experience with modbus. I have a question about the data returned by some read methods:

  • Read discrete's and Read coils are supposed to return data in hex. Is it getting converted to "int" somewhere in the code?
  • How to get the value for a single coil or register?
  • For ReadRegisters, is the data getting converted to int8 somewhere? I see some samples returning data as [205 0 0].

Thanks for your help.

macOS RTU not work

modbus RTU not work on macOS.
It seem serial port config (termios) not correct, not config to raw mode.

Need the RS485 config support at modbus package

The serial package has the RS485 configuration item(RS485 RS485Config) in the Config struct:

// Config is common configuration for serial port.
type Config struct {
	// Device path (/dev/ttyS0)
	Address string
	// Baud rate (default 19200)
	BaudRate int
	// Data bits: 5, 6, 7 or 8 (default 8)
	DataBits int
	// Stop bits: 1 or 2 (default 1)
	StopBits int
	// Parity: N - None, E - Even, O - Odd (default E)
	// (The use of no parity requires 2 stop bits.)
	Parity string
	// Read (Write) timeout.
	Timeout time.Duration
	// Configuration related to RS485
	RS485 RS485Config
}

For the ModBus RTU can transfer through RS232 and RS485, I think the RS485Config should be configurable at the modbus package too?

Working with multiple serial devices

Hi

I've successfully used the library to interact with one RS485 device, however working with multiple devices seems less than ideal.
Currently SlaveId is a property of the handler which needs to be adjusted every time. I think it'd make more sense to derive multiple Clients each with its own SlaveId from the handler and then be able to work with them without touching the handler. What do you think?

Windows serial receive

I am getting serial timeout issues in Windows 7. I created a new Device Id command, code here: imr@c476ad3 since the equipment I am interfacing with does not use typical commands such as writing or reading coils. I can see the equipment response on an oscilloscope, but the command keeps returning an error of "serial timeout".

Here is the initialization code for the RTC client:
handler := modbus.NewRTUClientHandler("\\\\.\\COM14")
handler.BaudRate = 19200
handler.DataBits = 8
handler.Parity = "E"
handler.StopBits = 1
handler.SlaveId = 1
handler.Timeout = 2000

COM14 is definitely the correct port and it is possible to interact with the equipment using a Labview program.

Tag a version

With recent advancements in go, most notable dep and as of golang 1.11 go modules, it would be nice to tag a version. What do you think about tagging a v1.0.0, maybe together with #22 (maybe #27)?

Use of the library with Raspberry Pi 3 and a MAX13487E that has AutoDirection Control

Hello,

I hope someone can help me. I am trying to use the library with a Raspberry Pi 3 and a MAX13487E that has AutoDirection Control. My problem is that the RX line is receiving constantly what the TX line is sending. Probably it is a problem with the MAX13487E circuit, and I will try to solve it, but is it possible somehow to just ignore what is sent on the TX line, i.e ignore its own messages?

The log is as follows:
2020/08/29 19:06:16 modbus: response crc '37180' does not match expected '37144'
test: 2020/08/29 19:06:17 modbus: sending 01 04 00 00 00 01 31 ca
test: 2020/08/29 19:06:17 modbus: received 01 04 00 00 00 01 31 ca 01 04 02 0e 02 3c 91

It is obvious that modbus is receiving also what is sent. Isn't there a simple way to just ignore that?

Thanks,

Slave Modbus RTU over TCP

I am attempting to create a holding register for simulating a modbus RTU slave. I am working in python and need some direction to create this. Any suggestions.

EOF panic modbus tcp-client.

i just create simple mobdus tcp-client(modbus master). Everythings works perfectly. But, some of condition, my program panic triggeren and closed. this is my piece of code:

			data, err := client.ReadHoldingRegisters(41201, 100)
			if err != nil {
				fmt.Println("e1:", err)
				if strings.Contains(err.Error(), "tcp") {
					break
				}
			}

simple and this code is buggy. my program always panic and closed when the ethernet wire is disconnected(accidentally). the error caused by EOF. how to detect EOF and i can reconnect if possible?

Check if handler is connected

Hi

follow this example ...

// Modbus TCP
handler := modbus.NewTCPClientHandler("localhost:502")
handler.Timeout = 10 * time.Second
handler.SlaveId = 0xFF
handler.Logger = log.New(os.Stdout, "test: ", log.LstdFlags)
// Connect manually so that multiple requests are handled in one connection session
err := handler.Connect()
defer handler.Close()

How can I check if the handler is still connected to my modbus controller?

Maybe something like ..... ?

handler.isConected 
handler.conn != nil 

Error: response transaction id does not match request

If you leave this driver running long enough, you get this:

2020-08-21T12:36:40Z I! [inputs.modbusgw] Modbus Error: modbus: response transaction id '51219' does not match request '51220'
2020-08-21T12:36:40Z I! [inputs.modbusgw] Modbus Error: modbus: response transaction id '51220' does not match request '51221'
2020-08-21T12:36:40Z I! [inputs.modbusgw] Modbus Error: modbus: response transaction id '51221' does not match request '51222'

forever. I have seen this type of thing before... I think the normal fix is to make sure that if you get a transaction with a transaction ID earlier than the one you requested, recognize that it's old and throw it away.

Managing multiple slaves with the RTU API, perhaps concurrently.

For a use case I have I may need to talk to multiple slaves across a single RTU serial connection. It seems that the way to cater for this case is to update RTUClientHandler.SlaveId immediately prior to each IO so that the packets are always encoded with the correct slave id.

Is my reading of the code correct?

I could do this in my application code, but then I have to pass around the RTUClientHandler object as well as the Client which isn't something I was planning to do.

I might also want to handle concurrent access to the underlying handler from multiple goroutines. Again, I can add locks in my code to ensure this happens.

However, I am wondering if there is case for a per-slave proxy of the Client interface which transparently switches the slaveId on the underlying handler and acquires a shared lock prior to invoking the underlying Client. My application would then have one Client for each slave and they would all safely share the underlying RTUClientHandler.

I will probably add this kind of Client proxy to my own application, but if you think the idea would be useful to other users of your API let me know and I'll submit a PR. If I am fundamentally misunderstanding something about how the API is intended to be used, let me know that too!

Polling modbus TCP

HI; just a ticket for asking you a question.

I am currently working on a personal project requiring me to do a continuous polling loop on a modbus TCP server; see https://github.com/mhemeryck/modbridge for my project. The idea is to push any detected changes from the polling loop into an MQTT event. The use case I am looking at is having something PLC-like in a home automation setup.

For the modbus part, I heavily rely on your excellent modbus package. Some questions I have come across now:

  • polling coils separately or as groups: my implementation solely relies on polling the modbus coils (for now). Initially, I figured to do a continuous polling of all the different coils one-by-one (in a goroutine). This works, but it seems rather overkill, considering in practice most of the coil addresses are sequential in nature thus allowing for this range to be polled and then interpreting these results. However, initial results do not seem to indicate that much of a performance gain. Question: do you think it is better to poll the coils one-by-one or rather in a group?
  • TCP connections: if I am not mistaken, each of the calls would involve creating another TCP connection; do you think there could be a gain by keeping the same TCP connection open for continuous polling? Added to that, what would be the best way to implement something like that? (i.e. yet another implementation of the transporter interface?)
  • architecture-wise: coming from python, I still have a lot to learn switching to golang for this project. I currently pass in a modbus client instance to my polling functions; would it make more sense to have something like a pointer to a singleton? Any comments on the idiomatic way to handle this?

Thanks in advance, and thanks again on this great package!

Feature Request: Modbus slave simulator

Have you already thought about implementing a Modbus slave (TCP server)?

This would be a prerequisite for the following special use-case: say a certain slave device (lets call it "remote") only works in single-master mode (meaning only one master connected at any time). To connect it to multiple masters, one could create a "proxy" consisting of a slave and a master. The proxy slave forwards requests to the proxy master which in turn requests from the remote. The remote response is then returned to the masters via the proxy slave.

Another use-case would be to mask a Modbus RTU-only device with a TCP proxy to make it more widely available.

I would like to help out where I can after making myself more familiar with the code base.

Serial connection timing out

I am trying to port some existing C code over to Go using this package but keep getting a serial: timeout error on reading registers. I've tried with both ReadHoldingRegisters and ReadInputRegisters, and with timeouts up to 60s.

I have a solar charge controller with RS232 MODBUS port (spec here) connected to a Raspberry Pi running arch linux, through a USB to RS232 converter. I'm on go version go1.6 linux/arm.

The C program is here, and essentially does:

#define SUNSAVER_ADDR    0x01
#define SERIALPORT      "/dev/ttyUSB0"
ctx = modbus_new_rtu(SERIALPORT, 9600, 'N', 8, 2);
modbus_set_slave(ctx, SUNSAVER_ADDR);
rc = modbus_read_registers(ctx, 0x08, 22, data);

(new rtu call here, read registers call here. Uses libmodbus.)

However, when I perform the same setup with this package I see the timeout:

handler := modbus.NewRTUClientHandler("/dev/ttyUSB0")
handler.BaudRate = 9600
handler.DataBits = 8
handler.Parity = "N"
handler.StopBits = 2
handler.SlaveId = 1
handler.Timeout = 5 * time.Second
handler.Logger = log.New(os.Stdout, "mb: ", log.Lshortfile)

if err := handler.Connect(); err != nil {
        fmt.Println("error conecting: ", err)
        return
}

defer handler.Close()

client := modbus.NewClient(handler)

results, err := client.ReadHoldingRegisters(8, 22)
if err != nil {
        fmt.Println("error reading registers:", err)
        return
}

Output:

mb: rtuclient.go:120: modbus: sending 01 03 00 08 00 16 45 c6
error reading registers: serial: timeout

Is there any debugging info I can provide to help track down the culprit?

Serial Timeout after certain request fails

When I use got timeout very frequent but didn't have any issue with modbuspoll

Please correct me if I'm doing any mistake,
FOR MODBUSPOLL:
/data/modpoll/modpoll/linux_arm-eabihf/modpoll -b 115200 -p none -m rtu -a 1 -r 618 -c 13 -t 3 -o 0.1 -l 200 /dev/ttyUSB_HRT

FOR GOBURROW=> MODBUS_RTU
handler1 := modbus.NewRTUClientHandler("/dev/ttyUSB_HRT")
handler1.BaudRate = 115200
handler1.DataBits = 8
handler1.Parity = "N"
handler1.StopBits = 1
handler1.SlaveId = 1
handler1.Timeout = 100 * time.Millisecond

Result While Status Reading Register 334 :=== [0 0 0 0]
Result While Status Reading Register 335 :=== [0 0 0 0]
Result While Status Reading Register 336 :=== [0 0 0 0]
Result While Status Reading Register 337 :=== [0 0 0 0]
Result While Status Reading Register 338 :=== [0 0 0 0]
Result While Status Reading Register 339 :=== [0 0 0 0]
Result While Status Reading Register 340 :=== [0 0 0 0]
Result While Status Reading Register 341 :=== [0 0 0 0]
Result While Status Reading Register 342 :=== [0 0 0 0]
Result While Status Reading Register 343 :=== [0 0 0 0]
Result While Status Reading Register 344 :=== [0 0 0 0]
Error While Status Reading Register 345 :== serial: timeout
Error While Status Reading Register 346 :== serial: timeout
Error While Status Reading Register 347 :== modbus: exception '2' (illegal data address), function '6'

[error] Can't use on arm

Hello,

I'm trying to use your package on arm v7 board (beagle bone black), but with no luck.

Error:

./serial_linux.go:121: cannot use mb.Timeout.Nanoseconds() / 100000000 (type int64) as type int32 in assignment
./serial_linux.go:122: cannot use mb.Timeout.Nanoseconds() % 1000000000 / 1000 (type int64) as type int32 in assignment

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.