『瀚思彼岸』» 智能家居技术论坛

 找回密码
 立即注册
楼主: lijunxiong2006

【经济实惠】使用ESP32追踪设备实现回家离家自动化

  [复制链接]

0

主题

50

帖子

628

积分

高级会员

Rank: 4

积分
628
金钱
578
HASS币
0
发表于 2022-3-30 11:09:06 | 显示全部楼层
xudefu 发表于 2022-3-26 00:36
有没有成功的 ,分享下成功

编译和烧录成功了,还无法用上。
回复

使用道具 举报

1

主题

182

帖子

1238

积分

金牌会员

Rank: 6Rank: 6

积分
1238
金钱
1056
HASS币
0
发表于 2022-4-10 15:18:26 | 显示全部楼层
已开始使用,感谢分享
回复

使用道具 举报

105

主题

2954

帖子

1万

积分

超级版主

智能家居&单板滑雪痴迷爱好者

Rank: 8Rank: 8

积分
12119
金钱
9100
HASS币
460

教程狂人突出贡献

发表于 2022-5-3 10:42:57 | 显示全部楼层
yylwhy 发表于 2021-11-20 20:45
我用这款esp32 的板子编译完 传完。。串口全是重启。。。楼主是不是这个不支持啊 。

你这个是烧写不正确
回复

使用道具 举报

0

主题

33

帖子

352

积分

中级会员

Rank: 3Rank: 3

积分
352
金钱
319
HASS币
0
发表于 2022-5-9 23:56:56 来自手机 | 显示全部楼层
XCray 发表于 2022-5-3 10:42
你这个是烧写不正确

请问大佬,烧写正确后下一步该怎么做,configeration文件应该怎么写,能分享一下代码嘛
回复

使用道具 举报

105

主题

2954

帖子

1万

积分

超级版主

智能家居&单板滑雪痴迷爱好者

Rank: 8Rank: 8

积分
12119
金钱
9100
HASS币
460

教程狂人突出贡献

发表于 2022-5-10 07:54:35 | 显示全部楼层
banquolol 发表于 2022-5-9 23:56
请问大佬,烧写正确后下一步该怎么做,configeration文件应该怎么写,能分享一下代码嘛 ...

仔细看作者的说明呀
回复

使用道具 举报

11

主题

49

帖子

346

积分

中级会员

Rank: 3Rank: 3

积分
346
金钱
297
HASS币
0
发表于 2022-5-10 09:00:07 | 显示全部楼层
学习学习啊
回复

使用道具 举报

1

主题

61

帖子

430

积分

中级会员

Rank: 3Rank: 3

积分
430
金钱
369
HASS币
0
发表于 2022-5-18 01:15:31 | 显示全部楼层
学习学习
回复

使用道具 举报

59

主题

677

帖子

4365

积分

论坛元老

Rank: 8Rank: 8

积分
4365
金钱
3683
HASS币
20
发表于 2022-6-22 17:33:32 | 显示全部楼层
XCray 发表于 2021-7-12 20:23
感谢楼主分享!

如果能加到ESPHome里面就更美了!

大佬编译时候报错可以救一下吗  在windows安装最新版本 和 esp32的库了 还是报错搞不懂了
微信截图_20220622173151.png
回复

使用道具 举报

105

主题

2954

帖子

1万

积分

超级版主

智能家居&单板滑雪痴迷爱好者

Rank: 8Rank: 8

积分
12119
金钱
9100
HASS币
460

教程狂人突出贡献

发表于 2022-6-22 18:51:40 | 显示全部楼层
gmshiwoge 发表于 2022-6-22 17:33
大佬编译时候报错可以救一下吗  在windows安装最新版本 和 esp32的库了 还是报错搞不懂了
...

这截图,错误信息都没显示完整为啥不复制粘贴呢?

好像你用了中文的目录名?这可能是一个原因。
回复

使用道具 举报

59

主题

677

帖子

4365

积分

论坛元老

Rank: 8Rank: 8

积分
4365
金钱
3683
HASS币
20
发表于 2022-6-23 09:28:46 | 显示全部楼层
本帖最后由 gmshiwoge 于 2022-6-23 09:29 编辑
XCray 发表于 2022-6-22 18:51
这截图,错误信息都没显示完整为啥不复制粘贴呢?

好像你用了中文的目录名?这可能是一个原因。 ...

