2017-08-22 7 views
0

これは私の最初の投稿ですので、どこが間違っているか教えてください。正しいMQTTブローカー・サーバーが見つからない

これは私の設定です。 SCLとSTAを介してESP8266開発キットに接続されたセンサーがあります。 私の言語はarduinoです。これは動作し、私はシリアルモニタに温度と湿度を出すことができます。私はラズベリーパイ(3?)も持っていますが、現在はWiFiルーターとして機能しています。私はこれを行うためにhostapdを使いました。私はアマゾンAWSにもサインアップしており、AWSIoTをpiと接続させています。これはブローカーとしてモスキートを実行しています。私の目標は、センサーを使ってpiとespをイーサネットに接続し、温度と湿度をキバナブラウザに来てデータを見ることができるようにすることです。

これは私の問題です。 mosquittoは、mosquitto_subおよびmosquitto_pubクライアントで動作します。しかし、私のarduinoコードは接続できません。私はこれがIPアドレスの問題だと思っていたので、インターネットに相談してテストサイトを多数取得しましたが、IPアドレスをmqttブローカーサーバーにする場所を教えてくれませんでした。私は自分のコードを含んでいて、私は日本に住んでいるので、時間の設定に驚かないでください。あなたが見ることができるように、私は多分働くことができる多くの異なるものを試してきました。

#include "SparkFun_Si7021_Breakout_Library.h" 
#include <Wire.h> 
#include <ESP8266WiFi.h> 
#include <PubSubClient.h> 
#include <time.h> 
#include <WiFiUdp.h> 

float humidity = 0; 
float tempf = 0; 
const char* SSID = "ssid"; 
const char* PASSWORD = "password"; 
const int MQTTPORT = 1883; 

ここではさまざまなipsを試しましたが、どれもうまくいきませんでした。 (のconst char型を使用するには、*下記フォーマット)

//const char* MQTTSERVER = "mosquitto.service"; 
//const char* MQTTSERVER = "systemctl"; 
//const char* MQTTSERVER = "bridgeawsiot2"; 
const char* MQTTINITTOPIC = "/dev/init/msg/"; 
const char* MQTTSNTOPIC = "/ras-xdv2/Si7021"; 
const char* MQTTINITTOPICMSG = "{\"dev\"=\"Si7021\",\"msg\"=\"init\"}"; 

// APRIME 
WiFiUDP ntpUDP; 
const char* NTPSERVER = "ntp.nict.jp"; 
const int NTPTIMEOFFSET = 9 * 60 * 60; 

WiFiClient espClient; 
PubSubClient client(espClient); 

//Create Instance of HTU21D or SI7021 temp and humidity sensor and MPL3115A2   barrometric sensor 
Weather sensor; 
//--------------------------------------------------------------- 
void setup_wifi() { 

    delay(10); 
    Serial.print("WiFi CONNECTION..."); 
    Serial.println(SSID); 

    WiFi.begin(SSID, PASSWORD); 

    while (WiFi.status() != WL_CONNECTED){ 
    delay(500); 
    Serial.print("Waiting..."); 
    } 

    randomSeed(micros()); 


    Serial.println(" "); 
    Serial.println("WiFi connected"); 
    Serial.println("ESP8266 ip:"); 
    Serial.println(WiFi.localIP()); 


} 
//--------------------------------------------------------------- 
void mqttConnect() { 

// client.setServer(MQTTSERVER, MQTTPORT); 

    while (!client.connected()) { 
    Serial.print("MQTT communications need more time..."); 



    String clientId = "ESP8266-"; 
    clientId += String(random(0xffff)); 
delay(3000); 
    if (client.connect(clientId.c_str())) { 
     Serial.println("MQTT communications online!"); 
     client.publish(MQTTINITTOPIC, MQTTINITTOPICMSG); 

    } else { 
     Serial.print("MQTT communications unavailible, rc="); 

     Serial.print(client.state()); 
     delay(2000); 
     Serial.println("Attempting connection in t-2 Seconds..."); 
     delay(2000); 
    } 
    } 
} 



//--------------------------------------------------------------- 
void setup() 
{ 
    Serial.begin(115200); 
     sensor.begin(); 
setup_wifi(); 
client.setServer(MQTTSERVER, MQTTPORT); 
delay(5000); 
/*if (!sensor.begin()) { 
    Serial.print("sensor ded :("); 
    while (1); 
}*/ 
configTime(NTPTIMEOFFSET, 0, NTPSERVER); 


} 
//--------------------------------------------------------------- 

