Beispiel #1
0
 def __init__(self):
     self.logger = log.create_logger('camera')
     self.stop_flag = False
     paths.init_path_to_libs()
     import numpy as np
     import cv2 as cv2
     self.np = np
     self.cv2 = cv2
     signal.signal(signal.SIGINT, self.intercept_signal)
     signal.signal(signal.SIGTERM, self.intercept_signal)
     if len(sys.argv) > 2:
         self.user_token = sys.argv[1]
         mac = sys.argv[2]
     else:
         ul = user_login.UserLogin(self)
         ul.wait()
         self.user_token = ul.user_token
         mac = None
     self.image_extension = config.get_settings()["camera"]["img_ext"]
     self.image_quality = config.get_settings()["camera"]["img_qual"]
     self.hardware_resize = config.get_settings(
     )["camera"]["hardware_resize"]
     self.min_loop_time = config.get_settings()["camera"]["min_loop_time"]
     self.search_cameras()
     self.http_client = http_client.HTTPClient(self,
                                               keep_connection_flag=True)
     if mac:
         self.http_client.mac = mac  #we need to use MAC from client to ensure that it's not changed on camera restart
     self.main_loop()
 def __init__(self, app):
     self.logger = logging.getLogger("app." + __name__)
     self.app = app
     self.login = None
     self.user_token = None
     self.http_client = http_client.HTTPClient()
     login, password = read_login()
     if login:
         error = self.login_as_user(login, password)
         if error:
             self.logger.info(str(error))
 def __init__(self, app):
     self.app = app
     self.login = None
     self.user_token = None
     self.http_client = http_client.HTTPClient()
     CheckerWaiter.__init__(self, app, self.check_if_login_complete)
     login, password = read_login()
     if login:
         error = self.login_as_user(login, password)
         if error:
             self.logger.info(str(error))
Beispiel #4
0
 def __init__(self, usb_info, user_token):
     self.usb_info = usb_info
     self.user_token = user_token
     self.http_client = http_client.HTTPClient(True)
     self.printer = None
     self.printer_token = None
     self.acknowledge = None
     self.sender_error = None
     self.stop_flag = False
     self.report = None
     self.logger = logging.getLogger('app.' + __name__)
     self.logger.info('New printer interface for %s' % str(usb_info))
     super(PrinterInterface, self).__init__()
Beispiel #5
0
 def __init__(self, app):
     self.app = app
     self.login = None
     self.user_token = None
     self.http_client = http_client.HTTPClient(self.app)
     CheckerWaiter.__init__(self, app, self.check_if_login_complete)
     if not app.stop_flag:
         login_password = read_login()
         if login_password:
             error = self.login_as_user(login_password[0],
                                        login_password[1],
                                        save_password_flag=False)
             if error:
                 self.logger.info(str(error))
 def __init__(self, parent):
     self.logger = parent.logger
     self.printer_token = parent.printer_token
     self.image_extension = '.jpg'  # config.get_settings()["camera"]["img_ext"]
     self.image_quality = 60  # config.get_settings()["camera"]["img_qual"]
     self.hardware_resize = True  # config.get_settings()["camera"]["hardware_resize"]
     self.min_loop_time = 1  # config.get_settings()["camera"]["min_loop_time"]
     self.stop_flag = False
     self.parent = parent
     self.http_client = http_client.HTTPClient(self,
                                               keep_connection_flag=True,
                                               max_send_retry_count=0,
                                               debug=False)
     self.ip = '127.0.0.1'
     # self.port = 8080
     # self.camera_url = 'http://' + self.ip + ':' + str(self.port) + '/?action=snapshot'
     self.camera_url = 'http://' + self.ip + '/webcam/?action=snapshot'
     self._max_image_size = 100000
 def run(self):
     self.last_operational_time = time.time()
     acknowledge = None
     can_restart = True
     stop_before_new_loop = False
     while not self.parent.stop_flag and (not self.stop_flag
                                          or self.errors):
         if self != self.parent.pi or self.printer_token != self.parent.token:
             can_restart = False
             self.stop_flag = True
             if self.errors:
                 stop_before_new_loop = True
             else:
                 break
         if not self.http_client:
             self.http_client = http_client.HTTPClient(
                 self, keep_connection_flag=True)
         if self.parent.camera_enabled:
             self.start_camera()
         else:
             self.stop_camera()
         self.check_operational_status()
         message, kw_message = self.form_command_request(acknowledge)
         answer = self.http_client.pack_and_send('command', *message,
                                                 **kw_message)
         if answer is not None:
             self.logger.debug("Answer: " + str(answer))
             acknowledge = self.execute_server_command(answer)
         if stop_before_new_loop:
             break
         if not self.stop_flag and not self.parent.stop_flag:
             if self.stop_in_next_loop_flag:
                 self.stop_flag = True
             else:
                 time.sleep(self.COMMAND_REQUEST_PERIOD)
     if self.http_client:
         self.http_client.close()
     self.close_printer_sender()
     self.logger.info('Printer interface was stopped')
     if can_restart and not self.parent.stop_flag:
         self.logger.info('Trying to restart Printer interface')
         self.parent.restart_printer_interface()
