/******************************************************************** connect establishes a connection to the Slack RTM API ********************************************************************/ bool ArduinoSlackBot::connect() { // Step 1: Find WebSocket address via RTM API (https://api.slack.com/methods/rtm.start) HTTPClient http; String slackAddr = "https://slack.com/api/rtm.start?token="; slackAddr = String(slackAddr + slackToken); PRINTLN(slackAddr); http.begin(slackAddr.c_str(), slackSSLFingerprint); int httpCode = http.GET(); if (httpCode != HTTP_CODE_OK) { PRINTF("HTTP GET failed with code %d\n", httpCode); return false; } WiFiClient *client = http.getStreamPtr(); client->find("wss:\\/\\/"); String host = client->readStringUntil('\\'); String path = client->readStringUntil('"'); path.replace("\\/", "/"); // Step 2: Open WebSocket connection and register event handler PRINTLN("WebSocket Host=" + host + " Path=" + path); webSocket.beginSSL(host, 443, path, "", ""); webSocket.onEvent(webSocketEvent); return true; }
/** * \brief open function * \return True if file open succeeds, false otherwise.. * * This function is used to open a file on the SD card. */ boolean EngduinoSDClass::open(const char *filepath, uint8_t mode) { PRINTLN("open(..., ...)"); if(!isAttached()) return false; regTmp = TIMSK4; TIMSK4 = 0x00; // Disable TMR4 interrupts (Used by LEDs). PRINTLN("SD.open"); file = SD.open(filepath, mode); if(file) { // if the file is available return true PRINTLN("File is available."); strncpy(filePath, filepath, 12); // Maximum length of file name is 8. filePath[12] = 0; fileMode = mode; opened = true; autoOpenClose = false; TIMSK4 = regTmp; // Enable TMR4 interrupts (Used by LEDs). return true; } else { PRINTLN("File is not available!"); } opened = false; TIMSK4 = regTmp; // Enable TMR4 interrupts (Used by LEDs). return false; }
void PGcode() { for(;;) { /* Get a character */ while(UART_getchar_present() == 0); (*p_buffer) = UART_getchar(); UART_putchar((*p_buffer)); (*(p_buffer+sizeof(char))) = 0; if((*p_buffer) == BS) p_buffer -= sizeof(char); /* Check for end of command */ if((*p_buffer) == CR) { GCODE_STATUS st; LINEFEED; st = ProcessCommand(); if(st == GCODE_DONE) break; p_buffer = &buffer[0]-(sizeof(char)); } /* Go for next char */ if(p_buffer < buffer+BUF_SIZE*sizeof(char)) p_buffer += sizeof(char); else { LINEFEED; PRINTLN("Buffer overflow"); PRINTLN("Returning to terminal"); break; } } }
/******************************************************************** parse the websocket json and look for a message type ********************************************************************/ void ArduinoSlackBot::parseResponse(char *payload) { DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.parseObject(payload); if (root.success()) { if (root.containsKey("type")) { slackMsg.type = root["type"]; PRINTLN(slackMsg.type); PRINT("free heap size:"); PRINTLN(ESP.getFreeHeap()); if (strcasecmp(slackMsg.type, "message") == 0) { slackMsg.channel = root["channel"]; slackMsg.user = root["user"]; slackMsg.text = root["text"]; slackMsg.timestamp = root["ts"]; slackMsg.team = root["team"]; PRINTLN("parseCommands"); parseCmds(); } } } else { PRINTLN("parse fail"); } }
bool UbirchSIM800::wakeup() { PRINTLN("!!! SIM800 wakeup"); expect_AT_OK(F("")); // check if the chip is already awake, otherwise start wakeup if (!expect_AT_OK(F(""), 5000)) { PRINTLN("!!! SIM800 using PWRKEY wakeup procedure"); pinMode(SIM800_KEY, OUTPUT); pinMode(SIM800_PS, INPUT); do { digitalWrite(SIM800_KEY, HIGH); delay(10); digitalWrite(SIM800_KEY, LOW); delay(1100); digitalWrite(SIM800_KEY, HIGH); delay(2000); } while (digitalRead(SIM800_PS) == LOW); // make pin unused (do not leak) pinMode(SIM800_KEY, INPUT_PULLUP); PRINTLN("!!! SIM800 ok"); } else { PRINTLN("!!! SIM800 already awake"); } return reset(); }
void printUserButtonState(const ButtonState_t s) { #if USE_PRINT if (s == BUTTON_PRESSED) { PRINTLN("Button Pressed"); } else { PRINTLN("Button Released"); } #endif }
boolean EngduinoSDClass::isAttached() { PRINTLN("isAttached(...)"); // Read the input on analog pin SDCARD_ATTACHED: int analogIn = analogRead(SDCARD_ATTACHED); // Goes from 0 - 1023 if(analogIn < 300) {PRINTLN("Attached"); return true;} // less than ~1V PRINTLN("NOT Attached"); return false; }
unsigned short int UbirchSIM800::HTTP_post(const char *url, unsigned long int &length, STREAM &file, uint32_t size) { expect_AT_OK(F("+HTTPTERM")); delay(100); if (!expect_AT_OK(F("+HTTPINIT"))) return 1000; if (!expect_AT_OK(F("+HTTPPARA=\"CID\",1"))) return 1101; if (!expect_AT_OK(F("+HTTPPARA=\"UA\",\"UBIRCH#1\""))) return 1102; if (!expect_AT_OK(F("+HTTPPARA=\"REDIR\",1"))) return 1103; println_param("AT+HTTPPARA=\"URL\"", url); if (!expect_OK()) return 1110; print(F("AT+HTTPDATA=")); print(size); print(F(",")); println((uint32_t) 120000); if (!expect(F("DOWNLOAD"))) return 0; uint8_t *buffer = (uint8_t *) malloc(SIM800_BUFSIZE); uint32_t pos = 0, r = 0; do { for (r = 0; r < SIM800_BUFSIZE; r++) { int c = file.read(); if (c == -1) break; _serial.write((uint8_t) c); } if (r < SIM800_BUFSIZE) { #if !defined(NDEBUG) && defined(DEBUG_PROGRESS) PRINTLN("EOF"); #endif break; } #ifndef NDEBUG if ((pos % 10240) == 0) { PRINT(" "); DEBUGLN(pos); } else if (pos % (1024) == 0) { PRINT(">"); } #endif pos += r; } while (r == SIM800_BUFSIZE); free(buffer); PRINTLN(""); if (!expect_OK(5000)) return 1005; if (!expect_AT_OK(F("+HTTPACTION=1"))) return 1004; // wait for the action to be completed, give it 5s for each try uint16_t status; while (!expect_scan(F("+HTTPACTION: 1,%hu,%lu"), &status, &length, 5000)); return status; }
uint8_t EngduinoSDClass::read() { if(fileMode != FILE_READ) { PRINTLN("read(...) fileMode != FILE_READ"); return 0; } if(!file) { PRINTLN("read(...) file error!"); return 0; } return file.read(); }
void myDetachedThread::run() { PRINTLN("myDetachedThread is starting"); cxxtools::MutexLock lock(conditionMutex); running.broadcast(); lock.unlock(); ::sleep(1); PRINTLN("myDetachedThread waits"); ::sleep(2); PRINTLN("myDetachedThread is ready"); }
//connect with the to the lora gateway bool ATTDevice::Connect(unsigned char* devAddress, unsigned char* appKey, unsigned char* nwksKey, bool adr) { PRINT("ATT lib version: "); PRINTLN(VERSION); if(!_modem->Stop()){ //stop any previously running modems PRINTLN("can't communicate with modem: possible hardware issues"); return false; } if (!_modem->SetLoRaWan(adr)){ //switch to LoRaWan mode instead of peer to peer PRINTLN("can't set adr: possible hardware issues?"); return false; } if(!_modem->SetDevAddress(devAddress)){ PRINTLN("can't assign device address to modem: possible hardware issues?"); return false; } if(!_modem->SetAppKey(appKey)){ PRINTLN("can't assign app session key to modem: possible hardware issues?"); return false; } if(!_modem->SetNWKSKey(nwksKey)){ PRINTLN("can't assign network session key to modem: possible hardware issues?"); return false; } bool result = _modem->Start(); //start the modem up if(result == true){ PRINTLN("modem initialized"); } else{ PRINTLN("Parameters loaded, but modem won't start: initialization failed"); } return result; //we have created a connection successfully. }
/* * Terminal loop application. */ void terminal() { char c = 48; for(;;) { LINEFEED; UART_putchar('>'); while(UART_getchar_present() == 0); c = UART_getchar(); switch(c) { case 'w': PRINTLN("Moving UP"); MoveY(-MOVE_DIST); break; case 's': PRINTLN("Moving DOWN"); MoveY(MOVE_DIST); break; case 'a': PRINTLN("Moving LEFT"); MoveX(-MOVE_DIST); break; case 'd': PRINTLN("Moving RIGHT"); MoveX(MOVE_DIST); break; case 'h': PRINTLN("Going Home..."); MoveHome(); break; case 'z': PRINTLN("Zeroed at current position."); MoveSetZero(); break; case 'g': PRINTLN("Entering Pseudo G-Code mode."); PGcode(); break; case 'o': PRINTLN("Draw a circle?"); DrawCircle(50); break; case ' ': PRINTLN("Pen action"); penp = 100 - penp; PWM_setPosition(penp); break; } } }
boolean EngduinoSDClass::_write(const String &str, boolean ln) { PRINTLN("write(...)"); if(fileMode != FILE_WRITE) return false; if(!isAttached()) return false; if(!initialized) return false; if(!opened) return false; regTmp = TIMSK4; TIMSK4 = 0x00; // Disable TMR4 interrupts (Used by LEDs). if(autoOpenClose) { file = SD.open(filePath, fileMode); if(file) { (ln) ? file.println(str) : file.print(str); file.close(); TIMSK4 = regTmp; // Enable TMR4 interrupts (Used by LEDs). return true; } } else { if(file) { (ln) ? file.println(str) : file.print(str); TIMSK4 = regTmp; // Enable TMR4 interrupts (Used by LEDs). return true; } } TIMSK4 = regTmp; // Enable TMR4 interrupts (Used by LEDs). return false; }
unsigned short int UbirchSIM800::HTTP_get(const char *url, unsigned long int &length, STREAM &file) { unsigned short int status = HTTP_get(url, length); PRINT("HTTP STATUS: "); DEBUGLN(status); PRINT("FILE LENGTH: "); DEBUGLN(length); if (length == 0) return status; char *buffer = (char *) malloc(SIM800_BUFSIZE); uint32_t pos = 0; do { size_t r = HTTP_read(buffer, pos, SIM800_BUFSIZE); #if !defined(NDEBUG) && defined(DEBUG_PROGRESS) if ((pos % 10240) == 0) { PRINT(" "); DEBUGLN(pos); } else if (pos % (1024) == 0) { PRINT("<"); } #endif pos += r; file.write(buffer, r); } while (pos < length); free(buffer); PRINTLN(""); return status; }
/** @brief make reponse header such as html, gif, jpeg,etc. */ void make_http_response_head( uint8 * buf, /**< pointer to response header to be made */ int8 type, /**< response type */ uint32 len /**< size of response header */ ) { char * head; char tmp[10]; /* file type*/ if (type == PTYPE_HTML) head = RES_HTMLHEAD_OK; else if (type == PTYPE_CGI) head = RES_HTMLHEAD_OK; else if (type == PTYPE_PL) head = RES_HTMLHEAD_OK; else if (type == PTYPE_GIF) head = RES_GIFHEAD_OK; else if (type == PTYPE_TEXT) head = RES_TEXTHEAD_OK; else if (type == PTYPE_JPEG) head = RES_JPEGHEAD_OK; else if (type == PTYPE_FLASH) head = RES_FLASHHEAD_OK; else if (type == PTYPE_MPEG) head = RES_MPEGHEAD_OK; else if (type == PTYPE_PDF) head = RES_PDFHEAD_OK; #ifdef HTTPD_DEBUG else PRINTLN("\r\n\r\n-MAKE HEAD UNKNOWN-\r\n"); #endif sprintf(tmp,"%ld", len); strcpy((char*)buf, head); strcat((char*)buf, tmp); strcat((char*)buf, "\r\n\r\n"); }
/** * \brief begin function - must be called before using other functions * \return True if initialization succeeds, false otherwise.. * * This function performs the initialisation required by the sdfatlib library. */ boolean EngduinoSDClass::begin() { PRINTLN("begin() init"); if(initialized) return true; // If we are already initialized, return true. if(!isAttached()) return false; // make sure that the default chip select pin is set to // output, even if you don't use it: pinMode(SPI_SS_PIN, OUTPUT); regTmp = TIMSK4; TIMSK4 = 0x00; // Disable TMR4 interrupts (Used by LEDs). PRINTLN("SD.begin..."); boolean b = SD.begin(SDCARD_CS); TIMSK4 = regTmp; // Enable TMR4 interrupts (Used by LEDs). if(b) {initialized = true; PRINTLN("SD.begin...success"); return true;} return false; }
unsigned char EmbitLoRaModem::ReadPacket(unsigned char index) { uint32_t maxTS = millis() + PACKET_TIME_OUT; uint16_t length = 4; unsigned char firstByte = 0; unsigned char result = 0; PRINT("Receiving: "); size_t i = 0; while ((maxTS > millis()) && (i < length)) { while ((!_stream->available()) && (maxTS > millis())); if (_stream->available()) { unsigned char value = _stream->read(); if (i == 0) firstByte = value; else if (i == 1) length = firstByte * 256 + value; else if(i == index) result = value; printHex(value); i++; } } if (i < length) { PRINT("Timeout"); } PRINTLN(); return result; }
int EngduinoSDClass::available() { if(!file) { PRINTLN("available(...) file error!"); return 0; } return file.available(); }
bool EmbitLoRaModem::SetLoRaWan(bool adr) { PRINTLN("Setting the network preferences to LoRaWAN private network"); if(adr == true) SendPacket(CMD_LORA_PRVNET, sizeof(CMD_LORA_PRVNET)); else SendPacket(CMD_LORA_PRVNET, sizeof(CMD_LORA_PRVNET_NO_ADR)); return ReadPacket(); }
bool EmbitLoRaModem::Start() { PRINTLN("Sending the netowrk start command"); SendPacket(CMD_START, sizeof(CMD_START)); ReadPacket(); //toddo: check result of readPacket and return actual success or not. return true; }
// build JSON object hierarchy JSON * JSON::parse_private(Lexer *lexer) { // check token to determine what JSON type to construct Json_Token token = lexer->get_token(); switch (token) { case Object_start_token: return parse_object(lexer); case Array_start_token: return parse_array(lexer); case String_token: return new_string(lexer->token_src, lexer->token_len); case Null_token: return new_null(); case True_token: return new_boolean(true); case False_token: return new_boolean(false); case Float_token: return new_float(lexer->float_num); case Unsigned_token: return new_unsigned(lexer->unsigned_num); case Signed_token: return new_signed(lexer->signed_num); default: #ifdef DEBUG PRINTLN(F("JSON syntax error")); #endif return null; } token = lexer->get_token(); if (token != Error_token) { #ifdef DEBUG PRINTLN(F("JSON syntax error")); #endif return null; } return null; }
void AvlNode::print_keys(AvlIndex tree) { if (tree) { print_keys(AVLNODE(tree)->left); PRINT(F(" ")); PRINTLN((int)AVLNODE(tree)->key); print_keys(AVLNODE(tree)->right); } }
/* * Parse and execute Gcode command */ GCODE_STATUS ProcessCommand() { uint32_t x[2]; char *split; int i = 0; // Redirect pointer to beginning p_buffer = &buffer[0]; // Terminate if(strcmp( p_buffer, "end\r" ) == 0) { PRINTLN("EXIT G-code mode"); return GCODE_DONE; } // Paused else if(strcmp( p_buffer, "pause\r") == 0 ) { PRINTLN("G-code PAUSE"); return GCODE_PAUSE; } // Else parse goto command split = strtok(p_buffer,"g ,"); while( (split != NULL) & (i<2) ) { x[i++] = atoi(split); split = strtok( NULL, "g ,"); } // Check bounds if((x[0] < MIN_BOUND) | (x[0] > MAX_BOUND) | (x[1] < MIN_BOUND) | (x[1] > MAX_BOUND)) { PRINTLN("Bad coordinates"); return GCODE_ERROR; } else { printf("Going to: (%d, %d)\n\r",x[0],x[1]); MoveToAbsolute(x[0],x[1]); PRINTLN("Done"); return GCODE_OK; } }
bool UbirchSIM800::registerNetwork(uint16_t timeout) { PRINTLN("!!! SIM800 waiting for network registration"); expect_AT_OK(F("")); while (timeout -= 1000) { unsigned short int n = 0; println(F("AT+CREG?")); expect_scan(F("+CREG: 0,%hu"), &n); #if !defined(NDEBUG) && defined(DEBUG_PROGRESS) switch (n) { case 0: PRINT("_"); break; case 1: PRINT("H"); break; case 2: PRINT("S"); break; case 3: PRINT("D"); break; case 4: PRINT("?"); break; case 5: PRINT("R"); break; default: DEBUG(n); break; } #endif if ((n == 1 || n == 5)) { #if !defined(NDEBUG) && defined(DEBUG_PROGRESS) PRINTLN(""); #endif return true; } delay(1000); } return false; }
bool UbirchSIM800::shutdown() { PRINTLN("!!! SIM800 shutdown"); disableGPRS(); expect_AT_OK(F("+CPOWD=1")); expect(F("NORMAL POWER DOWN"), 5000); if (urc_status != 12 && digitalRead(SIM800_PS) == HIGH) { PRINTLN("!!! SIM800 shutdown using PWRKEY"); pinMode(SIM800_KEY, OUTPUT); pinMode(SIM800_PS, INPUT); digitalWrite(SIM800_KEY, LOW); for (uint8_t s = 30; s > 0 && digitalRead(SIM800_PS) != LOW; --s) delay(1000); digitalWrite(SIM800_KEY, HIGH); pinMode(SIM800_KEY, INPUT); pinMode(SIM800_KEY, INPUT_PULLUP); } PRINTLN("!!! SIM800 shutdown ok"); return true; }
/******************************************************************** parseCmds loops through a list of hear functions and tries to match queries and execute reply response functions ********************************************************************/ void ArduinoSlackBot::parseCmds() { struct slre_cap matches[4]; //you must reference the bot to get a response if (slre_match(botID, slackMsg.text, strlen(slackMsg.text), matches, 4, 0) > 0) { PRINTLN(ESP.getFreeHeap()); for (int i=0; i <= qrListLength-1; i++) { //match the provided regex if (slre_match(qrList[i]->query, slackMsg.text, strlen(slackMsg.text), matches, 4, 0) > 0) { PRINTLN(matches[0].ptr); qrList[i]->resp(); //execute provided bot response return; //stop matching if match is found } } replyMsg(failMsg); } }
JSON * JSON::parse(const char *src, unsigned int length, Names *names) { Lexer lexer; lexer.src = (unsigned char *)src; lexer.length = length; lexer.names = names; #ifdef DEBUG PRINT(F("parsing ")); PRINTLN(src); #endif return parse_private(&lexer); }
/** * Entry point for the greedyBFS partition routine */ partition* greedyBFS_partition(list_graph* graph, int* seeds, int pnum){ PRINTLN("----------"); partition* p = greedyBFS_helper(graph, pnum, seeds); int i = 0; for (i=0; i < pnum; i++){ partition_print(&p[i]); } return p; }
int main() { try { cxxtools::MutexLock lock(conditionMutex); // detached threads are created on the heap. // They are deleted automatically when the thread ends. cxxtools::Thread* d = new myDetachedThread; d->create(); running.wait(lock); PRINTLN("myDetachedThread is running"); // run a function as a attached thread cxxtools::AttachedThread th( cxxtools::callable(someFunction) ); th.start(); // run a method of a object as a thread AClass aInstance("a instance"); AClass aInstance2("a instance 2"); cxxtools::AttachedThread aclassThread( cxxtools::callable(aInstance, &AClass::run) ); cxxtools::AttachedThread aclassThread2( cxxtools::callable(aInstance2, &AClass::run) ); aclassThread.start(); aclassThread2.start(); ::sleep(2); aclassThread.join(); aclassThread2.join(); // The detached thread is killed, if it does not come to an end before main. // The attached thread blocks the main-program, until it is ready. PRINTLN("main stops"); } catch (const std::exception& e) { std::cerr << "ERROR: " << e.what() << std::endl; } std::cout << "main stopped" << std::endl; }
bool EmbitLoRaModem::Send(LoRaPacket* packet, bool ack) { unsigned char length = packet->Write(sendBuffer); PRINTLN("Sending payload: "); for (unsigned char i = 0; i < length; i++) { printHex(sendBuffer[i]); } PRINTLN(); if(ack == true) SendPacket(CMD_SEND_PREFIX, sizeof(CMD_SEND_PREFIX), sendBuffer, length); else SendPacket(CMD_SEND_PREFIX_NO_ACK, sizeof(CMD_SEND_PREFIX_NO_ACK), sendBuffer, length); unsigned char result = ReadPacket(3); if(result != 0){ PRINTLN("Failed to send packet"); return false; } else return true; }