/
conn.py
198 lines (157 loc) · 5.43 KB
/
conn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import json
import threading
import socket
import select
import subprocess
from os import path, devnull
from pigeon.logger import Logger
from pigeon.parser import JsonParser
QKCONNECT_EXE = "C:\\Users\\mribeiro\\qkthings_local\\build\\qt\\qkconnect\\release\\qkconnect.exe"
_DEVNULL = open(devnull, 'w')
class Conn(object):
_NextID = 0
StateInit = 0
StateRunning = 1
StateStopped = 2
def __init__(self, type, params=[]):
self.log = Logger()
self._id = Conn._NextID
self._type = type
self._params = params
self._state = Conn.StateInit
self._callbacks = {
"packet_received": None,
"state_changed": None,
"error": None
}
def set_callback(self, name, cb):
self._callbacks[name] = cb
def id(self):
return self._id
def state(self):
return self._state
def run(self):
return True
def stop(self):
return True
def send_packet(self, pkt):
pass
def _set_state(self, new_state):
self._state = new_state
if self._callbacks["state_changed"] is not None:
self._callbacks["state_changed"](self._state)
def _error(self, text):
self.log.error(text)
if self._callbacks["error"] is not None:
self._callbacks["error"](text)
class QkConnect(Conn):
_nextID = 0
_next_port = 1238
def __init__(self, port, type, params={}):
super(QkConnect, self).__init__(type, params)
self._hostname = "localhost"
self._port = port
self._json_parser = JsonParser()
self._json_parser.set_callback("parsed", self._handle_json)
self._client = None
self._thread_listener = None
self._alive = False
self._event = threading.Event()
self._process = None
self._process_thread = None
self._event.clear()
def __del__(self):
print "Deleting QkConnect %d" % self._id
def __repr__(self):
id_hex = hex(self._id)[2:0].zfill(4)
return "%s %s %s" % (id_hex, self._type, self._params)
def run(self):
self._event.clear()
qkconnect_exe = path.normpath(QKCONNECT_EXE)
cmd = [qkconnect_exe, self._hostname, "%d" % self._port, self._type, "--verbose"]
self.log.debug("%s CMD: %s" % (self.__class__.__name__, cmd))
self._process = subprocess.Popen(
cmd,
stdin=_DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=1
)
self._process_thread = threading.Thread(target=self._process_listener, args=[self._process.stdout])
self._process_thread.setDaemon(True)
self._process_thread.start()
if self._event.wait(3.0) is False:
self._error("Failed to create QkConnect")
return False
QkConnect._nextID += 1
self._connect()
self._set_state(Conn.StateRunning)
return True
def _connect(self):
self._client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._client.connect((self._hostname, self._port))
self._thread_listener = threading.Thread(target=self._listener)
self._thread_listener.setDaemon(True)
self._alive = True
self._thread_listener.start()
def stop(self):
self._alive = False
self._client.close()
self._thread_listener.join()
self._process.terminate()
self._set_state(Conn.StateStopped)
def _handle_json(self, json_str):
json_data = json.loads(json_str)
json_keys = json_data.keys()
#TODO add timestamps to packets
if "pkt" in json_keys:
json_data.update({
"conn": {
"id": self._id
}
})
if self._callbacks["packet_received"] is not None:
self._callbacks["packet_received"](json_data)
else:
self._error("Unknown JSON format: %s" % json_str)
def _process_listener(self, stdout):
while self._process.poll() is None:
for line in iter(stdout.readline, b""):
nline = line.rstrip("\r\n")
if "ready" in nline:
self.log.debug("QkConnect is READY")
self._event.set()
self.log.debug("STDOUT %s %s: %s" % (self, self._port, nline))
def _listener(self):
while self._alive:
input,output,err = select.select([self._client], [], [])
for rd in input:
if self._alive is True:
data = rd.recv(256)
self._json_parser.parse_data(data)
def send_packet(self, pkt):
pkt_json_str = json.dumps(pkt)
self._client.send(pkt_json_str)
class ConnFactory(object):
_next_qkconnect_port = 1238
def __init__(self):
self._conns = []
def create(self, type, params={}):
conn = QkConnect(ConnFactory._next_qkconnect_port, type, params)
if conn.run():
self._conns.append(conn)
ConnFactory._next_qkconnect_port += 2
return conn
else:
del conn
return None
def destroy(self, conn):
conn.stop()
self._conns.remove(conn)
def conns(self):
return self._conns
def find(self, conn_id):
for conn in self._conns:
if conn.id() == conn_id:
return conn
return None