<commit_before># Copyright (c) 2015 <NAME>.
# Cura is released under the terms of the AGPLv3 or higher.

from .avr_isp import stk500v2, ispBase, intelHex
import serial
import threading
import time
import queue
import re
import functools
import os
import os.path

from UM.Application import Application
from UM.Signal import Signal, SignalEmitter
from UM.Resources import Resources
from UM.Logger import Logger
from UM.OutputDevice.OutputDevice import OutputDevice
from UM.OutputDevice import OutputDeviceError
from UM.PluginRegistry import PluginRegistry

from PyQt5.QtQuick import QQuickView
from PyQt5.QtQml import QQmlComponent, QQmlContext
from PyQt5.QtCore import QUrl, QObject, pyqtSlot, pyqtProperty, pyqtSignal, Qt

from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")

class PrinterConnection(OutputDevice, QObject, SignalEmitter):
    def __init__(self, serial_port, parent = None):
        QObject.__init__(self, parent)
        OutputDevice.__init__(self, serial_port)
        SignalEmitter.__init__(self)
        #super().__init__(serial_port)
        self.setName(catalog.i18nc("@item:inmenu", "USB printing"))
        self.setShortDescription(catalog.i18nc("@action:button", "Print with USB"))
        self.setDescription(catalog.i18nc("@info:tooltip", "Print with USB"))
        self.setIconName("print")

        self._serial = None
        self._serial_port = serial_port
        self._error_state = None

        self._connect_thread = threading.Thread(target = self._connect)
        self._connect_thread.daemon = True

        self._end_stop_thread = threading.Thread(target = self._pollEndStop)
        self._end_stop_thread.deamon = True

        # Printer is connected
        self._is_connected = False

        # Printer is in the process of connecting
        self._is_connecting = False

        # The baud checking is done by sending a number of m105 commands to the printer and waiting for a readable
        # response. If the baudrate is correct, this should make sense, else we get giberish.
        self._required_responses_auto_baud = 3

        self._progress = 0

        self._listen_thread = threading.Thread(target=self._listen)
        self._listen_thread.daemon = True

        self._update_firmware_thread = threading.Thread(target= self._updateFirmware)
        self._update_firmware_thread.deamon = True
        
        self._heatup_wait_start_time = time.time()

        ## Queue for commands that need to be send. Used when command is sent when a print is active.
        self._command_queue = queue.Queue()

        self._is_printing = False

        ## Set when print is started in order to check running time.
        self._print_start_time = None
        self._print_start_time_100 = None

        ## Keep track where in the provided g-code the print is
        self._gcode_position = 0

        # List of gcode lines to be printed
        self._gcode = []

        # Number of extruders
        self._extruder_count = 1

        # Temperatures of all extruders
        self._extruder_temperatures = [0] * self._extruder_count

        # Target temperatures of all extruders
        self._target_extruder_temperatures = [0] * self._extruder_count

        #Target temperature of the bed
        self._target_bed_temperature = 0 

        # Temperature of the bed
        self._bed_temperature = 0

        # Current Z stage location 
        self._current_z = 0

        self._x_min_endstop_pressed = False
        self._y_min_endstop_pressed = False
        self._z_min_endstop_pressed = False

        self._x_max_endstop_pressed = False
        self._y_max_endstop_pressed = False
        self._z_max_endstop_pressed = False

        # In order to keep the connection alive we request the temperature every so often from a different extruder.
        # This index is the extruder we requested data from the last time.
        self._temperature_requested_extruder_index = 0 

        self._updating_firmware = False

        self._firmware_file_name = None

        self._control_view = None

    onError = pyqtSignal()
    progressChanged = pyqtSignal()
    extruderTemperatureChanged = pyqtSignal()
    bedTemperatureChanged = pyqtSignal()

    endstopStateChanged = pyqtSignal(str ,bool, arguments = ["key","state"])

    @pyqtProperty(float, notify = progressChanged)
    def progress(self):
        return self._progress

    @pyqtProperty(float, notify = extruderTemperatureChanged)
    def extruderTemperature(self):
        return self._extruder_temperatures[0]

    @pyqtProperty(float, notify = bedTemperatureChanged)
    def bedTemperature(self):
        return self._bed_temperature

    @pyqtProperty(str, notify = onError)
    def error(self):
        return self._error_state

    # TODO: Might need to add check that extruders can not be changed when it started printing or loading these settings from settings object    
    def setNumExtuders(self, num):
        self._extruder_count = num
        self._extruder_temperatures = [0] * self._extruder_count
        self._target_extruder_temperatures = [0] * self._extruder_count

    ##  Is the printer actively printing
    def isPrinting(self):
        if not self._is_connected or self._serial is None:
            return False
        return self._is_printing

    @pyqtSlot()
    def startPrint(self):
        self.writeStarted.emit(self)
        gcode_list = getattr( Application.getInstance().getController().getScene(), "gcode_list")
        self.printGCode(gcode_list)

    ##  Start a print based on a g-code.
    #   \param gcode_list List with gcode (strings).
    def printGCode(self, gcode_list):
        if self.isPrinting() or not self._is_connected:
            Logger.log("d", "Printer is busy or not connected, aborting print")
            self.writeError.emit()
            return

        self._gcode.clear()
        for layer in gcode_list:
            self._gcode.extend(layer.split("\n"))

        #Reset line number. If this is not done, first line is sometimes ignored
        self._gcode.insert(0, "M110")
        self._gcode_position = 0
        self._print_start_time_100 = None
        self._is_printing = True
        self._print_start_time = time.time()

        for i in range(0, 4): #Push first 4 entries before accepting other inputs
            self._sendNextGcodeLine()

        self.writeFinished.emit()

    ##  Get the serial port string of this connection.
    #   \return serial port
    def getSerialPort(self):
        return self._serial_port

    ##  Try to connect the serial. This simply starts the thread, which runs _connect.
    def connect(self):
        if not self._updating_firmware and not self._connect_thread.isAlive():
            self._connect_thread.start()

    ##  Private fuction (threaded) that actually uploads the firmware.
    def _updateFirmware(self):<commit_msg>Added self to output device signals<commit_after># Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.

