runtime/WampClient.py
changeset 1901 e8cf68d69447
parent 1900 9d1547578f55
child 1955 a1ea9856013a
equal deleted inserted replaced
1900:9d1547578f55 1901:e8cf68d69447
    22 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
    22 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
    23 
    23 
    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
       
    28 import time
    27 import time
    29 import os
       
    30 import json
    28 import json
    31 from autobahn.twisted import wamp
    29 from autobahn.twisted import wamp
    32 from autobahn.twisted.websocket import WampWebSocketClientFactory, connectWS
    30 from autobahn.twisted.websocket import WampWebSocketClientFactory, connectWS
    33 from autobahn.wamp import types, auth
    31 from autobahn.wamp import types, auth
    34 from autobahn.wamp.serializer import MsgPackSerializer
    32 from autobahn.wamp.serializer import MsgPackSerializer
    35 from autobahn.wamp.exception import ApplicationError
       
    36 from twisted.internet.defer import inlineCallbacks
    33 from twisted.internet.defer import inlineCallbacks
    37 from twisted.internet.protocol import ReconnectingClientFactory
    34 from twisted.internet.protocol import ReconnectingClientFactory
    38 
    35 
    39 
    36 
    40 _WampSession = None
    37 _WampSession = None
    53     "GetLogMessage",
    50     "GetLogMessage",
    54     "ResetLogCount",
    51     "ResetLogCount",
    55 ]
    52 ]
    56 
    53 
    57 # Those two lists are meant to be filled by customized runtime
    54 # Those two lists are meant to be filled by customized runtime
    58 # or User python code. 
    55 # or User python code.
    59 
    56 
    60 """ crossbar Events to register to """  
    57 """ crossbar Events to register to """
    61 SubscribedEvents = []
    58 SubscribedEvents = []
    62 
    59 
    63 """ things to do on join (callables) """  
    60 """ things to do on join (callables) """
    64 DoOnJoin = []
    61 DoOnJoin = []
    65 
    62 
    66 
    63 
    67 def GetCallee(name):
    64 def GetCallee(name):
    68     """ Get Callee or Subscriber corresponding to '.' spearated object path """
    65     """ Get Callee or Subscriber corresponding to '.' spearated object path """
    73     return obj
    70     return obj
    74 
    71 
    75 
    72 
    76 class WampSession(wamp.ApplicationSession):
    73 class WampSession(wamp.ApplicationSession):
    77     def onConnect(self):
    74     def onConnect(self):
    78         if self.config.extra.has_key("secret"):
    75         if "secret" in self.config.extra:
    79             user = self.config.extra["ID"].encode('utf8')
    76             user = self.config.extra["ID"].encode('utf8')
    80             self.join(u"Automation", [u"wampcra"], user)
    77             self.join(u"Automation", [u"wampcra"], user)
    81         else:
    78         else:
    82             self.join(u"Automation")
    79             self.join(u"Automation")
    83 
    80 
    91 
    88 
    92     @inlineCallbacks
    89     @inlineCallbacks
    93     def onJoin(self, details):
    90     def onJoin(self, details):
    94         global _WampSession
    91         global _WampSession
    95         _WampSession = self
    92         _WampSession = self
    96         ID = self.config.extra["ID"] # this is unicode
    93         ID = self.config.extra["ID"]
    97         print('WAMP session joined by :', ID)
    94         print('WAMP session joined by :', ID)
    98         for name in ExposedCalls:
    95         for name in ExposedCalls:
    99             regoption = types.RegisterOptions(u'exact',u'last',None, None)
    96             regoption = types.RegisterOptions(u'exact', u'last', None, None)
   100             yield self.register(GetCallee(name), u'.'.join((ID, name)), regoption)
    97             yield self.register(GetCallee(name), u'.'.join((ID, name)), regoption)
   101 
    98 
   102         for name in SubscribedEvents:
    99         for name in SubscribedEvents:
   103             yield self.subscribe(GetCallee(name), unicode(name))
   100             yield self.subscribe(GetCallee(name), unicode(name))
   104 
   101 
   111         print(_('WAMP session left'))
   108         print(_('WAMP session left'))
   112 
   109 
   113 
   110 
   114 class ReconnectingWampWebSocketClientFactory(WampWebSocketClientFactory, ReconnectingClientFactory):
   111 class ReconnectingWampWebSocketClientFactory(WampWebSocketClientFactory, ReconnectingClientFactory):
   115     def clientConnectionFailed(self, connector, reason):
   112     def clientConnectionFailed(self, connector, reason):
   116         print _("WAMP Client connection failed (%s) .. retrying .." %time.ctime())
   113         print(_("WAMP Client connection failed (%s) .. retrying .." % time.ctime()))
   117         ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
   114         ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
   118 
   115 
   119     def clientConnectionLost(self, connector, reason):
   116     def clientConnectionLost(self, connector, reason):
   120         print _("WAMP Client connection lost (%s) .. retrying .." %time.ctime())
   117         print(_("WAMP Client connection lost (%s) .. retrying .." % time.ctime()))
   121         ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
   118         ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
   122 
   119 
   123 
   120 
   124 def LoadWampClientConf(wampconf):
   121 def LoadWampClientConf(wampconf):
   125     try:
   122     try:
   128     except ValueError, ve:
   125     except ValueError, ve:
   129         print(_("WAMP load error: "), ve)
   126         print(_("WAMP load error: "), ve)
   130         return None
   127         return None
   131     except Exception:
   128     except Exception:
   132         return None
   129         return None
       
   130 
   133 
   131 
   134 def LoadWampSecret(secretfname):
   132 def LoadWampSecret(secretfname):
   135     try:
   133     try:
   136         WSClientWampSecret = open(secretfname, 'rb').read()
   134         WSClientWampSecret = open(secretfname, 'rb').read()
   137         return WSClientWampSecret
   135         return WSClientWampSecret
   156         WSClientConf["secret"] = WampSecret
   154         WSClientConf["secret"] = WampSecret
   157 
   155 
   158     # create a WAMP application session factory
   156     # create a WAMP application session factory
   159     component_config = types.ComponentConfig(
   157     component_config = types.ComponentConfig(
   160         realm=WSClientConf["realm"],
   158         realm=WSClientConf["realm"],
   161         extra=WSClientConf) # pass a dict containing unicode values
   159         extra=WSClientConf)
   162     session_factory = wamp.ApplicationSessionFactory(
   160     session_factory = wamp.ApplicationSessionFactory(
   163         config=component_config)
   161         config=component_config)
   164     session_factory.session = WampSession
   162     session_factory.session = WampSession
   165 
   163 
   166     # create a WAMP-over-WebSocket transport client factory
   164     # create a WAMP-over-WebSocket transport client factory