ruby-on-rails - Arduino 可以使用 REST API 方法向 Rails Server 发送数据吗?

标签 ruby-on-rails rest api server arduino

我们可以使用API​​​​将数据从使用以太网或wifi屏蔽的arduino发送到RAILS服务器吗?如果可能的话,你能告诉我哪个库以及如何使用它吗?

最佳答案

是的,您可以通过以太网或 WiFi 扩展板从 Arduino 调用 RESTful API。我更喜欢使用标准库,例如 Ethernet / Ethernet 2 .

这是一个示例(以太网)实现供您引用:

#include <Ethernet2.h>
#include <EthernetClient.h>
#include <EthernetUdp2.h>
#include <util.h>

IPAddress _ip(192, 168, 1, 12); // Client (Arduino) IP address
byte _mac[] = {0x90, 0xA2, 0xDA, 0x11, 0x3C, 0x69}; // Arduino mac address
char _server[] = "192.168.1.10"; // Server IP address
int _port = 9200; // Server port number
EthernetClient _client;

void setup() {    
  Ethernet.begin(_mac, _ip);
  delay(1000);
  Serial.print("Local IP: ");
  Serial.println(Ethernet.localIP());

  if (_client.connect(_server, _port)) {
    Serial.println("SUCCESS: Connected to the server!");
  } else {
    Serial.println("ERROR: Connection failed to the server!");
    return;
  }
  delay(1000);
}

void loop() {       
  // JSON formatted data package including sample 
  // 'temperature', 'humidity', and 'timestamp' values
  String data = "{\"temperature\": " + String(temperature) + ", " +
    "\"humidity\": " + String(humidity) + ", " +
    "\"timestamp\": " + String(timestamp) + "}";

  String url = "/my-api/savedata"; // API url hosted on the server

  // Finally, make an API call: POST request
  _client.print("POST " + url + " HTTP/1.1 \r\n" +
    "Content-Type: application/json \r\n" +
    "Content-Length: " + data.length() + " \r\n" +
    "\r\n" + data);

  delay(500); // Give the network some time

  // Read all the lines of the reply from server and 
  // print them to Serial to validate your API call
  while (_client.available()) {
    String reply = _client.readStringUntil('\r');
    Serial.print(reply);
  }
  Serial.println();
}

关于ruby-on-rails - Arduino 可以使用 REST API 方法向 Rails Server 发送数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48972895/

相关文章:

web-services - 有没有人成功使用过新的 WCF REST Starter Kit,你会再次使用它吗?

api - 使用 Trello API 创建卡片后如何解析响应

ruby-on-rails - 使用 RSpec stub ActiveRecord 动态查找器

ruby-on-rails - Ruby on Rails捕获摄像头视频和音频

ruby-on-rails - 安装 Rails 时出错 : Failed to build Gem native extension, 'lack of libraries or headers'

ruby-on-rails - Rails 5 ActionCable WebSockets 未返回状态为 101 升级响应的升级 header

rest - 在 REST API 中处理非常深的关系

android - 如何在 android 中调用 Https Rest 服务

python - Duo API Bash 调用

javascript - 获取当前持续时间的 Facebook 视频 api