from .avr_isp import stk500v2, ispBase, intelHex
import serial
import threading
import time
import queue
import re
import functools
import os
import os.path

from UM.Application import Application
from UM.Signal import Signal, SignalEmitter
from UM.Resources import Resources
from UM.Logger import Logger
from UM.OutputDevice.OutputDevice import OutputDevice
from UM.OutputDevice import OutputDeviceError
from UM.PluginRegistry import PluginRegistry

from PyQt5.QtQuick import QQuickView
from PyQt5.QtQml import QQmlComponent, QQmlContext
from PyQt5.QtCore import QUrl, QObject, pyqtSlot, pyqtProperty, pyqtSignal, Qt

from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")

class PrinterConnection(OutputDevice, QObject, SignalEmitter):
    def __init__(self, serial_port, parent = None):
        QObject.__init__(self, parent)
        OutputDevice.__init__(self, serial_port)
        SignalEmitter.__init__(self)
        #super().__init__(serial_port)
        self.setName(catalog.i18nc("@item:inmenu", "USB printing"))
        self.setShortDescription(catalog.i18nc("@action:button", "Print with USB"))
        self.setDescription(catalog.i18nc("@info:tooltip", "Print with USB"))
        self.setIconName("print")

        self._serial = None
        self._serial_port = serial_port
        self._error_state = None

        self._connect_thread = threading.Thread(target = self._connect)
        self._connect_thread.daemon = True

        self._end_stop_thread = threading.Thread(target = self._pollEndStop)
        self._end_stop_thread.deamon = True

        # Printer is connected
        self._is_connected = False

        # Printer is in the process of connecting
        self._is_connecting = False

        # The baud checking is done by sending a number of m105 commands to the printer and waiting for a readable
        # response. If the baudrate is correct, this should make sense, else we get giberish.
        self._required_responses_auto_baud = 3

        self._progress = 0

        self._listen_thread = threading.Thread(target=self._listen)
        self._listen_thread.daemon = True

        self._update_firmware_thread = threading.Thread(target= self._updateFirmware)
        self._update_firmware_thread.deamon = True
        
        self._heatup_wait_start_time = time.time()

        ## Queue for commands that need to be send. Used when command is sent when a print is active.
        self._command_queue = queue.Queue()

        self._is_printing = False

        ## Set when print is started in order to check running time.
        self._print_start_time = None
        self._print_start_time_100 = None

        ## Keep track where in the provided g-code the print is
        self._gcode_position = 0

        # List of gcode lines to be printed
        self._gcode = []

        # Number of extruders
        self._extruder_count = 1

        # Temperatures of all extruders
        self._extruder_temperatures = [0] * self._extruder_count

        # Target temperatures of all extruders
        self._target_extruder_temperatures = [0] * self._extruder_count

        #Target temperature of the bed
        self._target_bed_temperature = 0 

        # Temperature of the bed
        self._bed_temperature = 0

        # Current Z stage location 
        self._current_z = 0

        self._x_min_endstop_pressed = False
        self._y_min_endstop_pressed = False
        self._z_min_endstop_pressed = False

        self._x_max_endstop_pressed = False
        self._y_max_endstop_pressed = False
        self._z_max_endstop_pressed = False

        # In order to keep the connection alive we request the temperature every so often from a different extruder.
        # This index is the extruder we requested data from the last time.
        self._temperature_requested_extruder_index = 0 

        self._updating_firmware = False

        self._firmware_file_name = None

        self._control_view = None

    onError = pyqtSignal()
    progressChanged = pyqtSignal()
    extruderTemperatureChanged = pyqtSignal()
    bedTemperatureChanged = pyqtSignal()

    endstopStateChanged = pyqtSignal(str ,bool, arguments = ["key","state"])

    @pyqtProperty(float, notify = progressChanged)
    def progress(self):
        return self._progress

    @pyqtProperty(float, notify = extruderTemperatureChanged)
    def extruderTemperature(self):
        return self._extruder_temperatures[0]

    @pyqtProperty(float, notify = bedTemperatureChanged)
    def bedTemperature(self):
        return self._bed_temperature

    @pyqtProperty(str, notify = onError)
    def error(self):
        return self._error_state

    # TODO: Might need to add check that extruders can not be changed when it started printing or loading these settings from settings object    
    def setNumExtuders(self, num):
        self._extruder_count = num
        self._extruder_temperatures = [0] * self._extruder_count
        self._target_extruder_temperatures = [0] * self._extruder_count

    ##  Is the printer actively printing
    def isPrinting(self):
        if not self._is_connected or self._serial is None:
            return False
        return self._is_printing

    @pyqtSlot()
    def startPrint(self):
        self.writeStarted.emit(self)
        gcode_list = getattr( Application.getInstance().getController().getScene(), "gcode_list")
        self.printGCode(gcode_list)

    ##  Start a print based on a g-code.
    #   \param gcode_list List with gcode (strings).
    def printGCode(self, gcode_list):
        if self.isPrinting() or not self._is_connected:
            Logger.log("d", "Printer is busy or not connected, aborting print")
            self.writeError.emit(self)
            return

        self._gcode.clear()
        for layer in gcode_list:
            self._gcode.extend(layer.split("\n"))

        #Reset line number. If this is not done, first line is sometimes ignored
        self._gcode.insert(0, "M110")
        self._gcode_position = 0
        self._print_start_time_100 = None
        self._is_printing = True
        self._print_start_time = time.time()

        for i in range(0, 4): #Push first 4 entries before accepting other inputs
            self._sendNextGcodeLine()

        self.writeFinished.emit(self)

    ##  Get the serial port string of this connection.
    #   \return serial port
    def getSerialPort(self):
        return self._serial_port

    ##  Try to connect the serial. This simply starts the thread, which runs _connect.
    def connect(self):
        if not self._updating_firmware and not self._connect_thread.isAlive():
            self._connect_thread.start()

    ##  Private fuction (threaded) that actually uploads the firmware.
    def _updateFirmware(self):
{'fraction_non_alphanumeric': 0.07114308553157474, 'fraction_numerical': 0.007848266841072597, 'mean_word_length': 2.872256612267867, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7045944', 'n_tokens_mistral': 4050, 'n_tokens_neox': 3843, 'n_words': 1141}