Edouard@1440: #!/usr/bin/env python Edouard@1440: # -*- coding: utf-8 -*- Edouard@1440: # Edouard@1440: #Copyright (C) 2015: Edouard TISSERANT Edouard@1440: # Edouard@1440: #See COPYING file for copyrights details. Edouard@1440: # Edouard@1440: #This library is free software; you can redistribute it and/or Edouard@1440: #modify it under the terms of the GNU General Public Edouard@1440: #License as published by the Free Software Foundation; either Edouard@1440: #version 2.1 of the License, or (at your option) any later version. Edouard@1440: # Edouard@1440: #This library is distributed in the hope that it will be useful, Edouard@1440: #but WITHOUT ANY WARRANTY; without even the implied warranty of Edouard@1440: #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Edouard@1440: #General Public License for more details. Edouard@1440: # Edouard@1440: #You should have received a copy of the GNU General Public Edouard@1440: #License along with this library; if not, write to the Free Software Edouard@1440: #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Edouard@1440: Edouard@1441: import sys, traceback, atexit Edouard@1440: #from twisted.python import log Edouard@1440: from twisted.internet import reactor, threads Edouard@1440: from autobahn.twisted import wamp Edouard@1440: from autobahn.twisted.websocket import WampWebSocketClientFactory, connectWS Edouard@1440: from autobahn.wamp import types Edouard@1440: from autobahn.wamp.exception import TransportLost Edouard@1440: from autobahn.wamp.serializer import MsgPackSerializer Edouard@1440: from threading import Thread, Event Edouard@1440: Edouard@1440: _WampSession = None Edouard@1441: _WampConnection = None Edouard@1440: _WampSessionEvent = Event() Edouard@1440: Edouard@1440: class WampSession(wamp.ApplicationSession): Edouard@1440: def onJoin(self, details): Edouard@1441: global _WampSession, _WampSessionEvent Edouard@1440: _WampSession = self Edouard@1440: _WampSessionEvent.set() Edouard@1440: print 'WAMP session joined for :', self.config.extra["ID"] Edouard@1440: Edouard@1440: def onLeave(self, details): Edouard@1441: global _WampSession, _WampSessionEvent Edouard@1440: _WampSessionEvent.clear() Edouard@1440: _WampSession = None Edouard@1440: print 'WAMP session left' Edouard@1440: Edouard@1440: PLCObjDefaults = { "StartPLC": False, Edouard@1440: "GetTraceVariables" : ("Broken",None), Edouard@1440: "GetPLCstatus" : ("Broken",None), Edouard@1440: "RemoteExec" : (-1, "RemoteExec script failed!")} Edouard@1440: Edouard@1440: def WAMP_connector_factory(uri, confnodesroot): Edouard@1440: """ Edouard@1440: WAMP://127.0.0.1:12345/path#realm#ID Edouard@1440: WAMPS://127.0.0.1:12345/path#realm#ID Edouard@1440: """ Edouard@1440: servicetype, location = uri.split("://") Edouard@1440: urlpath, realm, ID = location.split('#') Edouard@1440: urlprefix = {"WAMP":"ws", Edouard@1440: "WAMPS":"wss"}[servicetype] Edouard@1440: url = urlprefix+"://"+urlpath Edouard@1440: Edouard@1440: def RegisterWampClient(): Edouard@1440: Edouard@1440: ## start logging to console Edouard@1440: # log.startLogging(sys.stdout) Edouard@1440: Edouard@1440: # create a WAMP application session factory Edouard@1440: component_config = types.ComponentConfig( Edouard@1440: realm = realm, Edouard@1440: extra = {"ID":ID}) Edouard@1440: session_factory = wamp.ApplicationSessionFactory( Edouard@1440: config = component_config) Edouard@1440: session_factory.session = WampSession Edouard@1440: Edouard@1440: # create a WAMP-over-WebSocket transport client factory Edouard@1440: transport_factory = WampWebSocketClientFactory( Edouard@1440: session_factory, Edouard@1440: url = url, Edouard@1440: serializers = [MsgPackSerializer()], Edouard@1440: debug = False, Edouard@1440: debug_wamp = False) Edouard@1440: Edouard@1440: # start the client from a Twisted endpoint Edouard@1440: conn = connectWS(transport_factory) Edouard@1440: confnodesroot.logger.write(_("WAMP connecting to URL : %s\n")%url) Edouard@1440: return conn Edouard@1440: Edouard@1441: AddToDoBeforeQuit = confnodesroot.AppFrame.AddToDoBeforeQuit Edouard@1441: def ThreadProc(): Edouard@1441: global _WampConnection Edouard@1441: _WampConnection = RegisterWampClient() Edouard@1441: AddToDoBeforeQuit(reactor.stop) Edouard@1441: reactor.run(installSignalHandlers=False) Edouard@1441: Edouard@1440: def WampSessionProcMapper(funcname): Edouard@1443: wampfuncname = '.'.join((ID,funcname)) Edouard@1440: def catcher_func(*args,**kwargs): Edouard@1441: global _WampSession Edouard@1440: if _WampSession is not None : Edouard@1440: try: Edouard@1440: return threads.blockingCallFromThread( Edouard@1443: reactor, _WampSession.call, wampfuncname, Edouard@1440: *args,**kwargs) Edouard@1440: except TransportLost, e: Edouard@1440: confnodesroot.logger.write_error("Connection lost!\n") Edouard@1440: confnodesroot._SetConnector(None) Edouard@1440: except Exception,e: Edouard@1440: errmess = traceback.format_exc() Edouard@1440: confnodesroot.logger.write_error(errmess+"\n") Edouard@1440: print errmess Edouard@1440: #confnodesroot._SetConnector(None) Edouard@1440: return PLCObjDefaults.get(funcname) Edouard@1440: return catcher_func Edouard@1440: Edouard@1440: class WampPLCObjectProxy(object): Edouard@1440: def __init__(self): Edouard@1441: global _WampSessionEvent, _WampConnection Edouard@1440: if not reactor.running: Edouard@1440: Thread(target=ThreadProc).start() Edouard@1440: else: Edouard@1441: _WampConnection = threads.blockingCallFromThread( Edouard@1440: reactor, RegisterWampClient) Edouard@1440: if not _WampSessionEvent.wait(5): Edouard@1441: _WampConnection = stopConnecting() Edouard@1440: raise Exception, _("WAMP connection timeout") Edouard@1440: Edouard@1440: def __del__(self): Edouard@1441: global _WampConnection Edouard@1441: _WampConnection.disconnect() Edouard@1441: # Edouard@1441: # reactor.stop() Edouard@1440: Edouard@1440: def __getattr__(self, attrName): Edouard@1440: member = self.__dict__.get(attrName, None) Edouard@1440: if member is None: Edouard@1440: member = WampSessionProcMapper(attrName) Edouard@1440: self.__dict__[attrName] = member Edouard@1440: return member Edouard@1440: Edouard@1440: # Try to get the proxy object Edouard@1440: try : Edouard@1440: return WampPLCObjectProxy() Edouard@1440: except Exception, msg: Edouard@1440: confnodesroot.logger.write_error(_("WAMP connection to '%s' failed.\n")%location) Edouard@1440: confnodesroot.logger.write_error(traceback.format_exc()) Edouard@1440: return None Edouard@1440: Edouard@1440: Edouard@1440: Edouard@1440: