diff --git a/doc/mainpage.md b/doc/mainpage.md index cc2990a..0db1146 100644 --- a/doc/mainpage.md +++ b/doc/mainpage.md @@ -1,52 +1,52 @@ # %AtCore %AtCore is a API to manage the serial connection between the computer and 3D Printers. This project is under [LGPL-2.0]+. %AtCore is written by [KDE] members, - Chris Rizzitello - Patrick José Pereira - - Lays Rodrigues
+ - Lays Rodrigues
- Tomaz Canabrava ## Supported Firmwares Currenty the following firmwares are supported. Firmware Name |Basic Use| Control SD :------------:|:-------:|:----------: Repetier | YES | YES Marlin | YES | YES Teacup | YES | NO APrinter | YES | NO SPrinter | YES | NO Smoothie | YES | NO GRBL | YES | NO ## Building Deploying %AtCore See: [Building and Deploying] ## Importing %AtCore in your CMakeList CMake should find %AtCore using the following in your CMakeLists ```CMake include (AtCore REQUIRED COMPONATES AtCore ) ``` ## Getting Involved - [IRC] - freenode \#kde-atelier - [Telegram] - Atelier group - [Web] - Our web page - Report Bugs to our [Bug Tracker]. - Support us by making a [Donation] - [Contribute] to %AtCore. [IRC]: https://webchat.freenode.net/ [Telegram]: telegram.me/KDEAtelier [Bug Tracker]: https://bugs.kde.org/enter_bug.cgi?product=Atelier&component=AtCore [KDE]:https://www.kde.org [Web]: https://atelier.kde.org [LGPL-2.0]:https://www.gnu.org/licenses/old-licenses/lgpl-2.0.html [Building and Deploying]:build.md [Contribute]:contrib.md [Donation]:https://kde.org/donate/?app=atcore diff --git a/src/atcore.cpp b/src/atcore.cpp index 6738e2b..c66c077 100644 --- a/src/atcore.cpp +++ b/src/atcore.cpp @@ -1,756 +1,772 @@ /* 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 { IFirmware *firmwarePlugin = nullptr;//!< @param firmwarePlugin: pointer to firmware plugin SerialLayer *serial = nullptr; //!< @param serial: pointer to the serial layer QPluginLoader pluginLoader; //!< @param pluginLoader: QPluginLoader QDir pluginsDir; //!< @param pluginsDir: Directory where plugins were found 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 -//For Windows and Mac we always look in plugins folder of the program using atcore. -//On others we use AtCoreDirectories::pluginDir to hold a list of dirs to check + //Attempt to find our plugins + //For Windows and Mac we always look in plugins folder of the program using atcore. + //On others we use AtCoreDirectories::pluginDir to hold a list of dirs to check #if defined(Q_OS_WIN) || defined(Q_OS_MAC) d->pluginsDir = qApp->applicationDirPath() + QStringLiteral("/plugins"); #else for (const auto &path : AtCoreDirectories::pluginDir) { qCDebug(ATCORE_PLUGIN) << "Lookin for plugins in " << path; if (QDir(path).exists()) { d->pluginsDir = QDir(path); qCDebug(ATCORE_PLUGIN) << "Valid path for plugins found !"; break; } } #endif if (!d->pluginsDir.exists()) { qCritical() << "No valid path for plugin !"; } qCDebug(ATCORE_PLUGIN) << d->pluginsDir; findFirmwarePlugins(); 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) { qWarning() << "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) << "Find Firmware Called" << 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 d->extruderCount = message.at(message.indexOf("EXTRUDER_COUNT:") + 15) - '0'; } qCDebug(ATCORE_CORE) << "Extruder Count:" << QString::number(extruderCount()); loadFirmwarePlugin(fwName); } void AtCore::loadFirmwarePlugin(const QString &fwName) { + qCDebug(ATCORE_PLUGIN) << "Looking for Plugin:" << 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_PLUGIN) << "Plugin Loading: Failed."; qCDebug(ATCORE_PLUGIN) << d->pluginLoader.errorString(); - } else { - qCDebug(ATCORE_PLUGIN) << "Loading plugin."; - } - d->firmwarePlugin = qobject_cast(d->pluginLoader.instance()); - - if (!firmwarePluginLoaded()) { - qCDebug(ATCORE_PLUGIN) << "No plugin loaded."; - qCDebug(ATCORE_PLUGIN) << "Looking plugin in folder:" << d->pluginsDir; setState(AtCore::CONNECTING); } else { - qCDebug(ATCORE_PLUGIN) << "Connected to" << firmwarePlugin()->name(); + //Plugin was loaded successfully. + d->firmwarePlugin = qobject_cast(d->pluginLoader.instance()); firmwarePlugin()->init(this); + qCDebug(ATCORE_PLUGIN) << "Plugin Loading: Successful"; 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) << "No Firmware Loaded"; + qCDebug(ATCORE_CORE) << "Plugin:" << fwName << ": Not found."; } } 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); return true; } else { qCDebug(ATCORE_CORE) << "Failed to open device for Read / Write."; 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()) { foreach (const QSerialPortInfo &serialPortInfo, serialPortInfoList) { #ifdef Q_OS_MAC - //Mac OS has callout serial ports starting with cu. They can only receive data and it's necessary to filter them out + //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 (newTime == 0) { - if (d->serialTimer) { - disconnect(d->serialTimer, &QTimer::timeout, this, &AtCore::locateSerialPort); - delete d->serialTimer; - } - return; - } if (!d->serialTimer) { + //There is no timer. We need to create one. d->serialTimer = new QTimer(); connect(d->serialTimer, &QTimer::timeout, this, &AtCore::locateSerialPort); } + //Start over with the new time. 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); 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; } - //START A THREAD AND CONNECT TO IT + //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 print if printing from the host. - //disconnecting from a printer printing via sd card should not affect its print. + //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("success") : QStringLiteral("FAIL"); + qCDebug(ATCORE_PLUGIN) << QStringLiteral("Firmware plugin %1 unload: %2").arg(name, msg); } - QString name = firmwarePlugin()->name(); - QString msg = d->pluginLoader.unload() ? QStringLiteral("success") : QStringLiteral("FAIL"); - qCDebug(ATCORE_PLUGIN) << QStringLiteral("Firmware plugin %1 unload: %2").arg(name, msg); serial()->close(); + //Clear our copy of the sdcard filelist clearSdCardFileList(); setState(AtCore::DISCONNECTED); } } AtCore::STATES AtCore::state(void) { return d->printerState; } void AtCore::setState(AtCore::STATES state) { if (state != d->printerState) { qCDebug(ATCORE_CORE) << "Atcore state changed from [" \ << d->printerState << "] to [" << state << "]"; 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; } } + void AtCore::findFirmwarePlugins() { d->plugins.clear(); qCDebug(ATCORE_PLUGIN) << "plugin dir:" << d->pluginsDir; QStringList files = d->pluginsDir.entryList(QDir::Files); foreach (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 { qCDebug(ATCORE_PLUGIN) << "File" << file << "not plugin."; continue; } qCDebug(ATCORE_CORE) << "Found plugin file" << f; if (file.startsWith(QStringLiteral("lib"))) { file = file.remove(QStringLiteral("lib")); } file = file.toLower().simplified(); QString pluginString; pluginString.append(d->pluginsDir.path()); pluginString.append(QChar::fromLatin1('/')); pluginString.append(f); d->plugins[file] = pluginString; qCDebug(ATCORE_CORE) << tr("plugins[%1]=%2").arg(file, pluginString); } } + QStringList AtCore::availableFirmwarePlugins() const { return d->plugins.keys(); } -void AtCore::detectFirmware() -{ - connect(serial(), &SerialLayer::receivedCommand, this, &AtCore::findFirmware); -} - 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::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::setIdleHold(uint delay) +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() { pushCommand(GCode::toCommand(GCode::M27)); } diff --git a/src/atcore.h b/src/atcore.h index 69f21c7..03fb5ed 100644 --- a/src/atcore.h +++ b/src/atcore.h @@ -1,563 +1,557 @@ /* 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() - * - Auto detect the firmware with detectFirmware() + * - 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. * - Windows and Mac Os will always look in appdir/plugins for plugins. * * Others Search: * 1. Build Dir/plugins (buildtime) * 2. ECM set KDE PLUGIN DIR (buildtime) * 3. Qt Plugin path/AtCore (runtime) * 4. plugins (runtime) */ 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 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) //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(),detectFirmware() + * @sa availableFirmwarePlugins(),loadFirmwarePlugin() */ Q_INVOKABLE IFirmware *firmwarePlugin() const; /** * @brief List of available firmware plugins - * @sa loadFirmwarePlugin(),firmwarePlugin(),detectFirmware() + * @sa loadFirmwarePlugin(),firmwarePlugin() */ QStringList availableFirmwarePlugins() const; /** * @brief Load A firmware plugin * @param fwName : name of the firmware - * @sa firmwarePlugin(),availableFirmwarePlugins(),detectFirmware() + * @sa firmwarePlugin(),availableFirmwarePlugins() */ Q_INVOKABLE void loadFirmwarePlugin(const QString &fwName); - /** - * @brief Attempt to autodetect the firmware of connect serial device - * @sa loadFirmwarePlugin(),availableFirmwarePlugins(),firmwarePlugin() - */ - Q_INVOKABLE void detectFirmware(); - /** * @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 */ 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 New number of extruders * @sa extruderCount() */ void extruderCountChanged(); /** * @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() - */ + /** + * @brief New interval between serial timer + * @sa setSerialTimerInterval() + */ void serialTimerIntervalChanged(); /** * @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 Disables idle hold of motors after a delay - * @param delay: Seconds until idle hold is released. 0= No delay + * @brief Disable motors after a delay + * @param delay: Seconds until motors are disabled. 0= No delay */ - Q_INVOKABLE void setIdleHold(uint delay = 0); + 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 detectFirmware() + * 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 */ void findFirmwarePlugins(); /** * @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. */ AtCorePrivate *d; protected: /** * @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/testclient/mainwindow.cpp b/testclient/mainwindow.cpp index 5565e40..482f220 100644 --- a/testclient/mainwindow.cpp +++ b/testclient/mainwindow.cpp @@ -1,629 +1,626 @@ /* AtCore Test Client Copyright (C) <2016> Authors: Patrick José Pereira Lays Rodrigues Chris Rizzitello Tomaz Canabrava This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include #include "mainwindow.h" #include "seriallayer.h" #include "gcodecommands.h" #include "widgets/axiscontrol.h" #include "widgets/about.h" Q_LOGGING_CATEGORY(TESTCLIENT_MAINWINDOW, "org.kde.atelier.core") int MainWindow::fanCount = 4; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), core(new AtCore(this)), logFile(new QTemporaryFile(QDir::tempPath() + QStringLiteral("/AtCore_"))) { ui->setupUi(this); setWindowIcon(QIcon(QStringLiteral(":/icon/windowIcon"))); QCoreApplication::setApplicationVersion(core->version()); ui->serialPortCB->setEditable(true); QValidator *validator = new QIntValidator(); ui->baudRateLE->setValidator(validator); ui->baudRateLE->addItems(core->portSpeeds()); ui->baudRateLE->setCurrentIndex(9); ui->pluginCB->addItem(tr("Autodetect")); ui->pluginCB->addItems(core->availableFirmwarePlugins()); AxisControl *axisControl = new AxisControl; ui->moveDockContents->layout()->addWidget(axisControl); addLog(tr("Attempting to locate Serial Ports")); core->setSerialTimerInterval(1000); setDangeriousDocksDisabled(true); populateCBs(); //Icon for actionQuit #ifndef Q_OS_MAC ui->actionQuit->setIcon(QIcon::fromTheme(QStringLiteral("application-exit"))); #endif //hide the printing progress bar. ui->printLayout->setVisible(false); ui->statusBar->addWidget(ui->statusBarWidget); printTime = new QTime(); printTimer = new QTimer(); printTimer->setInterval(1000); printTimer->setSingleShot(false); connect(printTimer, &QTimer::timeout, this, &MainWindow::updatePrintTime); connect(ui->connectPB, &QPushButton::clicked, this, &MainWindow::connectPBClicked); connect(ui->saveLogPB, &QPushButton::clicked, this, &MainWindow::saveLogPBClicked); connect(ui->sendPB, &QPushButton::clicked, this, &MainWindow::sendPBClicked); connect(ui->commandLE, &QLineEdit::returnPressed, this, &MainWindow::sendPBClicked); connect(ui->homeAllPB, &QPushButton::clicked, this, &MainWindow::homeAllPBClicked); connect(ui->homeXPB, &QPushButton::clicked, this, &MainWindow::homeXPBClicked); connect(ui->homeYPB, &QPushButton::clicked, this, &MainWindow::homeYPBClicked); connect(ui->homeZPB, &QPushButton::clicked, this, &MainWindow::homeZPBClicked); connect(ui->bedTempPB, &QPushButton::clicked, this, &MainWindow::bedTempPBClicked); connect(ui->extTempPB, &QPushButton::clicked, this, &MainWindow::extTempPBClicked); connect(ui->mvAxisPB, &QPushButton::clicked, this, &MainWindow::mvAxisPBClicked); connect(ui->fanSpeedPB, &QPushButton::clicked, this, &MainWindow::fanSpeedPBClicked); connect(ui->printPB, &QPushButton::clicked, this, &MainWindow::printPBClicked); connect(ui->sdPrintPB, &QPushButton::clicked, this, &MainWindow::sdPrintPBClicked); connect(ui->sdDelPB, &QPushButton::clicked, this, &MainWindow::sdDelPBClicked); connect(ui->printerSpeedPB, &QPushButton::clicked, this, &MainWindow::printerSpeedPBClicked); connect(ui->flowRatePB, &QPushButton::clicked, this, &MainWindow::flowRatePBClicked); connect(ui->showMessagePB, &QPushButton::clicked, this, &MainWindow::showMessage); connect(ui->pluginCB, &QComboBox::currentTextChanged, this, &MainWindow::pluginCBChanged); connect(ui->disableMotorsPB, &QPushButton::clicked, this, &MainWindow::disableMotorsPBClicked); connect(ui->sdListPB, &QPushButton::clicked, this, &MainWindow::getSdList); connect(core, &AtCore::stateChanged, this, &MainWindow::printerStateChanged); connect(ui->stopPB, &QPushButton::clicked, core, &AtCore::stop); connect(ui->emergencyStopPB, &QPushButton::clicked, core, &AtCore::emergencyStop); connect(axisControl, &AxisControl::clicked, this, &MainWindow::axisControlClicked); connect(core, &AtCore::portsChanged, this, &MainWindow::locateSerialPort); connect(core, &AtCore::printProgressChanged, this, &MainWindow::printProgressChanged); connect(core, &AtCore::sdMountChanged, this, &MainWindow::sdChanged); connect(core, &AtCore::sdCardFileListChanged, [ & ](QStringList fileList) { ui->sdFileListView->clear(); ui->sdFileListView->addItems(fileList); }); connect(&core->temperature(), &Temperature::bedTemperatureChanged, [ this ](float temp) { checkTemperature(0x00, 0, temp); ui->plotWidget->appendPoint(tr("Actual Bed"), temp); ui->plotWidget->update(); }); connect(&core->temperature(), &Temperature::bedTargetTemperatureChanged, [ this ](float temp) { checkTemperature(0x01, 0, temp); ui->plotWidget->appendPoint(tr("Target Bed"), temp); ui->plotWidget->update(); }); connect(&core->temperature(), &Temperature::extruderTemperatureChanged, [ this ](float temp) { checkTemperature(0x02, 0, temp); ui->plotWidget->appendPoint(tr("Actual Ext.1"), temp); ui->plotWidget->update(); }); connect(&core->temperature(), &Temperature::extruderTargetTemperatureChanged, [ this ](float temp) { checkTemperature(0x03, 0, temp); ui->plotWidget->appendPoint(tr("Target Ext.1"), temp); ui->plotWidget->update(); }); connect(ui->actionQuit, &QAction::triggered, this, &MainWindow::close); connect(ui->actionShowDockTitles, &QAction::toggled, this, &MainWindow::toggleDockTitles); connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::about); ui->menuView->insertAction(nullptr, ui->connectDock->toggleViewAction()); ui->menuView->insertAction(nullptr, ui->tempControlsDock->toggleViewAction()); ui->menuView->insertAction(nullptr, ui->commandDock->toggleViewAction()); ui->menuView->insertAction(nullptr, ui->printDock->toggleViewAction()); ui->menuView->insertAction(nullptr, ui->moveDock->toggleViewAction()); ui->menuView->insertAction(nullptr, ui->tempTimelineDock->toggleViewAction()); ui->menuView->insertAction(nullptr, ui->logDock->toggleViewAction()); ui->menuView->insertAction(nullptr, ui->sdDock->toggleViewAction()); //more dock stuff. setTabPosition(Qt::LeftDockWidgetArea, QTabWidget::North); setTabPosition(Qt::RightDockWidgetArea, QTabWidget::North); tabifyDockWidget(ui->moveDock, ui->tempControlsDock); tabifyDockWidget(ui->moveDock, ui->sdDock); ui->moveDock->raise(); tabifyDockWidget(ui->connectDock, ui->printDock); tabifyDockWidget(ui->connectDock, ui->commandDock); ui->connectDock->raise(); setCentralWidget(nullptr); } void MainWindow::closeEvent(QCloseEvent *event) { core->close(); event->accept(); } MainWindow::~MainWindow() { delete logFile; delete ui; } QString MainWindow::getTime() { return QTime::currentTime().toString(QStringLiteral("hh:mm:ss:zzz")); } QString MainWindow::logHeader() { return QStringLiteral("[%1] ").arg(getTime()); } QString MainWindow::rLogHeader() { return QStringLiteral("[%1]< ").arg(getTime()); } QString MainWindow::sLogHeader() { return QStringLiteral("[%1]> ").arg(getTime()); } void MainWindow::writeTempFile(QString text) { /* A QTemporaryFile will always be opened in QIODevice::ReadWrite mode, this allows easy access to the data in the file. This function will return true upon success and will set the fileName() to the unique filename used. */ logFile->open(); logFile->seek(logFile->size()); logFile->write(text.toLatin1()); logFile->putChar('\n'); logFile->close(); } void MainWindow::addLog(QString msg) { QString message(logHeader() + msg); ui->logTE->appendPlainText(message); writeTempFile(message); } void MainWindow::addRLog(QString msg) { QString message(rLogHeader() + msg); ui->logTE->appendPlainText(message); writeTempFile(message); } void MainWindow::addSLog(QString msg) { QString message(sLogHeader() + msg); ui->logTE->appendPlainText(message); writeTempFile(message); } void MainWindow::checkReceivedCommand(const QByteArray &message) { addRLog(QString::fromUtf8(message)); } void MainWindow::checkPushedCommands(QByteArray bmsg) { QString msg = QString::fromUtf8(bmsg); QRegExp _newLine(QChar::fromLatin1('\n')); QRegExp _return(QChar::fromLatin1('\r')); msg.replace(_newLine, QStringLiteral("\\n")); msg.replace(_return, QStringLiteral("\\r")); addSLog(msg); } void MainWindow::checkTemperature(uint sensorType, uint number, uint temp) { QString msg; switch (sensorType) { case 0x00: // bed msg = QString::fromLatin1("Bed Temperature "); break; case 0x01: // bed target msg = QString::fromLatin1("Bed Target Temperature "); break; case 0x02: // extruder msg = QString::fromLatin1("Extruder Temperature "); break; case 0x03: // extruder target msg = QString::fromLatin1("Extruder Target Temperature "); break; case 0x04: // enclosure msg = QString::fromLatin1("Enclosure Temperature "); break; case 0x05: // enclosure target msg = QString::fromLatin1("Enclosure Target Temperature "); break; } msg.append(QString::fromLatin1("[%1] : %2")); msg = msg.arg(QString::number(number)) .arg(QString::number(temp)); addRLog(msg); } /** * @brief MainWindow::locateSerialPort * Locate all active serial ports on the computer and add to the list * of serial ports */ void MainWindow::locateSerialPort(const QStringList &ports) { ui->serialPortCB->clear(); if (!ports.isEmpty()) { ui->serialPortCB->addItems(ports); addLog(tr("Found %1 Ports").arg(QString::number(ports.count()))); } else { QString portError(tr("No available ports! Please connect a serial device to continue!")); if (! ui->logTE->toPlainText().endsWith(portError)) { addLog(portError); } } } void MainWindow::connectPBClicked() { if (core->state() == AtCore::DISCONNECTED) { if (core->initSerial(ui->serialPortCB->currentText(), ui->baudRateLE->currentText().toInt())) { connect(core, &AtCore::receivedMessage, this, &MainWindow::checkReceivedCommand); connect(core->serial(), &SerialLayer::pushedCommand, this, &MainWindow::checkPushedCommands); ui->connectPB->setText(tr("Disconnect")); addLog(tr("Serial connected")); if (ui->pluginCB->currentText().contains(tr("Autodetect"))) { addLog(tr("No plugin loaded !")); addLog(tr("Requesting Firmware...")); - core->detectFirmware(); } else { core->loadFirmwarePlugin(ui->pluginCB->currentText()); } } else { addLog(tr("Failed to open serial in r/w mode")); } } else { disconnect(core, &AtCore::receivedMessage, this, &MainWindow::checkReceivedCommand); disconnect(core->serial(), &SerialLayer::pushedCommand, this, &MainWindow::checkPushedCommands); core->closeConnection(); core->setState(AtCore::DISCONNECTED); addLog(tr("Disconnected")); ui->connectPB->setText(tr("Connect")); } } void MainWindow::sendPBClicked() { QString comm = ui->commandLE->text().toUpper(); core->pushCommand(comm); ui->commandLE->clear(); } void MainWindow::homeAllPBClicked() { addSLog(tr("Home All")); core->home(); } void MainWindow::homeXPBClicked() { addSLog(tr("Home X")); core->home(AtCore::X); } void MainWindow::homeYPBClicked() { addSLog(tr("Home Y")); core->home(AtCore::Y); } void MainWindow::homeZPBClicked() { addSLog(tr("Home Z")); core->home(AtCore::Z); } void MainWindow::bedTempPBClicked() { if (ui->cb_andWait->isChecked()) { addSLog(GCode::description(GCode::M190)); } else { addSLog(GCode::description(GCode::M140)); } core->setBedTemp(ui->bedTempSB->value(), ui->cb_andWait->isChecked()); } void MainWindow::extTempPBClicked() { if (ui->cb_andWait->isChecked()) { addSLog(GCode::description(GCode::M109)); } else { addSLog(GCode::description(GCode::M104)); } core->setExtruderTemp(ui->extTempSB->value(), ui->extTempSelCB->currentIndex(), ui->cb_andWait->isChecked()); } void MainWindow::mvAxisPBClicked() { addSLog(GCode::description(GCode::G1)); if (ui->mvAxisCB->currentIndex() == 0) { core->move(AtCore::X, ui->mvAxisSB->value()); } else if (ui->mvAxisCB->currentIndex() == 1) { core->move(AtCore::Y, ui->mvAxisSB->value()); } else if (ui->mvAxisCB->currentIndex() == 2) { core->move(AtCore::Z, ui->mvAxisSB->value()); } } void MainWindow::fanSpeedPBClicked() { addSLog(GCode::description(GCode::M106)); core->setFanSpeed(ui->fanSpeedSB->value(), ui->fanSpeedSelCB->currentIndex()); } void MainWindow::printPBClicked() { QString fileName; switch (core->state()) { case AtCore::DISCONNECTED: QMessageBox::information(this, tr("Error"), tr("Not Connected To a Printer")); break; case AtCore::CONNECTING: QMessageBox::information(this, tr("Error"), tr(" A Firmware Plugin was not loaded!\n Please send the command M115 and let us know what your firmware returns, so we can improve our firmware detection. We have loaded the most common plugin \"repetier\" for you. You may try to print again after this message")); ui->pluginCB->setCurrentText(QStringLiteral("repetier")); break; case AtCore::IDLE: fileName = QFileDialog::getOpenFileName(this, tr("Select a file to print"), QDir::homePath(), QStringLiteral("*.gcode")); if (fileName.isNull()) { addLog(tr("No File Selected")); } else { addLog(tr("Print: %1").arg(fileName)); core->print(fileName); } break; case AtCore::BUSY: core->pause(ui->postPauseLE->text()); break; case AtCore::PAUSE: core->resume(); break; default: qCDebug(TESTCLIENT_MAINWINDOW) << "ERROR / STOP unhandled."; } } void MainWindow::saveLogPBClicked() { // Note that if a file with the name newName already exists, copy() returns false (i.e. QFile will not overwrite it). QString fileName = QDir::homePath() + QChar::fromLatin1('/') + QFileInfo(logFile->fileName()).fileName() + QStringLiteral(".txt"); QString saveFileName = QFileDialog::getSaveFileName(this, tr("Save Log to file"), fileName); QFile::copy(logFile->fileName(), saveFileName); logFile->close(); } void MainWindow::pluginCBChanged(QString currentText) { if (core->state() != AtCore::DISCONNECTED) { if (!currentText.contains(tr("Autodetect"))) { core->loadFirmwarePlugin(currentText); - } else { - core->detectFirmware(); } } } void MainWindow::flowRatePBClicked() { core->setFlowRate(ui->flowRateSB->value()); } void MainWindow::printerSpeedPBClicked() { core->setPrinterSpeed(ui->printerSpeedSB->value()); } void MainWindow::printerStateChanged(AtCore::STATES state) { QString stateString; switch (state) { case AtCore::IDLE: ui->printPB->setText(tr("Print File")); stateString = QStringLiteral("Connected to ") + core->connectedPort(); break; case AtCore::STARTPRINT: stateString = QStringLiteral("START PRINT"); ui->printPB->setText(tr("Pause Print")); ui->printLayout->setVisible(true); printTime->start(); printTimer->start(); break; case AtCore::FINISHEDPRINT: stateString = QStringLiteral("Finished Print"); ui->printPB->setText(tr("Print File")); ui->printLayout->setVisible(false); printTimer->stop(); break; case AtCore::PAUSE: stateString = QStringLiteral("Paused"); ui->printPB->setText(tr("Resume Print")); break; case AtCore::BUSY: stateString = QStringLiteral("Printing"); ui->printPB->setText(tr("Pause Print")); break; case AtCore::DISCONNECTED: stateString = QStringLiteral("Not Connected"); setDangeriousDocksDisabled(true); break; case AtCore::CONNECTING: stateString = QStringLiteral("Connecting"); setDangeriousDocksDisabled(false); break; case AtCore::STOP: stateString = QStringLiteral("Stoping Print"); break; case AtCore::ERRORSTATE: stateString = QStringLiteral("Command ERROR"); break; } ui->lblState->setText(stateString); } void MainWindow::populateCBs() { // Extruders for (int count = 0; count < core->extruderCount(); count++) { ui->extTempSelCB->insertItem(count, tr("Extruder %1").arg(count)); } // Fan for (int count = 0; count < fanCount; count++) { ui->fanSpeedSelCB->insertItem(count, tr("Fan %1 speed").arg(count)); } } void MainWindow::showMessage() { core->showMessage(ui->messageLE->text()); } void MainWindow::updatePrintTime() { QTime temp(0, 0, 0); ui->time->setText(temp.addMSecs(printTime->elapsed()).toString(QStringLiteral("hh:mm:ss"))); } void MainWindow::printProgressChanged(int progress) { ui->printingProgress->setValue(progress); if (progress > 0) { QTime temp(0, 0, 0); ui->timeLeft->setText(temp.addMSecs((100 - progress) * (printTime->elapsed() / progress)).toString(QStringLiteral("hh:mm:ss"))); } else { ui->timeLeft->setText(QStringLiteral("??:??:??")); } } void MainWindow::toggleDockTitles() { if (ui->actionShowDockTitles->isChecked()) { delete ui->connectDock->titleBarWidget(); delete ui->logDock->titleBarWidget(); delete ui->tempTimelineDock->titleBarWidget(); delete ui->commandDock->titleBarWidget(); delete ui->moveDock->titleBarWidget(); delete ui->tempControlsDock->titleBarWidget(); delete ui->printDock->titleBarWidget(); delete ui->sdDock->titleBarWidget(); } else { ui->connectDock->setTitleBarWidget(new QWidget()); ui->logDock->setTitleBarWidget(new QWidget()); ui->tempTimelineDock->setTitleBarWidget(new QWidget()); ui->commandDock->setTitleBarWidget(new QWidget()); ui->moveDock->setTitleBarWidget(new QWidget()); ui->tempControlsDock->setTitleBarWidget(new QWidget()); ui->printDock->setTitleBarWidget(new QWidget()); ui->sdDock->setTitleBarWidget(new QWidget()); } } void MainWindow::setDangeriousDocksDisabled(bool disabled) { ui->commandDock->widget()->setDisabled(disabled); ui->moveDock->widget()->setDisabled(disabled); ui->tempControlsDock->widget()->setDisabled(disabled); ui->printDock->widget()->setDisabled(disabled); ui->sdDock->widget()->setDisabled(disabled); } void MainWindow::about() { About *aboutDialog = new About(this); aboutDialog->exec(); } void MainWindow::axisControlClicked(QLatin1Char axis, int value) { core->setRelativePosition(); core->move(axis, value); core->setAbsolutePosition(); } void MainWindow::disableMotorsPBClicked() { - core->setIdleHold(0); + core->disableMotors(0); } void MainWindow::sdChanged(bool mounted) { QString labelText = mounted ? QStringLiteral("SD") : QString(); ui->lbl_sd->setText(labelText); } void MainWindow::getSdList() { core->sdFileList(); } void MainWindow::sdPrintPBClicked() { if (ui->sdFileListView->currentRow() < 0) { QMessageBox::information(this, QStringLiteral("Print Error"), QStringLiteral("You must Select a file from the list")); } else { core->print(ui->sdFileListView->currentItem()->text(), true); } } void MainWindow::sdDelPBClicked() { if (ui->sdFileListView->currentRow() < 0) { QMessageBox::information(this, QStringLiteral("Delete Error"), QStringLiteral("You must Select a file from the list")); } else { core->sdDelete(ui->sdFileListView->currentItem()->text()); ui->sdFileListView->setCurrentRow(-1); } }