Error while get mqtt config

The problem Receiving this error in the Core log: [2021-12-14 07:02:53,221] [tuya-openmq] error while get mqtt config 2021-12-14 07:02:53 ERROR (Thread-9) [tuya_iot] error while get mqtt config Not...

@CC91300

The problem
Receiving this error in the Core log:

[2021-12-14 07:02:53,221] [tuya-openmq] error while get mqtt config
2021-12-14 07:02:53 ERROR (Thread-9) [tuya_iot] error while get mqtt config

Note: All Tuya devices are working correctly.

What version of Home Assistant Core has the issue?
core-2021.12.1

What was the last working version of Home Assistant Core?
core-2021.12.0

What type of installation are you running?
Home Assistant OS

Integration causing the issue
Tuya

Link to integration documentation on our website
https://www.home-assistant.io/integrations/tuya/

Example YAML snippet
N/A
Anything in the logs that might be useful for us?
[2021-12-14 07:02:53,221] [tuya-openmq] error while get mqtt config
2021-12-14 07:02:53 ERROR (Thread-9) [tuya_iot] error while get mqtt config

@DIMMonchik

The same error appeared after the update to version 2021.12.3

@MaxK99

@dgthomson

A workaround as posted elsewhere:

Edit: credit to ResteNarquois

In configuration.yaml add (or confirm it contains):

system_log:
  fire_event: true

In automations.yaml, add:

- id: "TuyaIOT"
  alias: "TuyaIOT Restart"
  trigger:
  - platform: event
    event_type: system_log_event
    event_data:
      level: ERROR
      name: tuya_iot
  condition:
  - condition: template
    value_template: >-
      {{ "error while get mqtt config" in trigger.event.data.message[0] }}
  action:
  - service: homeassistant.reload_config_entry
    data:
      entity_id:
        - switch.living_room_lamp

Important! Change switch.living_room_lamp to the id of one of your system’s own Tuya entities.

Works like a charm by resetting Tuya when error while get mqtt config occurs.

@CC91300

在别处发布的解决方法:

编辑:归功于ResteNarquois

