Skip to content

Commit

Permalink
Merge pull request #1 from vinichou94/poursuite_python3
Browse files Browse the repository at this point in the history
Purcue python3
  • Loading branch information
vincsdev authored Feb 25, 2017
2 parents 8103978 + 291fe83 commit 90eda37
Show file tree
Hide file tree
Showing 73 changed files with 936 additions and 746 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ build/
dist/
pymodbus.egg-info/
.coverage
*__pycache__
5 changes: 5 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
Version 1.3.0
------------------------------------------------------------

* Porting to Python 3

Version 1.2.0
------------------------------------------------------------

Expand Down
5 changes: 3 additions & 2 deletions examples/common/asynchronous-client.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,10 @@
# helper method to test deferred callbacks
#---------------------------------------------------------------------------#
def dassert(deferred, callback):
def _assertor(value): assert(value)
def _assertor(value, message=None):
assert value, message
deferred.addCallback(lambda r: _assertor(callback(r)))
deferred.addErrback(lambda _: _assertor(False))
deferred.addErrback(lambda e: _assertor(False, e))

#---------------------------------------------------------------------------#
# specify slave to query
Expand Down
3 changes: 2 additions & 1 deletion examples/common/callback-server.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from pymodbus.datastore import ModbusSparseDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusRtuFramer, ModbusAsciiFramer
from pymodbus.compat import iterkeys

#---------------------------------------------------------------------------#
# import the python libraries we need
Expand Down Expand Up @@ -44,7 +45,7 @@ def __init__(self, devices, queue):
self.devices = devices
self.queue = queue

values = {k:0 for k in devices.iterkeys()}
values = {k:0 for k in iterkeys(devices)}
values[0xbeef] = len(values) # the number of devices
super(CallbackDataBlock, self).__init__(values)

Expand Down
2 changes: 1 addition & 1 deletion examples/common/changing-framers.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
#---------------------------------------------------------------------------#
# Initialize the client
#---------------------------------------------------------------------------#
client = ModbusClient('localhost', port=5020, framer=ModbusFramer)
client = ModbusClient('localhost', port=502, framer=ModbusFramer)
client.connect()

#---------------------------------------------------------------------------#
Expand Down
2 changes: 1 addition & 1 deletion examples/common/custom-message.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,5 @@ def __init__(self, address):
with ModbusClient('127.0.0.1') as client:
request = CustomModbusRequest(0)
result = client.execute(request)
print result
print(result)

19 changes: 10 additions & 9 deletions examples/common/modbus-payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.payload import BinaryPayloadBuilder
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
from pymodbus.compat import iteritems

#---------------------------------------------------------------------------#
# configure the client logging
Expand Down Expand Up @@ -36,7 +37,7 @@
# - an 8 bit bitstring [0,1,0,1,1,0,1,0]
#---------------------------------------------------------------------------#
builder = BinaryPayloadBuilder(endian=Endian.Little)
builder.add_string('abcdefgh')
builder.add_string(b'abcdefgh')
builder.add_32bit_float(22.34)
builder.add_16bit_uint(0x1234)
builder.add_8bit_int(0x12)
Expand Down Expand Up @@ -64,17 +65,17 @@
decoder = BinaryPayloadDecoder.fromRegisters(result.registers, endian=Endian.Little)
decoded = {
'string': decoder.decode_string(8),
'float': decoder.decode_32bit_float(),
'float': decoder.decode_32bit_float(),
'16uint': decoder.decode_16bit_uint(),
'8int': decoder.decode_8bit_int(),
'bits': decoder.decode_bits(),
'8int': decoder.decode_8bit_int(),
'bits': decoder.decode_bits(),
}

print "-" * 60
print "Decoded Data"
print "-" * 60
for name, value in decoded.iteritems():
print ("%s\t" % name), value
print("-" * 60)
print("Decoded Data")
print("-" * 60)
for name, value in iteritems(decoded):
print(("%s\t" % name), value)

#---------------------------------------------------------------------------#
# close the client
Expand Down
4 changes: 2 additions & 2 deletions examples/common/performance.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def single_client_test(host, cycles):

