Example #1
0
def process_octoprint_status(printer, status):
    octoprint_settings = status.get('octoprint_settings')
    if octoprint_settings:
        redis.printer_settings_set(printer.id, settings_dict(octoprint_settings))

    octoprint_data = dict()
    set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'state')
    set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'progress')
    set_as_str_if_present(octoprint_data, status, 'octoprint_temperatures', 'temperatures')
    redis.printer_status_set(printer.id, octoprint_data, ex=STATUS_TTL_SECONDS)

    if status.get('current_print_ts'): # New plugin version that passes current_print_ts
        process_octoprint_status_with_ts(status, printer)
        channels.send_status_to_web(printer.id)
        return

    ### Old way of determining a print. For backward compatibility
    filename, printing, cancelled = file_printing(status, printer)
    if printing is not None:
        if printing:
            printer.set_current_print(filename)
        else:
            printer.unset_current_print(cancelled)

    channels.send_status_to_web(printer.id)
Example #2
0
def process_octoprint_status(printer: Printer, status: Dict) -> None:
    octoprint_settings = status.get('octoprint_settings')
    if octoprint_settings:
        cache.printer_settings_set(printer.id, settings_dict(octoprint_settings))

    # for backward compatibility
    if status.get('octoprint_data'):
        if 'octoprint_temperatures' in status:
            status['octoprint_data']['temperatures'] = status['octoprint_temperatures']

    if status.get('octoprint_data', {}).get('_ts'):   # data format for plugin 1.6.0 and higher
        cache.printer_status_set(printer.id, json.dumps(status.get('octoprint_data', {})), ex=STATUS_TTL_SECONDS)
    else:
        octoprint_data: Dict = dict()
        set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'state')
        set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'progress')
        set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'file_metadata')
        set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'currentZ')
        set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'job')
        set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'temperatures')
        cache.printer_status_set(printer.id, octoprint_data, ex=STATUS_TTL_SECONDS)

    if status.get('current_print_ts'):
        process_octoprint_status_with_ts(status, printer)

    channels.send_status_to_web(printer.id)

    temps = status.get('octoprint_data', {}).get('temperatures', None)
    if temps:
        process_heater_temps(printer, temps)
 def send_command_response(self, printer, succeeded, user_credited):
     send_status_to_web(printer.id)
     serializer = self.serializer_class(printer)
     return Response(
         dict(succeeded=succeeded,
              user_credited=user_credited,
              printer=serializer.data))
def command_response(printer):
    send_commands_to_printer(printer.id)
    send_status_to_web(printer.id)
    commands = PrinterCommand.objects.filter(printer=printer,
                                             status=PrinterCommand.PENDING)
    resp = Response({'commands': [json.loads(c.command) for c in commands]})
    commands.update(status=PrinterCommand.SENT)
    return resp
Example #5
0
    def post(self, request):
        printer = request.auth
        printer.refresh_from_db()  # Connection is keep-alive, which means printer object can be stale.

        pic = request.FILES['pic']
        pic = cap_image_size(pic)
        pic_id = str(timezone.now().timestamp())

        if not printer.current_print:     # Some times pics come in when current_print is not set - maybe because printer status is out of sync between plugin and server?
            pic_path = f'{printer.id}/0/{pic_id}.jpg'
        else:
            pic_path = f'{printer.id}/{printer.current_print.id}/{pic_id}.jpg'
        internal_url, external_url = save_file_obj(f'raw/{pic_path}', pic, settings.PICS_CONTAINER, long_term_storage=False)

        if not printer.should_watch() or not printer.actively_printing():
            cache.printer_pic_set(printer.id, {'img_url': external_url}, ex=IMG_URL_TTL_SECONDS)
            send_status_to_web(printer.id)
            return Response({'result': 'ok'})

        req = requests.get(settings.ML_API_HOST + '/p/', params={'img': internal_url}, headers=ml_api_auth_headers(), verify=False)
        req.raise_for_status()
        resp = req.json()

        cache.print_num_predictions_incr(printer.current_print.id)

        detections = resp['detections']
        prediction, _ = PrinterPrediction.objects.get_or_create(printer=printer)
        update_prediction_with_detections(prediction, detections)
        prediction.save()

        if prediction.current_p > settings.THRESHOLD_LOW * 0.2:  # Select predictions high enough for focused feedback
            cache.print_high_prediction_add(printer.current_print.id, prediction.current_p, pic_id)

        pic.file.seek(0)  # Reset file object pointer so that we can load it again
        tagged_img = io.BytesIO()
        detections_to_visualize = [d for d in detections if d[1] > VISUALIZATION_THRESH]
        overlay_detections(Image.open(pic), detections_to_visualize).save(tagged_img, "JPEG")
        tagged_img.seek(0)

        _, external_url = save_file_obj(f'tagged/{pic_path}', tagged_img, settings.PICS_CONTAINER, long_term_storage=False)
        cache.printer_pic_set(printer.id, {'img_url': external_url}, ex=IMG_URL_TTL_SECONDS)

        prediction_json = serializers.serialize("json", [prediction, ])
        p_out = io.BytesIO()
        p_out.write(prediction_json.encode('UTF-8'))
        p_out.seek(0)
        save_file_obj(f'p/{printer.id}/{printer.current_print.id}/{pic_id}.json', p_out, settings.PICS_CONTAINER, long_term_storage=False)

        if is_failing(prediction, printer.detective_sensitivity, escalating_factor=settings.ESCALATING_FACTOR):
            pause_if_needed(printer)
        elif is_failing(prediction, printer.detective_sensitivity, escalating_factor=1):
            alert_if_needed(printer)

        send_status_to_web(printer.id)
        return Response({'result': 'ok'})