configuration.yaml添加(或确认它包含:

system_log:
  fire_event: true

Automations.yaml 中,添加:

- id: "TuyaIOT"
  alias: "TuyaIOT Restart"
  trigger:
  - platform: event
    event_type: system_log_event
    event_data:
      level: ERROR
      name: tuya_iot
  condition:
  - condition: template
    value_template: >-
      {{ "error while get mqtt config" in trigger.event.data.message[0] }}
  action:
  - service: homeassistant.reload_config_entry
    data:
      entity_id:
        - switch.living_room_lamp

**重要的!**更改switch.living_room_lamp为您系统自己的涂鸦实体之一的 id。

通过在error while get mqtt config发生时重置 Tuya 来发挥魅力。

Thank you very much, according to your method has been solved

@dgthomson

@viciovb

Permanent fix for those happy to dig deep is here…

home-assistant/core#62408 (comment)

it didn’t work for me because I don’t have any /usr/local/lib/python3.9/site-packages/tuya_iot folder in my HA

@psampatakos

Permanent fix for those happy to dig deep is here…
home-assistant/core#62408 (comment)

it didn’t work for me because I don’t have any /usr/local/lib/python3.9/site-packages/tuya_iot folder in my HA

That is my case also. No tuya_iot directory

@kristiankjaer

The fix worked for me. Running HA in docker. The directory/file should be there inside the docker — it was in my case at least (running HA 2021.11.1).
Copied out the file locally:
sudo docker cp homeassistant:/usr/local/lib/python3.9/site-packages/tuya_iot/openapi.py .
Modified the two lines (18 and 157) to:
18: TO_C_REFRESH_TOKEN_API_PRE = «/v1.0/token/»
157: response = self.get(
Copied back the file to the docker:
sudo docker cp ./openapi.py homeassistant:/usr/local/lib/python3.9/site-packages/tuya_iot/openapi.py
Works :)
I expect this to revert on next upgrade, however, I’ll cross my fingers the tuya integration has included the fix by then.

@MaxK99

@dinan5

I’m still getting this issue. I’m at 2021.12.10

@JeroenTuinstra

Just to remind everyone and keep this threat open. The issue is still there in version 2022.4.6.
I guess Tuya is not commited to making this work and their «big» announcement cooperating with Home Assistant was/is very short lived and a nice publicity stunt.
Really disappointed with Tuya, and I don’t understand why Home Assistant actually keeps including this integration as it clearly does not work for more than 6 months.

@outofsight

same error on 2022.5
can add the integration, but no devices/entities found

@sschw56

Same here on 2022.5.4
Just this error and no devices or entities. The connection and project on Tuya worked perfectly fine.

@markdepalma

@helldog136

@philharmonie

Having this issue as well

@preethaml7

Still experiencing the same issue.

@520xcy

@bektorkhan

When is this to be solved?
Tuya has a big audience…..

Running ova HassOS in Vbox

2022-08-21 22:25:40.821 ERROR (Thread-3) [tuya_iot] error while get mqtt config
2022-08-21 22:25:40.836 ERROR (Thread-3) [root] Uncaught thread exception
Traceback (most recent call last):
File «/usr/local/lib/python3.10/threading.py», line 1016, in _bootstrap_inner
self.run()
File «/usr/local/lib/python3.10/site-packages/tuya_iot/openmq.py», line 161, in run
time.sleep(self.mq_config.expire_time — 60)
AttributeError: ‘NoneType’ object has no attribute ‘expire_time’

@Yiivgeny

Same issue on core-2022.8.7

@koczis78

Still the same on 2022.10.0

@frontendbuddy

@bektorkhan

AttributeError: ‘NoneType’ object has no attribute ‘expire_time’

This just feels like a field is missing when you get the IoT core trial extended.
I have exactly the same issue. It was working for 1 month and then the trial expired, I contacted Tuya and got it extended to 6 months although the Tuya Integration either does not recognize that change or the change on their side was to set the expire_time in a different field which is understood by their IoT Platform Web Interface but not by the integration.

That’s just my feeling, dunno what exactly to do with this. I’ve e-mailed Tuya about this and I’m awaiting for some response.
I don’t know how to get into the /usr/local/lib/python3.10 to look around, my HA is on RPi 2.

@frontendbuddy

Got it fixed by Tuya support after mailing them the details.

@rursache

i’m having the same issue on 2022.11.4
EDIT: fixed by contacting tuya like @frontendbuddy said

@koczis78

Got it fixed by Tuya support after mailing them the details.

They only corrected it for you? or globally ? because I still have this problem.

@rursache

Got it fixed by Tuya support after mailing them the details.

They only corrected it for you? or globally ? because I still have this problem.

unfortunately i had to contact tuya again to fix it, it seems they fix it per account 😓😒

@bprosman

Got it fixed by Tuya support after mailing them the details.

What did you exactly request from them ? Mine was expired as well and I requested a 6 month extension from them via the portal which is currently under review

@leoshusar

I too wrote them and now I’m waiting for review. This is ridiculous.

I wasn’t even worth saying «hello», lol
SmartSelect_20221019_120903_Chrome.jpg

@bprosman

I too wrote them and now I’m waiting for review. This is ridiculous.

I wasn’t even worth saying «hello», lol SmartSelect_20221019_120903_Chrome.jpg

Ah ok, same for me, extended (or at least requested) and now (also) awaiting review.

@bprosman

Got it fixed by Tuya support after mailing them the details.

Is it possible to mention your ticket # so that I can refer to that ?

@frontendbuddy

@leoshusar

So mine was approved too and the integration still doesn’t work even after deleting and adding again.

@Sparky32

I had the same , solved it by making new project in tuya iot .
And put the new id and code in the tuya intergration. And all worked again

@bprosman

So mine was approved too and the integration still doesn’t work even after deleting and adding again.
I reported that as well and this was their response , (so I will wait another 24 hours).

«Hello, your IOT Core is still under review, please wait patiently, it is expected to be available for normal use at the latest the day after tomorrow. (Note: The actual audit completion time is one day later than the time displayed on the page)»

The application shows as «Approved».

@leoshusar

It’s already been 10 hours since my approval and new project also doesn’t work. But I’ll give them another 14 hours.

Meanwhile I’m going to finally reflash some of my non-ESP Tuya devices to OpenBK7231T (Tasmota «clone»). It’s just those lightbulbs which are quite easy to disassemble but nearly impossible to reassemble…

Edit: I had to write them again and they did something, now it finally works. He said just «try it again now».

@bprosman

YEEEEYYYYYY , Mine started to work again this morning after I referred them to Frontendbuddy’s ticket #, not sure if that helped. Most important it works and is extended for 6 months. Having that said decided to flash my smart plugs with Tasmota to become more independant.

@luizfeliperc

I’m having the same problem and I don’t know what else to do to try to solve it. The problem started last night and when redoing all the configuration the devices do not appear.
My trial was renewed for another 6 months, I created a new project and my devices still do not appear in the integration.

Home Assistant 2022.10.5

Logs:

image

image

@leoshusar

You have to write them, for me new project also didn’t work. They have to do something on their side.

@bprosman

Raise a ticket and if you want refer to ours.
Mine was :
T202210200012

@kingp0dd

I’m experiencing the same issue.

  • tried unlinking and relinking
  • tried creating new Cloud project
  • my Cloud API Services are already extended for 6 months yesterday

Logs are:


2022-10-24 16:39:22.855 ERROR (Thread-4) [tuya_iot] error while get mqtt config
2022-10-24 16:39:22.873 ERROR (Thread-4) [root] Uncaught thread exception
Traceback (most recent call last):
File "/usr/local/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.10/site-packages/tuya_iot/openmq.py", line 161, in run
time.sleep(self.mq_config.expire_time - 60)
AttributeError: 'NoneType' object has no attribute 'expire_time'

@dariokkk

Hi.
I have the same problem here.
It worked like a charm until last Friday.
The project was expired, I requested six extra months and it was approved.
I’m getting error on openmq.py in line 166. Before recreate the project the error was in line 161, like the other posts.
I did the sames steps than kingp0dd and also added Device Status Notification in the new project.
I’m using HA 2022.10.5

@bprosman

Even after the extension (6 months) was approved, for me it took at least 24 Hours before things started to work again.

@luizfeliperc

Guys, I have good news.
It seems to me that the problem was really in the IoT Core trial. Even though they renewed for another 6 months, the warning message still persisted. After opening a ticket and reporting the problem, the integration started working again.

image

image

@kingp0dd

It seems that you really need to open a ticket even after being renewed for
6 months. For now, i create a new account, which works too

@koczis78

@kingp0dd

Do you need a separate email for the new account?

On Tue, Oct 25, 2022, 9:58 PM koczis78 ***@***.***> wrote:
Hi, I contacted tuya support, they fixed something and the problem with
expire_time no longer occurs, but there is a new, similar problem as
@bprosman <https://github.com/bprosman> wrote about: AttributeError:
‘NoneType’ object has no attribute ‘disconnect’. After another contact
with support, they recommended deleting and create new the account in
«Development Users». After doing this and reinstalling tuya integration in
HA, it works great. My ticketID: T202210240056
[image: tuya2]
<https://user-images.githubusercontent.com/646734/197792542-eca3ab40-114c-4ec6-a1c3-529c2f16f625.png>
[image: tuya3]
<https://user-images.githubusercontent.com/646734/197793348-4770af8c-3208-48ac-9ada-5ac30115a22d.png>
[image: tuya4]
<https://user-images.githubusercontent.com/646734/197793083-d125dcab-b02b-4425-a990-f86ab31d49fa.png>


Reply to this email directly, view it on GitHub
<#741 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ACGD6KTRMHJPXMWIPELOZWDWE7RR7ANCNFSM5KKNXQAA>
.
You are receiving this because you commented.Message ID:
***@***.***>

@koczis78

No, I deleted the existing ones and added the same again with new password.

@leoshusar

I think this just confirms that Tuya has no intention to support Home Assistant anymore, when they advise to create new account instead of them fixing anything.

I say move from them as fast as you can, because once Tuya integration stops working (maybe HASS adds some breaking change or something, idk), they won’t fix this integration and you will get stuck with the last working version.
I wouldn’t even be surprised if they slowly limited their APIs to the point it won’t be usable for HASS.

Look at the OpenBK7231T project and Tuya Cloudcutter, if you have devices with non ESP chips and want to flash them.

@kingp0dd

Haven’t heard of tuya cloud cutter before, have you had any luck with that?

On Tue, Oct 25, 2022, 10:19 PM leoshusar ***@***.***> wrote:
I think this just confirms that Tuya has no intention to support Home
Assistant anymore, when they advise to create new account instead of them
fixing anything.

I say move from them as fast as you can, because once Tuya integration
stops working (maybe HASS adds some breaking change or something, idk),
they *won’t* fix this integration and you will get stuck with the last
working version.
I wouldn’t even be surprised if they slowly limited their APIs to the
point it won’t be usable for HASS.

Look at the OpenBK7231T project and Tuya Cloudcutter, if you have devices
with non ESP chips and want to flash them.


Reply to this email directly, view it on GitHub
<#741 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ACGD6KRIY5UMIHV35DI33ULWE7T7HANCNFSM5KKNXQAA>
.
You are receiving this because you commented.Message ID:
***@***.***>

@leoshusar

Cloudcutter needs a device profile that’s specific to each device model, somebody has to dump the firmware and send it to them. After they create the profile, it’s possible for others to do 2 things:

  • just cut the cloud (for local controlling using e.g. LocalTuya)
  • flash alternative firmware (OpenBK7231T)

I’ve successfully flashed my 2 smart sockets with it, there was already functional profile for mine.
I also have RGB bulbs, but there is no profile for my model yet, so I dumped the firmware and now I’m waiting for profile. Unfortunately they are not much active at this moment, but it’s worth a try, it’s not possible to break anything using wrong profile.

I can also flash them via UART, but reassembling those bulbs is almost impossible.

Another way is to replace the whole chip with ESP and then use Tasmota or ESPHome, I have done this to one device too.

@bprosman

Cloudcutter needs a device profile that’s specific to each device model, somebody has to dump the firmware and send it to them. After they create the profile, it’s possible for others to do 2 things:

  • just cut the cloud (for local controlling using e.g. LocalTuya)
  • flash alternative firmware (OpenBK7231T)

I’ve successfully flashed my 2 smart sockets with it, there was already functional profile for mine. I also have RGB bulbs, but there is no profile for my model yet, so I dumped the firmware and now I’m waiting for profile. Unfortunately they are not much active at this moment, but it’s worth a try, it’s not possible to break anything using wrong profile.

I can also flash them via UART, but reassembling those bulbs is almost impossible.

Another way is to replace the whole chip with ESP and then use Tasmota or ESPHome, I have done this to one device too.

My older sockets I could reflash with Tasmota. I also have a bunch of GU10 Warm White / Cool White , they internally have a : ESP8285 and BP5778.

@dariokkk

Hi guys.
Its working again for me.
After receive the extention time I revoked the IoT core permission in the project, then added it again.
About six hours after this, it started to work again. If I had just wait, maybe the result was the same.
Some devices I renamed in the Smart Life APP changed their names after reintegration. I had to adjust my red node flows and everything is fine now.

tuya_project

@Murada99

Same for me.
Opening the Iot Platform I saw that the trial period was expired (cloud menu/ cloud services)

image

Button was available to extend the period, I just clicked the button, asked for an extension of 6 months and now after reload the integration and restart HA, all entities are back.

I can see that the end date was extended.

image

More info : home-assistant/core#80278

@rmroc451

Same for me. Opening the Iot Platform I saw that the trial period was expired (cloud menu/ cloud services)

image

Button was available to extend the period, I just clicked the button, asked for an extension of 6 months and now after reload the integration and restart HA, all entities are back.

I can see that the end date was extended.

image

More info : home-assistant/core#80278

Ditto, just did the same thing.

@Phunixx

Running HA on a VM on a Synology NAS:
Home Assistant 2022.11.5
Supervisor 2022.11.2
Operating System 9.3
Frontend 20221108.0 — latest

Knipsel

If i restart HA it works a few hours, but after a while same errors, lamps not turning on or off.
Already re registered tuya api stuff, unlinked and relinked account….
Still no avail

@dgthomson

Running HA on a VM on a Synology NAS: Home Assistant 2022.11.5 Supervisor 2022.11.2 Operating System 9.3 Frontend 20221108.0 — latest

Knipsel

If i restart HA it works a few hours, but after a while same errors, lamps not turning on or off. Already re registered tuya api stuff, unlinked and relinked account…. Still no avail

have you added the workaround posted here?

@Phunixx

@recklezz

So do we need to manually extend this trial every 6 months?

@Sparky32

So do we need to manually extend this trial every 6 months?

Yes

EDIT: It’s working now. Thanks to all who helped.

My setup: Home Assistant core-2022.4.5 running on Debian.

Following Mark Watt’s video, last night I flashed this launchpad coordinator to my SONOFF Zigbee 3.0 USB Dongle. No issues.

Both Configuration | Host | Hardware and ls -l /dev/serial/by-id report that the Sonoff dongle is on /dev/ttyUSB0:

$ ls -l /dev/serial/by-id
total 0
lrwxrwxrwx 1 root root 13 Apr 19 05:41 usb-0658_0200-if00 -> ../../ttyACM0
lrwxrwxrwx 1 root root 13 Apr 19 13:26 usb-ITead_Sonoff_Zigbee_3.0_USB_Dongle_Plus_169749bd0986ec11a369631719c2d21c-if00-port0 -> ../../ttyUSB0

Here’s my Zigbee2mqtt configuration:

data_path: /config/zigbee2mqtt
socat:
  enabled: false
  master: pty,raw,echo=0,link=/tmp/ttyZ2M,mode=777
  slave: tcp-listen:8485,keepalive,nodelay,reuseaddr,keepidle=1,keepintvl=1,keepcnt=5
  options: '-d -d'
  log: false
mqtt:
  base_topic: zigbee2mqtt
  user: mqtt_user
  password: mqtt_password
  server: mqtt://localhost:1883
serial:
  port: /dev/ttyUSB0
homeassistant: true
frontend:
  port: 8099

Zigbee2mqtt just won’t start. The log reports «Failed to connect to the adapter»:

[14:14:48] INFO: Handing over control to Zigbee2mqtt Core ...
> zigbee2mqtt@1.25.0 start
> node index.js
Zigbee2MQTT:info  2022-04-19 14:14:52: Logging to console and directory: '/config/zigbee2mqtt/log/2022-04-19.14-14-51' filename: log.txt
Zigbee2MQTT:info  2022-04-19 14:14:52: Starting Zigbee2MQTT version 1.25.0 (commit #unknown)
Zigbee2MQTT:info  2022-04-19 14:14:52: Starting zigbee-herdsman (0.14.20)
Zigbee2MQTT:error 2022-04-19 14:15:13: Error while starting zigbee-herdsman
Zigbee2MQTT:error 2022-04-19 14:15:13: Failed to start zigbee
Zigbee2MQTT:error 2022-04-19 14:15:13: Check https://www.zigbee2mqtt.io/guide/installation/20_zigbee2mqtt-fails-to-start.html for possible solutions
Zigbee2MQTT:error 2022-04-19 14:15:13: Exiting...
Zigbee2MQTT:error 2022-04-19 14:15:13: Error: Failed to connect to the adapter (Error: SRSP - SYS - ping after 6000ms)
    at ZStackAdapter.start (/app/node_modules/zigbee-herdsman/src/adapter/z-stack/adapter/zStackAdapter.ts:102:27)
    at Controller.start (/app/node_modules/zigbee-herdsman/src/controller/controller.ts:123:29)
    at Zigbee.start (/app/lib/zigbee.ts:58:27)
    at Controller.start (/app/lib/controller.ts:100:27)
    at start (/app/index.js:101:5)

Thinking that maybe my USB extension cable might be at fault, I also tried plugging the dongle directly into the USB port. No change.

Also re-flashed. Also no change.

Can anyone spot what might be going on?

One ESP32 is in APSTA mode

  • AP to other ESP32
  • STA to keep it connecting it to the internet

This worked fine after testing it

The mosquitto config file is as follows:-

listener 1883 
allow_anonymous true

And on the other, I am trying to use the example from esp-idf protocol/MQTT/tcp

In idf.py menuconfig :-

  • I changed the username and password (ESP32 connection to AP is not an issue reason being I tested the wifi/getting_started/station and it worked fine)
  • Default broker URL mqtt://mqtt.eclipseprojects.io

then after erasing flash using esptool.py --port /dev/ttyUSB0 erase_flash

After build I uploaded the code to ESP32 using

idf.py build
idf.py -p /dev/ttyUSB0 flash

And when I monitor it

idf.py -p /dev/ttyUSB0 monitor

It showed the following error

E (562605) esp-tls: couldn't get hostname for :mqtt.eclipseprojects.io: getaddrinfo() returns 202, addrinfo=0x0
E (562605) transport_base: Failed to open a new connection: 32769
E (562605) mqtt_client: Error transport connect
I (562615) MQTT_EXAMPLE: MQTT_EVENT_ERROR
E (562615) MQTT_EXAMPLE: Last error reported from esp-tls: 0x8001
I (562625) MQTT_EXAMPLE: Last errno string (Success)
I (562625) MQTT_EXAMPLE: MQTT_EVENT_DISCONNECTED
I (572635) MQTT_EXAMPLE: Other event id:7

Here is the protocol/MQTT/tcp code that I mentioned in question
and APSTA-code as mentioned in question

APSTA main code file


/* The example of ESP-IDF
 *
 * This sample code is in the public domain.
 */

#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"

static const char *TAG = "MAIN";

static EventGroupHandle_t wifi_event_group;
const int CONNECTED_BIT = BIT0;


static void event_handler(void* arg, esp_event_base_t event_base,
                                int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
        ESP_LOGI(TAG, "WIFI_EVENT_STA_DISCONNECTED");
        esp_wifi_connect();
        xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
        ESP_LOGI(TAG, "IP_EVENT_STA_GOT_IP");
        xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
    }
}

static void initialise_wifi(void)
{
    esp_log_level_set("wifi", ESP_LOG_WARN);
    static bool initialized = false;
    if (initialized) {
        return;
    }
    ESP_ERROR_CHECK(esp_netif_init());
    wifi_event_group = xEventGroupCreate();
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_t *ap_netif = esp_netif_create_default_wifi_ap();
    assert(ap_netif);
    esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
    assert(sta_netif);
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK( esp_wifi_init(&cfg) );
    ESP_ERROR_CHECK( esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &event_handler, NULL) );
    ESP_ERROR_CHECK( esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL) );

    ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) );
    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_NULL) );
    ESP_ERROR_CHECK( esp_wifi_start() );

    initialized = true;
}