Arduino:1.8.18 (Mac OS X), 开发板:"ESP32 Dev Module, Disabled, Huge APP (3MB No OTA/1MB SPIFFS), 240MHz (WiFi/BT), QIO, 80MHz, 4MB (32Mb), 921600, Core 1, Core 1, None"











In file included from /Users/lirenzhao/Library/Arduino15/packages/esp32/hardware/esp32/2.0.3/libraries/BLE/src/BLEScan.h:16,
                 from /Users/lirenzhao/Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/2.0b4.0.9/bcd7ecf2b2b4bf8b075d282c1cf677e3/Message/MessageTemp/ece62559b8235f24e074d56e3de86bf7/File/esp_ble_tracker/TrackerI/TrackerI.ino:7:
/Users/lirenzhao/Library/Arduino15/packages/esp32/hardware/esp32/2.0.3/libraries/BLE/src/BLEAdvertisedDevice.h:99:7: error: 'vector' in namespace 'std' does not name a template type
  std::vector<BLEUUID> m_serviceUUIDs;
       ^~~~~~
/Users/lirenzhao/Library/Arduino15/packages/esp32/hardware/esp32/2.0.3/libraries/BLE/src/BLEAdvertisedDevice.h:99:2: note: 'std::vector' is defined in header '<vector>'; did you forget to '#include <vector>'?
/Users/lirenzhao/Library/Arduino15/packages/esp32/hardware/esp32/2.0.3/libraries/BLE/src/BLEAdvertisedDevice.h:19:1:
+#include <vector>

/Users/lirenzhao/Library/Arduino15/packages/esp32/hardware/esp32/2.0.3/libraries/BLE/src/BLEAdvertisedDevice.h:99:2:
  std::vector<BLEUUID> m_serviceUUIDs;
  ^~~
/Users/lirenzhao/Library/Arduino15/packages/esp32/hardware/esp32/2.0.3/libraries/BLE/src/BLEAdvertisedDevice.h:101:7: error: 'vector' in namespace 'std' does not name a template type
  std::vector<std::string> m_serviceData;
       ^~~~~~
/Users/lirenzhao/Library/Arduino15/packages/esp32/hardware/esp32/2.0.3/libraries/BLE/src/BLEAdvertisedDevice.h:101:2: note: 'std::vector' is defined in header '<vector>'; did you forget to '#include <vector>'?
  std::vector<std::string> m_serviceData;
  ^~~
/Users/lirenzhao/Library/Arduino15/packages/esp32/hardware/esp32/2.0.3/libraries/BLE/src/BLEAdvertisedDevice.h:102:7: error: 'vector' in namespace 'std' does not name a template type
  std::vector<BLEUUID> m_serviceDataUUIDs;
       ^~~~~~
/Users/lirenzhao/Library/Arduino15/packages/esp32/hardware/esp32/2.0.3/libraries/BLE/src/BLEAdvertisedDevice.h:102:2: note: 'std::vector' is defined in header '<vector>'; did you forget to '#include <vector>'?
  std::vector<BLEUUID> m_serviceDataUUIDs;
  ^~~
"WiFi.h" 对应多个库
已使用: /Users/lirenzhao/Library/Arduino15/packages/esp32/hardware/esp32/2.0.3/libraries/WiFi
未使用:/private/var/folders/k2/lrzc6mn149182n4_cp8gfbch0000gn/T/AppTranslocation/03E44196-A46E-40B7-AEB2-E3256F88C052/d/Arduino.app/Contents/Java/libraries/WiFi
exit status 1
为开发板 ESP32 Dev Module 编译时出错。


在文件 -> 首选项开启
“编译过程中显示详细输出”选项
这份报告会包含更多信息。
---------------------------------------------------------
今日换了个mac编译还是这样的

#include <sstream>
#include <soc/soc.h>
#include <soc/rtc_cntl_reg.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <ArduinoJson.h>

#include "irk.h"

#ifndef WiFiSSID
#define WiFiSSID "wifi"
#endif

#ifndef WiFiPWD
#define WiFiPWD "12345678"
#endif

#ifndef MQTT_SERVER
#define MQTT_SERVER "192.168.50.13"
#endif

#ifndef MQTT_PORT
#define MQTT_PORT 1883 //default
#endif

#ifndef MQTT_USER
#define MQTT_USER "admin"
#endif

#ifndef MQTT_PWD
#define MQTT_PWD "adminadmin"
#endif