void loop() 
{ 

    time_t t = time(NULL); 
    struct tm *tm; 
    tm = localtime(&t); 
    char dt[25]; 
    sprintf(dt, "%04d-%02d-%02dT%02d:%02d:%02d+09:00", tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); 

    Serial.printf(dt); 



    if(!client.connected()){ 
    mqttConnect(); 
    } else { 
    client.loop(); 
    } 
    char pub_json[100]; 

    //Get readings from all sensors 
    getWeather(); 
    printInfo(); 
    delay(10000); 

    char tempfbuf[4]; 
     char humiditybuf[4]; 
    sprintf(pub_json,"{\"Temperature\":%s,\"Humidity\": %s, \"@timestamp\": %s}]}",dtostrf(tempf, 4, 2, tempfbuf), dtostrf(humidity, 4, 2, humiditybuf), dt); 

    client.publish(MQTTSNTOPIC, pub_json); 
    Serial.println("TEMPERATURE BEING PUBLISHED..."); 
    Serial.println(pub_json); 

    delay(60000 * 10); 

} 
//--------------------------------------------------------------- 
void getWeather() 
{ 
    // Measure Relative Humidity from the HTU21D or Si7021 
    humidity = sensor.getRH(); 

    // Measure Temperature from the HTU21D or Si7021 
    tempf = sensor.getTemp(); 
    // Temperature is measured every time RH is requested. 
    // It is faster, therefore, to read it from previous RH 
    // measurement with getTemp() instead with readTemp() 
} 
//--------------------------------------------------------------- 
void printInfo() 
{ 
//This function prints the weather data out to the default Serial Port 

    Serial.print("Temp:"); 
    Serial.print(tempf); 
    Serial.print("F, "); 

    Serial.print("Humidity:"); 
    Serial.print(humidity); 
    Serial.println("%"); 
} 

mosquitto.confファイルは、私が最初にmosquittoをダウンロードした際にnonexistantだった(私はそれらを除外する理由は、(右?)セキュリティのためである)ので、私はそれを作成し、使用しますこの:私は、機密情報を掲載場合

を教えてください:私はこれに新しいです:)

c4message_size_limit 0 
clientid bridgeawsiot2 
persistence true 
persistence_file mosquitto.db 
persistence_location /var/mosquitto/ 
log_type all 
connection_messages true 
log_timestamp true 
allow_anonymous true 
password_file /etc/mosquitto/conf.d/users 
allow_anonymous true 
listener 9001 127.0.0.1 
protocol websockets 
connection_messages true 
log_timestamp true 
listener 1883 
connection <awsiot> 
address yl42kju76zjjodsbm6nfl4yycq.ap-northeast-1.es.amazonaws.com:8883 
topic /esp8266/Si7021/slack out 1 
cleansession true 
notifications false 

start_type automatic 
bridge_cafile /etc/mosquitto/certs/root-CA.crt 
bridge_certfile /etc/mosquitto/certs/RAS-XD.cert.pem 
bridge_keyfile /etc/mosquitto/certs/RAS-XD.private.key 

を多分問題はWebSocketをする事でしょうか? ご協力いただければ幸いです!

文字通りあらゆる:)私はArduinoのIDEを使用してesp8266とMQTTとかなり良い仕事をしています

答えて

0

。私は自分のmqttブローカーにログオンしています。これは、x509証明書を使用して暗号化されたcentos 7ボックスに設定しました。

あなたがそれについて考えるとき、私は、オペレーティングシステムがmosquittoブローカーが無料で、無料で、MySQLサーバは無料で、同じマシン上で

を設定したMySQLデータベースとユーザーアクセスを管理するために、mosquitto-AUTH-プラグインを使用し

独自の設定を行う唯一の費用は、固定IPで十分な接続です。あなたは紺碧の仮想マシンでかなり安くセットアップできます。

私が最初に友人(最初のnodemcu .9ボードを私に売った人)を始めたときは、とにかく。私はこのスクリプトを使って私を夢中にしました。

私が好きな部分は、mqttボックスなどのクライアントからmqttを監視した場合です。チップが最初に起動すると、ペイロード "Start"がトピック "device_name/status"に送信されます。こうすることで、いつオンラインになったかをいつでも把握できます。

彼が私に与えたメモをコピーしました。

幸運は

/* 
* Skeleton for ESPP based sensors. 
* Supports: 
* - OTA fw update via HTTP 
* http://ipaddr/update 
* - REST access 
* http://ipaddr:8080/<id> 
* - MQTT publish and subscribe 
*/ 

#include <ESP8266WiFi.h> 
#include <PubSubClient.h> 
#include <ESP8266mDNS.h> 
#include <WiFiUdp.h> 
#include <ESP8266WebServer.h> 
#include <ESP8266mDNS.h> 
#include <ESP8266HTTPUpdateServer.h> 
#include <aREST.h> 

