-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTCPClient.py
83 lines (65 loc) · 1.94 KB
/
TCPClient.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
# (c) 2020-2021, ETH Zurich, Power Electronic Systems Laboratory, T. Guillod
import socket
class TCPClient():
"""
Class for communicating with the FuG power source over TCP/IP.
"""
def __init__(self, data):
"""
Constructor of the TCPClient class.
"""
self.data = data
self.link = None
self.data_buffer = ''
def open(self):
"""
Connect to the power source and set the timeout of the connection.
"""
self.link = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.link.connect((self.data["ip"], self.data["port"]))
self.link.settimeout(self.data["timeout"])
def close(self):
"""
Close the connection.
"""
self.data_buffer = ''
self.link.close()
self.link = None
def start_command(self):
"""
Clear the buffer for starting a new command.
"""
self._receive_bytes()
self.data_buffer = ''
def send_byte(self, msg):
"""
Send a byte to the power source.
"""
try:
self.link.send(msg.encode())
except Exception:
raise ValueError("send fail")
def receive(self):
"""
Get responses from the power source where the newline is the delimiter.
"""
response = []
buffer_new = self._receive_bytes()
for char in buffer_new:
if char == '\n':
response.append(self.data_buffer)
self.data_buffer = ''
else:
self.data_buffer += char
return response
def _receive_bytes(self):
"""
Get bytes from the power sources.
"""
try:
try:
return self.link.recv(self.data["buffer"]).decode()
except socket.timeout:
return ''
except Exception:
raise ValueError("receive fail")