try:
count = 0
client = ModbusTcpClient(host)
client = ModbusTcpClient(host, port=5020)
while count < cycles:
result = client.read_holding_registers(10, 1).getRegister(0)
count += 1
Expand All @@ -75,4 +75,4 @@ def single_client_test(host, cycles):
any(p.start() for p in procs) # start the workers
any(p.join() for p in procs) # wait for the workers to finish
stop = time()
print "%d requests/second" % ((1.0 * cycles) / (stop - start))
print("%d requests/second" % ((1.0 * cycles) / (stop - start)))
51 changes: 45 additions & 6 deletions examples/contrib/bcd-payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
that can be used in the pymodbus library. Below is a
simple binary coded decimal builder and decoder.
'''
import unittest
from struct import pack, unpack
from pymodbus.constants import Endian
from pymodbus.interfaces import IPayloadBuilder
Expand All @@ -23,7 +24,7 @@ def convert_to_bcd(decimal):
while decimal > 0:
nibble = decimal % 10
bcd += nibble << place
decimal /= 10
decimal //= 10
place += 4
return bcd

Expand Down Expand Up @@ -76,12 +77,12 @@ def __init__(self, payload=None, endian=Endian.Little):
self._payload = payload or []
self._endian = endian

def __str__(self):
def to_string(self):
''' Return the payload buffer as a string
:returns: The payload buffer as a string
'''
return ''.join(self._payload)
return b''.join(self._payload)

def reset(self):
''' Reset the payload buffer
Expand All @@ -96,10 +97,10 @@ def build(self):
:returns: The payload buffer as a list
'''
string = str(self)
string = self.to_string()
length = len(string)
string = string + ('\x00' * (length % 2))
return [string[i:i+2] for i in xrange(0, length, 2)]
string = string + (b'\x00' * (length % 2))
return [string[i:i+2] for i in range(0, length, 2)]

def add_bits(self, values):
''' Adds a collection of bits to be encoded
Expand Down Expand Up @@ -217,6 +218,44 @@ def decode_string(self, size=1):
return self._payload[self._pointer - size:self._pointer]


#---------------------------------------------------------------------------#
# Fixture
#---------------------------------------------------------------------------#
class BcdPayloadUtilityTests(unittest.TestCase):

def setUp(self):
'''
Initializes the test environment and builds request/result
encoding pairs
'''
self.bitstring = [True, False, False, False, True, False, False, False]
self.payload = \
b'\x01\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00\x00' \
b'\x00\x00\x00\xff\xfe\xff\xfd\xff\xff\xff\xfc\xff' \
b'\xff\xff\xff\xff\xff\xff\x00\x00\xa0\x3f\x00\x00' \
b'\x00\x00\x00\x00\x19\x40\x74\x65\x73\x74\x11'

def testPayloadBuilder(self):
''' Test basic bit message encoding/decoding '''
builder = BcdPayloadBuilder(endian=Endian.Little)
builder.add_number(1)
builder.add_string(b'test')
builder.add_bits(self.bitstring)
self.assertEqual(self.payload, builder.to_string())

def testPayloadDecoder(self):
''' Test basic bit message encoding/decoding '''
decoder = BcdPayloadDecoder(self.payload)
self.assertEqual(1, decoder.decode_int())
self.assertEqual(b'test', decoder.decode_string(4))
self.assertEqual(self.bitstring, decoder.decode_bits())

#---------------------------------------------------------------------------#
# unit tests
#---------------------------------------------------------------------------#
if __name__ == "__main__":
unittest.main()

#---------------------------------------------------------------------------#
# Exported Identifiers
#---------------------------------------------------------------------------#
Expand Down
23 changes: 13 additions & 10 deletions examples/contrib/message-generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
The following is an example of how to generate example encoded messages
for the supplied modbus format:
* tcp - `./generate-messages.py -f tcp -m rx -b`
* ascii - `./generate-messages.py -f ascii -m tx -a`
* rtu - `./generate-messages.py -f rtu -m rx -b`
* binary - `./generate-messages.py -f binary -m tx -b`
* tcp - `./message-generator.py -f tcp -m rx -b`
* ascii - `./message-generator.py -f ascii -m tx -a`
* rtu - `./message-generator.py -f rtu -m rx -b`
* binary - `./message-generator.py -f binary -m tx -b`
'''
from __future__ import print_function
import binascii
from optparse import OptionParser
#--------------------------------------------------------------------------#
# import all the available framers
Expand Down Expand Up @@ -165,11 +167,12 @@ def generate_messages(framer, options):
messages = _request_messages if options.messages == 'tx' else _response_messages
for message in messages:
message = message(**_arguments)
print "%-44s = " % message.__class__.__name__,
print("%-44s = " % message.__class__.__name__, end = '')
packet = framer.buildPacket(message)
if not options.ascii:
packet = packet.encode('hex') + '\n'
print packet, # because ascii ends with a \r\n
packet = binascii.b2a_hex(packet).decode('utf8') + '\n'
else: packet = packet.decode()
print(packet, end='') # because ascii ends with a \r\n


#---------------------------------------------------------------------------#
Expand Down Expand Up @@ -213,9 +216,9 @@ def main():
if option.debug:
try:
modbus_log.setLevel(logging.DEBUG)
logging.basicConfig()
except Exception, e:
print "Logging is not supported on this system"
logging.basicConfig()
except Exception as e:
print("Logging is not supported on this system")

framer = lookup = {
'tcp': ModbusSocketFramer,
Expand Down
44 changes: 23 additions & 21 deletions examples/contrib/message-parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@
import sys
import collections
import textwrap
import binascii
from optparse import OptionParser
from pymodbus.utilities import computeCRC, computeLRC
from pymodbus.factory import ClientDecoder, ServerDecoder
from pymodbus.transaction import ModbusSocketFramer
from pymodbus.transaction import ModbusBinaryFramer
from pymodbus.transaction import ModbusAsciiFramer
from pymodbus.transaction import ModbusRtuFramer
from pymodbus.compat import iteritems

#--------------------------------------------------------------------------#
# Logging
Expand Down Expand Up @@ -51,24 +53,24 @@ def decode(self, message):
:param message: The messge to decode
'''
value = message if self.encode else message.encode('hex')
print "="*80
print "Decoding Message %s" % value
print "="*80
value = message if self.encode else binascii.hexlify(message)
print("=" * 80)
print("Decoding Message %s" % value.decode())
print("=" * 80)
decoders = [
self.framer(ServerDecoder()),
self.framer(ClientDecoder()),
]
for decoder in decoders:
print "%s" % decoder.decoder.__class__.__name__
print "-"*80
print("%s" % decoder.decoder.__class__.__name__)
print("-" * 80)
try:
decoder.addToFrame(message)
if decoder.checkFrame():
decoder.advanceFrame()
decoder.processIncomingPacket(message, self.report)
else: self.check_errors(decoder, message)
except Exception, ex: self.check_errors(decoder, message)
except Exception as ex: self.check_errors(decoder, message)

