# This file is part of Beremiz
# Copyright (C) 2019: Edouard TISSERANT
# See COPYING file for copyrights details.
from __future__ import absolute_import
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.web.static import File
from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol
from autobahn.websocket.protocol import WebSocketProtocol
from autobahn.twisted.resource import WebSocketResource
svghmi_send_collect_callback_t = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_uint32, ctypes.c_void_p)
svghmi_register_send_collect_callback = PLCBinary.svghmi_register_send_collect_callback
svghmi_register_send_collect_callback.restype = ctypes.c_int # error or 0
svghmi_register_send_collect_callback.argtypes = [svghmi_send_collect_callback_t]
svghmi_recv_dispatch = PLCBinary.svghmi_recv_dispatch
svghmi_recv_dispatch.restype = ctypes.c_int # error or 0
svghmi_recv_dispatch.argtypes = [
ctypes.c_char_p] # data ptr
# TODO multiclient : switch to arrays
class HMISession(object):
def __init__(self, protocol_instance):
# Creating a new HMISession closes pre-existing HMISession
if svghmi_session is not None:
self.protocol_instance = protocol_instance
# svghmi_sessions.append(self)
# get a unique bit index amont other svghmi_sessions,
# so that we can match flags passed by C->python callback
if svghmi_session == self:
self.protocol_instance.sendClose(WebSocketProtocol.CLOSE_STATUS_CODE_NORMAL)
def onMessage(self, msg):
# pass message to the C side recieve_message()
svghmi_recv_dispatch(len(msg), msg)
# TODO multiclient : pass client index as well
def sendMessage(self, msg):
self.protocol_instance.sendMessage(msg, True)
class HMIProtocol(WebSocketServerProtocol):
def __init__(self, *args, **kwargs):
WebSocketServerProtocol.__init__(self, *args, **kwargs)
assert(self._hmi_session is None)
self._hmi_session = HMISession(self)
def onClose(self, wasClean, code, reason):
def onMessage(self, msg, isBinary):
assert(self._hmi_session is not None)
self._hmi_session.onMessage(msg)
class HMIWebSocketServerFactory(WebSocketServerFactory):
def send_collect_callback(size, ptr):
# TODO multiclient : dispatch to sessions
if svghmi_session is not None:
return svghmi_session.sendMessage(ctypes.string_at(ptr,size))
# Called by PLCObject at start
def _runtime_svghmi0_start():
global svghmi_listener, svghmi_root
svghmi_root.putChild("ws", WebSocketResource(HMIWebSocketServerFactory()))
svghmi_listener = reactor.listenTCP(8008, Site(svghmi_root))
# # start a thread that call the C part of SVGHMI
svghmi_register_send_collect_callback(svghmi_send_collect_callback_t(send_collect_callback))
# Called by PLCObject at stop
def _runtime_svghmi0_stop():
global svghmi_listener, svghmi_root, svghmi_session
if svghmi_session is not None:
svghmi_root.delEntity("ws")
svghmi_listener.stopListening()
# plc cleanup calls svghmi_(locstring)_cleanup and unlocks send thread