Advertisement
Guest User

Spark Core Code

a guest
Jul 1st, 2014
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.05 KB | None | 0 0
  1. /*This is the code that will be on the Spark Core*/
  2.  
  3. #define NUM_TRIES 2
  4. #define MAXLINE 1024
  5. TCPClient client;
  6. byte server[] = { 10,0,0,18 }; // Rpi server
  7. int port = 17060;
  8.  
  9. char *connect_and_send(char* message);
  10. void *get_response(char *response);
  11. char *response_buf = (char*)malloc(sizeof(char) * MAXLINE/4);;
  12.  
  13. void setup()
  14. {
  15.     pinMode(D7, OUTPUT);
  16.     Spark.variable("response", response_buf, STRING);
  17. }
  18.  
  19. void loop()
  20. {
  21.     char *response = connect_and_send("GET pi.txt");
  22.     if(response == NULL)
  23.     {
  24.         return;
  25.     }
  26.     strcpy(response_buf, response);
  27.     digitalWrite(D7, HIGH);
  28.     delay(5000);
  29.     if(response != NULL)
  30.         free(response);
  31.     digitalWrite(D7, LOW);
  32. }
  33.  
  34.  
  35. //Call this function to connect and send a message. Returns the message it received
  36. //TODO: make it return an array and make verbose mode where it will echo the response
  37. inline char *connect_and_send(char *message)
  38. {
  39.     bool connected = false;
  40.     char *response = (char*)malloc(sizeof(char) * MAXLINE/4);
  41.     if(response == NULL)
  42.         return response;
  43.        
  44.    
  45.     // Tries to connect to server multiple times
  46.     for(int i = 0; i < NUM_TRIES; i++)
  47.     {
  48.         if(client.connect(server,port)) //if connected, send message
  49.         {
  50.             connected = true;
  51.             client.println(message);
  52.             break;
  53.         }
  54.     }
  55.    
  56.     if(connected)   //if connection succeeded, get the file
  57.     {
  58.         get_response(response);
  59.     }
  60.  
  61.     delay(100);
  62.     client.flush();
  63.     client.stop();
  64.     return response;
  65. }
  66.  
  67. //Gets the file response from the Raspberry Pi and modifies pointer response
  68. void *get_response(char *response)
  69. {
  70.     int count = 0;
  71.     if (client.connected())
  72.     {
  73.         // echo all available bytes back to the client
  74.         while (client.available())
  75.         {
  76.             char c = client.read();
  77.             response[count] = c;
  78.             count += 1;
  79.         }
  80.     }
  81.     else
  82.     {
  83.         digitalWrite(D7, HIGH);
  84.         delay(500);
  85.         digitalWrite(D7, LOW);
  86.     }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement