Files
sics/site_ansto/instrument/TEST_SICS/fakeGalil/galilfactory.py
2013-02-21 14:26:26 +11:00

89 lines
3.4 KiB
Python

#!/usr//bin/env python
# vim: ts=8 sts=4 sw=4 expandtab
# Author: Douglas Clowes (dcl@ansto.gov.au) 2012-06-29
from twisted.internet.protocol import Protocol
from twisted.internet.protocol import ServerFactory
from galilcontroller import GalilController
class GalilProtocol(Protocol):
"""Protocol object used by the Twisted Infrastructure to handle connections
"""
def __init__(self, thisDevice):
print "GalilProtocol protocol ctor", thisDevice
self.device = thisDevice
self.term = "\r\n"
def write(self, response):
self.response = self.response + response
def connectionMade(self):
self.pdu = ""
self.response = ""
self.device.protocol = self
self.factory.numProtocols = self.factory.numProtocols + 1
print "connectionMade: connection number", self.factory.numProtocols
if self.factory.numProtocols > 2:
print "Too many connections - rejecting"
self.transport.write("Too many connections, try later\r\n")
self.transport.loseConnection()
'''else:
self.transport.write("Welcome connection %d\r\n" % self.factory.numProtocols)'''
def connectionLost(self, reason):
self.factory.numProtocols = self.factory.numProtocols - 1
print "connectionLost: connections left", self.factory.numProtocols
def dataReceived(self, data):
#print "dataReceived - len:", len(data)
last_was_cr = False
for c in data:
if c == "\r" or c == ";" or c == "\n":
if c == "\n" and last_was_cr:
continue
last_was_cr = False
if c == "\r":
last_was_cr = True
if len(self.pdu) > 0:
#print "Request: ", self.pdu
the_response = self.device.dataReceived(self.pdu)
#print "Response:", the_response
for item in the_response:
self.write(item + self.term)
self.pdu = ""
if c == ";":
if len(self.response) > 0 and self.response[-1] != ":":
self.response = self.response + ":"
else:
if len(self.response) > 0:
if self.response[-1] == ";":
self.response = self.response[:-1]
if len(self.response) > 0 and self.response[-1] != ":":
self.response = self.response + ":"
if len(self.response) == 0:
self.response = self.response + ":"
if len(self.response) > 0:
#print "Protocol Response: %s" % self.response
self.transport.write(self.response)
self.response = ""
else:
self.pdu = self.pdu + c
class GalilFactory(ServerFactory):
"""Factory object used by the Twisted Infrastructure to create a Protocol
object for incomming connections"""
protocol = GalilProtocol
def __init__(self, thePort):
print "GalilFactory ctor: "
self.port = thePort
self.device = GalilController(thePort)
self.numProtocols = 0
def buildProtocol(self, addr):
p = self.protocol(self.device)
p.factory = self
return p