#if CONFIG_WIFI_CONNECT_AP
static bool wifi_ap(void)
{
    wifi_config_t wifi_config = { 0 };
    strcpy((char *)wifi_config.ap.ssid,CONFIG_AP_WIFI_SSID);
    strcpy((char *)wifi_config.ap.password, CONFIG_AP_WIFI_PASSWORD);
    wifi_config.ap.authmode = WIFI_AUTH_WPA_WPA2_PSK;
    wifi_config.ap.ssid_len = strlen(CONFIG_AP_WIFI_SSID);
    wifi_config.ap.max_connection = CONFIG_AP_MAX_STA_CONN;
    wifi_config.ap.channel = CONFIG_AP_WIFI_CHANNEL;

    if (strlen(CONFIG_AP_WIFI_PASSWORD) == 0) {
        wifi_config.ap.authmode = WIFI_AUTH_OPEN;
    }


    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_AP) );
    ESP_ERROR_CHECK( esp_wifi_set_config(ESP_IF_WIFI_AP, &wifi_config) );
    ESP_ERROR_CHECK( esp_wifi_start() );
    ESP_LOGI(TAG, "WIFI_MODE_AP started. SSID:%s password:%s channel:%d",
             CONFIG_AP_WIFI_SSID, CONFIG_AP_WIFI_PASSWORD, CONFIG_AP_WIFI_CHANNEL);
    return ESP_OK;
}
#endif


