server.py 2.64 KB
Newer Older
1
2
3
4
"""
Python class to run a driver as a server class
"""
import argparse
5
6
7
8
import socketserver
import re
import pickle
import socket
9
import traceback
10
11

parser = argparse.ArgumentParser(description='Server for an instrument driver')
12
parser.add_argument('id', metavar='SH1',
Christian Schneider's avatar
Christian Schneider committed
13
                    type=str,
14
                    help='Name of the class to run as driver server')
15
parser.add_argument('port', metavar=9001, type=int,
16
17
18
                    help='Port')


Christian Schneider's avatar
Christian Schneider committed
19
class Server(socketserver.StreamRequestHandler):
20
    """
Christian Schneider's avatar
Christian Schneider committed
21
    Request handler for instruments.
22
23
24
25
26
    """

    def handle(self):
        """Handle incoming function calls"""
        # Get command
27
        data = self.rfile.readline().strip().decode('utf-8')
28
        
29
30
        # get name and arguments by using regular expressions
        p = r'^(?P<function>[\w\d_\-]+)\((?P<args>[\w\s\?\-\,=.\[\]\'\"]*)\)$'
31
32
33
        m = re.match(p, data).groupdict()

        # If command is a valid command of the instrument, execute it
34
        if m['function'] in Instrument.__dir__():
35
36
            command = 'Instrument.' + data
            # Execute command
37
38
39
40
41
42
43
44
45
46
            try:
                resp = eval(command)
            except Exception as e:
                print('----------------------------------')
                print('Error happened:')
                print(traceback.format_exc())
                self.wfile.write(pickle.dumps({'Traceback': traceback.format_exc()}))
            else:
                # Send response back to client
                self.wfile.write(pickle.dumps(resp))
47

Christian Schneider's avatar
Christian Schneider committed
48

49
50
if __name__ == '__main__':
    host = socket.gethostname()
51
52
    args = parser.parse_args()
    port = args.port
53

54
55
56
    # Print information
    print("Starting up server...")
    print("To stop the server press Ctrl+C ")
57

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
    print(args.id)
    print(host)
    print(port)

    if args.id =='SM200C':
        from Instruments.Drivers.SignalHound.SM200C import SM200C
        ## The parameter for the SM200C is fixed by the configuration of the network
        Instrument = SM200C()
        print("Driver connected to Signalhound:")
        print(Instrument.identify())
    else:
        # Init driver
        from SIGNALHOUND import SignalHound
        Instrument = SignalHound(args.id)
        print("Driver connected to Signalhound:")
        print("SA124B, serial number:"+str(Instrument.GetSerialNumber()))
74
75

    # Listen to specified port
76
77
78
79
80
81
82
83
84
85
    try:
        with socketserver.TCPServer((host, port), Server) as server:
            server.serve_forever()
    except KeyboardInterrupt:
        if args.id =='SM200C':
            Instrument.close_driver()
        else:
            ## Might useful to cleanly close the SA124B ?
            pass
        print('Server closed!')