// Define device name 
const char* device_name = "myHostName"; 
const char* ssid = "WiFiSSID"; 
const char* password = "wiFiPassword"; 
const char* mqtt_server = "mqtt_hostname.example.com"; 
char host[14]; 

int rest_test = 7467; 

/* WiFi Client */ 
WiFiClient espClient; 

/* MQTT Client */ 
PubSubClient client(espClient); 

/* HTTP client, for remote updates */ 
ESP8266WebServer httpServer(80); 
ESP8266HTTPUpdateServer httpUpdater; 

/* Rest server */ 
aREST rest = aREST(); 
WiFiServer restServer(8080); 

void setup() { 
    char topic[80]; 

    Serial.begin(115200); 

    /* Start WiFi */ 
    setup_wifi(); 

    /* Setup MQTT client */ 
    client.setServer(mqtt_server, 1883); 
    client.setCallback(mqtt_callback); 

    /* Start the HTTP update server */ 
    MDNS.begin(host); 
    httpUpdater.setup(&httpServer); 
    httpServer.begin(); 
    MDNS.addService("http", "tcp", 80); 

    /* Set REST variables */ 
    rest.set_id("1"); 
    rest.set_name(host); 
    rest.variable("test", &rest_test); 
    /* 
    rest.variable("temperature", &temp); 
    rest.variable("distance", &dist); 
    rest.variable("reset_count", &reset_count); 
    rest.set_id("1"); 
    rest.set_name("esp8266"); 
    */ 
    restServer.begin(); 

    /* Connect to the MQTT broker */ 
    reconnect(); 
    client.subscribe("network/broadcast"); 
    sprintf(topic, "network/%s", device_name); 
    client.subscribe(topic); 
    sprintf(topic, "%s/status", device_name); 
    client.publish(topic, "start"); 

    Serial.print("Node "); 
    Serial.print(device_name); 
    Serial.println(" started."); 

    Serial.print("Hostname "); 
    Serial.println(host); 

    Serial.print("IP Address "); 
    Serial.println(WiFi.localIP()); 


} 

void setup_wifi() { 
    uint8_t mac[6]; 

    delay(10); 

    WiFi.begin(ssid, password); 
    WiFi.macAddress(mac); 
    sprintf(host, "esp-%02x%02x%02x", mac[3], mac[4], mac[5]); 
    WiFi.hostname(host); 

    while (WiFi.status() != WL_CONNECTED) { 
    delay(500); 
    } 
} 

/* Handle incoming MQTT messages */ 
void mqtt_callback(char* topic, byte* payload, unsigned int length) { 
    char payloadStr[80]; 

    if (length > 79) { 
    length = 79; 
    } 
    memcpy(payloadStr, payload, length); 
    payloadStr[length] = '\0'; 


    if (strcmp(payloadStr, "discover") == 0) { 
    delay(random(10, 1000)); 
    client.publish("network/presence", device_name); 
    } 

    if (strcmp(payloadStr, "refresh") == 0) { 
    /* Publish all sensor data */ 

    } 
} 

/* Connect (or re-connect) to the MQTT broker */ 
void reconnect() { 
    // Loop until we're reconnected 
    while (!client.connected()) { 
    // Attempt to connect 
    /* TODO: Create this based on the MAC address */ 
    if (client.connect(host)) { 

    } else { 

     // Wait 5 seconds before retrying 
     delay(5000); 
    } 
    } 
} 

void loop() { 
    WiFiClient restClient; 

    /* Check MQTT connection, reconnect if needed */ 
    if (!client.connected()) { 
    reconnect(); 
    } 

    /* Process MQTT tasks */ 
    client.loop(); 

    /* Process HTTP FW update requests */ 
    httpServer.handleClient(); 

    /* Process REST requests */ 
    restClient = restServer.available(); 
    if (restClient) { 
    while (!restClient.available()) { 
     delay(1); 
    } 
    rest.handle(restClient); 
    } 


    /* Insert normal sensor code here. */ 
    /* Publish results with client.publish(topic, value); */ 

} 

私のコードは、それ自身のデバイス名を設定しMQTTトピック「ネットワーク/ブロードキャスト」、「ネットワーク/(デバイス名)」に加入しています。

起動すると、ペイロードが「開始」の「(デバイス名)/ステータス」が送信されます。

ペイロードが「検出」の「ネットワーク/ブロードキャスト」を取得すると、「ネットワーク/プレゼンス」とその名前を公開して応答します。

基本的に、client.publish(topic、payload)でMQTTイベントを送信しました。

client.subscribe(トピック)でイベントを購読します。

サブスクリプションに一致するイベントが受信されると、mqtt_callbackが呼び出され、トピック、ペイロード、および長さが与えられます。

希望に役立ちます。

関連する問題