首页 文章

找不到正确的MQTT代理服务器

提问于
浏览
0

这是我的第一篇文章,告诉我哪里出错了 .

这是我的设置 . 我有一个传感器通过SCL和STA连接到ESP8266开发套件 . 我的语言是arduino . 这样可以,我可以将温度和湿度输出到串行监视器中 . 我还有一个覆盆子pi(3?),目前作为一个wifi路由器 . 我使用hostapd来做到这一点 . 我还注册了amazon AWS,并让AWSIoT与pi连接,我有mosquitto作为经纪人运行 . 我的目标是能够将pi和esp与传感器放在一个位置,pi与以太网连接,并让温度和湿度来到kibana浏览器,我能够看到数据 .

这是我的问题 . mosquitto与mosquitto_sub和mosquitto_pub客户端一起工作 . 但是,我的arduino代码无法连接 . 我怀疑这是IP地址的问题,所以我咨询了互联网,并获得了许多测试站点,但没有人告诉我在哪里可以找到作为mqtt代理服务器的IP . 我已经包含了我的代码,而且我住在日本,所以不要被时间设置吓到 . 正如你所看到的,我一直在尝试许多可能有用的不同的东西:/ .

#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时,mosquitto.conf文件是不存在的,所以我创建它并使用它:

请告诉我是否发布了敏感信息:我是新来的:)

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

也许问题是websockets的事情?任何帮助表示赞赏!

字面上任何:)

1 回答

  • 0

    我正在使用arduino IDE与esp8266和mqtt做一些相当不错的工作 . 我已经登录到我自己的mqtt经纪人,我在一个使用x509证书加密的centos 7盒子中设置 .

    我使用mosquitto-auth-plug来管理用户访问,同时在同一台机器上设置mysql数据库

    当你想到它时,操作系统是免费的,mosquitto broker是免费的,而mysql服务器是免费的 .

    拥有自己的设置的唯一费用是固定IP和足够快的连接 . 你可以在azure上的虚拟机中设置相当便宜的 .

    无论如何,当我第一次开始一个朋友(那个卖我第一个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主题“network / broadcast”,“network /(device name)” .

    当它启动时,它发送“(device_name)/ status”,其有效负载为“start” .

    当它获得具有“发现”有效载荷的“网络/广播”时,它通过发布“网络/存在”及其名称来回复 .

    基本上,您使用client.publish(topic,payload)发送了MQTT事件 .

    您使用client.subscribe(topic)订阅事件 .

    当收到与您的订阅匹配的事件时,它将调用mqtt_callback并为其提供主题,有效负载和长度 .

    希望有所帮助 .

相关问题