connectors/WAMP/__init__.py
changeset 1784 64beb9e9c749
parent 1782 5b6ad7a7fd9d
child 1826 91796f408540
equal deleted inserted replaced
1729:31e63e25b4cc 1784:64beb9e9c749
    20 #
    20 #
    21 # You should have received a copy of the GNU General Public License
    21 # You should have received a copy of the GNU General Public License
    22 # along with this program; if not, write to the Free Software
    22 # along with this program; if not, write to the Free Software
    23 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
    23 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
    24 
    24 
    25 import sys, traceback, atexit
    25 import sys
    26 #from twisted.python import log
    26 import traceback
       
    27 import atexit
    27 from twisted.internet import reactor, threads
    28 from twisted.internet import reactor, threads
    28 from autobahn.twisted import wamp
    29 from autobahn.twisted import wamp
    29 from autobahn.twisted.websocket import WampWebSocketClientFactory, connectWS
    30 from autobahn.twisted.websocket import WampWebSocketClientFactory, connectWS
    30 from autobahn.wamp import types
    31 from autobahn.wamp import types
    31 from autobahn.wamp.exception import TransportLost
    32 from autobahn.wamp.exception import TransportLost
    33 from threading import Thread, Event
    34 from threading import Thread, Event
    34 
    35 
    35 _WampSession = None
    36 _WampSession = None
    36 _WampConnection = None
    37 _WampConnection = None
    37 _WampSessionEvent = Event()
    38 _WampSessionEvent = Event()
       
    39 
    38 
    40 
    39 class WampSession(wamp.ApplicationSession):
    41 class WampSession(wamp.ApplicationSession):
    40     def onJoin(self, details):
    42     def onJoin(self, details):
    41         global _WampSession, _WampSessionEvent
    43         global _WampSession, _WampSessionEvent
    42         _WampSession = self
    44         _WampSession = self
    47         global _WampSession, _WampSessionEvent
    49         global _WampSession, _WampSessionEvent
    48         _WampSessionEvent.clear()
    50         _WampSessionEvent.clear()
    49         _WampSession = None
    51         _WampSession = None
    50         print 'WAMP session left'
    52         print 'WAMP session left'
    51 
    53 
    52 PLCObjDefaults = { "StartPLC": False,
    54 
    53                    "GetTraceVariables" : ("Broken",None),
    55 PLCObjDefaults = {
    54                    "GetPLCstatus" : ("Broken",None),
    56     "StartPLC":          False,
    55                    "RemoteExec" : (-1, "RemoteExec script failed!")}
    57     "GetTraceVariables": ("Broken", None),
       
    58     "GetPLCstatus":      ("Broken", None),
       
    59     "RemoteExec":        (-1, "RemoteExec script failed!")
       
    60 }
       
    61 
    56 
    62 
    57 def WAMP_connector_factory(uri, confnodesroot):
    63 def WAMP_connector_factory(uri, confnodesroot):
    58     """
    64     """
    59     WAMP://127.0.0.1:12345/path#realm#ID
    65     WAMP://127.0.0.1:12345/path#realm#ID
    60     WAMPS://127.0.0.1:12345/path#realm#ID
    66     WAMPS://127.0.0.1:12345/path#realm#ID
    61     """
    67     """
    62     servicetype, location = uri.split("://")
    68     servicetype, location = uri.split("://")
    63     urlpath, realm, ID = location.split('#')
    69     urlpath, realm, ID = location.split('#')
    64     urlprefix = {"WAMP":"ws",
    70     urlprefix = {"WAMP":  "ws",
    65                  "WAMPS":"wss"}[servicetype]
    71                  "WAMPS": "wss"}[servicetype]
    66     url = urlprefix+"://"+urlpath
    72     url = urlprefix+"://"+urlpath
    67 
    73 
    68     def RegisterWampClient():
    74     def RegisterWampClient():
    69 
    75 
    70         ## start logging to console
    76         # start logging to console
    71         # log.startLogging(sys.stdout)
    77         # log.startLogging(sys.stdout)
    72 
    78 
    73         # create a WAMP application session factory
    79         # create a WAMP application session factory
    74         component_config = types.ComponentConfig(
    80         component_config = types.ComponentConfig(
    75             realm = realm,
    81             realm=realm,
    76             extra = {"ID":ID})
    82             extra={"ID": ID})
    77         session_factory = wamp.ApplicationSessionFactory(
    83         session_factory = wamp.ApplicationSessionFactory(
    78             config = component_config)
    84             config=component_config)
    79         session_factory.session = WampSession
    85         session_factory.session = WampSession
    80 
    86 
    81         # create a WAMP-over-WebSocket transport client factory
    87         # create a WAMP-over-WebSocket transport client factory
    82         transport_factory = WampWebSocketClientFactory(
    88         transport_factory = WampWebSocketClientFactory(
    83             session_factory,
    89             session_factory,
    84             url = url,
    90             url=url,
    85             serializers = [MsgPackSerializer()],
    91             serializers=[MsgPackSerializer()],
    86             debug = False,
    92             debug=False,
    87             debug_wamp = False)
    93             debug_wamp=False)
    88 
    94 
    89         # start the client from a Twisted endpoint
    95         # start the client from a Twisted endpoint
    90         conn = connectWS(transport_factory)
    96         conn = connectWS(transport_factory)
    91         confnodesroot.logger.write(_("WAMP connecting to URL : %s\n")%url)
    97         confnodesroot.logger.write(_("WAMP connecting to URL : %s\n") % url)
    92         return conn
    98         return conn
    93 
    99 
    94     AddToDoBeforeQuit = confnodesroot.AppFrame.AddToDoBeforeQuit
   100     AddToDoBeforeQuit = confnodesroot.AppFrame.AddToDoBeforeQuit
       
   101 
    95     def ThreadProc():
   102     def ThreadProc():
    96         global _WampConnection
   103         global _WampConnection
    97         _WampConnection = RegisterWampClient()
   104         _WampConnection = RegisterWampClient()
    98         AddToDoBeforeQuit(reactor.stop)
   105         AddToDoBeforeQuit(reactor.stop)
    99         reactor.run(installSignalHandlers=False)
   106         reactor.run(installSignalHandlers=False)
   100 
   107 
   101     def WampSessionProcMapper(funcname):
   108     def WampSessionProcMapper(funcname):
   102         wampfuncname = '.'.join((ID,funcname))
   109         wampfuncname = '.'.join((ID, funcname))
   103         def catcher_func(*args,**kwargs):
   110 
       
   111         def catcher_func(*args, **kwargs):
   104             global _WampSession
   112             global _WampSession
   105             if _WampSession is not None :
   113             if _WampSession is not None:
   106                 try:
   114                 try:
   107                     return threads.blockingCallFromThread(
   115                     return threads.blockingCallFromThread(
   108                         reactor, _WampSession.call, wampfuncname,
   116                         reactor, _WampSession.call, wampfuncname,
   109                         *args,**kwargs)
   117                         *args, **kwargs)
   110                 except TransportLost, e:
   118                 except TransportLost, e:
   111                     confnodesroot.logger.write_error(_("Connection lost!\n"))
   119                     confnodesroot.logger.write_error(_("Connection lost!\n"))
   112                     confnodesroot._SetConnector(None)
   120                     confnodesroot._SetConnector(None)
   113                 except Exception,e:
   121                 except Exception, e:
   114                     errmess = traceback.format_exc()
   122                     errmess = traceback.format_exc()
   115                     confnodesroot.logger.write_error(errmess+"\n")
   123                     confnodesroot.logger.write_error(errmess+"\n")
   116                     print errmess
   124                     print errmess
   117                     #confnodesroot._SetConnector(None)
   125                     # confnodesroot._SetConnector(None)
   118             return PLCObjDefaults.get(funcname)
   126             return PLCObjDefaults.get(funcname)
   119         return catcher_func
   127         return catcher_func
   120 
   128 
   121     class WampPLCObjectProxy(object):
   129     class WampPLCObjectProxy(object):
   122         def __init__(self):
   130         def __init__(self):
   126             else:
   134             else:
   127                 _WampConnection = threads.blockingCallFromThread(
   135                 _WampConnection = threads.blockingCallFromThread(
   128                     reactor, RegisterWampClient)
   136                     reactor, RegisterWampClient)
   129             if not _WampSessionEvent.wait(5):
   137             if not _WampSessionEvent.wait(5):
   130                 _WampConnection = stopConnecting()
   138                 _WampConnection = stopConnecting()
   131                 raise Exception, _("WAMP connection timeout")
   139                 raise Exception(_("WAMP connection timeout"))
   132 
   140 
   133         def __del__(self):
   141         def __del__(self):
   134             global _WampConnection
   142             global _WampConnection
   135             _WampConnection.disconnect()
   143             _WampConnection.disconnect()
   136             #
   144             #
   142                 member = WampSessionProcMapper(attrName)
   150                 member = WampSessionProcMapper(attrName)
   143                 self.__dict__[attrName] = member
   151                 self.__dict__[attrName] = member
   144             return member
   152             return member
   145 
   153 
   146     # Try to get the proxy object
   154     # Try to get the proxy object
   147     try :
   155     try:
   148         return WampPLCObjectProxy()
   156         return WampPLCObjectProxy()
   149     except Exception, msg:
   157     except Exception, msg:
   150         confnodesroot.logger.write_error(_("WAMP connection to '%s' failed.\n")%location)
   158         confnodesroot.logger.write_error(_("WAMP connection to '%s' failed.\n") % location)
   151         confnodesroot.logger.write_error(traceback.format_exc())
   159         confnodesroot.logger.write_error(traceback.format_exc())
   152         return None
   160         return None
   153 
       
   154 
       
   155 
       
   156