Arduino MKR1000 Как отправить сообщение в центр IoT Azure
Я пытаюсь настроить базовый пример отправки сообщения из Arduino MKR1000 в концентратор событий IOT Azure, но не могу заставить работать какие-либо онлайн-примеры, и я новичок в Arduino.
Любые указатели для простого рабочего примера?
Я попробовал этот пример и слегка изменил POST сообщение, а не получил, но не повезло. Я могу подключиться к Wi-Fi без проблем, просто при публикации запроса HTTP он выдает ошибку "Ошибка HTTP 411. Запрос должен быть разделен на части или иметь длину содержимого". Это также не кажется самым чистым подходом, но я просто не хочу пока что-то заводить, чтобы поиграть:)
Пример кода:
#include <SPI.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID; // your network SSID (name)
char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
const int MKR1000_LED = 6 ;
///*** Azure IoT Hub Config ***///
//see: http://mohanp.com/ for details on getting this right if you are not sure.
char hostname[] = "*****.azure-devices.net"; // host name address for your Azure IoT Hub
char feeduri[] = "/devices/MKR1000/messages/events?api-version=2018-06-30"; //feed URI
char authSAS[] = "SharedAccessSignature sr=******.azure-devices.net%2Fdevices%2FMKR1000&sig=*****&se=******";
///*** Azure IoT Hub Config ***///
unsigned long lastConnectionTime = 0;
const unsigned long pollingInterval = 5L * 1000L; // 5 sec polling delay, in milliseconds
int status = WL_IDLE_STATUS;
WiFiSSLClient client;
void setup() {
Serial.println("setup...");
pinMode(MKR1000_LED, OUTPUT);
//check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
// don't continue:
while (true);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Wifi connected...");
}
void loop()
{
String response = "";
char c;
///read response if WiFi Client is available
while (client.available()) {
c = client.read();
response.concat(c);
}
if (!response.equals(""))
{
Serial.println(response);
//if there are no messages in the IoT Hub Device queue, Azure will return 204 status code.
if (response.startsWith("HTTP/1.1 204"))
{
//turn off onboard LED
digitalWrite(MKR1000_LED, LOW);
}
else
{
//turn on onboard LED
digitalWrite(MKR1000_LED, HIGH);
}
}
// polling..if pollingInterval has passed
if (millis() - lastConnectionTime > pollingInterval) {
digitalWrite(MKR1000_LED, LOW);
azureHttpRequest("{TEST MESSAGE!}");
}
}
// this method makes an HTTPS connection to the Azure IOT Hub Server:
void azureHttpRequest(String data) {
// close any connection before send a new request.
// This will free the socket on the WiFi shield
client.stop();
// if there's a successful connection:
if (client.connect(hostname, 443)) {
//make the GET request to the Azure IOT device feed uri
client.print("POST "); //Do a GET
client.print(feeduri); // On the feedURI
client.println(" HTTP/1.1");
client.print("Host: ");
client.println(hostname); //with hostname header
client.print("Authorization: ");
client.println(authSAS); //Authorization SAS token obtained from Azure IoT device explorer
//client.println("Connection: close");
client.println("Content-Type: application/json");
client.println("Content-Length: " + data.length());
client.println("\r\n\r\n" + data);
// note the time that the connection was made:
lastConnectionTime = millis();
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
}
}
Изменить: я видел, что есть полная библиотека Azure IOT с простым примером HTTP, но он также не запускается (он проходит через соединение Wi-Fi и терпит неудачу при вызове Azure), но этот пример проекта довольно большой, и я был надеясь на простой пример, на котором можно основываться!
0 ответов
Здесь у вас есть готовый пример: https://github.com/firedog1024/mkr1000-iotc.
Обратите внимание, что для подготовки используется служба подготовки устройств Azure IoT, поэтому вам нужно будет настроить экземпляр DPS вместе с центром Интернета вещей.