上一篇说到用JAVA写Linstener 。
很多人会问网上有很多现成的(可视化的),为啥要自己写呢?
我想说自己写的话对MQTT协议会更加的了解,而且得到的数据到时候会更加好处理,现成的东西不带这功能。
作为一个准电子工程师,必要的编程(Ctrl-C 、Ctrl-V)技能还是要有的。
所需工具:Apache Apollo(已运行的登录,参考上一篇)
ESP-IDF(参考环境搭建)
Eclipse(JAVA IDE环境)
本篇内用参考Apache Apollo->Example->MQTT->JAVA;
然而好像我的电脑用maven来Build老是有点奇奇怪怪的Bug,
所以我选用了Eclispe这IDE来编写执行。
首先 要安装JDK,默认你们看了上一篇了,JAVA环境变量什么的都搭好了。
地址https://www.eclipse.org/downloads/packages/
一个企业 一个个人,二选一。
下载->解压->运行
新建JAVA工程
New->Java Project->...->Finish
添加外部JARS包 我们需要上github下载
参考链接:https://github.com/fusesource/mqtt-client
下载链接:https://repository.jboss.org/nexus/content/groups/fs-public/org/fusesource/mqtt-client/mqtt-client/1.7/mqtt-client-1.7-uber.jar
下载软件包
图中MQTT-....那个就是了
然后回到Eclispe
右键工程My_MQTT->Properties->Java Build Path->Libraries->Add External JARS->Appy & Close 添加并应用刚才的软件包
(如果左侧没有Project工具栏 在右上角Quick Access :输入关键字Browser 然后有Project Browser 点一下就行)
然后
然后在src文件夹右键New->Java Class(如果左侧没有Project工具栏 在右上角Quick Access :输入关键字Browser 然后有Project Browser 点一下就行)
然后
将内容全部替换为下面坨代码:
import org.fusesource.hawtbuf.*;
import org.fusesource.mqtt.client.*;
public class My_MQTT {
public static void main(String []args) throws Exception {
String user = env("APOLLO_USER", "admin");//set username
String password = env("APOLLO_PASSWORD", "password");//set password
String host = env("APOLLO_HOST", "localhost");//set localhost
int port = Integer.parseInt(env("APOLLO_PORT", "61613"));//set port
final String destination = arg(args, 0, "/topic/qos1");
//set topic
MQTT mqtt = new MQTT();
mqtt.setHost(host, port);
mqtt.setUserName(user);
mqtt.setPassword(password);
final CallbackConnection connection = mqtt.callbackConnection();
connection.listener(new org.fusesource.mqtt.client.Listener() {
long count = 0;
long start = System.currentTimeMillis();
public void onConnected() {
}
public void onDisconnected() {
}
public void onFailure(Throwable value) {
value.printStackTrace();
System.exit(-2);
}
public void onPublish(UTF8Buffer topic, Buffer msg, Runnable ack) {
String body = msg.utf8().toString();
System.out.println(String.format("Received %s", body));
}
});
connection.connect(new Callback() {
@Override
public void onSuccess(Void value) {
Topic[] topics = {new Topic(destination, QoS.AT_LEAST_ONCE)};
connection.subscribe(topics, new Callback() {
public void onSuccess(byte[] qoses) {
System.out.println(String.format("Connect Successfully"));
}
public void onFailure(Throwable value) {
value.printStackTrace();
System.exit(-2);
}
});
}
@Override
public void onFailure(Throwable value) {
value.printStackTrace();
System.exit(-2);
}
});
// Wait forever..
synchronized (My_MQTT.class) {
while(true)
My_MQTT.class.wait();
}
}
private static String env(String key, String defaultValue) {
String rc = System.getenv(key);
if( rc== null )
return defaultValue;
return rc;
}
private static String arg(String []args, int index, String defaultValue) {
if( index < args.length )
return args[index];
else
return defaultValue;
}
}
上面这堆东西就是设置 帐号 密码 端口 等等东西
点击Run
如果控制台出现Connect Successfully 就代表成功了
好这里只完成了JAVA部分 然后使用ESP32进行连接
ESP32
注意 这里电脑和ESP32要连到同一路由器(同一网段)
如何查本地地址 ifconfig
我的是192.168.0.225
进入到 修改 '/home/jasper/esp/esp-idf/examples/protocols/mqtt/tcp/main/app_main.c'
#include
#include
#include
#include
#include "esp_wifi.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event_loop.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"
#include "freertos/event_groups.h"
#include "lwip/sockets.h"
#include "lwip/dns.h"
#include "lwip/netdb.h"
#include "esp_log.h"
#include "mqtt_client.h"
static const char *TAG = "MQTT_EXAMPLE";
static EventGroupHandle_t wifi_event_group;
const static int CONNECTED_BIT = BIT0;
esp_mqtt_client_handle_t client;
static esp_err_t mqtt_event_handler(esp_mqtt_event_handle_t event)
{
// esp_mqtt_client_handle_t client = event->client;
client = event->client;
int msg_id;
// your_context_t *context = event->context;
switch (event->event_id) {
case MQTT_EVENT_CONNECTED:
ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
msg_id = esp_mqtt_client_publish(client, "/topic/qos1", "data_3", 0, 1, 0);
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos0", 0);
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 1);
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
msg_id = esp_mqtt_client_unsubscribe(client, "/topic/qos1");
ESP_LOGI(TAG, "sent unsubscribe successful, msg_id=%d", msg_id);
break;
case MQTT_EVENT_DISCONNECTED:
ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
break;
case MQTT_EVENT_SUBSCRIBED:
ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
break;
case MQTT_EVENT_UNSUBSCRIBED:
ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
break;
case MQTT_EVENT_PUBLISHED:
ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
break;
case MQTT_EVENT_DATA:
ESP_LOGI(TAG, "MQTT_EVENT_DATA");
printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
printf("DATA=%.*s\r\n", event->data_len, event->data);
break;
case MQTT_EVENT_ERROR:
ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
break;
default:
ESP_LOGI(TAG, "Other event id:%d", event->event_id);
break;
}
return ESP_OK;
}
static esp_err_t wifi_event_handler(void *ctx, system_event_t *event)
{
switch (event->event_id) {
case SYSTEM_EVENT_STA_START:
esp_wifi_connect();
break;
case SYSTEM_EVENT_STA_GOT_IP:
xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
esp_wifi_connect();
xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
break;
default:
break;
}
return ESP_OK;
}
static void wifi_init(void)
{
tcpip_adapter_init();
wifi_event_group = xEventGroupCreate();
ESP_ERROR_CHECK(esp_event_loop_init(wifi_event_handler, NULL));
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
wifi_config_t wifi_config = {
.sta = {
.ssid = CONFIG_WIFI_SSID,
.password = CONFIG_WIFI_PASSWORD,
},
};
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
ESP_LOGI(TAG, "start the WIFI SSID:[%s]", CONFIG_WIFI_SSID);
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(TAG, "Waiting for wifi");
xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);
}
static void mqtt_app_start(void)
{
esp_mqtt_client_config_t mqtt_cfg = {
.host="192.168.0.225",
.port=61613,
.username="admin",
.password="password",
.event_handle = mqtt_event_handler,
// .user_context = (void *)your_context
};
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
esp_mqtt_client_start(client);
}
void app_main()
{
unsigned int count;
char data_to_send[20];
ESP_LOGI(TAG, "[APP] Startup..");
ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());
esp_log_level_set("*", ESP_LOG_INFO);
esp_log_level_set("MQTT_CLIENT", ESP_LOG_VERBOSE);
esp_log_level_set("TRANSPORT_TCP", ESP_LOG_VERBOSE);
esp_log_level_set("TRANSPORT_SSL", ESP_LOG_VERBOSE);
esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
esp_log_level_set("OUTBOX", ESP_LOG_VERBOSE);
nvs_flash_init();
wifi_init();
mqtt_app_start();
for(count=0;count<1000;count++)
{
sprintf(data_to_send,"%s%d","Hello Jasper:",count);
esp_mqtt_client_publish(client, "/topic/qos1", data_to_send, 0, 1, 0);
vTaskDelay(1000/portTICK_PERIOD_MS);
}
}
其中修改 static void mqtt_app_start(void) 中mqtt的.host 我的是192.168.0.225,你的就不知道了
然后再修改 static void wifi_init(void) 中的 .ssid .password 为你wifi的帐号密码 记得带" "
make flash 烧录到你的ESP32中 运行
然后在Eclipse的命令行那看到
大功告成,收工睡觉。