Skip to content

Instantly share code, notes, and snippets.

@coboshm
Created February 8, 2015 22:05
Show Gist options
  • Save coboshm/80dac1f70c85ece38f8a to your computer and use it in GitHub Desktop.
Save coboshm/80dac1f70c85ece38f8a to your computer and use it in GitHub Desktop.
TCP Modbus java (master) - python (slave)
Marc Cobos
======
To execute the modbus master you have to do the following commands:
javac -classpath jamod-1.2-SNAPSHOT.jar:opencsv-3.1.jar modbus_client.java
java -cp jamod-1.2-SNAPSHOT.jar:opencsv-3.1.jar:. modbus_client
======
This code use the jamod and opencsv libraries
import java.net.*;
import java.sql.Timestamp;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.io.*;
import com.opencsv.CSVWriter;
import net.wimpi.modbus.*;
import net.wimpi.modbus.msg.*;
import net.wimpi.modbus.io.*;
import net.wimpi.modbus.net.*;
import net.wimpi.modbus.util.*;
public class modbus_client {
/**
* @param args
*/
public static void main(String[] args) {
TCPMasterConnection con = null;
ModbusTCPTransaction trans = null;
ReadInputRegistersRequest req = null;
ReadInputRegistersResponse res = null;
try {
//Data slave and what registers do you want to read
InetAddress addr = InetAddress.getByName("localhost");
int ref = 9;
int count = 7;
int repeat = 10000;
int port = 5021;
req = new ReadInputRegistersRequest(ref, count);
req.setUnitID(0x04);
System.out.println("Request: " + req.getHexMessage());
//write a header
String[] entries = new String[8];
entries[0] = "Registers [10 .. 16]";
entries[7] = "\t\t Timestamp";
CSVWriter writer = new CSVWriter(new FileWriter("modbus_registers.csv", true), '\t', CSVWriter.NO_QUOTE_CHARACTER);
writer.writeNext(entries);
writer.close();
//transaction each minute to read the registers 10 to 16
//I should read the guide style if it's better connect each minute or keep connected all the time
do {
con = new TCPMasterConnection(addr);
con.setPort(port);
con.connect();
//Prepare the transaction
trans = new ModbusTCPTransaction(con);
trans.setRequest(req);
trans.setReconnecting(false);
trans.execute();
res = (ReadInputRegistersResponse) trans.getResponse();
trans.getResponse();
System.out.println("Response: " + res.getHexMessage());
for (int i=0;i< res.getRegisters().length; i++){
entries[i] = Integer.toString(res.getRegisterValue(i));
}
Date date= new Date();
entries[count] = new Timestamp(date.getTime()).toString();
//csv file
writer = new CSVWriter(new FileWriter("modbus_registers.csv", true), '\t', CSVWriter.NO_QUOTE_CHARACTER);
writer.writeNext(entries);
writer.close();
TimeUnit.SECONDS.sleep(60);
con.close();
} while (true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
#!/usr/bin/env python
#---------------------------------------------------------------------------#
# import the various server implementations
#---------------------------------------------------------------------------#
from pymodbus.server.sync import StartTcpServer
from pymodbus.server.sync import StartUdpServer
from pymodbus.server.sync import StartSerialServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from threading import Thread
import time
import random
#---------------------------------------------------------------------------#
# configure the service logging
#---------------------------------------------------------------------------#
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
#---------------------------------------------------------------------------#
# initialize your data store
#---------------------------------------------------------------------------#
# The datastores only respond to the addresses that they are initialized to.
# Therefore, if you initialize a DataBlock to addresses of 0x00 to 0xFF, a
# request to 0x100 will respond with an invalid address exception. This is
# because many devices exhibit this kind of behavior (but not all)::
#
# block = ModbusSequentialDataBlock(0x00, [0]*0xff)
#
# Continuing, you can choose to use a sequential or a sparse DataBlock in
# your data context. The difference is that the sequential has no gaps in
# the data while the sparse can. Once again, there are devices that exhibit
# both forms of behavior::
#
# block = ModbusSparseDataBlock({0x00: 0, 0x05: 1})
# block = ModbusSequentialDataBlock(0x00, [0]*5)
#
# Alternately, you can use the factory methods to initialize the DataBlocks
# or simply do not pass them to have them initialized to 0x00 on the full
# address range::
#
# store = ModbusSlaveContext(di = ModbusSequentialDataBlock.create())
# store = ModbusSlaveContext()
#
# Finally, you are allowed to use the same DataBlock reference for every
# table or you you may use a seperate DataBlock for each table. This depends
# if you would like functions to be able to access and modify the same data
# or not::
#
# block = ModbusSequentialDataBlock(0x00, [0]*0xff)
# store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
#
# The server then makes use of a server context that allows the server to
# respond with different slave contexts for different unit ids. By default
# it will return the same context for every unit id supplied (broadcast
# mode). However, this can be overloaded by setting the single flag to False
# and then supplying a dictionary of unit id to context mapping::
#
# slaves = {
# 0x01: ModbusSlaveContext(...),
# 0x02: ModbusSlaveContext(...),
# 0x03: ModbusSlaveContext(...),
# }
# context = ModbusServerContext(slaves=slaves, single=False)
#
# The slave context can also be initialized in zero-mode which means that a
# request to address(0-7) will map to the address (0-7). The default is
# False which is based on section 4.4 of the specification, so address(0-7)
# will map to (1-8)::
#
# store = ModbusSlaveContext(..., zero-mode=True)
#---------------------------------------------------------------------------#
store = {
0x04: ModbusSlaveContext(
hr = ModbusSequentialDataBlock(0, range(0, 100, 1)),
ir = ModbusSequentialDataBlock(0, range(0, 100, 1))
)
}
# update the server dynamically: https://pymodbus.readthedocs.org/en/latest/examples/updating-server.html
context = ModbusServerContext(slaves=store, single=False)
#---------------------------------------------------------------------------#
# define your callback process
#---------------------------------------------------------------------------#
def updating_writer(a):
''' A worker process that runs every so often and
updates live values of the context. It should be noted
that there is a race condition for the update.
:param arguments: The input arguments to the call
'''
while(True):
time.sleep(5)
log.debug("updating the context")
context = a
register = 4
slave_id = 0x04
address = 0x00
values = context[slave_id].getValues(register, address, count=20)
values = [v + random.randint(1, 10) for v in values]
log.debug("new values: " + str(values))
context[slave_id].setValues(register, address, values)
#---------------------------------------------------------------------------#
# initialize the server information
#---------------------------------------------------------------------------#
# If you don't set this or any fields, they are defaulted to empty strings.
#---------------------------------------------------------------------------#
identity = ModbusDeviceIdentification()
identity.VendorName = 'Pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName = 'Pymodbus Server'
identity.MajorMinorRevision = '1.0'
#---------------------------------------------------------------------------#
# run the server you want
#---------------------------------------------------------------------------#
thread = Thread(target=updating_writer, args=(context,))
thread.start()
StartTcpServer(context, identity=identity, address=("localhost", 5021))
#StartUdpServer(context, identity=identity, address=("localhost", 502))
#StartSerialServer(context, identity=identity, port='/dev/pts/3', timeout=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment