wu_xinjun
2022-03-04 e839f2e83fed7eaceb677242f5f9650a79fb8c43
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import sys              # NOQA: E402    
import os
from flask import Flask
from numpy import true_divide
import pika
import uuid
import queue
from werkzeug.wrappers import request
 
from zmq import device
 
 
batfile_dir = os.path.join(__file__, "..", "protos/compile.bat" )
batfile_path = os.path.abspath(batfile_dir)
os.system(batfile_path)
 
from protos import aerial_pb2 as pb
from engine import MessageThreads as ths
 
 
 
class MyServer(Flask):
    def __init__(self, MQhost, MQuser, MQpassword, WEBhost, WEBport, SAVEfolder):
        Flask.__init__(self, __name__)
        # rabbit MQ
        self.MQhost = MQhost
        self.MQuser = MQuser
        self.MQpassword = MQpassword
        self.parameters = None
        # Web server
        self.WEBhost = WEBhost
        self.WEBport = WEBport
        self.SAVEfolder = SAVEfolder
        self.route('/api', methods=['POST'])(self.api)
        self.route('/', methods=['GET'])(self.hello)
        self._def_routes()
        # threads
        self._device_state_reveiver_thread = None
        self._alarm_state_receiver_thread = None
        self._command_request_sender_thread = None
        self._command_response_receiver_thread = None
        # queue
        self.command_request_queue = queue.Queue()
 
    def _connect_to_MQ(self):
        credentials = pika.PlainCredentials(self.MQuser, self.MQpassword)
        self.parameters = pika.ConnectionParameters(
            credentials=credentials, host=self.MQhost)
        # 连接队列服务器
        self.connection = pika.BlockingConnection(self.parameters)
        print(f"connected to MQ server: {self.MQhost} with user {self.MQuser}")
 
    def _start_device_state_up_msg_receiver_thread(self):
        """start device state thread"""
        if self._device_state_reveiver_thread is None:
            self._device_state_reveiver_thread = \
                ths.device_state_receiverThread(self.parameters,"server")
            self._device_state_reveiver_thread.setDaemon(True)
            self._device_state_reveiver_thread.start()
 
    def _stop_device_state_up_msg_receiver_thread(self):
        """stop device state thread"""
        if self._device_state_reveiver_thread is not None:
            self._device_state_reveiver_thread.stop()
            self._device_state_reveiver_thread = None
 
    def _start_alarm_state_up_msg_receiver_thread(self):
        """start alarm state thread"""
        if self._alarm_state_receiver_thread is None:
            self._alarm_state_receiver_thread = \
                ths.alarm_state_receiverThread(self.parameters,"server")
            self._alarm_state_receiver_thread.setDaemon(True)
            self._alarm_state_receiver_thread.start()
 
    def _stop_alarm_state_up_msg_receiver_thread(self):
        """stop alarm state thread"""
        if self._alarm_state_receiver_thread is not None:
            self._alarm_state_receiver_thread.stop()
            self._alarm_state_receiver_thread = None
 
    def _start_command_response_receiver_thread(self):
        """start command response thread"""
        if self._command_response_receiver_thread is None:
            self._command_response_receiver_thread = \
                ths.command_response_receiverThread(self.parameters,"server")
            self._command_response_receiver_thread.setDaemon(True)
            self._command_response_receiver_thread.start()
 
    def _stop_command_response_receiver_thread(self):
        """stop command response thread"""
        if self._command_response_receiver_thread is not None:
            self._command_response_receiver_thread.stop()
            self._command_response_receiver_thread = None
 
    def _start_command_request_sender_thread(self):
        """start command request thread"""
        if self._command_request_sender_thread is None:
            self._command_request_sender_thread = \
                ths.command_request_senderThread(self.parameters,self.command_request_queue,"server")
            self._command_request_sender_thread.setDaemon(True)
            self._command_request_sender_thread.start()
 
    def _stop_command_request_sender_thread(self):
        """stop command request thread"""
        if self._command_request_sender_thread is not None:
            self._command_request_sender_thread.stop()
            self._command_request_sender_thread = None
 
    def _def_routes(self):
        self.routes = {
            pb.SysCommand.SYS_COMMAND: self._on_sys_command,
        }
    
    def _on_sys_command(self, req: pb.RequestCommand, resp: pb.ResponseCommand):
 
        self.command_request_queue.put(ths.Message(None,None,req.command,req.target))
        return
 
    def _default(self, req: pb.RequestCommand, resp: pb.ResponseCommand):
        print('onknown command')
 
    def api(self):
 
        req = pb.RequestCommand()
        req.ParseFromString(request.data)
 
        # a function: _on_sys_command, refer to self._on_sys_command
        dispatcher = self.routes.get(req.sys_command, self._default)
 
        resp = pb.ResponseCommand()
        dispatcher(req, resp) # call the function
 
        resp.checksum = 12345
        response = Flask.response_class(
            resp.SerializeToString(),
            mimetype='application/x-protobuf'
        )
        return response, 200
 
    def hello(self):
        return 'Hello, This is acquisition demo API!'
 
    def run_rabbitmq(self):
        self._connect_to_MQ()
        self._start_device_state_up_msg_receiver_thread()
        self._start_alarm_state_up_msg_receiver_thread()
        self._start_command_response_receiver_thread()
        self._start_command_request_sender_thread()
 
    def run_all(self):
        self.run_rabbitmq()
        self.run(debug=False, host=self.WEBhost, port=self.WEBport)
 
 
if __name__ == "__main__":
    def help():
        print("Usage: Server.py [MQhost] [MQuser] [MQpassword] [WEBhost] [WEBport] [SAVEfolder]")
        print("EXAMPLE: Server.py localhost chai password123 0.0.0.0 5000 ./Received_data/")
        exit(1)
 
    if len(sys.argv) != 7:
        help()
    try:
        MQhost = str(sys.argv[1])
        MQuser = str(sys.argv[2])
        MQpassword = str(sys.argv[3])
        WEBhost = str(sys.argv[4])
        WEBport = int(sys.argv[5])
        SAVEfolder = str(sys.argv[6])
 
    except Exception as e:
        print(e)
        help()
    server = MyServer(MQhost, MQuser, MQpassword, WEBhost, WEBport, SAVEfolder)
    server.run_all()