无法将数据发布到我的本地mqtt服务器

如何解决无法将数据发布到我的本地mqtt服务器

请我希望有人可以帮助我。几周以来,我一直在努力工作,对此我还很陌生。

我想将数据从ESP32 SIM800L发送到mqtt代理。 mqtt服务器在我的本地机器上运行,ESP32 SIM800可以完美地连接到APN。 我看到许多教程都是通过WIFI连接实现的,但没有GPRS(我正在使用的是GPRS)。

我终于找到了:tinyGSM和这个:arduino mqtt mongodb

我按如下方法进行了修改,但仍然无法连接:

// Your GPRS credentials (leave empty,if not needed)
const char apn[]      = "internet.tn"; // APN (example: internet.vodafone.pt) use https://wiki.apnchanger.org
const char gprsUser[] = ""; // GPRS User
const char gprsPass[] = ""; // GPRS Password

// SIM card PIN (leave empty,if not defined)
const char simPIN[]   = ""; 

uint32_t lastReconnectAttempt = 0;

// TTGO T-Call pins
#define MODEM_RST            5
#define MODEM_PWKEY          4
#define MODEM_POWER_ON       23
#define MODEM_TX             27
#define MODEM_RX             26
#define I2C_SDA              21
#define I2C_SCL              22


// Set serial for debug console (to Serial Monitor,default speed 115200)
#define SerialMon Serial
// Set serial for AT commands (to SIM800 module)
#define SerialAT Serial1

// Configure TinyGSM library
#define TINY_GSM_MODEM_SIM800      // Modem is SIM800
#define TINY_GSM_RX_BUFFER   1024  // Set RX buffer to 1Kb

#include <Wire.h>
#include <TinyGsmClient.h>
#include <PubSubClient.h>

#ifdef DUMP_AT_COMMANDS
    #include <StreamDebugger.h>
    StreamDebugger debugger(SerialAT,SerialMon);
    TinyGsm modem(debugger);
#else
    TinyGsm modem(SerialAT);
#endif



// I2C for SIM800 (to keep it running when powered from battery)
TwoWire I2CPower = TwoWire(0);

const char* broker = "localhost";

const char* topicInit = "GsmClientTest/init";
// Function prototypes
void subscribeReceive(char* topic,byte* payload,unsigned int length);

// TinyGSM Client for Internet connection
// gsm and MQTT related objects
TinyGsmClient client(modem);
PubSubClient mqtt(client);

long mqtttimer = 0;                 // Timer for counting 5 seconds and retrying mqtt connection
byte mqtttarea = 1;   

#define uS_TO_S_FACTOR 1000000     /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP  3600        /* Time ESP32 will go to sleep (in seconds) 3600 seconds = 1 hour */

void mqttCallback(char* topic,unsigned int len) {
    SerialMon.print("Message arrived [");
    SerialMon.print(topic);
    SerialMon.print("]: ");
    SerialMon.write(payload,len);
    SerialMon.println();}

boolean mqttConnect() {
    SerialMon.print("Connecting to ");
    SerialMon.print(broker);

    // Connect to MQTT Broker
    boolean status = mqtt.connect("GsmClientTest");

    // Or,if you want to authenticate MQTT:
    //boolean status = mqtt.connect("GsmClientName","mqtt_user","mqtt_pass");

    if (status == false) {
        SerialMon.println(" fail");
        return false;
    }
    SerialMon.println(" success");
    mqtt.publish(topicInit,"GsmClientTest started");
    // mqtt.subscribe(topicLed);
    return mqtt.connected();}
void setup() {

    SerialMon.begin(9600);

    // Start I2C communication
    I2CPower.begin(I2C_SDA,I2C_SCL,400000);

    // Set modem reset,enable,power pins
    pinMode(MODEM_PWKEY,OUTPUT);
    pinMode(MODEM_RST,OUTPUT);
    pinMode(MODEM_POWER_ON,OUTPUT);
    digitalWrite(MODEM_PWKEY,LOW);
    digitalWrite(MODEM_RST,HIGH);
    digitalWrite(MODEM_POWER_ON,HIGH);

    // Set GSM module baud rate and UART pins
    SerialAT.begin(9600,SERIAL_8N1,MODEM_RX,MODEM_TX);
    delay(3000);

    // Restart SIM800 module,it takes quite some time
    // To skip it,call init() instead of restart()
    SerialMon.println("Initializing modem...");
    modem.restart();
    // use modem.init() if you don't need the complete restart

    // Unlock your SIM card with a PIN if needed
    if (strlen(simPIN) && modem.getSimStatus() != 3 ) {
        modem.simUnlock(simPIN);
    }
    SerialMon.print("Connecting to APN: ");
    SerialMon.print(apn);
    if (!modem.gprsConnect(apn,gprsUser,gprsPass)) {
        SerialMon.println(" fail");
    }
    else {
        SerialMon.println(" OK");
    }
    // MQTT Broker setup
    mqtt.setServer(broker,1883);
    mqtt.setCallback(mqttCallback);
    esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
}


void loop() {
    // This is needed at the top of the loop!
    if (!mqtt.connected()) {
        SerialMon.println("=== MQTT NOT CONNECTED ===");
        // Reconnect every 10 seconds
        uint32_t t = millis();
        if (t - lastReconnectAttempt > 10000L) {
            lastReconnectAttempt = t;
            if (mqttConnect()) {
                lastReconnectAttempt = 0;
            }
        }
        delay(100);
        return;
    }
    mqtt.publish(topicInit,"Hello");
    mqtt.loop();

}

解决方法

您将经纪人的名称设置为localhost

const char* broker = "localhost";

localhost和IP地址127.0.0.1表示“此代码在其上运行的主机”。在运行代理的计算机上键入命令时,localhost表示该计算机。它无法在ESP32上运行。

您需要运行代理的计算机的名称或IP地址。如何找到将取决于您正在运行的操作系统。

如果该计算机位于您的本地网络上,则可能使用的是专用IP地址,例如10.0.1.x192.168.1.x。如果是这种情况,您将需要在路由器中使用端口转发将数据包转发到该端口(然后,您将使用路由器的IP地址而不是代理的IP地址)。

如果您使用的是路由器的IP地址,该地址可能会更改而不会发出警告,因此您需要使用类似Dynamic DNS的名称来保持其当前IP地址的最新状态。

您最好在基于云的虚拟服务器上在网络外部运行代理,或者使用其中的几种商业MQTT服务之一。他们中的大多数都有免费套餐,每月可以允许相当数量的流量。

无论如何,localhost永远不会在这里工作。您需要真实,公开的IP地址或您的经纪人名称。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-