#ifndef MQTT_TOPIC_ACTION
#define MQTT_TOPIC_ACTION "v1/trackeri/action" //default action
#endif

#ifndef MQTT_TOPIC_HEARBEAT
#define MQTT_TOPIC_HEARBEAT "v1/trackeri/heartbeat" //default heartbeat
#endif

#ifndef MQTT_TOPIC_STATE
#define MQTT_TOPIC_STATE "v1/trackeri/state" //default state
#endif

#ifndef BLE_SCAN_TIME
#define BLE_SCAN_TIME 5
#endif

#ifndef BLE_SCAN_DELAY
#define BLE_SCAN_DELAY 2000
#endif

//targetStateChangeCount
#ifndef USER_STATE_CHANGE_MAX_COUNT
#define USER_STATE_CHANGE_MAX_COUNT 3
#endif

#ifndef HEARTBEAT_DELAY
#define HEARTBEAT_DELAY 5
#endif

#ifndef BLESCANTASKTIMEOUT
#define BLESCANTASKTIMEOUT 60
#endif

#ifndef WIFI_CONNECT_TIMEOUT
#define WIFI_CONNECT_TIMEOUT 20 
#endif

#ifndef DEV_MODE
#define DEV_MODE 0
#endif

#if DEV_MODE
#define PRINT(str) Serial.print(str)
#define PRINTLN(str) Serial.println(str)
#define PRINTF(...) Serial.printf(__VA_ARGS__)
#else
#define PRINT(str)
#define PRINTLN(str)
#define PRINTF(str,...)
#endif


void networkTask( void *pvParameters );
void bleScanTask( void *pvParameters );
void(* resetFunc) (void) = 0; //reset function

uint8_t irk[][ESP_BT_OCTET16_LEN] = {0xF9,xxxx,xxxx,xxxx,xxxx,xxxx,xxxx,xxxx,xxxx,xxxx,xxxx,xxxx,xxxx,,xxxx
  //your irks
  //eg:
  //{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
  //{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
};

String users[] = {
  //users
  //eg:
  "Jack", 
  //"LeeMing"
};

int irkListLength = sizeof(irk) / sizeof(irk[0]);



WiFiClient wifiClient;
PubSubClient pubSubClient(wifiClient);
BLEScan* trackerBLEScan;
char MAC_char_STA[18];

unsigned long networkTaskRunningTime;
unsigned long bleScanTaskRunningTime;

//signal led
int LED = 2;

// class TrackerAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
//     void onResult(BLEAdvertisedDevice advertisedDevice) {
//       PRINTF("Advertised Device: %s \n", advertisedDevice.toString().c_str());
//     }
// };

class UserDeviceInfo {
  public:
    uint8_t irk[ESP_BT_OCTET16_LEN];
    String userName;
    int currentState = -1;
    //int lostTargetCount = 0;
    int targetStateChangeCount = 0;
};
// UserDeviceInfo userDeviceInfos[irkListLength];
UserDeviceInfo *userDeviceInfos;

void setup() {
#if DEV_MODE
  Serial.begin(115200);
#endif
  initData();

  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);
  //start network task
  newNetWorkTask();

  //start ble scan task
  newBLEScanTask();

  //init led
  pinMode(LED, OUTPUT);
  

}

/**
   newNetWorkTask
*/
void newNetWorkTask() {
  xTaskCreatePinnedToCore(
    networkTask,
    "networkTask",
    10000,
    NULL,
    1,
    NULL,
    0
  );
}

/**
   newBLEScanTask
*/
void newBLEScanTask() {
  xTaskCreatePinnedToCore(
    bleScanTask,
    "bleScanTask",
    10000,
    NULL,
    1,
    NULL,
    1
  );
}

void networkTask(void *pvParameters) {
  //setup
  initWiFi();
  initMQTT();

  //loop
  for (;;) {
    //check wifi status
    if (WiFi.status() != WL_CONNECTED) {
      initWiFi();
    }

    //check mqtt connetc status
    if (!pubSubClient.connected()) {
      connectMQTTServer();
    }

    //mqtt runloop
    pubSubClient.loop();

    appHeartbeat();

    vTaskDelay(100);
  }
}

void bleScanTask(void *pvParameters) {
  //setup
  initBLEScan();

  //loop
  for (;;) {
    
    bleScanTaskRunningTime = getCurrentSecTime();
    vTaskDelay(BLE_SCAN_DELAY);
    bleScanTaskRunningTime = getCurrentSecTime();
    digitalWrite(LED, HIGH);
    startBLEScan();
    digitalWrite(LED, LOW);
  }
}

