This example file shows how to create a TCP client which can send commands to a server that is connected to a Squidstat.
This example file shows how to create a TCP client which can send commands to a server that is connected to a Squidstat.You can build experiments and recieve data from the server without having to interact with the instrument directly.
1"""! @example tcpClient.py This example file shows how to create a TCP client which can send commands to a server that is connected to a Squidstat.
2
3You can build experiments and recieve data from the server without having to interact with the instrument directly.
4"""
5
6import os
7import socket
8import threading
9import time
10
11
12client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
13activeSockets = [client_socket]
14
15
16SERVER_HOST = "localhost"
17SERVER_PORT = 12345
18
19
20def send_command(command):
21
22 try:
23 client_socket.send(command.encode())
24 except:
25 print("Connection was closed by host")
26 os._exit(1)
27
28
29 response = client_socket.recv(1024).decode()
30 print("Server response:", response)
31
32
33def interupt_listener():
34 print("Press <CTRL>+c to stop the program at any time.")
35 try:
36 while True:
37 input()
38 except (EOFError, KeyboardInterrupt):
39 pass
40 for socket in activeSockets:
41 socket.close()
42 os._exit(1)
43
44
45try:
46 client_socket.connect((SERVER_HOST, SERVER_PORT))
47except Exception as ex:
48 print("Unable to establish connection to server:\n%s" % ex)
49 exit()
50
51print("Connected to the server.")
52
53
54duration = 0
55while duration == 0:
56 try:
57 duration = int(input("Enter a duration for Open Circuit Potential: "))
58 except ValueError:
59 duration = 0
60 if(duration < 1):
61 print("Invalid entry.")
62 duration = 0
63
64
65send_command(f'startExperiment {duration}')
66
67interupt_thread = threading.Thread(target=interupt_listener)
68interupt_thread.start()
69
70
71while True:
72 try:
73 data = client_socket.recv(1024).decode()
74 except (ConnectionAbortedError, BrokenPipeError):
75
76 print("Finishing connection")
77 break
78 except ConnectionResetError:
79 print("The server closed the connection suddenly.")
80 break
81
82 if not data:
83 break
84
85
86 print(data)
87
88 if("Experiment Completed: " in data):
89 break
90
91os._exit(1)