-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPQ9Client.py
More file actions
73 lines (62 loc) · 2.56 KB
/
PQ9Client.py
File metadata and controls
73 lines (62 loc) · 2.56 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
72
73
import asyncio
import json
class PQ9Client:
def __init__(self, serverIP, serverPort):
super().__init__()
self.TCP_IP = serverIP
self.TCP_PORT = serverPort
self.pq9reader = 0
self.pq9writer = 0
self.loop = 0
def close(self):
self.loop.run_until_complete(self.AwaitedClose())
async def AwaitedClose(self):
#self.pq9reader.close()
self.pq9writer.close()
await self.pq9writer.wait_closed()
def connect(self):
try:
self.loop = asyncio.new_event_loop()
self.loop.run_until_complete(self.AwaitedConnect())
except ConnectionRefusedError:
print('connection refused')
except TimeoutError:
print('timeout error')
async def AwaitedConnect(self):
self.pq9reader, self.pq9writer = await asyncio.open_connection(self.TCP_IP, self.TCP_PORT, loop=self.loop)
print("PQ9Socket: Connected to "+str(self.TCP_IP)+":"+str(self.TCP_PORT))
def sendFrame(self, inputFrame):
self.loop.run_until_complete(self.AwaitedSendFrame(inputFrame))
async def AwaitedSendFrame(self,inputFrame):
cmdString = json.dumps(inputFrame) + '\n'
#print("Sending: "+cmdString, end="")
self.pq9writer.write(cmdString.encode())
await self.pq9writer.drain()
def getFrame(self):
status, msg = self.loop.run_until_complete(self.AwaitedGetFrame())
if(status == True):
# return status, json.loads(msg)["_raw_"]
return status, json.loads(msg)
else:
return status, []
async def AwaitedGetFrame(self):
try:
rxMsg = await asyncio.wait_for(self.pq9reader.readline(), timeout=2)
return True, rxMsg
except asyncio.TimeoutError:
print("PQ9EGSE Reply Timeout!")
return False, []
def processCommand(self, command):
self.sendFrame(command)
succes, msg = self.getFrame()
if(succes == False):
print("PQ9EGSE Reply Timeout!")
return False, []
else:
while((json.loads((msg["_raw_"]))[2] == (command["dest"]).split()[0]) and #if the destination == source and service == service
(json.loads((msg["_raw_"]))[3] == (command["data"]).split()[0])):
succes, msg = self.getFrame()
if(succes == False):
print("PQ9EGSE Reply Timeout!")
return False, []
return succes, msg