diff --git a/src/core/atcore.cpp b/src/core/atcore.cpp index 379a7ae..980f87e 100644 --- a/src/core/atcore.cpp +++ b/src/core/atcore.cpp @@ -1,782 +1,782 @@ /* AtCore Copyright (C) <2016> Authors: Tomaz Canabrava Chris Rizzitello Patrick José Pereira Lays Rodrigues This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include #include #include #include #include #include #include #include #include "atcore.h" #include "atcore_version.h" #include "seriallayer.h" #include "gcodecommands.h" #include "printthread.h" #include "atcore_default_folders.h" Q_LOGGING_CATEGORY(ATCORE_PLUGIN, "org.kde.atelier.core.plugin") Q_LOGGING_CATEGORY(ATCORE_CORE, "org.kde.atelier.core") /** * @brief The AtCorePrivate struct * Provides a private data set for atcore. */ -struct AtCorePrivate { +struct AtCore::AtCorePrivate { IFirmware *firmwarePlugin = nullptr;//!< @param firmwarePlugin: pointer to firmware plugin SerialLayer *serial = nullptr; //!< @param serial: pointer to the serial layer QPluginLoader pluginLoader; //!< @param pluginLoader: QPluginLoader QMap plugins; //!< @param plugins: Map of plugins name / path QByteArray lastMessage; //!< @param lastMessage: lastMessage from the printer int extruderCount = 1; //!< @param extruderCount: extruder count Temperature temperature; //!< @param temperature: Temperature object QStringList commandQueue; //!< @param commandQueue: the list of commands to send to the printer bool ready = false; //!< @param ready: True if printer is ready for a command QTimer *tempTimer = nullptr; //!< @param tempTimer: timer connected to the checkTemperature function float percentage; //!< @param percentage: print job percent QByteArray posString; //!< @param posString: stored string from last M114 return AtCore::STATES printerState; //!< @param printerState: State of the Printer QStringList serialPorts; //!< @param seralPorts: Detected serial Ports QTimer *serialTimer = nullptr; //!< @param serialTimer: Timer connected to locateSerialPorts bool sdCardMounted = false; //!< @param sdCardMounted: True if Sd Card is mounted. bool sdCardReadingFileList = false; //!< @param sdCardReadingFileList: True while getting file names from sd card bool sdCardPrinting = false; //!< @param sdCardPrinting: True if currently printing from sd card. QString sdCardFileName; //!< @param sdCardFileName: name of file being used from sd card. QStringList sdCardFileList; //!< @param sdCardFileList: List of files on sd card. }; AtCore::AtCore(QObject *parent) : QObject(parent), d(new AtCorePrivate) { //Register MetaTypes qRegisterMetaType("AtCore::STATES"); setState(AtCore::DISCONNECTED); //Create and start the timer that checks for temperature. d->tempTimer = new QTimer(this); d->tempTimer->setInterval(5000); d->tempTimer->setSingleShot(false); //Attempt to find our plugins qCDebug(ATCORE_PLUGIN) << "Detecting Plugin path"; for (const auto &path : AtCoreDirectories::pluginDir) { qCDebug(ATCORE_PLUGIN) << "Checking: " << path; QMap tempMap = findFirmwarePlugins(path); if (!tempMap.isEmpty()) { d->plugins = tempMap; return; } } setState(AtCore::DISCONNECTED); } QString AtCore::version() const { QString versionString = QString::fromLatin1(ATCORE_VERSION_STRING); #if defined GIT_REVISION if (!QStringLiteral(GIT_REVISION).isEmpty()) { versionString.append(QString::fromLatin1("-%1").arg(QStringLiteral(GIT_REVISION))); } #endif return versionString; } SerialLayer *AtCore::serial() const { return d->serial; } IFirmware *AtCore::firmwarePlugin() const { return d->firmwarePlugin; } void AtCore::close() { exit(0); } Temperature &AtCore::temperature() const { return d->temperature; } void AtCore::findFirmware(const QByteArray &message) { if (state() == AtCore::DISCONNECTED) { qCWarning(ATCORE_CORE) << tr("Cant find firwmware, serial not connected!"); return; } if (state() == AtCore::CONNECTING) { //Most Firmwares will return "start" on connect, some return their firmware name. if (message.contains("start")) { qCDebug(ATCORE_CORE) << "Waiting requestFirmware."; QTimer::singleShot(500, this, &AtCore::requestFirmware); return; } else if (message.contains("Grbl")) { loadFirmwarePlugin(QString::fromLatin1("grbl")); return; } else if (message.contains("Smoothie")) { loadFirmwarePlugin(QString::fromLatin1("smoothie")); return; } qCDebug(ATCORE_CORE) << "Waiting for firmware detect."; emit atcoreMessage(tr("Waiting for firmware detect.")); } qCDebug(ATCORE_CORE) << "Find Firmware: " << message; if (!message.contains("FIRMWARE_NAME:")) { qCDebug(ATCORE_CORE) << "No firmware yet."; return; } qCDebug(ATCORE_CORE) << "Found firmware string, Looking for Firmware Name."; QString fwName = QString::fromLocal8Bit(message); fwName = fwName.split(QChar::fromLatin1(':')).at(1); if (fwName.indexOf(QChar::fromLatin1(' ')) == 0) { //remove leading space fwName.remove(0, 1); } if (fwName.contains(QChar::fromLatin1(' '))) { //check there is a space or dont' resize fwName.resize(fwName.indexOf(QChar::fromLatin1(' '))); } fwName = fwName.toLower().simplified(); if (fwName.contains(QChar::fromLatin1('_'))) { fwName.resize(fwName.indexOf(QChar::fromLatin1('_'))); } qCDebug(ATCORE_CORE) << "Firmware Name:" << fwName; if (message.contains("EXTRUDER_COUNT:")) { //this code is broken if more then 9 extruders are detected. since only one char is returned setExtruderCount(message.at(message.indexOf("EXTRUDER_COUNT:") + 15) - '0'); } loadFirmwarePlugin(fwName); } void AtCore::loadFirmwarePlugin(const QString &fwName) { qCDebug(ATCORE_CORE) << "Loading plugin: " << d->plugins[fwName]; if (d->plugins.contains(fwName)) { d->pluginLoader.setFileName(d->plugins[fwName]); if (!d->pluginLoader.load()) { //Plugin was not loaded, Provide some debug info. qCDebug(ATCORE_CORE) << "Plugin Loading: Failed."; qCDebug(ATCORE_CORE) << d->pluginLoader.errorString(); setState(AtCore::CONNECTING); } else { //Plugin was loaded successfully. d->firmwarePlugin = qobject_cast(d->pluginLoader.instance()); firmwarePlugin()->init(this); disconnect(serial(), &SerialLayer::receivedCommand, this, &AtCore::findFirmware); connect(serial(), &SerialLayer::receivedCommand, this, &AtCore::newMessage); connect(firmwarePlugin(), &IFirmware::readyForCommand, this, &AtCore::processQueue); d->ready = true; // ready on new firmware load if (firmwarePlugin()->name() != QStringLiteral("Grbl")) { connect(d->tempTimer, &QTimer::timeout, this, &AtCore::checkTemperature); d->tempTimer->start(); } setState(IDLE); } } else { qCDebug(ATCORE_CORE) << "Plugin:" << fwName << ": Not found."; emit atcoreMessage(tr("No plugin found for %1.").arg(fwName)); } } bool AtCore::initSerial(const QString &port, int baud) { d->serial = new SerialLayer(port, baud); if (serialInitialized() && d->serial->isWritable()) { setState(AtCore::CONNECTING); connect(serial(), &SerialLayer::receivedCommand, this, &AtCore::findFirmware); d->serialTimer->stop(); return true; } else { qCDebug(ATCORE_CORE) << "Failed to open device for Read / Write."; emit atcoreMessage(tr("Failed to open device in read/write mode.")); return false; } } bool AtCore::serialInitialized() const { if (!d->serial) { return false; } return d->serial->isOpen(); } QString AtCore::connectedPort() const { return serial()->portName(); } QStringList AtCore::serialPorts() const { QStringList ports; QList serialPortInfoList = QSerialPortInfo::availablePorts(); if (!serialPortInfoList.isEmpty()) { for (const QSerialPortInfo &serialPortInfo : serialPortInfoList) { #ifdef Q_OS_MAC //Mac OS has callout serial ports starting with cu these devices are read only. //It is necessary to filter them out to help prevent user error. if (!serialPortInfo.portName().startsWith(QStringLiteral("cu."), Qt::CaseInsensitive)) { ports.append(serialPortInfo.portName()); } #else ports.append(serialPortInfo.portName()); #endif } } return ports; } void AtCore::locateSerialPort() { QStringList ports = serialPorts(); if (d->serialPorts != ports) { d->serialPorts = ports; emit portsChanged(d->serialPorts); } } quint16 AtCore::serialTimerInterval() const { if (d->serialTimer != nullptr) { return d->serialTimer->interval(); } return 0; } void AtCore::setSerialTimerInterval(const quint16 &newTime) { if (!d->serialTimer) { //There is no timer. We need to create one. d->serialTimer = new QTimer(); connect(d->serialTimer, &QTimer::timeout, this, &AtCore::locateSerialPort); } //emit the newtime if it has changed. if (newTime != d->serialTimer->interval()) { emit serialTimerIntervalChanged(newTime); } //Start the timer. d->serialTimer->start(newTime); } void AtCore::newMessage(const QByteArray &message) { //Evaluate the messages coming from the printer. d->lastMessage = message; //Check if the message has current coordinates. if (message.startsWith(QString::fromLatin1("X:").toLocal8Bit())) { d->posString = message; d->posString.resize(d->posString.indexOf('E')); d->posString.replace(':', ""); } //Check if have temperature info and decode it if (d->lastMessage.contains("T:") || d->lastMessage.contains("B:")) { temperature().decodeTemp(message); } emit receivedMessage(d->lastMessage); } void AtCore::setRelativePosition() { pushCommand(GCode::toCommand(GCode::G91)); } void AtCore::setAbsolutePosition() { pushCommand(GCode::toCommand(GCode::G90)); } float AtCore::percentagePrinted() const { return d->percentage; } void AtCore::print(const QString &fileName, bool sdPrint) { if (state() == AtCore::CONNECTING) { qCDebug(ATCORE_CORE) << "Load a firmware plugin to print."; return; } //Start a print job. setState(AtCore::STARTPRINT); //Only try to print from Sd if the firmware has support for sd cards if (firmwarePlugin()->isSdSupported()) { if (sdPrint) { //Printing from the sd card requires us to send some M commands. pushCommand(GCode::toCommand(GCode::M23, fileName)); d->sdCardFileName = fileName; pushCommand(GCode::toCommand(GCode::M24)); setState(AtCore::BUSY); d->sdCardPrinting = true; connect(d->tempTimer, &QTimer::timeout, this, &AtCore::sdCardPrintStatus); return; } } //Process the gcode with a printThread. //The Thread processes the gcode without freezing the libary. //Only sends a command back when the printer is ready, avoiding buffer overflow in the printer. QThread *thread = new QThread(); PrintThread *printThread = new PrintThread(this, fileName); printThread->moveToThread(thread); connect(printThread, &PrintThread::printProgressChanged, this, &AtCore::printProgressChanged, Qt::QueuedConnection); connect(thread, &QThread::started, printThread, &PrintThread::start); connect(printThread, &PrintThread::finished, thread, &QThread::quit); connect(thread, &QThread::finished, printThread, &PrintThread::deleteLater); if (!thread->isRunning()) { thread->start(); } } void AtCore::pushCommand(const QString &comm) { //Append command to the commandQueue d->commandQueue.append(comm); if (d->ready) { //The printer is ready for a command now so push one. processQueue(); } } void AtCore::closeConnection() { if (serialInitialized()) { if (AtCore::state() == AtCore::BUSY && !d->sdCardPrinting) { //We have to clean up the print job if printing from the host. //However disconnecting while printing from sd card should not affect the print job. setState(AtCore::STOP); } if (firmwarePluginLoaded()) { disconnect(firmwarePlugin(), &IFirmware::readyForCommand, this, &AtCore::processQueue); disconnect(serial(), &SerialLayer::receivedCommand, this, &AtCore::newMessage); if (firmwarePlugin()->name() != QStringLiteral("Grbl")) { disconnect(d->tempTimer, &QTimer::timeout, this, &AtCore::checkTemperature); d->tempTimer->stop(); } //Attempt to unload the firmware plugin. QString name = firmwarePlugin()->name(); QString msg = d->pluginLoader.unload() ? QStringLiteral("closed.") : QStringLiteral("Failed to close."); qCDebug(ATCORE_CORE) << QStringLiteral("Firmware plugin %1 %2").arg(name, msg); } serial()->close(); //Clear our copy of the sdcard filelist clearSdCardFileList(); setState(AtCore::DISCONNECTED); d->serialTimer->start(); } } AtCore::STATES AtCore::state(void) { return d->printerState; } void AtCore::setState(AtCore::STATES state) { if (state != d->printerState) { qCDebug(ATCORE_CORE) << QStringLiteral("Atcore state changed from [%1] to [%2]") .arg(QVariant::fromValue(d->printerState).value(), QVariant::fromValue(state).value()); d->printerState = state; if (state == AtCore::FINISHEDPRINT && d->sdCardPrinting) { //Clean up the sd card print d->sdCardPrinting = false; disconnect(d->tempTimer, &QTimer::timeout, this, &AtCore::sdCardPrintStatus); } emit stateChanged(d->printerState); } } void AtCore::stop() { //Stop a print job setState(AtCore::STOP); d->commandQueue.clear(); if (d->sdCardPrinting) { stopSdPrint(); } setExtruderTemp(0, 0); setBedTemp(0); home(AtCore::X); } void AtCore::emergencyStop() { //Emergency Stop. Stops the machine //Clear the queue, and any print job //Before sending the command to ensure //Less chance of movement after the restart. d->commandQueue.clear(); if (AtCore::state() == AtCore::BUSY) { if (!d->sdCardPrinting) { //Stop our running print thread setState(AtCore::STOP); } } //push command through serial to bypass atcore's queue. serial()->pushCommand(GCode::toCommand(GCode::M112).toLocal8Bit()); } void AtCore::stopSdPrint() { //Stop an SdCard Print. pushCommand(GCode::toCommand(GCode::M25)); d->sdCardFileName = QString(); pushCommand(GCode::toCommand(GCode::M23, d->sdCardFileName)); AtCore::setState(AtCore::FINISHEDPRINT); AtCore::setState(AtCore::IDLE); } void AtCore::requestFirmware() { if (serialInitialized()) { qCDebug(ATCORE_CORE) << "Sending " << GCode::description(GCode::M115); serial()->pushCommand(GCode::toCommand(GCode::M115).toLocal8Bit()); } else { qCDebug(ATCORE_CORE) << "There is no open device to send commands"; } } bool AtCore::firmwarePluginLoaded() const { if (firmwarePlugin()) { return true; } else { return false; } } QMap AtCore::findFirmwarePlugins(const QString &path) { QMap detectedPlugins; QStringList files = QDir(path).entryList(QDir::Files); for (const QString &f : files) { QString file = f; #if defined(Q_OS_WIN) if (file.endsWith(QStringLiteral(".dll"))) #elif defined(Q_OS_MAC) if (file.endsWith(QStringLiteral(".dylib"))) #else if (file.endsWith(QStringLiteral(".so"))) #endif file = file.split(QChar::fromLatin1('.')).at(0); else { continue; } if (file.startsWith(QStringLiteral("lib"))) { file = file.remove(QStringLiteral("lib")); } file = file.toLower().simplified(); QString pluginString = path; pluginString.append(QChar::fromLatin1('/')); pluginString.append(f); detectedPlugins[file] = pluginString; qCDebug(ATCORE_PLUGIN) << QStringLiteral("Plugin:[%1]=%2").arg(file, pluginString); } return detectedPlugins; } QStringList AtCore::availableFirmwarePlugins() const { return d->plugins.keys(); } void AtCore::pause(const QString &pauseActions) { if (d->sdCardPrinting) { pushCommand(GCode::toCommand(GCode::M25)); } //Push the command to request current coordinates. //This will be read by AtCore::newMessage and stored for use on resume. pushCommand(GCode::toCommand(GCode::M114)); if (!pauseActions.isEmpty()) { QStringList temp = pauseActions.split(QChar::fromLatin1(',')); for (int i = 0; i < temp.length(); i++) { pushCommand(temp.at(i)); } } setState(AtCore::PAUSE); } void AtCore::resume() { if (d->sdCardPrinting) { pushCommand(GCode::toCommand(GCode::M24)); } else { //Move back to previous coordinates. pushCommand(GCode::toCommand(GCode::G0, QString::fromLatin1(d->posString))); } setState(AtCore::BUSY); } /*~~~~~Control Slots ~~~~~~~~*/ void AtCore::home() { pushCommand(GCode::toCommand(GCode::G28)); } void AtCore::home(uchar axis) { QString args; if (axis & AtCore::X) { args.append(QStringLiteral("X0 ")); } if (axis & AtCore::Y) { args.append(QStringLiteral("Y0 ")); } if (axis & AtCore::Z) { args.append(QStringLiteral("Z0")); } pushCommand(GCode::toCommand(GCode::G28, args)); } void AtCore::setExtruderTemp(uint temp, uint extruder, bool andWait) { if (andWait) { pushCommand(GCode::toCommand(GCode::M109, QString::number(temp), QString::number(extruder))); } else { pushCommand(GCode::toCommand(GCode::M104, QString::number(extruder), QString::number(temp))); } } void AtCore::setBedTemp(uint temp, bool andWait) { if (andWait) { pushCommand(GCode::toCommand(GCode::M190, QString::number(temp))); } else { pushCommand(GCode::toCommand(GCode::M140, QString::number(temp))); } } void AtCore::setFanSpeed(uint speed, uint fanNumber) { pushCommand(GCode::toCommand(GCode::M106, QString::number(fanNumber), QString::number(speed))); } void AtCore::setPrinterSpeed(uint speed) { pushCommand(GCode::toCommand(GCode::M220, QString::number(speed))); } void AtCore::setFlowRate(uint speed) { pushCommand(GCode::toCommand(GCode::M221, QString::number(speed))); } void AtCore::move(AtCore::AXES axis, int arg) { static QLatin1Char a('?'); switch (axis) { case AtCore::X: a = QLatin1Char('X'); break; case AtCore::Y: a = QLatin1Char('Y'); break; case AtCore::Z: a = QLatin1Char('Z'); break; case AtCore::E: a = QLatin1Char('E'); break; default: break; }; move(a, arg); } void AtCore::move(QLatin1Char axis, int arg) { pushCommand(GCode::toCommand(GCode::G1, QStringLiteral("%1 %2").arg(axis).arg(QString::number(arg)))); } int AtCore::extruderCount() const { return d->extruderCount; } void AtCore::setExtruderCount(int newCount) { if (d->extruderCount != newCount && newCount >= 1) { d->extruderCount = newCount; emit extruderCountChanged(newCount); qCDebug(ATCORE_CORE) << "Extruder Count:" << QString::number(extruderCount()); } } void AtCore::processQueue() { d->ready = true; if (d->commandQueue.isEmpty()) { return; } if (!serialInitialized()) { qCDebug(ATCORE_PLUGIN) << "Can't process queue ! Serial not initialized."; return; } QString text = d->commandQueue.takeAt(0); if (firmwarePluginLoaded()) { serial()->pushCommand(firmwarePlugin()->translate(text)); } else { serial()->pushCommand(text.toLocal8Bit()); } d->ready = false; } void AtCore::checkTemperature() { //One request for the temperature in the queue at a time. if (d->commandQueue.contains(GCode::toCommand(GCode::M105))) { return; } pushCommand(GCode::toCommand(GCode::M105)); } void AtCore::showMessage(const QString &message) { if (!message.isEmpty()) { pushCommand(GCode::toCommand((GCode::M117), message)); } } void AtCore::setUnits(AtCore::UNITS units) { switch (units) { case AtCore::METRIC: pushCommand(GCode::toCommand(GCode::G21)); break; case AtCore::IMPERIAL: pushCommand(GCode::toCommand(GCode::G20)); break; } } QStringList AtCore::portSpeeds() const { return serial()->validBaudRates(); } void AtCore::disableMotors(uint delay) { //Disables motors if (delay) { pushCommand(GCode::toCommand(GCode::M84, QString::number(delay))); } else { pushCommand(GCode::toCommand(GCode::M84)); } } //Most firmwares will not report if an sdcard is mounted on boot. bool AtCore::isSdMounted() const { return d->sdCardMounted; } void AtCore::setSdMounted(bool mounted) { if (mounted != isSdMounted()) { d->sdCardMounted = mounted; emit sdMountChanged(d->sdCardMounted); } } void AtCore::getSDFileList() { pushCommand(GCode::toCommand(GCode::M20)); } QStringList AtCore::sdFileList() { if (!d->sdCardReadingFileList) { getSDFileList(); } return d->sdCardFileList; } void AtCore::appendSdCardFileList(const QString &fileName) { d->sdCardFileList.append(fileName); emit sdCardFileListChanged(d->sdCardFileList); } void AtCore::clearSdCardFileList() { d->sdCardFileList.clear(); emit sdCardFileListChanged(d->sdCardFileList); } void AtCore::sdDelete(const QString &fileName) { if (d->sdCardFileList.contains(fileName)) { pushCommand(GCode::toCommand(GCode::M30, fileName)); getSDFileList(); } else { qCDebug(ATCORE_CORE) << "Delete failed file not found:" << fileName; } } void AtCore::mountSd(uint slot) { pushCommand(GCode::toCommand(GCode::M21, QString::number(slot))); } void AtCore::umountSd(uint slot) { pushCommand(GCode::toCommand(GCode::M22, QString::number(slot))); } bool AtCore::isReadingSdCardList() const { return d->sdCardReadingFileList; } void AtCore::setReadingSdCardList(bool readingList) { d->sdCardReadingFileList = readingList; } void AtCore::sdCardPrintStatus() { //One request for the Sd Job status in the queue at a time. if (d->commandQueue.contains(GCode::toCommand(GCode::M27))) { return; } pushCommand(GCode::toCommand(GCode::M27)); } diff --git a/src/core/atcore.h b/src/core/atcore.h index 1827bca..eebc9e9 100644 --- a/src/core/atcore.h +++ b/src/core/atcore.h @@ -1,579 +1,578 @@ /* AtCore Copyright (C) <2016> Authors: Tomaz Canabrava Chris Rizzitello Patrick José Pereira Lays Rodrigues This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #pragma once #include #include #include #include "ifirmware.h" #include "temperature.h" #include "atcore_export.h" class SerialLayer; class IFirmware; class QTime; -struct AtCorePrivate; - /** * @brief The AtCore class * aims to provides a high level interface for serial based gcode devices
* * #### General Workflow * - Connect to a serial port with initSerial() * - Firmware will be auto detected. Use loadFirmwarePLugin() to force load a firmware. * - Send commands to the device (pushCommand(),print(),...) * - AtCore::close() when you are all done. * #### How AtCore Finds Plugins. * AtCore will check each directory below for plugins. * 1. QApplication::applicationDirPath/plugins (runtime) * 2. QApplication::applicationDirPath/AtCore (runtime) * 3. QApplication::applicationDirPath/../PlugIns/AtCore (runtime) * 4. Fullpath of KDE_PLUGIN_DIR (buildtime) * 5. Qt Plugin path/AtCore (runtime) * 6. ECM set KDE PLUGIN DIR (buildtime) * 7. Build Dir/plugins (buildtime) */ class ATCORE_EXPORT AtCore : public QObject { Q_OBJECT Q_PROPERTY(QString version READ version) Q_PROPERTY(QStringList availableFirmwarePlugins READ availableFirmwarePlugins) Q_PROPERTY(int extruderCount READ extruderCount WRITE setExtruderCount NOTIFY extruderCountChanged) Q_PROPERTY(quint16 serialTimerInterval READ serialTimerInterval WRITE setSerialTimerInterval NOTIFY serialTimerIntervalChanged) Q_PROPERTY(QStringList serialPorts READ serialPorts NOTIFY portsChanged) Q_PROPERTY(float percentagePrinted READ percentagePrinted NOTIFY printProgressChanged) Q_PROPERTY(QStringList portSpeeds READ portSpeeds) Q_PROPERTY(QString connectedPort READ connectedPort) Q_PROPERTY(AtCore::STATES state READ state WRITE setState NOTIFY stateChanged) Q_PROPERTY(bool sdMount READ isSdMounted WRITE setSdMounted NOTIFY sdMountChanged) Q_PROPERTY(QStringList sdFileList READ sdFileList NOTIFY sdCardFileListChanged) friend class AtCoreTests; //Add friends as Sd Card support is extended to more plugins. friend class RepetierPlugin; friend class MarlinPlugin; //friend class SmoothiePlugin; //friend class TeacupPlugin; //friend class AprinterPlugin; //friend class SprinterPlugin; public: /** * @brief STATES enum Possible states the printer can be in */ enum STATES { DISCONNECTED, //!< Not Connected to a printer, initial state CONNECTING, //! * @param port: the port to initialize * @param baud: the baud of the port * @return True is connection was successful * @sa serialPorts(),serial(),closeConnection() */ Q_INVOKABLE bool initSerial(const QString &port, int baud); /** * @brief Returns a list of valid baud speeds */ QStringList portSpeeds() const; /** * @brief Main access to the serialLayer * @return Current serialLayer * @sa initSerial(),serialPorts(),closeConnection() */ SerialLayer *serial() const; /** * @brief Close the current serial connection * @sa initSerial(),serial(),serialPorts(),AtCore::close() */ Q_INVOKABLE void closeConnection(); /** * @brief Main access to the loaded firmware plugin * @return IFirmware * to currently loaded plugin * @sa availableFirmwarePlugins(),loadFirmwarePlugin() */ Q_INVOKABLE IFirmware *firmwarePlugin() const; /** * @brief List of available firmware plugins * @sa loadFirmwarePlugin(),firmwarePlugin() */ QStringList availableFirmwarePlugins() const; /** * @brief Load A firmware plugin * @param fwName : name of the firmware * @sa firmwarePlugin(),availableFirmwarePlugins() */ Q_INVOKABLE void loadFirmwarePlugin(const QString &fwName); /** * @brief Get Printer state * @return State of the printer * @sa setState(),stateChanged(),AtCore::STATES */ AtCore::STATES state(void); /** * @brief extruderCount * @return The number of detected Extruders Default is 1 * @sa setExtruderCount(int newCount), extruderCountChanged(int newCount) */ int extruderCount() const; /** * @brief Return printed percentage * @sa printProgressChanged() */ float percentagePrinted() const; /** * @brief The temperature of the current hotend as told by the Firmware. */ Temperature &temperature() const; /** * @brief Return the amount of miliseconds the serialTimer is set to. 0 = Disabled */ quint16 serialTimerInterval() const; /** * @brief Attempt to Mount an sd card * @param slot: Sd card Slot on machine (0 is default) */ Q_INVOKABLE void mountSd(uint slot = 0); /** * @brief Attempt to Unmount an sd card * @param slot: Sd card Slot on machine (0 is default) */ Q_INVOKABLE void umountSd(uint slot = 0); /** * @brief sdFileList * @return List of files on the sd card. */ QStringList sdFileList(); /** * @brief Check if an sd card is mounted on the printer * @return True if card mounted */ bool isSdMounted() const; signals: /** * @brief Message emit from atcore these should be displayed to the user for debug. * * Possable Messages Are: * - Waiting for firmware detect. * - No Plugin found for (detected FW) * - Failed to open device in Read / Write mode. * @param msg: the message. */ void atcoreMessage(const QString &msg); /** * @brief New number of extruders * @sa extruderCount(), setExtruderCount(int newCount) */ void extruderCountChanged(const int newCount); /** * @brief Print job's precentage changed. * @param newProgress : Message * @sa percentagePrinted() */ void printProgressChanged(const float &newProgress); /** * @brief New message was received from the printer * @param message: Message that was received */ void receivedMessage(const QByteArray &message); /** * @brief New interval between serial timer * @sa setSerialTimerInterval() */ void serialTimerIntervalChanged(const quint16 newTime); /** * @brief The Printer's State Changed * @param newState : the new state of the printer * @sa setState(),state(),AtCore::STATES */ void stateChanged(AtCore::STATES newState); /** * @brief Available serialports Changed */ void portsChanged(const QStringList &portList); /** * @brief Sd Card Mount Changed */ void sdMountChanged(bool newState); /** * @brief The files on the sd card have changed. */ void sdCardFileListChanged(const QStringList &fileList); public slots: /** * @brief Set the printers state * @param state : printer state. * @sa state(),stateChanged(),AtCore::STATES */ void setState(AtCore::STATES state); /** * @brief Push a command into the command queue * * @param comm : Command */ Q_INVOKABLE void pushCommand(const QString &comm); /** * @brief Public Interface for printing a file * @param fileName: the gcode file to print. * @param sdPrint: set true to print fileName from Sd card */ Q_INVOKABLE void print(const QString &fileName, bool sdPrint = false); /** * @brief Stop the Printer by empting the queue and aborting the print job (if running) * @sa emergencyStop(),pause(),resume() */ Q_INVOKABLE void stop(); /** * @brief stop the printer via the emergency stop Command (M112) * @sa stop(),pause(),resume() */ Q_INVOKABLE void emergencyStop(); /** * @brief pause an in process print job * * Sends M114 on pause to store the location where the head stoped. * This is known to cause problems on fake printers * @param pauseActions: Gcode to run after pausing commands are ',' separated * @sa resume(),stop(),emergencyStop() */ void pause(const QString &pauseActions); /** * @brief resume a paused print job. * After returning to location pause was triggered. * @sa pause(),stop(),emergencyStop() */ Q_INVOKABLE void resume(); /** * @brief Send home \p axis command * @param axis: the axis(es) to home (use X Y Z or any combo of) * @sa home(), move() */ Q_INVOKABLE void home(uchar axis); /** * @brief Send home all command * @sa home(uchar axis), move() */ Q_INVOKABLE void home(); /** * @brief Set extruder temperature * @param temp : new temperature * @param extruder : extruder number * @param andWait: True for heat and ignore commands until temperature is reached */ Q_INVOKABLE void setExtruderTemp(uint temp = 0, uint extruder = 0, bool andWait = false); /** * @brief move an axis of the printer * @param axis the axis to move AXES (X Y Z E ) * @param arg the distance to move the axis or the place to move to depending on printer mode * @sa home(), home(uchar axis), move(QLatin1Char axis, int arg) */ Q_INVOKABLE void move(AtCore::AXES axis, int arg); /** * @brief move an axis of the printer * @param axis the axis to move AXES (X Y Z E ) * @param arg the distance to move the axis or the place to move to depending on printer mode * @sa home(), home(uchar axis), move(AtCore::AXES, int arg) */ Q_INVOKABLE void move(QLatin1Char axis, int arg); /** * @brief Set the bed temperature * @param temp : new temperature * @param andWait: True for heat and ignore commands until temperature is reached * @sa setExtruderTemp() */ Q_INVOKABLE void setBedTemp(uint temp = 0, bool andWait = false); /** * @brief setFanSpeed set the fan speed * @param fanNumber: fan number * @param speed: new speed of the fan 0-100 */ Q_INVOKABLE void setFanSpeed(uint speed = 0, uint fanNumber = 0); /** * @brief Set printer to absolute position mode * @sa setRelativePosition() */ Q_INVOKABLE void setAbsolutePosition(); /** * @brief Set printer to relative position mode * @sa setAbsolutePosition() */ Q_INVOKABLE void setRelativePosition(); /** * @brief Disable motors after a delay * @param delay: Seconds until motors are disabled. 0= No delay */ Q_INVOKABLE void disableMotors(uint delay = 0); /** * @brief set the Printers speed * @param speed: speed in % (default is 100); */ Q_INVOKABLE void setPrinterSpeed(uint speed = 100); /** * @brief set extruder Flow rate * @param rate: flow rate in % (default is 100) */ Q_INVOKABLE void setFlowRate(uint rate = 100); /** * @brief close any open items. * You should call this on close events to force any stuck jobs to close * @sa closeConnection() */ Q_INVOKABLE void close(); /** * @brief showMessage push a message to the printers LCD * @param message: message to show on the LCD */ Q_INVOKABLE void showMessage(const QString &message); /** * @brief setUnits sets the measurement units do be used * @param units : the measurement units to use(METRIC / IMPERIAL) * @sa AtCore::UNITS */ Q_INVOKABLE void setUnits(AtCore::UNITS units); /** * @brief Set the time between checks for new serialPorts (0 is default) * @param newTime: Milliseconds between checks. 0 will Disable Checks. */ void setSerialTimerInterval(const quint16 &newTime); /** * @brief delete file from sd card */ Q_INVOKABLE void sdDelete(const QString &fileName); /** * @brief Queue the Printer for status of sd card print */ void sdCardPrintStatus(); private slots: /** * @brief processQueue send commands from the queue. */ void processQueue(); /** * @brief Send M105 to the printer if one is not in the Queue */ void checkTemperature(); /** * @brief Connect to SerialLayer::receivedCommand * @param message: new message. */ void newMessage(const QByteArray &message); /** * @brief Search for firmware string in message. * A Helper function for Firmware detection * @param message */ void findFirmware(const QByteArray &message); /** * @brief Search for new serial ports */ void locateSerialPort(); /** * @brief Send request to the printer for the sd card file list. */ void getSDFileList(); private: /** * @brief True if a firmware plugin is loaded */ bool firmwarePluginLoaded() const; /** * @brief True if a serial port is initialized */ bool serialInitialized() const; /** * @brief send firmware request to the printer */ void requestFirmware(); /** * @brief Search for atcore firmware plugins * @param path: the path to check * @return QMap of the plugings found */ QMap findFirmwarePlugins(const QString &path); /** * @brief returns AtCorePrivate::sdCardReadingFileList * @return True if printer is returning sd card file list */ bool isReadingSdCardList() const; /** * @brief stops print just for sd prints used internally * @sa stop(),emergencyStop() */ void stopSdPrint(); /** * @brief Hold private data of AtCore. */ + struct AtCorePrivate; AtCorePrivate *d; protected: /** * @brief Set the number of extruders on the machine. * @param newCount * @sa extruderCount(), extruderCountChanged(int newCount) */ void setExtruderCount(int newCount); /** * @brief Append a file to AtCorePrivate::sdCardFileList. * @param fileName: new FileName */ void appendSdCardFileList(const QString &fileName); /** * @brief Clear AtCorePrivate::sdCardFileList. */ void clearSdCardFileList(); /** * @brief Set if the sd card is mounted by the printer * @param mounted: True is mounted */ void setSdMounted(const bool mounted); /** * @brief set AtCorePrivate::sdCardReadingFileList * @param readingList set true if reading file list */ void setReadingSdCardList(bool readingList); }; diff --git a/src/core/ifirmware.cpp b/src/core/ifirmware.cpp index 17c4333..6625947 100644 --- a/src/core/ifirmware.cpp +++ b/src/core/ifirmware.cpp @@ -1,76 +1,76 @@ /* AtCore Copyright (C) <2016> Authors: Tomaz Canabrava Patrick José Pereira This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "ifirmware.h" #include "atcore.h" /** * @brief The IFirmwarePrivate struct * @param parent: parent of this object */ -struct IFirmwarePrivate { +struct IFirmware::IFirmwarePrivate { AtCore *parent; /** * @brief command finished string */ static const QString _ok; }; -const QString IFirmwarePrivate::_ok = QStringLiteral("ok"); +const QString IFirmware::IFirmwarePrivate::_ok = QStringLiteral("ok"); IFirmware::IFirmware() : d(new IFirmwarePrivate) { } void IFirmware::init(AtCore *parent) { d->parent = parent; connect(d->parent, &AtCore::receivedMessage, this, &IFirmware::checkCommand); } AtCore *IFirmware::core() const { return d->parent; } IFirmware::~IFirmware() { } void IFirmware::checkCommand(const QByteArray &lastMessage) { validateCommand(QString::fromLatin1(lastMessage)); } void IFirmware::validateCommand(const QString &lastMessage) { if (lastMessage.contains(d->_ok)) { emit readyForCommand(); } } QByteArray IFirmware::translate(const QString &command) { return command.toLocal8Bit(); } diff --git a/src/core/ifirmware.h b/src/core/ifirmware.h index 51831b1..85a9f52 100644 --- a/src/core/ifirmware.h +++ b/src/core/ifirmware.h @@ -1,99 +1,99 @@ /* AtCore Copyright (C) <2016> Authors: Tomaz Canabrava Chris Rizzitello Patrick José Pereira This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #pragma once #include #include #include "atcore_export.h" class Temperature; class AtCore; -struct IFirmwarePrivate; /** * @brief The IFirmware class * Base Class for Firmware Plugins */ class ATCORE_EXPORT IFirmware : public QObject { Q_OBJECT Q_PROPERTY(QString name READ name) Q_PROPERTY(bool sdSupport READ isSdSupported) public: IFirmware(); void init(AtCore *parent); ~IFirmware() override; /** * @brief Check for plugin support of sd cards. * @return True if firmware plugin supports sd cards. */ virtual bool isSdSupported() const = 0; /** * @brief Virtual name to be reimplemnted by Firmware plugin * * Return the name the firmware the plugin is for * @return Firmware Name */ virtual QString name() const = 0; /** * @brief Vitural validateCommand to filter commands from messages * @param lastMessage: last Message from printer */ virtual void validateCommand(const QString &lastMessage); /** * @brief Virtual translate to be reimplemnted by Firmwareplugin * * Translate common commands to firmware specific command. * @param command: Command command to translate * @return firmware specific translated command */ virtual QByteArray translate(const QString &command); /** * @brief AtCore Parent of the firmware plugin * @return */ AtCore *core() const; private: + struct IFirmwarePrivate; IFirmwarePrivate *d; public slots: /** * @brief call Validate Command * @param lastMessage: last message from printer */ void checkCommand(const QByteArray &lastMessage); signals: /** * @brief emit when firmware is ready for a command */ void readyForCommand(void); }; Q_DECLARE_INTERFACE(IFirmware, "org.kde.atelier.core.firmware") diff --git a/src/core/printthread.cpp b/src/core/printthread.cpp index f04c402..156a396 100644 --- a/src/core/printthread.cpp +++ b/src/core/printthread.cpp @@ -1,229 +1,229 @@ /* AtCore Copyright (C) <2017> Authors: Chris Rizzitello This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include #include #include #include #include #include "printthread.h" Q_LOGGING_CATEGORY(PRINT_THREAD, "org.kde.atelier.core.printThread") /** * @brief The PrintThreadPrivate class */ -class PrintThreadPrivate +class PrintThread::PrintThreadPrivate { public: AtCore *core = nullptr; //!<@param core: Pointer to AtCore QTextStream *gcodestream = nullptr; //!<@param gcodestream: Steam the job is read from float printProgress = 0; //!<@param printProgress: Progress of the print job qint64 totalSize = 0; //!<@param totalSize: total file size qint64 stillSize = 0; //!<@param stillSize: remaining file QString cline; //!<@param cline: current line AtCore::STATES state = AtCore::IDLE;//!<@param state: printer state QFile *file = nullptr; //!<@param file: gcode File to stream from QList options = { {QCommandLineOption(QStringLiteral("pause"))}, {QCommandLineOption(QStringLiteral("extruder temperature"))}, {QCommandLineOption(QStringLiteral("bed temperature"))}, {QCommandLineOption(QStringLiteral("print speed"))}, {QCommandLineOption(QStringLiteral("fan speed"))}, {QCommandLineOption(QStringLiteral("flow rate"))}, {QCommandLineOption(QStringLiteral("message"))}, {QCommandLineOption(QStringLiteral("command"))} }; //!<@param options: injectable commands. }; PrintThread::PrintThread(AtCore *parent, QString fileName) : d(new PrintThreadPrivate) { d->core = parent; d->state = d->core->state(); d->file = new QFile(fileName); d->file->open(QFile::ReadOnly); d->totalSize = d->file->bytesAvailable(); d->stillSize = d->totalSize; d->gcodestream = new QTextStream(d->file); } void PrintThread::start() { // we only want to do this when printing connect(d->core->firmwarePlugin(), &IFirmware::readyForCommand, this, &PrintThread::processJob, Qt::QueuedConnection); connect(this, &PrintThread::nextCommand, d->core, &AtCore::pushCommand, Qt::QueuedConnection); connect(this, &PrintThread::stateChanged, d->core, &AtCore::setState, Qt::QueuedConnection); connect(d->core, &AtCore::stateChanged, this, &PrintThread::setState, Qt::QueuedConnection); connect(this, &PrintThread::finished, this, &PrintThread::deleteLater); // force a command if the printer doesn't send "wait" when idle processJob(); } void PrintThread::processJob() { if (d->gcodestream->atEnd()) { endPrint(); } switch (d->state) { case AtCore::STARTPRINT: case AtCore::IDLE: case AtCore::BUSY: setState(AtCore::BUSY); nextLine(); while (d->cline.isEmpty() && !d->gcodestream->atEnd()) { nextLine(); } if (!d->cline.isEmpty() && d->core->state() != AtCore::PAUSE) { qCDebug(PRINT_THREAD) << "cline:" << d->cline; emit nextCommand(d->cline); } break; case AtCore::ERRORSTATE: qCDebug(PRINT_THREAD) << "Error State"; break; case AtCore::STOP: { endPrint(); break; } case AtCore::PAUSE: if (d->cline.startsWith(QStringLiteral(";-"))) { nextLine(); } break; default: qCDebug(PRINT_THREAD) << "Unknown State"; break; } } void PrintThread::endPrint() { emit printProgressChanged(100); qCDebug(PRINT_THREAD) << "atEnd"; disconnect(d->core->firmwarePlugin(), &IFirmware::readyForCommand, this, &PrintThread::processJob); disconnect(this, &PrintThread::nextCommand, d->core, &AtCore::pushCommand); disconnect(d->core, &AtCore::stateChanged, this, &PrintThread::setState); emit stateChanged(AtCore::FINISHEDPRINT); emit stateChanged(AtCore::IDLE); disconnect(this, &PrintThread::stateChanged, d->core, &AtCore::setState); emit finished(); } void PrintThread::nextLine() { d->cline = d->gcodestream->readLine(); qCDebug(PRINT_THREAD) << "Nextline:" << d->cline; d->stillSize -= d->cline.size() + 1; //remove read chars d->printProgress = float(d->totalSize - d->stillSize) * 100.0 / float(d->totalSize); qCDebug(PRINT_THREAD) << "progress:" << QString::number(d->printProgress); emit printProgressChanged(d->printProgress); if (d->cline.startsWith(QStringLiteral(";-"))) { injectCommand(d->cline); d->cline = QStringLiteral(""); return; } //Remove Comments from the gcode. //Type 1: Anything after ; is comment. //Example G28 Z; Home Axis Z if (d->cline.contains(QChar::fromLatin1(';'))) { d->cline.resize(d->cline.indexOf(QChar::fromLatin1(';'))); } //Type 2: Block Type anything between ( and ) is a comment // Example G28 (Home)Z if (d->cline.contains(QChar::fromLatin1('('))) { //Remove (.....) from the line d->cline.remove(QRegularExpression(QStringLiteral(".(?<=[(])(.*)(?=[)])."))); } d->cline = d->cline.simplified(); } void PrintThread::setState(const AtCore::STATES &newState) { if (d->state == AtCore::STATES::DISCONNECTED && ( newState == AtCore::STATES::PAUSE || newState == AtCore::STATES::STOP ) ) { qCDebug(PRINT_THREAD) << "Serial not connected !"; return; } if (newState != d->state) { qCDebug(PRINT_THREAD) << QStringLiteral("State changed from [%1] to [%2]") .arg(QVariant::fromValue(d->state).value(), QVariant::fromValue(newState).value()); disconnect(d->core, &AtCore::stateChanged, this, &PrintThread::setState); d->state = newState; emit stateChanged(d->state); connect(d->core, &AtCore::stateChanged, this, &PrintThread::setState, Qt::QueuedConnection); } } void PrintThread::injectCommand(QString &command) { //remove the ; command.remove(0, 1); command.prepend(QStringLiteral("0:")); QStringList cmd = command.split(QLatin1Char(':')); cmd.replace(1, cmd.at(1).simplified().toLower()); cmd.replace(2, cmd.at(2).simplified()); static QCommandLineParser parser; if (parser.optionNames().isEmpty()) { parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions); parser.addOptions(d->options); } qCDebug(PRINT_THREAD) << "attempting to inject " << cmd; parser.process(cmd); if (parser.isSet(QStringLiteral("pause"))) { d->core->pause(parser.positionalArguments().at(0)); } else if (parser.isSet(QStringLiteral("extruder temperature"))) { QStringList args = parser.positionalArguments().at(0).split(QLatin1Char(',')); bool wait = !QString::compare(args.at(2).simplified(), QStringLiteral("true"), Qt::CaseInsensitive); d->core->setExtruderTemp(args.at(0).toInt(), args.at(1).toInt(), wait); } else if (parser.isSet(QStringLiteral("bed temperature"))) { QStringList args = parser.positionalArguments().at(0).split(QLatin1Char(',')); bool wait = !QString::compare(args.at(1).simplified(), QStringLiteral("true"), Qt::CaseInsensitive); d->core->setBedTemp(args.at(0).toInt(), wait); } else if (parser.isSet(QStringLiteral("print speed"))) { d->core->setPrinterSpeed(parser.positionalArguments().at(0).toInt()); } else if (parser.isSet(QStringLiteral("fan speed"))) { d->core->setFanSpeed(parser.positionalArguments().at(0).toInt(), parser.positionalArguments().at(1).toInt()); } else if (parser.isSet(QStringLiteral("flow rate"))) { d->core->setFlowRate(parser.positionalArguments().at(0).toInt()); } else if (parser.isSet(QStringLiteral("message"))) { d->core->showMessage(parser.positionalArguments().at(0)); } else if (parser.isSet(QStringLiteral("command"))) { d->core->pushCommand(parser.positionalArguments().at(0)); } else { qCDebug(PRINT_THREAD) << "Attempted to inject unknown command: " << parser.positionalArguments(); } } diff --git a/src/core/printthread.h b/src/core/printthread.h index 82bbfc0..ce2beb9 100644 --- a/src/core/printthread.h +++ b/src/core/printthread.h @@ -1,153 +1,153 @@ /* AtCore Copyright (C) <2017> Authors: Chris Rizzitello This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #pragma once #include #include #include "atcore.h" -class PrintThreadPrivate; /** * @brief The PrintThread class * A Thread for running a print job * * see AtCore::print() for example of how to create a print thread. * */ class ATCORE_EXPORT PrintThread : public QObject { Q_OBJECT public: /** * @brief Create a new Print Thread * @param parent: Parent of the tread * @param fileName: gcode File to print */ PrintThread(AtCore *parent, QString fileName); signals: /** * @brief Print job has finished */ void finished(); /** * @brief A command has caused an error * @param err: the offending command */ void error(QString err); /** * @brief The print job's progress has changed */ void printProgressChanged(float); /** * @brief the next command of the job * @param comm: Command to be sent next */ void nextCommand(const QString &comm); /** * @brief Printer state was changed * @param state: new state */ void stateChanged(const AtCore::STATES &state); public slots: /** * @brief start the print thread */ void start(); private slots: /** * @brief process the current job */ void processJob(); /** * @brief Set printer state * @param state: the new printer state */ void setState(const AtCore::STATES &state); private: /** * @brief parse the next line */ void nextLine(); /** * @brief end the print */ void endPrint(); /** * @brief injectCommand Attempt to inject a Command from the currently printing file. * * One of the following on a line that starts with ';-' \n * example line ;-Message: Hello \n * * - Pause: ppc\n * Pause the print job and then run the comma seperated commands after pausing the job.\n * + ppc: A comma seperated list of Commands to send after pause. ex(G91, G0 Z1, G90, G1 X0 Y195)\n *\n * - Extruder %Temperature:newTemp,extnum,wait \n * Set extruder temperature. \n * + newTemp: new target temperature. \n * + extnum: Extruder number you want to Heat. Starting at 0. \n * + wait: ignore commands until the target is reached. [true | false] \n *\n * - Bed %Temperature: newTemp,wait \n * Set the bed temperature. \n * + newTemp: new target temperature \n * + wait: ignore commands until the target is reached. [true | false] \n *\n * - Fan Speed:newSpeed, fanNum \n * Set the Fan speed. \n * + newSpeed: new fan speed. \n * + fanNum: Fan number. Starting at 0.\n *\n * - Print Speed:newSpeed \n * Set the printer speed. \n * + newSpeed: the print speed. 100= movement speed defined in file. \n *\n * - Flow Rate:newRate \n * Set the flow rate \n * + newRate: the flow rate. 100 = flow rate defined in file. \n *\n * - Message:message \n * Show a message the printer's LCD \n * + message: the message to print. \n *\n * - Command:command \n * Inject your own command. Command are sent as is. Be sure your line is correct. \n * + command: Commands to inject \n */ void injectCommand(QString &command); /** * @brief d: Private storage for the thread */ + class PrintThreadPrivate; PrintThreadPrivate *d; }; diff --git a/src/core/seriallayer.cpp b/src/core/seriallayer.cpp index f0c4273..38a212a 100644 --- a/src/core/seriallayer.cpp +++ b/src/core/seriallayer.cpp @@ -1,147 +1,147 @@ /* AtCore Copyright (C) <2016> Authors: Patrick José Pereira Chris Rizzitello Tomaz Canabrava This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include #include "seriallayer.h" Q_LOGGING_CATEGORY(SERIAL_LAYER, "org.kde.atelier.core.serialLayer") namespace { QByteArray _return = QByteArray("\r"); QByteArray _newLine = QByteArray("\n"); QByteArray _newLineReturn = QByteArray("\n\r"); QStringList _validBaudRates = { QStringLiteral("9600"), QStringLiteral("14400"), QStringLiteral("19200"), QStringLiteral("28800"), QStringLiteral("38400"), QStringLiteral("57600"), QStringLiteral("76800"), QStringLiteral("115200"), QStringLiteral("230400"), QStringLiteral("250000"), QStringLiteral("500000"), QStringLiteral("1000000") }; } /** * @brief The SerialLayerPrivate class */ -class SerialLayerPrivate +class SerialLayer::SerialLayerPrivate { public: bool _serialOpened; //!< @param _serialOpened: is serial port opened QByteArray _rawData; //!< @param _rawData: the raw serial data QVector _rByteCommands; //!< @param _rByteCommand: received Messages QVector _sByteCommands; //!< @param _sByteCommand: sent Messages }; SerialLayer::SerialLayer(const QString &port, uint baud, QObject *parent) : QSerialPort(parent), d(new SerialLayerPrivate()) { setPortName(port); setBaudRate(baud); if (open(QIODevice::ReadWrite)) { d->_serialOpened = true; connect(this, &QSerialPort::readyRead, this, &SerialLayer::readAllData); } }; void SerialLayer::readAllData() { d->_rawData.append(readAll()); //Remove any \r in the string, then split by \n. //This removes any trailing \r or \n from the commands // Proper line endings are added when the command is pushed. d->_rawData = d->_rawData.replace(_return, QByteArray()); QList tempList = d->_rawData.split(_newLine.at(0)); for (auto i = tempList.begin(); i != tempList.end(); ++i) { // Get finished line to _byteCommands if (i < tempList.end() - 1) { d->_rByteCommands.append(*i); emit receivedCommand(*i); } else { d->_rawData.clear(); d->_rawData.append(*i); } } } void SerialLayer::pushCommand(const QByteArray &comm, const QByteArray &term) { if (!isOpen()) { qCDebug(SERIAL_LAYER) << "Serial not connected !"; return; } QByteArray tmp = comm + term; write(tmp); emit pushedCommand(tmp); } void SerialLayer::pushCommand(const QByteArray &comm) { pushCommand(comm, _newLineReturn); } void SerialLayer::add(const QByteArray &comm, const QByteArray &term) { QByteArray tmp = comm + term; d->_sByteCommands.append(tmp); } void SerialLayer::add(const QByteArray &comm) { add(comm, _newLineReturn); } void SerialLayer::push() { if (!isOpen()) { qCDebug(SERIAL_LAYER) << "Serial not connected !"; return; } for (const auto &comm : qAsConst(d->_sByteCommands)) { write(comm); emit pushedCommand(comm); } d->_sByteCommands.clear(); } bool SerialLayer::commandAvailable() const { return !d->_rByteCommands.isEmpty(); } QStringList SerialLayer::validBaudRates() const { return _validBaudRates; } diff --git a/src/core/seriallayer.h b/src/core/seriallayer.h index d699b87..0386804 100644 --- a/src/core/seriallayer.h +++ b/src/core/seriallayer.h @@ -1,124 +1,124 @@ /* AtCore Copyright (C) <2016> Authors: Patrick José Pereira Chris Rizzitello Tomaz Canabrava This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #pragma once #include #include #include "atcore_export.h" -class SerialLayerPrivate; /** * @brief The SerialLayer class. * Provide the low level serial operations */ class ATCORE_EXPORT SerialLayer : public QSerialPort { Q_OBJECT private: + class SerialLayerPrivate; SerialLayerPrivate *d; /** * @brief Read all available serial data * */ void readAllData(); signals: /** * @brief Emit signal when command is pushed * * @param comm : Command */ void pushedCommand(const QByteArray &comm); /** * @brief Emit signal when command is received * * @param comm : Command */ void receivedCommand(const QByteArray &comm); public: /** * @brief SerialLayer Class to realize communication * * @param port : Port (/dev/ttyUSB ACM) * @param baud : Baud rate (115200) * @param parent : Parent */ SerialLayer(const QString &port, uint baud, QObject *parent = nullptr); /** * @brief Add command to be pushed * * @param comm : Command * @param term : Terminator */ void add(const QByteArray &comm, const QByteArray &term); /** * @brief Add command to be pushed * * @param comm : Command, default terminator will be used */ void add(const QByteArray &comm); /** * @brief Push command directly * * @param comm : Command * @param term : Terminator */ void pushCommand(const QByteArray &comm, const QByteArray &term); /** * @brief Push command directly * * @param comm : Command, default terminator will be used */ void pushCommand(const QByteArray &comm); /** * @brief Push all commands used in add to serial write * */ void push(); /** * @brief Check if is a command available * * @return bool */ bool commandAvailable() const; /** * @brief Return a QStringList of valids serial baud rates * * @return QStringList */ QStringList validBaudRates() const; }; diff --git a/src/core/temperature.cpp b/src/core/temperature.cpp index f0a631c..33cfdb5 100644 --- a/src/core/temperature.cpp +++ b/src/core/temperature.cpp @@ -1,137 +1,137 @@ /* AtCore Copyright (C) <2016> Authors: Tomaz Canabrava Patrick José Pereira Chris Rizzitello This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include #include #include "temperature.h" /** * @brief The TemperaturePrivate class * * Private Data of Temperature */ -class TemperaturePrivate +class Temperature::TemperaturePrivate { public: float extruderTemp; //!< @param extruderTemp: Extruder current temperature float extruderTargetTemp; //!< @param extruderTargetTemp: Extruder target temperature float bedTemp; //!< @param bedTemp: Bed current temperature float bedTargetTemp; //!< @param bedTargetTemp: Bed target temperature }; Temperature::Temperature(QObject *parent) : QObject(parent) , d(new TemperaturePrivate) { } float Temperature::bedTargetTemperature() const { return d->bedTargetTemp; } float Temperature::bedTemperature() const { return d->bedTemp; } float Temperature::extruderTargetTemperature() const { return d->extruderTargetTemp; } float Temperature::extruderTemperature() const { return d->extruderTemp; } void Temperature::setBedTargetTemperature(float temp) { d->bedTargetTemp = temp; emit bedTargetTemperatureChanged(temp); } void Temperature::setBedTemperature(float temp) { d->bedTemp = temp; emit bedTemperatureChanged(temp); } void Temperature::setExtruderTargetTemperature(float temp) { d->extruderTargetTemp = temp; emit extruderTargetTemperatureChanged(temp); } void Temperature::setExtruderTemperature(float temp) { d->extruderTemp = temp; emit extruderTemperatureChanged(temp); } void Temperature::decodeTemp(const QByteArray &msg) { int bloc = msg.indexOf(QStringLiteral("B:")); float firstTargetTemperature = 0; float secondTargetTemperature = 0; QRegularExpression tempRegEx(QStringLiteral("(T:(?\\d+\\.?\\d*))")); QRegularExpression targetTempRegEx(QStringLiteral("(\\/)(?\\d*)(.+)")); QRegularExpressionMatch tempCheck = tempRegEx.match(QString::fromLatin1(msg)); QRegularExpressionMatch targetTempCheck = targetTempRegEx.match(QString::fromLatin1(msg)); if (tempCheck.hasMatch()) { setExtruderTemperature(tempCheck.captured(QStringLiteral("extruder")).toFloat()); } if (targetTempCheck.hasMatch()) { firstTargetTemperature = targetTempCheck.captured(QStringLiteral("extruderTarget")).toFloat(); } if (bloc != -1) { QRegularExpression bedRegEx(QStringLiteral("(B:(?\\d+\\.?\\d*))")); QRegularExpressionMatch bedCheck = bedRegEx.match(QString::fromLatin1(msg)); QRegularExpression targetBedRegEx(QStringLiteral("B:(.+)(\\/)(?\\d+)")); QRegularExpressionMatch targetBedCheck = targetBedRegEx.match(QString::fromLatin1(msg)); if (bedCheck.hasMatch()) { setBedTemperature(bedCheck.captured(QStringLiteral("bed")).toFloat()); } if (targetBedCheck.hasMatch()) { secondTargetTemperature = targetBedCheck.captured(QStringLiteral("bedTarget")).toFloat(); } } //Currently the first value after / is stored in firstTargetTemperature and the second / in secondTargetTemperature //Because of this we need to check what came first in the return and place the values //The regex for temperature needs to look at the whole T: or B: block to correctly decode targets if (bloc < msg.indexOf(QStringLiteral("T:")) && bloc != -1) { setExtruderTargetTemperature(secondTargetTemperature); setBedTargetTemperature(firstTargetTemperature); } else { setExtruderTargetTemperature(firstTargetTemperature); setBedTargetTemperature(secondTargetTemperature); } } diff --git a/src/core/temperature.h b/src/core/temperature.h index c37ad24..1ca7aff 100644 --- a/src/core/temperature.h +++ b/src/core/temperature.h @@ -1,129 +1,129 @@ /* AtCore Copyright (C) <2016> Authors: Tomaz Canabrava Patrick José Pereira This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #pragma once #include #include "atcore_export.h" -class TemperaturePrivate; /** * @brief The Temperature class * * Read and hold the Temperature info for the printer */ class ATCORE_EXPORT Temperature : public QObject { Q_OBJECT Q_PROPERTY(float bedTemperature READ bedTemperature WRITE setBedTemperature NOTIFY bedTemperatureChanged) Q_PROPERTY(float bedTargetTemperature READ bedTargetTemperature WRITE setBedTargetTemperature NOTIFY bedTargetTemperatureChanged) Q_PROPERTY(float extruderTemperature READ extruderTemperature WRITE setExtruderTemperature NOTIFY extruderTemperatureChanged) Q_PROPERTY(float extruderTargetTemperature READ extruderTargetTemperature WRITE setExtruderTargetTemperature NOTIFY extruderTargetTemperatureChanged) public: /** * @brief Create a new Temperature object * @param parent */ explicit Temperature(QObject *parent = nullptr); /** * @brief Get bed current temperature */ float bedTemperature() const; /** * @brief Get bed target temperature */ float bedTargetTemperature() const; /** * @brief Get extruder temperature */ float extruderTemperature() const; /** * @brief Get extruder target temperature */ float extruderTargetTemperature() const; /** * @brief decode Temp values from string \p msg * @param msg: string to read vaules from */ void decodeTemp(const QByteArray &msg); public slots: /** * @brief Set bed temperature * @param temp: bed temperature */ void setBedTemperature(float temp); /** * @brief Set bed target temperature * @param temp: bed target temperature */ void setBedTargetTemperature(float temp); /** * @brief Set exturder temperature * @param temp: bed temperature */ void setExtruderTemperature(float temp); /** * @brief Set extruder target temperature * @param temp: extruder target temperature */ void setExtruderTargetTemperature(float temp); signals: /** * @brief bed temperature has changed * @param temp : new bed temperature */ void bedTemperatureChanged(float temp); /** * @brief bed target temperature has changed * @param temp : new bed target temperature */ void bedTargetTemperatureChanged(float temp); /** * @brief extruder temperature has changed * @param temp : new extruder temperature */ void extruderTemperatureChanged(float temp); /** * @brief extruder target temperature has changed * @param temp : new extruder target temperature */ void extruderTargetTemperatureChanged(float temp); private: + class TemperaturePrivate; TemperaturePrivate *d; };