Beispiel #8
0
def compress_and_send(user_token, log_file_names=None):
    if not log_file_names:
        return
    logger = logging.getLogger('app.' + __name__)
    zip_file_name = time.strftime("%Y_%m_%d___%H_%M_%S",
                                  time.localtime()) + ".zip"
    for number, name in enumerate(log_file_names):
        log_file_names[number] = os.path.abspath(
            os.path.join(LOG_SNAPSHOTS_DIR, name))
    zip_file_name_path = os.path.abspath(
        os.path.join(LOG_SNAPSHOTS_DIR, zip_file_name))
    logger.info('Creating zip file : ' + zip_file_name)
    try:
        zf = zipfile.ZipFile(zip_file_name_path, mode='w')
        for name in log_file_names:
            if not name.endswith('zip'):
                zf.write(name,
                         os.path.basename(name),
                         compress_type=zipfile.ZIP_DEFLATED)
        zf.close()
    except Exception as e:
        logger.warning("Error while creating logs archive " + zip_file_name)
        logger.warning('Error: ' + e.message)
    else:
        get_path = http_client.HTTPClient()
        url = 'https://' + get_path.URL + get_path.token_send_logs_path
        user_token = {'user_token': user_token}
        logger.info('Sending logs to %s' % url)
        with open(zip_file_name_path, 'rb') as f:
            files = {'file_data': f}
            print(zip_file_name_path)
            r = requests.post(url, data=user_token, files=files)
        result = r.text
        logger.info("Log sending response: " + result)
        os.remove(zip_file_name_path)
        if '"success":true' in result:
            for name in log_file_names:
                os.remove(name)
        else:
            logger.warning('Error while sending logs: %s' % result)
            return result
 def __init__(self):
     self.logger = log.create_logger("app.camera")
     self.stop_flag = False
     paths.init_path_to_libs()
     import numpy as np
     import cv2 as cv2
     self.np = np
     self.cv2 = cv2
     signal.signal(signal.SIGINT, self.intercept_signal)
     signal.signal(signal.SIGTERM, self.intercept_signal)
     ul = user_login.UserLogin(self)
     ul.wait_for_login()
     self.user_token = ul.user_token
     self.image_extension = config.get_settings()["camera"]["img_ext"]
     self.image_quality = config.get_settings()["camera"]["img_qual"]
     self.hardware_resize = config.get_settings(
     )["camera"]["hardware_resize"]
     self.min_loop_time = config.get_settings()["camera"]["min_loop_time"]
     self.search_cameras()
     self.http_client = http_client.HTTPClient(keep_connection_flag=True)
     self.main_loop()
Beispiel #10
0
 def start_main_loop(self):
     self.last_flush_time = 0
     self.detector = usb_detect.USBDetector()
     self.http_client = http_client.HTTPClient()
     while not self.stop_flag:
         self.updater.timer_check_for_updates()
         self.time_stamp()
         self.detected_printers = self.detector.get_printers_list()
         self.check_and_connect()
         for pi in self.printer_interfaces:
             if pi.usb_info not in self.detected_printers:
                 self.disconnect_printer(pi, 'not_detected')
             elif not pi.is_alive():
                 self.disconnect_printer(pi, 'error')
         if not self.stop_flag:
             time.sleep(self.MAIN_LOOP_SLEEP)
         now = time.time()
         if now - self.last_flush_time > self.LOG_FLUSH_TIME:
             self.last_flush_time = now
             self.flush_log()
     self.quit()
