runtime/WampClient.py
changeset 1893 971de876b1af
parent 1892 daf40a1e7607
child 1894 f224383cc883
equal deleted inserted replaced
1892:daf40a1e7607 1893:971de876b1af
    24 
    24 
    25 from __future__ import absolute_import
    25 from __future__ import absolute_import
    26 from __future__ import print_function
    26 from __future__ import print_function
    27 import json
    27 import json
    28 
    28 
       
    29 import os
       
    30 import json
    29 from autobahn.twisted import wamp
    31 from autobahn.twisted import wamp
    30 from autobahn.twisted.websocket import WampWebSocketClientFactory, connectWS
    32 from autobahn.twisted.websocket import WampWebSocketClientFactory, connectWS
    31 from autobahn.wamp import types
    33 from autobahn.wamp import types, auth
    32 from autobahn.wamp.serializer import MsgPackSerializer
    34 from autobahn.wamp.serializer import MsgPackSerializer
       
    35 from autobahn.wamp.exception import ApplicationError
    33 from twisted.internet.defer import inlineCallbacks
    36 from twisted.internet.defer import inlineCallbacks
    34 from twisted.internet.protocol import ReconnectingClientFactory
    37 from twisted.internet.protocol import ReconnectingClientFactory
    35 
    38 
    36 
    39 
    37 _WampSession = None
    40 _WampSession = None
    64         obj = getattr(obj, names.pop(0))
    67         obj = getattr(obj, names.pop(0))
    65     return obj
    68     return obj
    66 
    69 
    67 
    70 
    68 class WampSession(wamp.ApplicationSession):
    71 class WampSession(wamp.ApplicationSession):
       
    72     def onConnect(self):
       
    73         secret = self.config.extra["secret"]
       
    74         if secret:
       
    75             user = self.config.extra["ID"].encode('utf8')
       
    76             self.join(u"Automation", [u"wampcra"], user)
       
    77         else:
       
    78             self.join(u"Automation")
       
    79 
       
    80     def onChallenge(self, challenge):
       
    81         if challenge.method == u"wampcra":
       
    82             secret = self.config.extra["secret"].encode('utf8')
       
    83             signature = auth.compute_wcs(secret, challenge.extra['challenge'].encode('utf8'))
       
    84             return signature.decode("ascii")
       
    85         else:
       
    86             raise Exception("don't know how to handle authmethod {}".format(challenge.method))
    69 
    87 
    70     @inlineCallbacks
    88     @inlineCallbacks
    71     def onJoin(self, details):
    89     def onJoin(self, details):
    72         global _WampSession
    90         global _WampSession
    73         _WampSession = self
    91         _WampSession = self
    98         print(_("WAMP Client connection lost .. retrying .."))
   116         print(_("WAMP Client connection lost .. retrying .."))
    99         ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
   117         ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
   100 
   118 
   101 
   119 
   102 def LoadWampClientConf(wampconf):
   120 def LoadWampClientConf(wampconf):
       
   121     try:
       
   122         WSClientConf = json.load(open(wampconf))
       
   123         return WSClientConf
       
   124     except ValueError, ve:
       
   125         print(_("WAMP load error: "), ve)
       
   126         return None
       
   127     except Exception:
       
   128         return None
   103 
   129 
   104     WSClientConf = json.load(open(wampconf))
   130 def LoadWampSecret(secretfname):
   105     return WSClientConf
   131     try:
       
   132         WSClientWampSecret = open(secretfname, 'rb').read()
       
   133         return WSClientWampSecret
       
   134     except ValueError, ve:
       
   135         print(_("Wamp secret load error:"), ve)
       
   136         return None
       
   137     except Exception:
       
   138         return None
   106 
   139 
   107 
   140 
   108 def RegisterWampClient(wampconf):
   141 def RegisterWampClient(wampconf, secretfname):
   109 
   142 
   110     WSClientConf = LoadWampClientConf(wampconf)
   143     WSClientConf = LoadWampClientConf(wampconf)
   111 
   144 
   112     # start logging to console
   145     if not WSClientConf:
   113     # log.startLogging(sys.stdout)
   146         print _("WAMP client connection not established!")
       
   147         return
       
   148 
       
   149     WampSecret = LoadWampSecret(secretfname)
   114 
   150 
   115     # create a WAMP application session factory
   151     # create a WAMP application session factory
   116     component_config = types.ComponentConfig(
   152     component_config = types.ComponentConfig(
   117         realm=WSClientConf["realm"],
   153         realm=WSClientConf["realm"],
   118         extra={"ID": WSClientConf["ID"]})
   154         extra=WSClientConf)
   119     session_factory = wamp.ApplicationSessionFactory(
   155     session_factory = wamp.ApplicationSessionFactory(
   120         config=component_config)
   156         config=component_config)
   121     session_factory.session = WampSession
   157     session_factory.session = WampSession
   122 
   158 
   123     # create a WAMP-over-WebSocket transport client factory
   159     # create a WAMP-over-WebSocket transport client factory
   124     transport_factory = ReconnectingWampWebSocketClientFactory(
   160     transport_factory = ReconnectingWampWebSocketClientFactory(
   125         session_factory,
   161         session_factory,
   126         url=WSClientConf["url"],
   162         url=WSClientConf["url"],
   127         serializers=[MsgPackSerializer()],
   163         serializers=[MsgPackSerializer()])
   128         debug=False,
       
   129         debug_wamp=False)
       
   130 
   164 
   131     # start the client from a Twisted endpoint
   165     # start the client from a Twisted endpoint
   132     conn = connectWS(transport_factory)
   166     conn = connectWS(transport_factory)
   133     print(_("WAMP client connecting to :"), _WSClientConf["url"])
   167     print(_("WAMP client connecting to :"), _WSClientConf["url"])
   134     return conn
   168     return conn