Example #6
0
    def connect(self):
        self.printer_id = self.scope['url_route']['kwargs']['printer_id']
        try:
            printer = Printer.objects.get(
                user=self.current_user(), id=self.printer_id
            )  # Exception for un-authenticated or un-authorized access

            async_to_sync(self.channel_layer.group_add)(
                channels.status_group_name(self.printer_id), self.channel_name)
            self.accept()
            channels.send_status_to_web(printer.id)
        except:
            self.close()
def process_octoprint_status(printer, status):
    octoprint_settings = status.get('octoprint_settings')
    if octoprint_settings:
        redis.printer_settings_set(printer.id, settings_dict(octoprint_settings))

    octoprint_data = dict()
    set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'state')
    set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'progress')
    set_as_str_if_present(octoprint_data, status, 'octoprint_temperatures', 'temperatures')
    redis.printer_status_set(printer.id, octoprint_data, ex=STATUS_TTL_SECONDS)

    if status.get('current_print_ts'):
        process_octoprint_status_with_ts(status, printer)

    channels.send_status_to_web(printer.id)
Example #8
0
    def connect(self):
        try:
            if self.scope['path'].startswith('/ws/shared/'):
                self.printer = self.current_user()
            else:
                # Exception for un-authenticated or un-authorized access
                self.printer = Printer.objects.get(
                    user=self.current_user(),
                    id=self.scope['url_route']['kwargs']['printer_id'])

            async_to_sync(self.channel_layer.group_add)(
                channels.status_group_name(self.printer.id), self.channel_name)
            self.accept()
            channels.send_status_to_web(self.printer.id)
            send_remote_status(self.printer, viewing=True)
        except:
            LOGGER.exception("Websocket failed to connect")
            self.close()
Example #9
0
    def post(self, request):
        printer = request.auth
        printer.refresh_from_db() # Connection is keep-alive, which means printer object can be stale.

        if not request.path.startswith('/api/v1'):
            LOGGER.warn(f'Beta plugin connecting from {printer.id}')

        pic = request.FILES['pic']
        pic_id = int(timezone.now().timestamp())
        internal_url, external_url = save_file_obj('raw/{}/{}.jpg'.format(printer.id, pic_id), pic, settings.PICS_CONTAINER)

        if not printer.should_watch() or not printer.actively_printing():
            redis.printer_pic_set(printer.id, {'img_url': external_url}, ex=STATUS_TTL_SECONDS)
            send_status_to_web(printer.id)
            return Response({'result': 'ok'})

        req = requests.get(settings.ML_API_HOST + '/p/', params={'img': internal_url}, headers=ml_api_auth_headers(), verify=False)
        req.raise_for_status()
        resp = req.json()

        detections = resp['detections']
        prediction, _ = PrinterPrediction.objects.get_or_create(printer=printer)
        update_prediction_with_detections(prediction, detections)
        prediction.save()

        pic.file.seek(0)  # Reset file object pointer so that we can load it again
        tagged_img = io.BytesIO()
        detections_to_visualize = [d for d in detections if d[1] > VISUALIZATION_THRESH]
        overlay_detections(Image.open(pic), detections_to_visualize).save(tagged_img, "JPEG")
        tagged_img.seek(0)
        _, external_url = save_file_obj('tagged/{}/{}.jpg'.format(printer.id, pic_id), tagged_img, settings.PICS_CONTAINER)
        redis.printer_pic_set(printer.id, {'img_url': external_url}, ex=STATUS_TTL_SECONDS)

        prediction_json = serializers.serialize("json", [prediction, ])
        redis.printer_p_json_set(printer.id, pic_id, prediction_json, ex=60*60*24*2)

        if is_failing(prediction, printer.detective_sensitivity, escalating_factor=settings.ESCALATING_FACTOR):
            pause_if_needed(printer)
        elif is_failing(prediction, printer.detective_sensitivity, escalating_factor=1):
            alert_if_needed(printer)

        redis.print_num_predictions_incr(printer.current_print.id)
        send_status_to_web(printer.id)
        return Response({'result': 'ok'})
def process_octoprint_status(printer: Printer, status: Dict) -> None:
    octoprint_settings = status.get('octoprint_settings')
    if octoprint_settings:
        cache.printer_settings_set(printer.id, settings_dict(octoprint_settings))

    octoprint_data: Dict = dict()
    set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'state')
    set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'progress')
    set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'file_metadata')
    set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'currentZ')
    set_as_str_if_present(octoprint_data, status.get('octoprint_data', {}), 'job')
    set_as_str_if_present(octoprint_data, status, 'octoprint_temperatures', 'temperatures')
    cache.printer_status_set(printer.id, octoprint_data, ex=STATUS_TTL_SECONDS)

    if status.get('current_print_ts'):
        process_octoprint_status_with_ts(status, printer)

    channels.send_status_to_web(printer.id)

    temps = status.get('octoprint_temperatures', None)
    if temps:
        process_heater_temps(printer, temps)