Подключение Arduino к сети Heroku, подключенной к базе данных Django - PullRequest
0 голосов
/ 03 мая 2020

Чтобы описать мою проблему Я пытался подключить Arduino UNO к веб-сайту, созданному мной в Heroku .

Основная цель состояла в том, чтобы вызвать rest api функцию в arduino, подключенную к Inte rnet и получить json data .

Мой код Arduino:

#include <ArduinoJson.h>
#include <Ethernet.h>
#include <SPI.h>

void setup() {
  // Initialize Serial port
  Serial.begin(9600);
  while (!Serial) continue;

  // Initialize Ethernet library
  byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  Ethernet.init(8);  // use pin 53 for Ethernet CS

  if (!Ethernet.begin(mac)) {
   Serial.println(F("Failed to configure Ethernet"));
   return;
  }
  delay(1000);

  Serial.println(F("Connecting..."));

  // Connect to HTTP server
  EthernetClient client;
  client.setTimeout(10000);
  if (!client.connect("https://salty-cliffs-06856.herokuapp.com", 80)) {
    Serial.println(F("Connection failed"));
    return;
  }

  Serial.println(F("Connected!"));

  // Send HTTP request
  client.println(F("GET /api/command/ HTTP/1.1"));
  client.println(F("Host: https://salty-cliffs-06856.herokuapp.com"));
  client.println(F("Connection: close"));
  Serial.println(F("Done"));
  if (client.println() == 0) {
    Serial.println(F("Failed to send request"));
    return;
  }


  // Check HTTP status
  char status[32] = {0};
  client.readBytesUntil('\r', status, sizeof(status));
  Serial.println(status);
  if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
    Serial.print(F("Unexpected response: "));
    Serial.println(status);
    return;
  }

  // Skip HTTP headers
  char endOfHeaders[] = "\r\n\r\n";
  if (!client.find(endOfHeaders)) {
    Serial.println(F("Invalid response"));
    return;
  }

  // Allocate JsonBuffer
  // Use arduinojson.org/assistant to compute the capacity.
  const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
  DynamicJsonBuffer jsonBuffer(capacity);

  // Parse JSON object
  JsonObject& root = jsonBuffer.parseObject(client);
  if (!root.success()) {
   Serial.println(F("Parsing failed!"));
   return;
  }

  // Extract values
  Serial.println(F("Response:"));
  Serial.println(root["command"].as<char*>());


  // Disconnect
  client.stop();

С этим кодом все работало нормально, когда я пытался поместить туда незащищенный HTTP адрес. После размещения там моего веба , работающего на Heroku , защищенного HTTPS Я всегда получаю ошибку .

Программа выдает ошибку, когда я был проверяя статус HTTP и в моем терминале порта Arduino я получил ответ:

Unexpected response: HTTP/1.1 400 Bad Request

Я проверил логи heroku, но там нет ни одного запроса от Arduino . (Просто чтобы убедиться, что я пытался вызвать API из веб-браузера, и он работает)

Не могли бы вы помочь мне, где может быть проблема? Я думал, что это может быть из-за безопасного HTTPS. Как вы думаете?

Спасибо за любую помощь:)

1 Ответ

0 голосов
/ 03 мая 2020

Сначала измените client.connect("https://salty-cliffs-06856.herokuapp.com", 80) с

`https` 

на

`http` 

, поскольку порт 80 не является https портом, а экран Ethe rnet не поддерживает SSL.

Во-вторых, у вас неправильный заголовок http для Host. HTTP 1.1 требует, чтобы использовалось только доменное имя без префикса протокола (т.е. http: //). Поэтому измените строку:

client.println(F("Host: https://salty-cliffs-06856.herokuapp.com"));

на:

client.println(F("Host: salty-cliffs-06856.herokuapp.com"));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...