rovio_http.cpp
Go to the documentation of this file.
00001 
00011 #include <rovio_shared/rovio_http.h>
00012 
00013 using namespace std;
00014 
00015 rovio_http::rovio_http(string user, string pass)
00016 {
00017   // create the CURL handle
00018   curl = curl_easy_init();
00019   if (curl == NULL)
00020   {
00021     ROS_ERROR("Curl was unable to initialize.");
00022     exit(-1);
00023   }
00024 
00025   // set the username and password
00026   curl_easy_setopt(curl, CURLOPT_USERPWD, user.append(":").append(pass).c_str());
00027   // set the pointer to the function which handles the responses
00028   curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &write_data);
00029 
00030   // create the semaphore
00031   sem_init(&sem, 0, 1);
00032 }
00033 
00034 rovio_http::~rovio_http()
00035 {
00036   // cleanup anything left by Curl
00037   curl_easy_cleanup(curl);
00038   // destroy the semaphore
00039   sem_destroy(&sem);
00040 }
00041 
00042 rovio_response *rovio_http::send(const char *url)
00043 {
00044   // wait for the curl handle to be free
00045   sem_wait(&sem);
00046 
00047   // create the response for the Rovio
00048   rovio_response *resp = (rovio_response *)malloc(sizeof(rovio_response));
00049   resp->size = 0;
00050   resp->data = NULL;
00051   curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp);
00052 
00053   //send the command to the Rovio
00054   curl_easy_setopt(curl, CURLOPT_URL, url);
00055   curl_easy_perform(curl);
00056 
00057   sem_post(&sem);
00058 
00059   return resp;
00060 }
00061 
00062 size_t write_data(char *ptr, size_t size, size_t nmemb, rovio_response *buf)
00063 {
00064   // actual size of the new data
00065   size_t new_data = size * nmemb;
00066 
00067   // see if there is any data
00068   if (new_data > 0)
00069   {
00070 
00071     // check if the buffer already has data
00072     if (buf->data)
00073       // resize the buffer
00074       buf->data = (char *)realloc(buf->data, buf->size + new_data + 1);
00075     else
00076       // allocate the initial memory
00077       buf->data = (char *)malloc(new_data + 1);
00078 
00079     // add the data to the buffer
00080     memcpy(&(buf->data[buf->size]), ptr, new_data);
00081     //update the size
00082     buf->size += new_data;
00083     // null terminate
00084     buf->data[buf->size] = '\0';
00085   }
00086 
00087   return new_data;
00088 }
00089 
00090 void rovio_response_clean(rovio_response *resp)
00091 {
00092   // check if the response is null
00093   if (resp)
00094   {
00095     // free the data (if any)
00096     if (resp->data)
00097       free(resp->data);
00098     // free the struct
00099     free(resp);
00100   }
00101 }


rovio_shared
Author(s): Russell Toris
autogenerated on Mon Oct 6 2014 07:13:07