-
Notifications
You must be signed in to change notification settings - Fork 3
/
ModbusDevice.py
36 lines (28 loc) · 1.21 KB
/
ModbusDevice.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from twisted.internet.protocol import Protocol, ServerFactory
class ModbusDeviceProtocol(Protocol):
# Twisted calls these functions
def connectionMade(self):
print "connectionMade: made connection"
def connectionLost(self, reason):
print "connectionLost: reason: %s" % str(reason)
def dataReceived(self, data):
"""
Twisted calls this function when we received data
TODO: Check for fragments
"""
print "dataReceived: got data. length: %d" % len(data)
print "dataReceived: ",
print [ hex(ord(c)) for c in data ]
# Add two bytes of 0s to designate it a Modbus packet
data = "\x00\x00" + data
readBytes = self.factory.writeRead(data)
self.transport.write(readBytes)
class ModbusDeviceFactory(ServerFactory):
protocol = ModbusDeviceProtocol
def __init__(self, deviceManager, serial):
self.deviceManager = deviceManager
self.serial = serial
def writeRead(self, writeMessage):
return self.deviceManager.writeRead(self.serial, writeMessage)
def clientConnectionLost(self, connector, reason):
print "Lost connection: %s" % reason.getErrorMessage()