# This file is part of Beremiz runtime.
# Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
# See COPYING.Runtime file for copyrights details.
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
from __future__ import absolute_import
from __future__ import print_function
from autobahn.twisted import wamp
from autobahn.twisted.websocket import WampWebSocketClientFactory, connectWS
from autobahn.wamp import types, auth
from autobahn.wamp.serializer import MsgPackSerializer
from twisted.internet.defer import inlineCallbacks
from twisted.internet.protocol import ReconnectingClientFactory
("SetTraceVariablesList", {}),
("GetTraceVariables", {}),
# Those two lists are meant to be filled by customized runtime
""" crossbar Events to register to """
""" things to do on join (callables) """
""" Get Callee or Subscriber corresponding to '.' spearated object path """
obj = getattr(obj, names.pop(0))
def getValidOptins(options, arguments):
validOptions[key] = options[key]
if len(validOptions) > 0:
class WampSession(wamp.ApplicationSession):
if "secret" in self.config.extra:
user = self.config.extra["ID"]
self.join(u"Automation", [u"wampcra"], user)
def onChallenge(self, challenge):
if challenge.method == u"wampcra":
secret = self.config.extra["secret"].encode('utf8')
signature = auth.compute_wcs(secret, challenge.extra['challenge'].encode('utf8'))
return signature.decode("ascii")
raise Exception("don't know how to handle authmethod {}".format(challenge.method))
def onJoin(self, details):
ID = self.config.extra["ID"]
for name, kwargs in ExposedCalls:
registerOptions = types.RegisterOptions(**kwargs)
print(_("TypeError register option: {}".format(e)))
yield self.register(GetCallee(name), u'.'.join((ID, name)), registerOptions)
for name in SubscribedEvents:
yield self.subscribe(GetCallee(name), unicode(name))
print(_('WAMP session joined (%s) by:' % time.ctime()), ID)
def onLeave(self, details):
global _WampSession, _transportFactory
super(WampSession, self).onLeave(details)
print(_('WAMP session left'))
class ReconnectingWampWebSocketClientFactory(WampWebSocketClientFactory, ReconnectingClientFactory):
def __init__(self, config, *args, **kwargs):
WampWebSocketClientFactory.__init__(self, *args, **kwargs)
protocolOptions = config.extra.get('protocolOptions', None)
self.setProtocolOptions(**protocolOptions)
print(_("Custom protocol options failed :"), e)
def buildProtocol(self, addr):
return ReconnectingClientFactory.buildProtocol(self, addr)
def clientConnectionFailed(self, connector, reason):
print(_("WAMP Client connection failed (%s) .. retrying .." % time.ctime()))
super(ReconnectingWampWebSocketClientFactory, self).clientConnectionFailed(connector, reason)
def clientConnectionLost(self, connector, reason):
print(_("WAMP Client connection lost (%s) .. retrying .." % time.ctime()))
super(ReconnectingWampWebSocketClientFactory, self).clientConnectionFailed(connector, reason)
def GetConfiguration(items=None):
WSClientConf = json.load(open(_WampConf))
if items and isinstance(items, list):
wampconf_value = WSClientConf.get(item, None)
if wampconf_value is not None:
WSClientConfItems[item] = wampconf_value
print(_("WAMP load error: "), ve)
print(_("WAMP load error: "), e)
def SetConfiguration(items):
WSClientConf = json.load(open(_WampConf))
for itemKey in items.keys():
wampconf_value = WSClientConf.get(itemKey, None)
if (wampconf_value is not None) and (items[itemKey] is not None) and (wampconf_value != items[itemKey]):
WSClientConf[itemKey] = items[itemKey]
with open(os.path.realpath(_WampConf), 'w') as f:
json.dump(WSClientConf, f, sort_keys=True, indent=4)
if 'active' in WSClientConf and WSClientConf['active']:
if _transportFactory and _WampSession:
StopReconnectWampClient()
StartReconnectWampClient()
StopReconnectWampClient()
print(_("WAMP save error: "), ve)
print(_("WAMP save error: "), e)
def LoadWampSecret(secretfname):
WSClientWampSecret = open(secretfname, 'rb').read()
return WSClientWampSecret
print(_("Wamp secret load error:"), ve)
if re.match(r'w{1}s{1,2}:{1}/{2}.+:{1}[0-9]+/{1}.+', uri):
def RegisterWampClient(wampconf=None, secretfname=None):
WSClientConf = GetConfiguration()
WSClientConf = GetConfiguration()
print(_("WAMP client connection not established!"))
if not IsCorrectUri(WSClientConf["url"]):
print(_("WAMP url {} is not correct!".format(WSClientConf["url"])))
WampSecret = LoadWampSecret(secretfname)
WampSecret = LoadWampSecret(_WampSecret)
if WampSecret is not None:
WSClientConf["secret"] = WampSecret
# create a WAMP application session factory
component_config = types.ComponentConfig(
realm=WSClientConf["realm"],
session_factory = wamp.ApplicationSessionFactory(
session_factory.session = WampSession
# create a WAMP-over-WebSocket transport client factory
ReconnectingWampWebSocketClientFactory(
serializers=[MsgPackSerializer()])
# start the client from a Twisted endpoint
conn = connectWS(_transportFactory)
print(_("WAMP client connecting to :"), WSClientConf["url"])
print(_("WAMP client can not connect to :"), WSClientConf["url"])
def StopReconnectWampClient():
_transportFactory.stopTrying()
return _WampSession.leave()
def StartReconnectWampClient():
_WampSession.disconnect()
return _WampSession and _WampSession.is_attached()
def SetServer(pysrv, wampconf=None, wampsecret=None):
global _PySrv, _WampConf, _WampSecret