#include "microcontroller.h" //relays void Microcontroller::relayToggle(int state, int relay) { char buffer[8]; int length = sprintf(buffer, "%d \n", relay); if(_port != nullptr) state ? _port->write("relay on ", sizeof("relay on ")-1) : _port->write("relay off ", sizeof("relay off ")-1); state ? std::cout<<"relay on " : std::cout<<"relay off "; std::cout<write(buffer, length); } void Microcontroller::relayOn(int relay) { relayToggle(true, relay); } void Microcontroller::relayOff(int relay) { relayToggle(false, relay); } //rgb lights void Microcontroller::rgbOn() { if(_port != nullptr) _port->write("rgb on\n", sizeof("rgb on\n")-1); } void Microcontroller::rgbOff() { if(_port != nullptr) _port->write( "rgb off\n", sizeof("rgb off\n")-1); } void Microcontroller::changeRgbColor(const QColor color) { char buffer[64]; int length = sprintf(buffer, "rgb set %03d %03d %03d \n", color.red(), color.green(), color.blue() ); if(_port != nullptr) _port->write(buffer, length); std::cout<write("rgb pattern ", sizeof("rgb pattern ")-1); int length = sprintf(buffer, "%d \n", pattern); _port->write(buffer, length); } bool Microcontroller::connected() { if(_port != nullptr) return _port->isOpen(); else return false; } void Microcontroller::run() { abort(); loop.reset(new QEventLoop); QTimer timer; connect(&timer, SIGNAL(timeout()), this, SLOT(doTick())); timer.setInterval(500); timer.start(); loop->exec(); } void Microcontroller::requestState() { if(_port != nullptr) _port->write("relay state\n", sizeof("relay state\n")); } void Microcontroller::abort() { if (!loop.isNull()) { loop->quit(); } } std::vector Microcontroller::getLastState() { return _relayStates; } //housekeeping Microcontroller::Microcontroller(QIODevice* port): _port(port) { requestState(); } Microcontroller::Microcontroller() { } Microcontroller::~Microcontroller() { if(_port != nullptr) delete _port; } void Microcontroller::setIODevice(QIODevice *port) { _port = port; requestState(); } void Microcontroller::processMicroReturn() { QString workbuff = _buffer; workbuff.remove(0, 2); QStringList workbufList = workbuff.split(','); int numberOfRelays = workbufList[0].toInt(); if(workbufList.size() >= numberOfRelays+1) { bool hasChanged = false; _relayStates.resize(numberOfRelays, false); for(int i = 0; i < numberOfRelays; i++) { if(_relayStates[i] != (bool)workbufList[i+1].toInt()) { _relayStates[i] = (bool)workbufList[i+1].toInt(); hasChanged = true; } } if(hasChanged)relayStateChanged(_relayStates); } } void Microcontroller::doTick() { if(_port != nullptr) { char charBuf; while(_port->getChar(&charBuf)) { _buffer.push_back(charBuf); if( _buffer.endsWith('\n') ) { if(_buffer.size() > 2 && _buffer[0] == "S" && _buffer[1] == "T") { processMicroReturn(); } textRecived(_buffer); _buffer.clear(); } } } }