#if CONFIG_WIFI_CONNECT_STA
static bool wifi_sta(int timeout_ms)
{
    wifi_config_t wifi_config = { 0 };
    strcpy((char *)wifi_config.sta.ssid, CONFIG_STA_WIFI_SSID);
    strcpy((char *)wifi_config.sta.password, CONFIG_STA_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_ERROR_CHECK( esp_wifi_connect() );

    int bits = xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT,
                                   pdFALSE, pdTRUE, timeout_ms / portTICK_PERIOD_MS);
    ESP_LOGI(TAG, "bits=%x", bits);
    if (bits) {
        ESP_LOGI(TAG, "WIFI_MODE_STA connected. SSID:%s password:%s",
             CONFIG_STA_WIFI_SSID, CONFIG_STA_WIFI_PASSWORD);
    } else {
        ESP_LOGI(TAG, "WIFI_MODE_STA can't connected. SSID:%s password:%s",
             CONFIG_STA_WIFI_SSID, CONFIG_STA_WIFI_PASSWORD);
    }
    return (bits & CONNECTED_BIT) != 0;
}
#endif

#if CONFIG_WIFI_CONNECT_APSTA
static bool wifi_apsta(int timeout_ms)
{
    wifi_config_t ap_config = { 0 };
    strcpy((char *)ap_config.ap.ssid,CONFIG_AP_WIFI_SSID);
    strcpy((char *)ap_config.ap.password, CONFIG_AP_WIFI_PASSWORD);
    ap_config.ap.authmode = WIFI_AUTH_WPA_WPA2_PSK;
    ap_config.ap.ssid_len = strlen(CONFIG_AP_WIFI_SSID);
    ap_config.ap.max_connection = CONFIG_AP_MAX_STA_CONN;
    ap_config.ap.channel = CONFIG_AP_WIFI_CHANNEL;

    if (strlen(CONFIG_AP_WIFI_PASSWORD) == 0) {
        ap_config.ap.authmode = WIFI_AUTH_OPEN;
    }

    wifi_config_t sta_config = { 0 };
    strcpy((char *)sta_config.sta.ssid, CONFIG_STA_WIFI_SSID);
    strcpy((char *)sta_config.sta.password, CONFIG_STA_WIFI_PASSWORD);


    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_APSTA) );
    ESP_ERROR_CHECK( esp_wifi_set_config(ESP_IF_WIFI_AP, &ap_config) );
    ESP_ERROR_CHECK( esp_wifi_set_config(ESP_IF_WIFI_STA, &sta_config) );
    ESP_ERROR_CHECK( esp_wifi_start() );
    ESP_LOGI(TAG, "WIFI_MODE_AP started. SSID:%s password:%s channel:%d",
             CONFIG_AP_WIFI_SSID, CONFIG_AP_WIFI_PASSWORD, CONFIG_AP_WIFI_CHANNEL);

    ESP_ERROR_CHECK( esp_wifi_connect() );
    int bits = xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT,
                                   pdFALSE, pdTRUE, timeout_ms / portTICK_PERIOD_MS);
    ESP_LOGI(TAG, "bits=%x", bits);
    if (bits) {
        ESP_LOGI(TAG, "WIFI_MODE_STA connected. SSID:%s password:%s",
             CONFIG_STA_WIFI_SSID, CONFIG_STA_WIFI_PASSWORD);
    } else {
        ESP_LOGI(TAG, "WIFI_MODE_STA can't connected. SSID:%s password:%s",
             CONFIG_STA_WIFI_SSID, CONFIG_STA_WIFI_PASSWORD);
    }
    return (bits & CONNECTED_BIT) != 0;
}
#endif