Beispiel #11
0
 def start_main_loop(self):
     self.last_flush_time = 0
     self.detector = usb_detect.USBDetector()
     self.http_client = http_client.HTTPClient()
     while not self.stop_flag:
         self.updater.timer_check_for_updates()
         self.time_stamp()
         self.detected_printers = self.detector.get_printers_list()
         if self.virtual_printer_enabled:
             self.detected_printers.append({
                 "VID": "ZZZZ",
                 "PID": "ZZZZ",
                 "SNR": "0",
                 "COM": None
             })
         self.connect_new_printers()
         for pi in self.printer_interfaces:
             if pi.usb_info not in self.detected_printers:
                 if not pi.error_state == "error":
                     config.create_error_report(
                         99,
                         "Printer is no longer detected as USB device.",
                         pi.usb_info,
                         self.logger,
                         is_blocking=True)
             if not pi.is_alive():
                 if not pi.stop_flag:
                     self.logger.warning(
                         "Printer interface of %s had crushed" %
                         pi.usb_info)
                 self.logger.info('Removing %s from printer list' %
                                  pi.usb_info)
                 self.printer_interfaces.remove(pi)
         if not self.stop_flag:
             time.sleep(self.MAIN_LOOP_SLEEP)
         now = time.time()
         if now - self.last_flush_time > self.LOG_FLUSH_TIME:
             self.last_flush_time = now
             self.flush_log()
     self.quit()