def check_errors(self, decoder, message):
''' Attempt to find message errors
Expand All @@ -82,20 +84,20 @@ def report(self, message):
:param message: The message to print
'''
print "%-15s = %s" % ('name', message.__class__.__name__)
for k,v in message.__dict__.iteritems():
print("%-15s = %s" % ('name', message.__class__.__name__))
for k,v in iteritems(message.__dict__):
if isinstance(v, dict):
print "%-15s =" % k
for kk,vv in v.items():
print " %-12s => %s" % (kk, vv)
print("%-15s =" % k)
for kk, vv in iteritems(v):
print(" %-12s => %s" % (kk, vv))

elif isinstance(v, collections.Iterable):
print "%-15s =" % k
print("%-15s =" % k)
value = str([int(x) for x in v])
for line in textwrap.wrap(value, 60):
print "%-15s . %s" % ("", line)
else: print "%-15s = %s" % (k, hex(v))
print "%-15s = %s" % ('documentation', message.__doc__)
print("%-15s . %s" % ("", line))
else: print("%-15s = %s" % (k, hex(v)))
print("%-15s = %s" % ('documentation', message.__doc__))


#---------------------------------------------------------------------------#
Expand Down Expand Up @@ -154,8 +156,8 @@ def get_messages(option):
for line in handle:
if line.startswith('#'): continue
if not option.ascii:
line = line.strip()
line = line.decode('hex')
line = line.strip().encode('ascii')
line = binascii.unhexlify(line)
yield line

def main():
Expand All @@ -166,9 +168,9 @@ def main():
if option.debug:
try:
modbus_log.setLevel(logging.DEBUG)
logging.basicConfig()
except Exception, e:
print "Logging is not supported on this system"
logging.basicConfig()
except Exception as e:
print("Logging is not supported on this system")

framer = lookup = {
'tcp': ModbusSocketFramer,
Expand Down
10 changes: 5 additions & 5 deletions examples/contrib/modbus-simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,15 +107,15 @@ def main():
try:
server_log.setLevel(logging.DEBUG)
protocol_log.setLevel(logging.DEBUG)
except Exception, e:
print "Logging is not supported on this system"
except Exception as e:
print("Logging is not supported on this system")

# parse configuration file and run
try:
conf = Configuration(opt.file)
StartTcpServer(context=conf.parse())
except ConfigurationException, err:
print err
except ConfigurationException as err:
print(err)
parser.print_help()

#---------------------------------------------------------------------------#
Expand All @@ -124,5 +124,5 @@ def main():
if __name__ == "__main__":
if root_test():
main()
else: print "This script must be run as root!"
else: print("This script must be run as root!")

2 changes: 1 addition & 1 deletion examples/contrib/modbus_mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@
import csv
import json
from collections import defaultdict
from StringIO import StringIO
from tokenize import generate_tokens
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.datastore.store import ModbusSparseDataBlock
from pymodbus.datastore.context import ModbusSlaveContext
from pymodbus.compat import StringIO


#---------------------------------------------------------------------------#
Expand Down
Loading

0 comments on commit 90eda37

Please sign in to comment.