void app_main()
{
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK( nvs_flash_erase() );
        err = nvs_flash_init();
    }
    ESP_ERROR_CHECK(err);

    initialise_wifi();

#if CONFIG_WIFI_CONNECT_AP
    ESP_LOGW(TAG, "Start AP Mode");
    wifi_ap();
#elif CONFIG_WIFI_CONNECT_STA
    ESP_LOGW(TAG, "Start STA Mode");
    wifi_sta(CONFIG_STA_CONNECT_TIMEOUT*1000);
#elif CONFIG_WIFI_CONNECT_APSTA
    ESP_LOGW(TAG, "Start APSTA Mode");
    wifi_apsta(CONFIG_STA_CONNECT_TIMEOUT*1000);
#endif
}

protocal/mqtt/tcp code


/* MQTT (over TCP) Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "esp_wifi.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "protocol_examples_common.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.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 void log_error_if_nonzero(const char *message, int error_code)
{
    if (error_code != 0) {
        ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code);
    }
}

/*
 * @brief Event handler registered to receive MQTT events
 *
 *  This function is called by the MQTT client event loop.
 *
 * @param handler_args user data registered to the event.
 * @param base Event base for the handler(always MQTT Base in this example).
 * @param event_id The id for the received event.
 * @param event_data The data for the event, esp_mqtt_event_handle_t.
 */