Beispiel #12
0
class Cloudsync:

    HOME_PATH = os.path.expanduser('~')
    PATH = join(HOME_PATH, 'CloudSync')
    SENDED_PATH = join(PATH, 'Successful')
    UNSENDABLE_PATH = join(PATH, 'Failed')
    favourites_link_path = join(HOME_PATH, "links\CloudSync.lnk")
    sendto_link_path = join(
        HOME_PATH, "AppData\Roaming\Microsoft\Windows\SendTo\CloudSync.lnk")
    desktop_link_path = join(HOME_PATH, "desktop\CloudSync Folder.lnk")
    get_url = http_client.HTTPClient()
    URL = 'https://' + get_url.URL + get_url.cloudsync_path
    CHECK_URL = URL + '/check'
    MAX_SEND_RETRY = config.get_settings()['cloud_sync']['max_send_retry']
    CONNECTION_TIMEOUT = 6

    @log.log_exception
    def __init__(self):
        self.logger = log.create_logger('cloud_sync', log.CLOUD_SYNC_LOG_FILE)
        signal.signal(signal.SIGINT, self.intercept_signal)
        signal.signal(signal.SIGTERM, self.intercept_signal)
        self.mswin = sys.platform.startswith('win')
        self.names_to_ignore = [
            os.path.basename(self.SENDED_PATH),
            os.path.basename(self.UNSENDABLE_PATH)
        ]
        self.user_token = None
        self.error_code = None
        self.error_message = ''
        self.start()

    def intercept_signal(self, signal_code, frame):
        self.logger.info(
            "SIGINT or SIGTERM received. Closing CloudSync Module...")
        self.stop_flag = True

    def process_error(self, error_code, error_message):
        self.error_code = error_code
        self.error_message = error_message
        self.logger.warning('Error ' + str(error_code) + ' in CloudSync. ' +
                            error_message)

    def login(self):
        self.logger.info('CloudSync login')
        ul = user_login.UserLogin(self)
        ul.wait()
        self.user_token = ul.user_token

    def create_folders(self):
        self.logger.info('Preparing CloudSync folder: ' + self.PATH)
        paths = [self.PATH, self.SENDED_PATH, self.UNSENDABLE_PATH]
        for path in paths:
            if not os.path.exists(path):
                os.mkdir(os.path.abspath(path))

    def create_shortcuts_win(self):
        paths = [
            self.desktop_link_path, self.sendto_link_path,
            self.favourites_link_path
        ]
        is_paths = []
        for path in paths:
            is_paths.append(os.path.exists(path))
        if any(is_paths):
            return
        for path in paths:
            Popen([
                'cscript', 'createLink.vbs',
                os.path.abspath(path),
                os.path.abspath(self.PATH),
                os.path.abspath(join(os.getcwd(), 'cloudsync.ico'))
            ])

    def remove_shortcuts_win(self):
        os.remove(self.sendto_link_path)
        os.remove(self.favourites_link_path)
        os.remove(self.desktop_link_path)

    def enable_virtual_drive(self):
        process = Popen(['subst'], stdout=PIPE, stderr=PIPE)
        stdout, stderr = process.communicate()
        if not stdout:
            abspath = os.path.abspath(self.PATH)
            letters = 'HIJKLMNOPQRSTUVWXYZ'
            for letter in letters:
                process = Popen(['subst', letter + ':', abspath],
                                stdout=PIPE,
                                stderr=PIPE)
                stdout, stderr = process.communicate()
                if not stdout:
                    self.logger.info("Virtual drive enabled.")
                    break

    def disable_virtual_drive(self):
        process = Popen(['subst'], stdout=PIPE, stderr=PIPE)
        stdout, stderr = process.communicate()
        if stdout:
            stdout = stdout[0]
            process = Popen(['subst', stdout + ':', '/d'],
                            stdout=PIPE,
                            stderr=PIPE)
            stdout, stderr = process.communicate()
            if not stdout:
                self.logger.info("Virtual drive disabled.")

    def move_file(self, current_path, destination_folder_path):
        new_file_name = os.path.basename(current_path)
        file_name, file_ext = os.path.splitext(new_file_name)
        name_count = 1
        while os.path.exists(join(destination_folder_path, new_file_name)):
            new_file_name = file_name + "(" + str(name_count) + ")" + file_ext
            name_count += 1
        shutil.move(current_path, join(destination_folder_path, new_file_name))
        self.logger.debug('Moving ' + os.path.basename(current_path) + ' to ' +
                          os.path.basename(destination_folder_path))

    def is_sendable(self, file_path):
        name = os.path.basename(file_path)
        if self.mswin and '?' in name:
            self.logger.warning(
                'Wrong file name ' + name +
                '\n Windows is unable to operate with such names')
            self.names_to_ignore.append(name)
            return
        if os.path.isdir(file_path):
            self.logger.warning('Folders are not sendable!')
            self.move_file(file_path, self.UNSENDABLE_PATH)
            return
        for char in name:
            if not char in string.printable:
                self.logger.warning(
                    'Warning! Filename containing unicode characters are not supported by 3DPrinterOS CloudSync'
                )
                self.move_file(file_path, self.UNSENDABLE_PATH)
                return
        return True

    def get_files_to_send(self):
        files_to_send = os.listdir(self.PATH)
        for name in self.names_to_ignore:
            files_to_send.remove(name)
        for index, name in enumerate(files_to_send):
            name = files_to_send[index] = join(self.PATH, name)
            if not self.is_sendable(name):
                files_to_send.remove(name)
        return files_to_send

    def get_file_size(self, file_path):
        file_size = os.path.getsize(file_path)
        while True:
            time.sleep(1)
            if file_size == os.path.getsize(file_path):
                break
            file_size = os.path.getsize(file_path)
        return file_size

    def get_permission_to_send(self, file_path):
        try:
            file_ext = file_path.split('.')[-1]
            file_size = self.get_file_size(file_path)
            data = {
                'user_token': self.user_token,
                'file_ext': file_ext,
                'file_size': file_size
            }
            result = requests.post(self.CHECK_URL,
                                   data=data,
                                   timeout=self.CONNECTION_TIMEOUT)
            if not '"result":true' in result.text:
                return result.text
        except Exception as e:
            return str(e)

    def send_file(self, file_path):
        error = self.get_permission_to_send(file_path)
        if error:
            return 'Permission to send denied: ' + error
        result = ''
        count = 1
        file = open(file_path, 'rb')
        file_name = os.path.basename(file_path)
        data = {'user_token': self.user_token, 'file_name': file_name}
        files = {'file': file}
        while count <= self.MAX_SEND_RETRY and not self.stop_flag:
            try:
                result = requests.post(self.URL,
                                       data=data,
                                       files=files,
                                       timeout=self.CONNECTION_TIMEOUT)
                result = str(result.text)
                if '"result":true' in result:
                    file.close()
                    return
            except Exception as e:
                result = str(e)
            self.logger.info('Retrying to send ' + os.path.basename(file_path))
            count += 1
        file.close()
        return result

    def upload(self):
        files_to_send = self.get_files_to_send()
        if files_to_send:
            error = ''
            for file_path in files_to_send:
                self.logger.info('Uploading ' + os.path.basename(file_path))
                error = self.send_file(file_path)
                if error:
                    self.logger.warning('Failed to upload ' +
                                        os.path.basename(file_path) + '. ' +
                                        error)
                    self.move_file(file_path, self.UNSENDABLE_PATH)
                else:
                    self.logger.info('Successfully uploaded: ' +
                                     os.path.basename(file_path))
                    self.move_file(file_path, self.SENDED_PATH)
            if not error:
                self.logger.info('Files successfully uploaded')

    def start(self):
        self.logger.info('CloudSync started!')
        self.stop_flag = False
        self.login()
        self.create_folders()
        if self.mswin:
            self.create_shortcuts_win()
            if config.get_settings()['cloud_sync']['virtual_drive_enabled']:
                self.enable_virtual_drive()
        self.main_loop()

    def main_loop(self):
        while not self.stop_flag:
            try:
                self.upload()
                time.sleep(3)
            except IOError:
                break
        self.quit()

    def stop(self):
        self.stop_flag = True

    def quit(self):
        if self.mswin and config.get_settings(
        )['cloud_sync']['virtual_drive_enabled']:
            self.disable_virtual_drive()
        self.logger.info('CloudSync stopped')
        os._exit(0)