void loop() {
}

/**
   initData
*/
void initData() {
  networkTaskRunningTime = 0;
  bleScanTaskRunningTime = 0;

  byte wifiMac[6];
  WiFi.macAddress(wifiMac);
  for (int i = 0;i < sizeof(wifiMac);i++){
    sprintf(MAC_char_STA,"%s%02x",MAC_char_STA,wifiMac[i]);
  }
  
  userDeviceInfos = new UserDeviceInfo[irkListLength];

  for (int i = 0; i < irkListLength; i++) {
    userDeviceInfos[i].userName = users[i];
    for (int j = 0; j < ESP_BT_OCTET16_LEN; j++) {
      userDeviceInfos[i].irk[j] = irk[i][j];
    }
  }
}

/**
   initWiFI
*/
void initWiFi() {

  WiFi.begin(WiFiSSID, WiFiPWD);

  if (WiFi.status() == WL_NO_SHIELD) {
    PRINTLN("[initWiFi]WiFi shield not present");
    while (true);
  }

  PRINTLN("[initWiFi]Connecting to AP ...");

  PRINT("[initWiFi]Attempting to connect to WPA SSID:");
  PRINT(WiFiSSID);

  long startTime = millis();
  for(;;){
    if (WiFi.status() == WL_CONNECTED){
      PRINTLN();
      PRINT("[initWiFi]Connected to AP");
      PRINTLN(WiFiSSID);
      PRINT("[initWiFi]IP address:");
      PRINTLN(WiFi.localIP());
      break;
    }else{
      if (millis() - startTime >= WIFI_CONNECT_TIMEOUT*1000){//wifi connect timeout reset boot
        resetFunc();//reset
        break;
      }else{
        PRINT(".");
      }
    }
  }
  while (WiFi.status() != WL_CONNECTED) {
    PRINT(".");
    delay(500);
  }
  

}

/**
   initMQTT
*/
void initMQTT() {
  PRINTLN("[initMQTT]Init MQTT client...");
  pubSubClient.setServer(MQTT_SERVER, MQTT_PORT);
  pubSubClient.setCallback(pubSubClientCallback);
  connectMQTTServer();
}

/**
   initBLEScan
*/
void initBLEScan() {
  PRINTLN("[initBLEScan]Init BLEScan...");
  BLEDevice::init("");
  trackerBLEScan = BLEDevice::getScan();
  // trackerBLEScan->setAdvertisedDeviceCallbacks(new TrackerAdvertisedDeviceCallbacks());
  trackerBLEScan->setActiveScan(true);
  trackerBLEScan->setInterval(100);
  trackerBLEScan->setWindow(99);
}

/**
   connectMQTTServer
*/
void connectMQTTServer() {
  while (!pubSubClient.connected()) {
    PRINTLN("[connectMQTTServer]Connecting to MQTT Server ...");
//    "TrackerI:"
    if (pubSubClient.connect(MAC_char_STA, MQTT_USER, MQTT_PWD)) {
      PRINTLN("[connectMQTTServer]MQTT service connect success");
      subscribeTopic();
    } else {
      PRINT("[connectMQTTServer]MQTT service connect fail:");
      PRINT(pubSubClient.state());
      PRINTLN(" retrying in 5 seconds");
      delay(5000);
    }
  }
}

/**
   subscribeTopic
*/
void subscribeTopic() {
  pubSubClient.subscribe(MQTT_TOPIC_ACTION);
  pubSubClient.publish(MQTT_TOPIC_ACTION, "{"code":0,"action":0}");
}

/**
   pubSubClientCallback
*/
void pubSubClientCallback(char*topic, byte* payload, unsigned int length) {
  PRINTLN(topic);
  for (int i = 0; i < length; i++)
  {
    PRINT((char)payload[i]);
  }
  PRINTLN();
  PRINTLN("-----------------------");
}

