runtime/WampClient.py
branchnevow_service_rework
changeset 2212 cf1718962567
parent 2207 c27b820cb96b
child 2215 f808ec7dc10e
equal deleted inserted replaced
2211:46447d99e5f9 2212:cf1718962567
    33 from autobahn.wamp import types, auth
    33 from autobahn.wamp import types, auth
    34 from autobahn.wamp.serializer import MsgPackSerializer
    34 from autobahn.wamp.serializer import MsgPackSerializer
    35 from twisted.internet.defer import inlineCallbacks
    35 from twisted.internet.defer import inlineCallbacks
    36 from twisted.internet.protocol import ReconnectingClientFactory
    36 from twisted.internet.protocol import ReconnectingClientFactory
    37 
    37 
       
    38 
       
    39 mandatoryConfigItems = ["ID", "active", "realm", "url"]
    38 
    40 
    39 _transportFactory = None
    41 _transportFactory = None
    40 _WampSession = None
    42 _WampSession = None
    41 _PySrv = None
    43 _PySrv = None
    42 _WampConf = None
    44 _WampConf = None
    72     obj = _PySrv.plcobj
    74     obj = _PySrv.plcobj
    73     while names:
    75     while names:
    74         obj = getattr(obj, names.pop(0))
    76         obj = getattr(obj, names.pop(0))
    75     return obj
    77     return obj
    76 
    78 
    77 def getValidOptins(options, arguments):
       
    78     validOptions = {}
       
    79     for key in options:
       
    80         if key in arguments:
       
    81             validOptions[key] = options[key]
       
    82     if len(validOptions) > 0:
       
    83         return validOptions
       
    84     else:
       
    85         return None
       
    86 
    79 
    87 class WampSession(wamp.ApplicationSession):
    80 class WampSession(wamp.ApplicationSession):
    88     def onConnect(self):
    81     def onConnect(self):
    89         if "secret" in self.config.extra:
    82         if "secret" in self.config.extra:
    90             user = self.config.extra["ID"]
    83             user = self.config.extra["ID"]
   162             super(ReconnectingWampWebSocketClientFactory, self).clientConnectionFailed(connector, reason)
   155             super(ReconnectingWampWebSocketClientFactory, self).clientConnectionFailed(connector, reason)
   163         else:
   156         else:
   164             del connector
   157             del connector
   165 
   158 
   166 
   159 
   167 def GetConfiguration(items=None):
   160 def GetConfiguration():
       
   161     WSClientConf = json.load(open(_WampConf))
       
   162     for itemName in mandatoryConfigItems:
       
   163         if WSClientConf.get(itemName, None) is None :
       
   164             raise Exception(_("WAMP configuration error : missing '{}' parameter.").format(itemName))
       
   165 
       
   166     return WSClientConf
       
   167 
       
   168 
       
   169 def SetConfiguration(WSClientConf):
   168     try:
   170     try:
   169         WSClientConf = json.load(open(_WampConf))
   171         with open(os.path.realpath(_WampConf), 'w') as f:
   170         if items and isinstance(items, list):
   172             json.dump(WSClientConf, f, sort_keys=True, indent=4)
   171             WSClientConfItems = {}
   173         if 'active' in WSClientConf and WSClientConf['active']:
   172             for item in items:
   174             if _transportFactory and _WampSession:
   173                 wampconf_value = WSClientConf.get(item, None)
       
   174                 if wampconf_value is not None:
       
   175                     WSClientConfItems[item] = wampconf_value
       
   176             if WSClientConfItems:
       
   177                 return WSClientConfItems
       
   178         return WSClientConf
       
   179     except ValueError, ve:
       
   180         print(_("WAMP load error: "), ve)
       
   181         return None
       
   182     except Exception, e:
       
   183         print(_("WAMP load error: "), e)
       
   184         return None
       
   185 
       
   186 def SetConfiguration(items):
       
   187     try:
       
   188         WSClientConf = json.load(open(_WampConf))
       
   189         saveChanges = False
       
   190         if items:
       
   191             for itemKey in items.keys():
       
   192                 wampconf_value = WSClientConf.get(itemKey, None)
       
   193                 if (wampconf_value is not None) and (items[itemKey] is not None) and (wampconf_value != items[itemKey]):
       
   194                     WSClientConf[itemKey] = items[itemKey]
       
   195                     saveChanges = True
       
   196 
       
   197         if saveChanges:
       
   198             with open(os.path.realpath(_WampConf), 'w') as f:
       
   199                 json.dump(WSClientConf, f, sort_keys=True, indent=4)
       
   200             if 'active' in WSClientConf and WSClientConf['active']:
       
   201                 if _transportFactory and _WampSession:
       
   202                     StopReconnectWampClient()
       
   203                 StartReconnectWampClient()
       
   204             else:
       
   205                 StopReconnectWampClient()
   175                 StopReconnectWampClient()
       
   176             StartReconnectWampClient()
       
   177         else:
       
   178             StopReconnectWampClient()
   206 
   179 
   207         return WSClientConf
   180         return WSClientConf
   208     except ValueError, ve:
   181     except ValueError, ve:
   209         print(_("WAMP save error: "), ve)
   182         print(_("WAMP save error: "), ve)
   210         return None
   183         return None
   211     except Exception, e:
   184     except Exception, e:
   212         print(_("WAMP save error: "), e)
   185         print(_("WAMP save error: "), e)
   213         return None
   186         return None
       
   187 
   214 
   188 
   215 def LoadWampSecret(secretfname):
   189 def LoadWampSecret(secretfname):
   216     try:
   190     try:
   217         WSClientWampSecret = open(secretfname, 'rb').read()
   191         WSClientWampSecret = open(secretfname, 'rb').read()
   218         return WSClientWampSecret
   192         return WSClientWampSecret
   228         return True
   202         return True
   229     else:
   203     else:
   230         return False
   204         return False
   231 
   205 
   232 
   206 
   233 def RegisterWampClient(wampconf=None, secretfname=None):
   207 def RegisterWampClient(wampconf=None, wampsecret=None):
   234     global _WampConf
   208     global _WampConf, _WampSecret
       
   209     if wampsecret:
       
   210         _WampSecret = wampsecret
   235     if wampconf:
   211     if wampconf:
   236         _WampConf = wampconf
   212         _WampConf = wampconf
   237         WSClientConf = GetConfiguration()
   213 
   238     else:
   214     WSClientConf = GetConfiguration()
   239         WSClientConf = GetConfiguration()
       
   240 
       
   241     if not WSClientConf:
       
   242         print(_("WAMP client connection not established!"))
       
   243         return False
       
   244 
   215 
   245     if not IsCorrectUri(WSClientConf["url"]):
   216     if not IsCorrectUri(WSClientConf["url"]):
   246         print(_("WAMP url {} is not correct!".format(WSClientConf["url"])))
   217         raise Exception(_("WAMP url {} is not correct!").format(WSClientConf["url"]))
   247         return False
   218 
   248 
   219     if not WSClientConf["active"]:
   249     if secretfname:
   220         print(_("WAMP deactivated in configuration"))
   250         WampSecret = LoadWampSecret(secretfname)
   221         return
   251     else:
   222 
   252         WampSecret = LoadWampSecret(_WampSecret)
   223     WampSecret = LoadWampSecret(_WampSecret)
   253 
   224 
   254     if WampSecret is not None:
   225     if WampSecret is not None:
   255         WSClientConf["secret"] = WampSecret
   226         WSClientConf["secret"] = WampSecret
   256 
   227 
   257     # create a WAMP application session factory
   228     # create a WAMP application session factory
   301 
   272 
   302 def StatusWampClient():
   273 def StatusWampClient():
   303     return _WampSession and _WampSession.is_attached()
   274     return _WampSession and _WampSession.is_attached()
   304 
   275 
   305 
   276 
   306 def SetServer(pysrv, wampconf=None, wampsecret=None):
   277 def SetServer(pysrv):
   307     global _PySrv, _WampConf, _WampSecret
       
   308     _PySrv = pysrv
   278     _PySrv = pysrv
   309     _WampConf = wampconf
       
   310     _WampSecret = wampsecret