Beispiel #13
0
 def __init__(self):
     self.logger = logging.getLogger('app.' + __name__)
     self.update_flag = False
     self.http_client = http_client.HTTPClient()
     self.check_time = 0
 def connect_to_server(
     self
 ):  #TODO REMOVE THIS UGLY METHOD - connection must server command, like gcodes or pause
     self.logger.info("Connecting to server with printer: %s" %
                      str(self.usb_info))
     self.http_client = http_client.HTTPClient(self,
                                               keep_connection_flag=True)
     while not self.stop_flag:
         external_errors = self.get_my_errors()
         if filter(lambda error: error['is_blocking'], external_errors):
             self.stop_flag = True
             return False
         message = ['printer_login', self.user_token, self.usb_info]
         kw_message = {}
         if self.printer_type_selection_request:
             kw_message[
                 'select_printer_type'] = self.printer_type_selection_request
         self.logger.debug('Printer login request:\n%s\n%s ' %
                           (str(message), str(kw_message)))
         answer = self.http_client.pack_and_send(*message, **kw_message)
         if answer:
             error = answer.get('error')
             self.printer_name = answer.get('name', '')
             if error:
                 self.logger.warning("Error while login %s:" % str(
                     (self.user_token, self.usb_info)))
                 self.logger.warning(
                     str(error['code']) + " " + error["message"])
                 if str(error['code']) == '8':
                     self.show_printer_type_selector = True
                     time.sleep(1)
                     continue
                 else:
                     config.create_error_report(
                         26, "Server had returned error: %s" % str(error))
                     return False
             elif answer.get('printer_profile') == "":
                 config.create_error_report(
                     62,
                     "Server return message with empty printer_profile field: %s"
                     % str(error))
             else:
                 groups = answer.get('current_groups', [])
                 self.set_groups(groups)
                 self.printer_type_selection_request = None
                 self.show_printer_type_selector = False
                 self.printer_rename_request = False
                 self.logger.info('Successfully connected to server.')
                 self.printer_token = answer['printer_token']
                 self.logger.info('Received answer: ' + str(answer))
                 self.printer_profile = json.loads(
                     answer["printer_profile"])
                 custom_timeout = self.printer_profile.get(
                     "operational_timeout", None)
                 if custom_timeout:
                     self.READY_TIMEOUT = custom_timeout
                 self.logger.debug('Setting profile: ' +
                                   str(self.printer_profile))
                 return True
         else:
             self.logger.warning(
                 "Error on printer login. No connection or answer from server."
             )
             time.sleep(0.1)