-
Notifications
You must be signed in to change notification settings - Fork 0
/
ethernet.py
57 lines (44 loc) · 1.32 KB
/
ethernet.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
#!/usr/bin/python3
import log
from singleton import singleton
from socket import socket, AF_INET, SOCK_STREAM
@singleton
class Ethernet:
def __init__(
self,
ip='192.168.1.12',
port=5025,
) -> None:
self.ip = ip
self.port = port
self.socket = socket(AF_INET, SOCK_STREAM)
self.socket.settimeout(1.5)
self.open_connection()
def __del__(self) -> None:
self.close_connection()
def open_connection(self) -> None:
try:
self.socket.connect((self.ip, self.port))
log.ok(f'socket {self.ip}:{self.port} is open')
except:
log.err(f'socket {self.ip}:{self.port} opening is fail')
exit(1)
def close_connection(self) -> None:
self.socket.close()
def read_response(self, size: int) -> bytes | None:
try:
response = self.socket.recv(size)
except TimeoutError:
response = b''
except:
log.err('the device was disconnected')
exit(1)
if response == b'':
return None
return response
def send_cmd(self, cmd: str) -> None:
try:
self.socket.send(bytes(f'{cmd}\n', 'utf-8'))
log.cmd(cmd)
except:
log.err('the device was disconnected')