static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
{
    ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, event_id);
    esp_mqtt_event_handle_t event = event_data;
    esp_mqtt_client_handle_t client = event->client;
    int msg_id;
    switch ((esp_mqtt_event_id_t)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=%.*srn", event->topic_len, event->topic);
        printf("DATA=%.*srn", event->data_len, event->data);
        break;
    case MQTT_EVENT_ERROR:
        ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
        if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) {
            log_error_if_nonzero("reported from esp-tls", event->error_handle->esp_tls_last_esp_err);
            log_error_if_nonzero("reported from tls stack", event->error_handle->esp_tls_stack_err);
            log_error_if_nonzero("captured as transport's socket errno",  event->error_handle->esp_transport_sock_errno);
            ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno));

        }
        break;
    default:
        ESP_LOGI(TAG, "Other event id:%d", event->event_id);
        break;
    }
}

static void mqtt_app_start(void)
{
    esp_mqtt_client_config_t mqtt_cfg = {
        .broker.address.uri = CONFIG_BROKER_URL,
    };
#if CONFIG_BROKER_URL_FROM_STDIN
    char line[128];

    if (strcmp(mqtt_cfg.broker.address.uri, "FROM_STDIN") == 0) {
        int count = 0;
        printf("Please enter url of mqtt brokern");
        while (count < 128) {
            int c = fgetc(stdin);
            if (c == 'n') {
                line[count] = '';
                break;
            } else if (c > 0 && c < 127) {
                line[count] = c;
                ++count;
            }
            vTaskDelay(10 / portTICK_PERIOD_MS);
        }
        mqtt_cfg.broker.address.uri = line;
        printf("Broker url: %sn", line);
    } else {
        ESP_LOGE(TAG, "Configuration mismatch: wrong broker url");
        abort();
    }
#endif /* CONFIG_BROKER_URL_FROM_STDIN */

    esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
    /* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    esp_mqtt_client_start(client);
}

void app_main(void)
{
    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("MQTT_EXAMPLE", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT_BASE", ESP_LOG_VERBOSE);
    esp_log_level_set("esp-tls", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
    esp_log_level_set("outbox", ESP_LOG_VERBOSE);

    ESP_ERROR_CHECK(nvs_flash_init());
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
     * Read "Establishing Wi-Fi or Ethernet Connection" section in
     * examples/protocols/README.md for more information about this function.
     */
    ESP_ERROR_CHECK(example_connect());

    mqtt_app_start();
}

Понравилась статья? Поделить с друзьями:
  • Error while committing the transaction фсс арм лпу
  • Error while executing the query postgresql
  • Error while executing gem errno enoent
  • Error while committing the transaction postgresql
  • Error while executing gem errno eacces