-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPQ9Client.py
More file actions
71 lines (58 loc) · 2.09 KB
/
Copy pathPQ9Client.py
File metadata and controls
71 lines (58 loc) · 2.09 KB
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
import asyncio
import json
class PQ9Client:
def __init__(self, serverIP, serverPort, timeout):
super().__init__()
self.TIMEOUT = timeout
self.TCP_IP = serverIP
self.TCP_PORT = serverPort
self.pq9reader = 0
self.pq9writer = 0
self.loop = 0
self.closed = True
def close(self):
try:
self.closed = True
self.loop.run_until_complete(self.AwaitedClose())
except RuntimeError:
pass # ignore exception
except RuntimeWarning:
pass # ignore warning
async def AwaitedClose(self):
self.pq9writer.close()
await self.pq9writer.wait_closed()
def connect(self):
self.loop = asyncio.new_event_loop()
self.loop.run_until_complete(self.AwaitedConnect())
async def AwaitedConnect(self):
self.pq9reader, self.pq9writer = await asyncio.open_connection(self.TCP_IP, self.TCP_PORT)
self.closed = False
def sendFrame(self, inputFrame):
cmdString = json.dumps(inputFrame) + '\n'
self.pq9writer.write(cmdString.encode())
def getFrame(self):
if self.closed:
raise PQ9ClientConnectionClosed('Connection closed')
status, msg = self.loop.run_until_complete(self.AwaitedGetFrame())
if(status == True):
return status, json.loads(msg)
else:
return status, []
async def AwaitedGetFrame(self):
try:
rxMsg = await asyncio.wait_for(self.pq9reader.readline(), timeout=self.TIMEOUT)
return True, rxMsg
except asyncio.TimeoutError:
return False, []
def processCommand(self, command):
self.sendFrame(command)
succes, msg = self.getFrame()
return succes, msg
class PQ9ClientConnectionClosed(Exception):
"""Exception raised by PQ9Client.
Attributes:
message -- explanation of the error
"""
def __init__(self, message=""):
self.message = message
super().__init__(self.message)