|
1 #!/usr/bin/env python |
|
2 # -*- coding: utf-8 -*- |
|
3 |
|
4 # This file is part of Beremiz |
|
5 # Copyright (C) 2019: Edouard TISSERANT |
|
6 # See COPYING file for copyrights details. |
|
7 |
|
8 from __future__ import absolute_import |
|
9 |
|
10 from twisted.web.server import Site |
|
11 from twisted.web.resource import Resource |
|
12 from twisted.internet import reactor |
|
13 from twisted.web.static import File |
|
14 |
|
15 from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol |
|
16 from autobahn.twisted.resource import WebSocketResource |
|
17 |
|
18 # TODO session list lock |
|
19 svghmi_sessions = [] |
|
20 |
|
21 class HMISession(object): |
|
22 def __init__(self, protocol_instance): |
|
23 global svghmi_sessions |
|
24 svghmi_sessions.append(self) |
|
25 |
|
26 # TODO multiclient : |
|
27 # get a unique bit index amont other svghmi_sessions, |
|
28 # so that we can match flags passed by C->python callback |
|
29 |
|
30 def __del__(self): |
|
31 global svghmi_sessions |
|
32 svghmi_sessions.remove(self) |
|
33 |
|
34 def onMessage(): |
|
35 # TODO : pass it to the C side recieve_message() |
|
36 # update HMITree |
|
37 # - values |
|
38 # - refresh rates / subsriptions |
|
39 |
|
40 # TODO multiclient : pass client index as well |
|
41 pass |
|
42 |
|
43 |
|
44 class HMIProtocol(WebSocketServerProtocol): |
|
45 |
|
46 def __init__(self, *args, **kwargs): |
|
47 self._hmi_session = None |
|
48 WebSocketServerProtocol.__init__(self, *args, **kwargs) |
|
49 |
|
50 def onOpen(self): |
|
51 self._hmi_session = HMISession(self) |
|
52 print "open" |
|
53 |
|
54 def onClose(self, wasClean, code, reason): |
|
55 del self._hmi_session |
|
56 self._hmi_session = None |
|
57 print "close" |
|
58 |
|
59 def onMessage(self, msg, isBinary): |
|
60 self._hmi_session.onMessage(msg) |
|
61 print msg |
|
62 #self.sendMessage(msg, binary) |
|
63 |
|
64 svghmi_root = None |
|
65 svghmi_listener = None |
|
66 |
|
67 # Called by PLCObject at start |
|
68 def _runtime_svghmi0_start(): |
|
69 global svghmi_listener, svghmi_root |
|
70 |
|
71 svghmi_root = Resource() |
|
72 |
|
73 wsfactory = WebSocketServerFactory() |
|
74 wsfactory.protocol = HMIProtocol |
|
75 |
|
76 # svghmi_root.putChild("",File(".svg")) |
|
77 svghmi_root.putChild("ws",WebSocketResource(wsfactory)) |
|
78 |
|
79 sitefactory = Site(svghmi_root) |
|
80 |
|
81 svghmi_listener = reactor.listenTCP(8008, sitefactory) |
|
82 |
|
83 # TODO |
|
84 # start a thread that call the C part of SVGHMI |
|
85 |
|
86 |
|
87 # Called by PLCObject at stop |
|
88 def _runtime_svghmi0_stop(): |
|
89 global svghmi_listener |
|
90 svghmi_listener.stopListening |