Integrated example - Thread
This example explains how to use the thread.
Example 1: Thread example
#----- thread 1: client comm. ---------------------
def fn_th_client():
global g_sock
global g_cmd
res, rx_data = client_socket_read(g_sock)
if res > 0:
g_cmd = rx_data.decode() #decode: Converts byte type into a string.
else: # Communication error
client_socket_close(g_sock)
exit() # Terminates the program.
wait(0.1)
return 0
#----- thread 2: check IO -------------------------
def fn_th_check_io():
if get_digital_input(1) == ON:
exit() # Terminates the program.
wait(0.1)
return 0
#----- main ---------------------------------------
g_sock = client_socket_open("192.168.137.2", 20002) # Connects to the server.
g_cmd = ""
g_th_id1 = thread_run(th_client, loop=True) # Runs the th_client thread.
g_th_id2 = thread_run(th_check_io, loop=True) # Runs the th_check_io thread.
p1 = posj(0, 0, 90, 0, 90, 0)
p2 = posj(10, 0, 90, 0, 90, 0)
p3 = posj(20, 0, 90, 0, 90, 0)
while 1:
if g_cmd == "a":
g_cmd = ""
movej(p1,vel=100,acc=100)
client_socket_write(g_sock, b"end")
if g_cmd == "b":
g_cmd = ""
movej(p2,vel=100,acc=100)
client_socket_write(g_sock, b"end")
if g_cmd == "c":
g_cmd = ""
movej(p3,vel=100,acc=100)
client_socket_write(g_sock, b"end")
wait(0.1)
th_client thread: Converts the data received from the server into a string and saves it in g_cmd.
th_check_io thread: Checks the state of contact no. 1 and terminates the program if it is ON.
main: Connects to the server.
2 threads run: th_client and th_check_io
If "a" is received from the server, it moves to p1 and sends "end" to the servers.
If "b" is received from the server, it moves to p2 and sends "end" to the servers.
If "c" is received from the server, it moves to p3 and sends "end" to the servers.