int main(int argc, char* argv[]) { // define Arguments and Application variables define_args(); // parse Arguments if (A.parseArgs(argc, argv) == false) { A.printArgs(); exit(EXIT_FAILURE); } // print Help if (A.getParam<bool>("p_help") == true) { A.printArgs(); exit(EXIT_SUCCESS); } TCPClient* client = new TCPClient(); TCPSocket* socket = client->connect(A.getParam<const char*>("p_server"), A.getParam<int>("p_port")); if (socket != NULL) { // build message std::string message(A.getArg(0)); for (size_t i = 1; i < A.numArg(); i++) { message += " "; message += A.getArg(i); } socket->send(message.c_str(), message.size()); char data[1024]; size_t datalen; datalen = socket->recv(data, sizeof(data)-1); data[datalen] = '\0'; std::cout << data; delete socket; } delete client; return 0; }
void setup() { // Set the pin mode pinMode(led, OUTPUT); // Initialize the Serial Serial.begin(9600); // Connect to the remote server if(client.connect(server, port)) { Serial.println("Connected"); } else { // if we can't connect, then we display an error. Serial.println("error"); } }
void TCPServer::connectClient() { emit info(classname, "adding new connection"); // Create socket and client while(server->hasPendingConnections()) { QTcpSocket *socket = server->nextPendingConnection(); QObject::connect(socket, SIGNAL(disconnected()), this, SLOT(disconnectClient())); socketMap[socket] = socket; TCPClient *client = new TCPClient(this); client->connect(socket); QObject::connect(client, SIGNAL(dataReceived(QByteArray)), this, SLOT(clientDataReceived(QByteArray))); QObject::connect(client, SIGNAL(info(QString,QString)), this, SLOT(clientInfo(QString,QString))); QObject::connect(client, SIGNAL(warning(QString,QString)), this, SLOT(clientWarning(QString,QString))); QObject::connect(client, SIGNAL(error(QString,QString)), this, SLOT(clientError(QString,QString))); clientMap[socket] = client; } emit connectionCount(socketMap.size()); }
char * http_get(char const * hostname, String path) { int i = 0; int j = 0; int k = 0; bool printOnce = false; if (client.connect(hostname, 80)) { client.print("GET "); client.print(path); client.println(" HTTP/1.1"); client.print("HOST: "); client.println(hostname); client.println("Connection: close"); client.println(); client.flush(); } else { if(DEBUG_SERIAL) Serial.println("\r\n\r\nConnection Failed!"); client.flush(); client.stop(); return NULL; } // wait 5 seconds or less for the host to respond uint32_t startTime = millis(); while(!client.available() && (millis() - startTime) < 5000); if(DEBUG_SERIAL) Serial.println("\r\n\r\nREADING HOST DATA......"); uint32_t lastRead = millis(); // If the host doesn't close it's connection, we'll timeout in 10 seconds. while (client.connected() && (millis() - lastRead) < 10000) { while (client.available()) { char c = client.read(); /* if(DEBUG_SERIAL) { Serial.print(c); if(i++ > 100) { delay(5); i = 0; } } */ if(c == -1) { Serial.print("\r\n\r\nERROR......\r\n\r\n"); client.flush(); client.stop(); } if(j++ >= SKIP_CHARS) { // don't buffer the first X bytes to save memory if(DEBUG_SERIAL && !printOnce) { Serial.print("\r\n\r\nSAVING......\r\n\r\n"); printOnce = true; } buffer[k++] = c; // save character to buffer Serial.print(c); delayMicroseconds(100); if(k >= BUFFER_SIZE_MAX) { // if we reach the end of our buffer, just bail. Serial.print("\r\n\r\nOUT OF BUFFER SPACE......\r\n\r\n"); client.flush(); client.stop(); } } // as long as we're reading data, reset the lastRead time. lastRead = millis(); } // END while(client.available()) } // END while(client.connected()) client.flush(); client.stop(); if(DEBUG_SERIAL) { Serial.print("\r\nCHARACTERS RECEIVED: "); Serial.println(SKIP_CHARS + k); } return buffer; }
void connect(const char* host, uint16_t port, char* const *args, int argCount) { TCPClient* client = new TCPClient(); TCPSocket* socket = client->connect(host, port); bool once = args != NULL && argCount > 0; if (socket != NULL) { do { string message; bool listening = false; if (!once) { cout << host << ": "; getline(cin, message); } else { for (int i = 0; i < argCount; i++) { if (i > 0) message += " "; bool quote = strchr(args[i], ' ') != NULL && strchr(args[i], '"') == NULL; if (quote) message += "\""; message += args[i]; if (quote) message += "\""; } } message += '\n'; socket->send(message.c_str(), message.size()); if (strcasecmp(message.c_str(), "Q") == 0 || strcasecmp(message.c_str(), "QUIT") == 0 || strcasecmp(message.c_str(), "STOP") == 0) break; if (message.length() > 0) { if (strcasecmp(message.c_str(), "L") == 0 || strcasecmp(message.c_str(), "LISTEN") == 0) { listening = true; while (listening && !cin.eof()) { string result(fetchData(socket, listening)); cout << result; if (strcasecmp(result.c_str(), "LISTEN STOPPED") == 0) break; } } else cout << fetchData(socket, listening); } } while (!once && !cin.eof()); delete socket; } else cout << "error connecting to " << host << ":" << port << endl; delete client; }
void loop() { int debug = digitalRead(debug_tx); if(!digitalRead(waitpin_C)){ // Skip mode, to ensure bootloader stays available char buffer[32]; sprintf(buffer,"skip state: %d\r\n",state); Serial1.print(buffer); digitalWrite(led, HIGH); // Turn ON the LED delay(100); return; }else{ digitalWrite(led, LOW); // Turn OFF the LED } delay(1); switch(state){ case 0: // Waiting for next time wait-=10; if(wait<0){ wait = 0; state = 1; } break; case 1: // Connecting if(debug) Serial1.println("connecting"); if (client.connect(server, 80)){ if(debug) Serial1.println("connected"); state = 2; }else{ if(debug) Serial1.println("connection failed state 1"); wait = RETRY_INTERVAL; state = 0; } break; case 2: // Requesting tries = 0; store = 0; hash = 0; command_i = 0; for(int i=0; i<COMMAND_SIZE; i++) command[i] = 0; if(client.connected()){ if(debug) client.println("GET // HTTP/1.0\r\n\r\n"); wait = RESPONSE_INTERVAL; state = 3; }else{ if(debug) Serial1.println("connection lost state 2"); wait = RETRY_INTERVAL; state = 0; } break; case 3: // Receiving if(client.connected()){ if (client.available() > 0) { // Print response to serial char c = client.read(); if(debug) Serial1.print(c); // If last expected char found, quit reading if(c =='>') hash = 1; // If first char of data found, start storing the string if(c =='<') store = 1; if(store){ command[command_i++] = c; } }else{ if(debug) Serial1.println("nd s3 "); delay(100); } // Quit reading if(hash){ Serial1.println(); state = 4; } }else{ // We lost connection if(debug) Serial1.println("connection lost state 3"); wait = RETRY_INTERVAL; state = 0; } break; case 4: // Disconnecting if(client.connected()){ client.stop(); if(debug) Serial1.println("connection closed state 4"); wait = RENEW_INTERVAL; state = 5; }else{ if(debug) Serial1.println("connection closed by server state 4"); wait = RENEW_INTERVAL; state = 5; } break; case 5: { int code = 0; // Parse data read client.stop(); if(debug) Serial1.println("I've got this:"); for(int i=0; i<COMMAND_SIZE; i++) Serial1.write(command[i]); Serial1.println(""); // Control display //int code = (command[1]*1000)+(command[2]*100)+(command[3]*10)+(command[4]*1); //float temp = atoi((const char*)&command[6]) + (0.1 * atoi((const char*)&command[8])); sscanf((const char*)command,"<%d;%f>",&code,&temperature); if(debug) Serial1.print("Code: ");Serial1.println(code); if(debug) Serial1.print("Temp: ");Serial1.println(temperature); display(temperature); /* char tempString[10]; //Used for sprintf Serial1.println(); Serial1.write('v'); sprintf(tempString, "%4d", temp); //Convert deciSecond into a string that is right adjusted Serial1.print(tempString); */ wait = RENEW_INTERVAL; state = 0; } break; } }
// Called in a loop forever void loop() { // When you push the button if (digitalRead(D0) == HIGH) { // It might take a couple of loop() iterations to // successfully connect to iamresponding.com connecting = true; // This is how to control the Spark's RGB LED RGB.control(true); // Red to indicate we're attempting to connect RGB.color(255, 0, 0); // Push the button once to respond to station. // Push it again to cancel. if (responding) { // Do just what the iamresponding.com app does data = "{\"keyEntryDesc\":\"CANCELLED\",\"memberIDS\":\"\",\"subscriberID\":\"\",\"userfullname\":\"Jack Bates\"}"; } else { data = "{\"keyEntryDesc\":\"Station\",\"memberIDS\":\"\",\"subscriberID\":\"\",\"userfullname\":\"Jack Bates\"}"; } } // We haven't successfully connected since the button was last // pushed, keep trying! if (connecting && client.connect(server, 80)) // HTTP is port { // number 80, FYI // We successfully connected, stop trying connecting = false; // Yellow to indicate we successfully connected and // sent the magic words RGB.color(255, 255, 0); // Again, just ape the iamresponding.com app client.println("POST /v3/keyEntries.asmx/AddCallEntry HTTP/1.0"); client.print("Content-Length: "); client.println(strlen(data)); client.println("Content-Type: application/json"); client.println("Host: iamresponding.com"); client.println(); // Send the magic words client.print(data); } // iamresponding.com sent something back to *us*. // (This is our only indication that TCPClient is done // transmitting the magic words. You're welcome to get clever // and check if iamresponding.com sent back confirmation or is // reporting an error, this just assumes it's confirmation.) if (client.available()) { // If we were already responding, then now we aren't // (cancelled) and vice versa (if we weren't, then now // we are). responding = !responding; if (responding) { // Blue to indicate that iamresponding.com // knows we're responding to station! RGB.color(0, 0, 255); } else { // Restore the default RGB LED behavior when // we're not responding (cancelled). // (By default it shows the Wi-Fi status.) RGB.control(false); } // Tricky: Clean up after transmitting the magic // words. Close the connection to iamresponding.com // and discard (flush) anything sent back to us, or // else in the next loop() iteration we'll think // iamresponding.com sent back something *again*. client.stop(); client.flush(); } }