Twitter.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. Twitter.cpp - Arduino library to Post messages to Twitter using OAuth.
  3. Copyright (c) NeoCat 2010-2011. All right reserved.
  4. This library is distributed in the hope that it will be useful,
  5. but WITHOUT ANY WARRANTY; without even the implied warranty of
  6. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  7. */
  8. // ver1.2 - Use <string.h>
  9. // ver1.3 - Support IDE 1.0
  10. #include <string.h>
  11. #include "Twitter.h"
  12. #define LIB_DOMAIN "arduino-tweet.appspot.com"
  13. #if defined(ARDUINO) && ARDUINO < 100
  14. static uint8_t server[] = {0,0,0,0}; // IP address of LIB_DOMAIN
  15. Twitter::Twitter(const char *token) : client(server, 80), token(token)
  16. {
  17. }
  18. #else
  19. Twitter::Twitter(const char *token) : token(token)
  20. {
  21. }
  22. #endif
  23. bool Twitter::post(const char *msg)
  24. {
  25. #if defined(ARDUINO) && ARDUINO < 100
  26. DNSError err = EthernetDNS.resolveHostName(LIB_DOMAIN, server);
  27. if (err != DNSSuccess) {
  28. return false;
  29. }
  30. #endif
  31. parseStatus = 0;
  32. statusCode = 0;
  33. #if defined(ARDUINO) && ARDUINO < 100
  34. if (client.connect()) {
  35. #else
  36. if (client.connect(LIB_DOMAIN, 80)) {
  37. #endif
  38. client.println("POST http://" LIB_DOMAIN "/update HTTP/1.0");
  39. client.print("Content-Length: ");
  40. client.println(strlen(msg)+strlen(token)+14);
  41. client.println();
  42. client.print("token=");
  43. client.print(token);
  44. client.print("&status=");
  45. client.println(msg);
  46. } else {
  47. return false;
  48. }
  49. return true;
  50. }
  51. bool Twitter::checkStatus(Print *debug)
  52. {
  53. if (!client.connected()) {
  54. if (debug)
  55. while(client.available())
  56. debug->print((char)client.read());
  57. client.flush();
  58. client.stop();
  59. return false;
  60. }
  61. if (!client.available())
  62. return true;
  63. char c = client.read();
  64. if (debug)
  65. debug->print(c);
  66. switch(parseStatus) {
  67. case 0:
  68. if (c == ' ') parseStatus++; break; // skip "HTTP/1.1 "
  69. case 1:
  70. if (c >= '0' && c <= '9') {
  71. statusCode *= 10;
  72. statusCode += c - '0';
  73. } else {
  74. parseStatus++;
  75. }
  76. }
  77. return true;
  78. }
  79. int Twitter::wait(Print *debug)
  80. {
  81. while (checkStatus(debug));
  82. return statusCode;
  83. }