-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket_ex.py
103 lines (80 loc) · 3.33 KB
/
socket_ex.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
from time import sleep
import socket
import re
from enum import Enum
class Status(Enum):
MOVING = 1
DONE = 2
ABORTED = 3
ERROR = 4
class SES_API:
def __init__(self):
self.HOST = "127.0.0.1" # Standard loopback interface address (localhost)
self.PORT = 5011 # Port to listen on (non-privileged ports are > 1023)
self.status = Status.DONE
self.conn = None
self.pos = {"R":3.14,"T":2.14,"P":86,"X":-2,"Y":8,"Z":-123}
self.move_reg = re.compile('(X|Y|Z|R|T|P)([+-]?([0-9]*[.])?[0-9]+)') #capturing X or Y or Z and float number
self.pos_reg = re.compile('(X|Y|Z|R|T|P)(\?)') #capturing X or Y or Z and float number
#P - polar T- tilt F - phi
def move(self,data):
self.status = Status.MOVING
print(data)
m = self.move_reg.findall(data)
print (m)
if m:
axis, pos = m[0][0] , m[0][1]
print(axis,pos)
self.pos[axis] = pos
#axis, pos = m[1][0] , m[1][1]
#print(axis,pos)
#self.pos[axis] = pos
# here we want to run a thread that keeps checking if position is arrived. Maybe not here but in the main
# but, then set this class to DONE.
#DO MOVE!
def send_pos(self,data):
#axis = self.pos_reg.search(data.decode("UTF-8")).group(0)
axis = data.replace("?","")
#print('sending pos')
#print("{}\n".format(self.pos[axis]))
self.conn.send("{}\n".format(self.pos[axis]).encode())
def stop(self):
print('stoping')
pass
def send_status(self):
#print('send status',self.status)
self.conn.send("{}\n".format(self.status.value).encode())
def handle_req(self,data):
if "STATUS" in data:
self.send_status()
else:
self.send_pos(data)
def handle_connection(self):#this is main loop.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((self.HOST, self.PORT))
s.listen()
while True:
print("listening")
self.conn, addr = s.accept()
with self.conn:
print("Connected by {}".format(addr))
while True:
data = self.conn.recv(512)
if data==b'':
continue
for data in data.decode("UTF-8").split('\n'):
if("?" in data):
self.handle_req(data) #Handle data request
elif "MOV" in data: #MOVX5.0 for example
self.move(data) #handle move request
elif "STOP" in data:
self.stop()
else:
print(data) # anything else pleas?
if data=="exit":
# closing connection, but awaiting another one...
break
sleep(0.1)
sleep(0.1)
api = SES_API()
api.handle_connection()