/**
   startBLEScan
*/
void startBLEScan() {
  PRINTLN("[startBLEScan] start Scan...");
  BLEScanResults foundDevices = trackerBLEScan->start(BLE_SCAN_TIME, false);
  int deviceCount = foundDevices.getCount();

  PRINTF("[startBLEScan] scan finish device count-->%d \n", deviceCount);
  int scanFlag[irkListLength] = {0};

  for (int i = 0; i < deviceCount; i++) {
    BLEAdvertisedDevice bleAdvertisedDevice = foundDevices.getDevice(i);
    for (int j = 0; j < irkListLength; j++) {
      BLEAddress bleAddress = bleAdvertisedDevice.getAddress();
      if (btm_ble_addr_resolvable(*(bleAddress.getNative()), userDeviceInfos[j].irk)) {
        scanFlag[j] = 1;
        break;
      }
    }
  }
  scanResultHandle(scanFlag);


  trackerBLEScan->clearResults();
}


/**
   scanResultHandle
*/
void scanResultHandle(int scanResultArr[]) {

  PRINTLN("[scanResultHandle]start process...");
  bool isInit = false;
  DynamicJsonDocument jsDoc(1024);
  for (int i = 0; i < irkListLength; i++) {
    UserDeviceInfo* userDeviceInfo = &userDeviceInfos[i];

    JsonObject jbUser = jsDoc.createNestedObject(userDeviceInfo->userName);

    int originState = userDeviceInfo->currentState;
    if (!isInit && -1 == userDeviceInfo->currentState) {
      isInit = true;
    }
    if (scanResultArr[i] == userDeviceInfo->currentState) {
      userDeviceInfo->targetStateChangeCount = 0;
    } else {
      userDeviceInfo->targetStateChangeCount ++;
      if (userDeviceInfo->targetStateChangeCount >= USER_STATE_CHANGE_MAX_COUNT) {
        PRINTF("[scanResultHandle]user %s has change \n", userDeviceInfos->userName);
        userDeviceInfo->currentState = scanResultArr[i];
        userDeviceInfo->targetStateChangeCount = 0;
      }
    }
    jbUser["currentState"] = userDeviceInfo->currentState;
    jbUser["originalState"] = originState;

    PRINTF("[scanResultHandle]%s-->%d\n", userDeviceInfo->userName, userDeviceInfo->currentState);
    // PRINT(userDeviceInfo->userName);
    // PRINT("-->");
    // PRINTLN(userDeviceInfo->currentState);
    //PRINT(scanResultArr[i]);
  }
  String userStateJsStr;
  serializeJson(jsDoc, userStateJsStr);
  PRINTLN(userStateJsStr);
  jsDoc.clear();
  if (!isInit) {
    //send message
    PRINTLN("[scanResultHandle]send scan result...");
    pushMQTTMsg(MQTT_TOPIC_STATE,userStateJsStr.c_str());
    PRINTLN("[scanResultHandle]send scan result finish");
  }
  PRINTLN("[scanResultHandle]handle finished!");
}


/**
 * pushMQTTMsg
 */
void pushMQTTMsg(const char* topic, const char* payload){
  if (WiFi.status() == WL_CONNECTED && pubSubClient.connected()){
    pubSubClient.publish(topic, payload);
  }
}

/**
 * appHeartbeat
 */
void appHeartbeat() {
  long currentTime = getCurrentSecTime();
  if (currentTime - networkTaskRunningTime >= HEARTBEAT_DELAY) {

    DynamicJsonDocument jsDoc(1024);
    jsDoc["code"] = 0;
    jsDoc["networkRunntime"] = currentTime;
    jsDoc["BLEScanRunntime"] = bleScanTaskRunningTime;
    String heartbeatJSStr;
    serializeJson(jsDoc, heartbeatJSStr);
    pushMQTTMsg(MQTT_TOPIC_HEARBEAT,heartbeatJSStr.c_str());
    jsDoc.clear();

    // std::stringstream fmt;
    // fmt << "{"code":0,"runntime":" << currentTime << "}";
    // PRINTLN(fmt.str().c_str());
    // pubSubClient.publish(MQTT_TOPIC_ACTION, fmt.str().c_str());
    networkTaskRunningTime = currentTime;
  }

  currentTime = getCurrentSecTime();
  if (currentTime - bleScanTaskRunningTime >= BLESCANTASKTIMEOUT) {
    PRINTLN("ble scan task maybe dead restart!");
    bleScanTaskRunningTime = currentTime;
    //newBLEScanTask();
    resetFunc();//reset
  }

}

/**
 * getCurrentSecTime
 */
long getCurrentSecTime(){
  return millis()/1000;
}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Hassbian

GMT+8, 2024-12-27 03:54 , Processed in 0.136690 second(s), 33 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表