-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
53 lines (44 loc) · 1.62 KB
/
utils.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
import socket
import struct
import requests
class SocketConnector():
protocol = ''
def __init__(self, ip, input_port, output_port, in_protocol='', out_protocol='', buffer_size=1024) -> None:
self.input_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.input_socket.bind(('', input_port))
self.input_socket.settimeout(0.002)
self.output_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.output_socket.connect((ip,output_port))
self.in_protocol = in_protocol
self.out_protocol = out_protocol
def send_text(self, data) -> None:
new_data = bytes(str(data), 'utf-8')
self.output_socket.send(new_data)
def recieve_str(self):
try:
data,_ = self.input_socket.recvfrom(1024)
return str(data, encoding='utf-8')
except TimeoutError:
return ''
def send(self, data) -> None:
new_data = struct.pack(self.out_protocol, *data)
self.output_socket.send(new_data)
def recieve(self):
try:
data,_ = self.input_socket.recvfrom(1024)
return struct.unpack(self.in_protocol, data)
except TimeoutError:
return None
class JsonConnctor():
url = ''
'''
Example:
JsonConnctor.send([{'name': '/controls/gear/gear-down', 'value': 0}])
'''
def __init__(self,ip,port):
self.url = f'http://{ip}:{port}/json/'
def send(self, props:dict):
try:
requests.post(self.url, json={"children":props}, timeout=0.5)
except requests.exceptions.ConnectTimeout:
pass