// // Created by robin on 5/5/16. // #include "HostCommunication.h" #include HostCommunication::HostCommunication() { } void HostCommunication::init() { Serial.begin(SERIAL_BAUDRATE); debug("Starting..."); } void HostCommunication::debug(String str) { #ifdef DEBUG send(PACKET_DEBUG, str); #endif } void HostCommunication::selfTest() { send(PACKET_SELF_TEST); } void HostCommunication::login(String uid, String password) { send(PACKET_LOGIN, uid + "\n" + password); } void HostCommunication::send(SERIAL_PACKET_TYPE type) { send(type, ""); } void HostCommunication::send(SERIAL_PACKET_TYPE type, String str) { Serial.write((SERIAL_PACKET_TYPE)type); Serial.write((SERIAL_PACKET_LENGTH_TYPE)str.length()); Serial.write(str.c_str()); } HostCommunicationResult HostCommunication::read(int timeout) { HostCommunicationResult res; res.length = 0; res.data = 0; res.isSuccess = false; if (!waitData(timeout, sizeof(SERIAL_PACKET_LENGTH_TYPE))) { return res; } SERIAL_PACKET_LENGTH_TYPE length = 0; Serial.readBytes((char*)&length, sizeof(SERIAL_PACKET_LENGTH_TYPE)); if (!waitData(timeout, length)) { return res; } res.data = new char[length]; Serial.readBytes(res.data, length); res.isSuccess = true; res.length = length; return res; } bool HostCommunication::waitData(int timeout, int length) { unsigned long secs = millis(); while (Serial.available() < length && millis() - secs < timeout) { delay(1); } return Serial.available() >= length; }