# Project name: SmartehIDE
# __init__.py.py: spacer widget module initialization
# 19. 01. 2017 12:24 Uporabnik
# Copyright (c) 2017 Smarteh d.o.o. <info@smarteh.si>
# THIS PROGRAM COMES WITH NO WARRANTY
from autobahn.twisted import wamp
from autobahn.twisted.websocket import WampWebSocketClientFactory, connectWS
from autobahn.wamp import types
from autobahn.wamp import auth
from autobahn.wamp.serializer import MsgPackSerializer
from twisted.internet import reactor, threads
from autobahn.wamp.exception import TransportLost
from threading import Thread, Event
# import connectors.WAMP as WAMP
# from connectors.WAMP import WAMP_connector_factory, WampSession
# from threading import _sleep
PLCObjDefaults = { "StartPLC": False,
"GetTraceVariables" : ("Broken",None),
"GetPLCstatus" : ("Broken",None),
"RemoteExec" : (-1, "RemoteExec script failed!")}
_WampSessionEvent = Event()
class MWWampSession(wamp.ApplicationSession):
self.join(u"Automation", [u"wampcra"], USER)
print "CRA checking init ..."
def onJoin(self, details):
global _WampSession, _WampSessionEvent
print 'WAMP session joined for :', self.config.extra["ID"]
def onChallenge(self, challenge):
if challenge.method == u"wampcra":
key = PASSWORDS[USER].encode('utf8')
key = auth.derive_key(key, "salt123", 100, 16)
signature = auth.compute_wcs(key, challenge.extra['challenge'].encode('utf8'))
return signature.decode('ascii')
raise Exception("don't know how to handle authmethod {}".format(challenge.method))
def onLeave(self, details):
global _WampSession, _WampSessionEvent
_WampSessionEvent.clear()
print 'WAMP session left'
# DefalutWAMP_connector_factory = WAMP_connector_factory
def MWRegisterWampClient(realm, ID, url, confnodesroot):
# create a WAMP application session factory
component_config = types.ComponentConfig(
session_factory = wamp.ApplicationSessionFactory(
config = component_config)
session_factory.session = MWWampSession
# create a WAMP-over-WebSocket transport client factory
transport_factory = WampWebSocketClientFactory(
serializers = [MsgPackSerializer()])
# settings autoPing in seconds
#transport_factory.autoPingInterval = 60
#transport_factory.autoPingTimeout = 20
# start the client from a Twisted endpoint
conn = connectWS(transport_factory)
confnodesroot.logger.write(_("WAMP connecting to URL : %s\n")%url)
def MWWAMP_connector_factory(uri, confnodesroot):
# def CustomFunctionCall(self, funcname, args=None):
# member = self.__dict__.get(funcname, None)
# member = WampSessionProcMapper(funcname)
# self.__dict__[funcname] = member
# WAMP.RegisterWampClient = MWRegisterWampClient
# WAMP.WampSession = MWWampSession
# wamp_connector = DefalutWAMP_connector_factory(uri, confnodesroot)
# wamp_connector.CustomFunctionCall = CustomFunctionCall
servicetype, location = uri.split("://")
urlpath, realm, ID = location.split('#')
urlprefix = {"WAMP": "ws",
"WAMPS": "wss"}[servicetype]
url = urlprefix + "://" + urlpath
AddToDoBeforeQuit = confnodesroot.AppFrame.AddToDoBeforeQuit
_WampConnection = MWRegisterWampClient(realm, ID, url, confnodesroot)
AddToDoBeforeQuit(reactor.stop)
reactor.run(installSignalHandlers=False)
def WampSessionProcMapper(funcname):
wampfuncname = unicode('.'.join((ID, funcname)))
def catcher_func(*args, **kwargs):
if _WampSession is not None:
return threads.blockingCallFromThread(
reactor, _WampSession.call, wampfuncname,
confnodesroot.logger.write_error(_("Connection lost!\n"))
confnodesroot._SetConnector(None)
errmess = traceback.format_exc()
confnodesroot.logger.write_error(errmess + "\n")
# confnodesroot._SetConnector(None)
return PLCObjDefaults.get(funcname)
class WampPLCObjectProxy(object):
global _WampSessionEvent, _WampConnection
Thread(target=ThreadProc).start()
_WampConnection = threads.blockingCallFromThread(
reactor, MWRegisterWampClient, realm, ID, url, confnodesroot)
if not _WampSessionEvent.wait(5):
_WampConnection = stopConnecting()
raise Exception, _("WAMP connection timeout")
_WampConnection.disconnect()
def __getattr__(self, attrName):
member = self.__dict__.get(attrName, None)
member = WampSessionProcMapper(attrName)
self.__dict__[attrName] = member
# Try to get the proxy object
return WampPLCObjectProxy()
confnodesroot.logger.write_error(_("WAMP connection to '%s' failed.\n") % location)
confnodesroot.logger.write_error(traceback.format_exc())
connectors.connectors["WAMP"] = lambda: MWWAMP_connector_factory