Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*This is the code that will be on the Spark Core*/
- #define NUM_TRIES 2
- #define MAXLINE 1024
- TCPClient client;
- byte server[] = { 10,0,0,18 }; // Rpi server
- int port = 17060;
- char *connect_and_send(char* message);
- void *get_response(char *response);
- char *response_buf = (char*)malloc(sizeof(char) * MAXLINE/4);;
- void setup()
- {
- pinMode(D7, OUTPUT);
- Spark.variable("response", response_buf, STRING);
- }
- void loop()
- {
- char *response = connect_and_send("GET pi.txt");
- if(response == NULL)
- {
- return;
- }
- strcpy(response_buf, response);
- digitalWrite(D7, HIGH);
- delay(5000);
- if(response != NULL)
- free(response);
- digitalWrite(D7, LOW);
- }
- //Call this function to connect and send a message. Returns the message it received
- //TODO: make it return an array and make verbose mode where it will echo the response
- inline char *connect_and_send(char *message)
- {
- bool connected = false;
- char *response = (char*)malloc(sizeof(char) * MAXLINE/4);
- if(response == NULL)
- return response;
- // Tries to connect to server multiple times
- for(int i = 0; i < NUM_TRIES; i++)
- {
- if(client.connect(server,port)) //if connected, send message
- {
- connected = true;
- client.println(message);
- break;
- }
- }
- if(connected) //if connection succeeded, get the file
- {
- get_response(response);
- }
- delay(100);
- client.flush();
- client.stop();
- return response;
- }
- //Gets the file response from the Raspberry Pi and modifies pointer response
- void *get_response(char *response)
- {
- int count = 0;
- if (client.connected())
- {
- // echo all available bytes back to the client
- while (client.available())
- {
- char c = client.read();
- response[count] = c;
- count += 1;
- }
- }
- else
- {
- digitalWrite(D7, HIGH);
- delay(500);
- digitalWrite(D7, LOW);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement