forked from mi8882255/3dprinteros-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_client.py
263 lines (232 loc) · 10.8 KB
/
http_client.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
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#Copyright (c) 2015 3D Control Systems LTD
#3DPrinterOS client is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#3DPrinterOS client is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU Affero General Public License for more details.
#You should have received a copy of the GNU Affero General Public License
#along with 3DPrinterOS client. If not, see <http://www.gnu.org/licenses/>.
# Author: Oleg Panasevych <panasevychol@gmail.com>, Vladimir Avdeev <another.vic@yandex.ru>
import re
import sys
import time
import json
import uuid
import httplib
import logging
from subprocess import Popen, PIPE
import config
import version
import platforms
from checker_waiter import CheckerWaiter
# machine id is mac address, but on RPi we use machine serial
def get_serial_number():
if sys.platform.startswith('linux'):
call = Popen(['cat', '/proc/cpuinfo'], stdout=PIPE, stderr=PIPE)
stdout, stderr = call.communicate()
stdout = stdout.replace('\t', '').split('\n')
for item in stdout:
if 'Serial: ' in item:
return item.replace('Serial: ', '')
class HTTPClient:
URL = config.get_settings()['URL']
HTTPS_MODE = config.get_settings()['HTTPS']
BASE_TIMEOUT = 6
MAX_FAILS = 2
MAX_TIMEOUT = BASE_TIMEOUT * 3
streamer_prefix = "/streamerapi"
user_login_path = streamer_prefix + "/user_login"
printer_login_path = streamer_prefix + "/printer_login"
command_path = streamer_prefix + "/command"
token_send_logs_path = streamer_prefix + "/sendLogs"
camera_path = streamer_prefix + "/camera" #json['image': base64_image ]
cloudsync_path = "/autoupload"
domain_path_re = re.compile("https?:\/\/(.+)(\/.*)")
def __init__(self, parent, keep_connection_flag = False, debug = False):
self.logger = logging.getLogger(__name__)
self.parent = parent
self.parent_usb_info = getattr(parent, 'usb_info', None)
if debug:
self.logger.setLevel('DEBUG')
else:
self.logger.setLevel('INFO')
self.keep_connection_flag = keep_connection_flag
self.timeout = self.BASE_TIMEOUT
self.connection = self.connect()
self.fails = 0
def get_mac_add_or_serial_number(self):
id = get_serial_number()
if not id:
id = self.get_mac_for_current_ip()
if not id:
time.sleep(1)
id = self.get_mac_for_current_ip()
if not id:
self.logger.error("Can't get mac address! Using uuid.getnode().")
id = hex(uuid.getnode())
return id
def format_mac_addr(self, mac):
mac = mac.replace(":", "")
mac = mac.replace("-", "")
mac = mac.lower()
return "0x" + mac + "L"
def get_mac_for_current_ip(self):
if platforms.PLATFORM in ("rpi", 'linux', "mac"):
process = Popen(['ifconfig'], stdout=PIPE)
stdout, _ = process.communicate()
interfaces = stdout.split("flags=") #will get name of interface wrong, but we don't need name
for interface in interfaces:
if "inet " + self.local_ip in interface:
search = re.search("ether\s([0-9a-f\:]+)", interface)
if search:
return self.format_mac_addr(search.group(1))
else:
process = Popen(['ipconfig' , "/all"], stdout=PIPE)
stdout, _ = process.communicate()
interfaces = stdout.split("\r\n\r\n")
for interface in interfaces:
search = re.search("IP.*:\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", interface)
if search:
ip = search.group(1)
if ip == self.local_ip:
search = re.search("[A-F0-9]{2}\-[A-F0-9]{2}\-[A-F0-9]{2}\-[A-F0-9]{2}\-[A-F0-9]{2}\-[A-F0-9]{2}", interface)
if search:
return self.format_mac_addr(search.group(0))
def connect(self):
self.logger.debug("{ Connecting...")
fails = 0
while not self.parent.stop_flag:
try:
if self.HTTPS_MODE:
connection = httplib.HTTPSConnection(self.URL, port = 443, timeout = self.timeout)
else:
connection = httplib.HTTPConnection(self.URL, port = 80, timeout = self.timeout)
connection.connect()
self.local_ip = connection.sock.getsockname()[0]
self.mac = self.get_mac_add_or_serial_number()
except Exception as e:
config.create_error_report(5, "Error during HTTP connection: " + str(e),
self.parent_usb_info, self.logger, is_blocking=False)
self.logger.debug("...failed }")
self.logger.warning("Warning: connection to %s failed." % self.URL)
if self.timeout < self.MAX_TIMEOUT:
self.timeout += self.BASE_TIMEOUT
time.sleep(1)
fails += 1
if fails > self.MAX_FAILS:
return
else:
self.logger.debug("...success }")
self.logger.info("Connecting from: %s\t%s" % (self.local_ip, self.mac))
return connection
def load_json(self, jdata):
try:
data = json.loads(jdata)
except ValueError:
config.create_error_report(2, "Received data is not valid json: "
+ jdata, self.parent_usb_info, self.logger, is_blocking=False)
else:
if data and type(data) == dict:
return data
else:
config.create_error_report(3, "Error parsing http message, data should be not empty dictionary: " +
str(data), self.parent_usb_info, self.logger, is_blocking=False)
def request(self, method, connection, path, payload, headers=None):
self.logger.debug("{ Requesting...")
if headers is None:
headers = {"Content-Type": "application/json", "Content-Length": str(len(payload))}
if self.keep_connection_flag:
headers["Connection"] = "keep-alive"
try:
connection.request(method, path, payload, headers)
resp = connection.getresponse()
except Exception as e:
config.create_error_report(6, "Error during HTTP request:" + str(e),
self.parent_usb_info, self.logger, is_blocking=False)
else:
#self.logger.debug("Request status: %s %s" % (resp.status, resp.reason))
try:
received = resp.read()
except Exception as e:
config.create_error_report(7, "Error reading response: " + str(e),
self.parent_usb_info, self.logger, is_blocking=False)
else:
if resp.status == httplib.OK and resp.reason == "OK":
self.logger.debug("...success }")
return received
else:
config.create_error_report(8, "Error: server responded with non 200 OK\nFull response: %s" %
received, self.parent_usb_info, self.logger, is_blocking=False)
self.logger.debug("...failed }")
self.logger.warning("Warning: HTTP request failed!")
def pack_and_send(self, target, *payloads, **kwargs_payloads):
path, packed_message = self.pack(target, *payloads, **kwargs_payloads)
return self.send(path, packed_message)
def send(self, path, data):
fails = 0
while not self.parent.stop_flag:
if not self.connection:
self.connection = self.connect()
if self.connection:
answer = self.request("POST", self.connection, path, data)
if not self.keep_connection_flag:
self.connection.close()
self.connection = None
if answer:
self.fails = 0
return self.load_json(answer)
elif self.connection:
self.connection.close()
self.connection = None
time.sleep(1)
fails += 1
if fails > self.MAX_FAILS:
return
def pack(self, target, *args, **kwargs):
if target == 'user_login':
data = { 'login': {'user': args[0], 'password': args[1]},
'platform': platforms.PLATFORM, 'host_mac': self.mac,
'local_ip' : self.local_ip, 'version': version.version}
if 'disposable_token' in kwargs:
data['login']['disposable_token'] = kwargs['disposable_token']
path = self.user_login_path
#self.logger.debug(data)
elif target == 'printer_login':
data = { 'user_token': args[0], 'printer': args[1], "version": version.version,
"data_time": time.ctime(), "camera": config.get_app().camera_controller.get_current_camera_name() }
path = self.printer_login_path
elif target == 'command':
data = { 'printer_token': args[0], 'report': args[1], 'command_ack': args[2] }
if not data['command_ack']:
data.pop('command_ack')
path = self.command_path
elif target == 'camera':
data = { 'user_token': args[0], 'camera_number': args[1], 'camera_name': args[2],
'file_data': args[3], 'host_mac': self.mac}
path = self.camera_path
elif target == 'cloudsync':
data = { 'user_token': args[0], 'file_data': args[1]}
path = self.cloudsync_path
else:
config.create_error_report(4, 'No such target for packaging: ' + target, None,
self.logger, is_blocking=False)
data, path = None, None
for key, value in kwargs.items():
data[key] = value
return path, json.dumps(data)
def close(self):
if self.connection:
self.connection.close()
class NetworkConnectionChecker(CheckerWaiter):
NAME_FOR_LOGGING = 'network connection check'
def __init__(self, app):
self.app = app
CheckerWaiter.__init__(self, app, self.check_connection)
def check_connection(self):
http_client = HTTPClient(self.app)
return bool(http_client.connection)
if __name__ == '__main__':
http_client = HTTPClient()