clean up loop()

This commit is contained in:
2019-07-22 20:02:52 +03:00
parent c50c3354fb
commit 472011554d
5 changed files with 60 additions and 29 deletions

View File

@@ -10,7 +10,9 @@
class Executor
{
private:
/* data */
unsigned long lastStsTime;
I2CStatusMsg lastSts;
static constexpr int lastStsTTL = 1;
public:
Executor(/* args */);
void execCommand(Command command);

View File

@@ -64,15 +64,27 @@ void Executor::execCommand(Command command) {
I2CStatusMsg Executor::status() {
unsigned long reqTime = millis();
Wire.requestFrom(8, 1);
int tries = 0;
while (!Wire.available()) {
if (millis() - reqTime > 100) {
Wire.requestFrom(8, 1);
reqTime = millis();
}
if (reqTime - lastStsTime < lastStsTTL) {
return lastSts;
}
Wire.requestFrom(8, 1);
while (!Wire.available()) {
if (millis() - reqTime > 10 && tries < 10) {
Wire.requestFrom(8, 1);
tries++;
reqTime = millis();
} else {
return I2CStatusMsg::TIMEOUT;
}
delay(1);
}
int resp = Wire.read();
return static_cast<I2CStatusMsg>(resp);
lastStsTime = millis();
lastSts = static_cast<I2CStatusMsg>(resp);
return lastSts;
}

View File

@@ -27,10 +27,12 @@ void Power::enable12v() {
enabled12v = true;
}
bool Power::isEnabled12v() {
return enabled12v;
}
bool Power::isEnabled12v() { return enabled12v; }
void Power::commandHook() {
lastCmdTime = millis();
if (!isEnabled12v()) {
enable12v();
delay(100);
}
}

View File

@@ -2,13 +2,16 @@
#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <Wire.h>
#include "Executor.h"
#include "GCodeParser.h"
#include "Globals.h"
#include "Executor.h"
#include "Power.h"
#include "common/Commands.h"
String inString;
String commandBuf;
bool newCommand;
bool shouldPrintSts;
void setup() {
Serial.begin(115200);
@@ -16,6 +19,21 @@ void setup() {
power.enable12v();
}
void sendCommand(String command) {
power.commandHook();
executor.execCommand(parseGCode(command));
shouldPrintSts = true;
}
void printSts(I2CStatusMsg status) {
if (status == I2CStatusMsg::WAIT) {
shouldPrintSts = true;
} else if (status == I2CStatusMsg::NEXT) {
Serial.println("OK");
} else {
Serial.println("Error");
}
}
void loop() {
while (Serial.available() > 0) {
@@ -24,24 +42,19 @@ void loop() {
if (inChar == '\n') {
inString.trim();
if (!power.isEnabled12v()) {
power.enable12v();
delay(100);
}
power.commandHook();
executor.execCommand(parseGCode(inString));
I2CStatusMsg response;
do {
response = executor.status();
if (response == I2CStatusMsg::WAIT) {
delay(1);
} else if (response == I2CStatusMsg::NEXT) {
Serial.println("OK");
} else {
Serial.println("Error");
}
} while (response != I2CStatusMsg::NEXT);
commandBuf = inString;
inString = "";
newCommand = true;
}
}
I2CStatusMsg status = executor.status();
if (shouldPrintSts) {
shouldPrintSts = false;
printSts(status);
}
if (newCommand && status == I2CStatusMsg::NEXT) {
newCommand = false;
sendCommand(commandBuf);
}
}

View File

@@ -10,6 +10,8 @@ enum bcAxis {
enum class I2CStatusMsg {
WAIT = 0,
NEXT,
TIMEOUT,
ERR,
};
enum PosMsg {