数码之家

 找回密码
 立即注册
搜索
查看: 2611|回复: 0

【零知ESP8266】教程:MESH 组网示例

[复制链接]
发表于 2019-6-19 14:09:06 | 显示全部楼层 |阅读模式

1、概述

MESH组网技术在IOT领域具有非常大的作用,应用非常广泛,主流的无线技术从最开始的Zigbee,到蓝牙,到这里的WIFI都实现了MESH组网技术。在这里使用零知开源平台演示WIFI WESH组网的使用。

2、软件和硬件

硬件使用零知-ESP8266开发板:

软件使用零知开发工具,自带示例:

3、方法步骤


(1)先在零知开发工具中打开HelloMesh示例,或者复制下面的代码到零知开发工具中:

  1. /**********************************************************
  2. *    文件: x.ino      by 零知实验室
  3. *    -^^- 零知开源,让电子制作变得更简单! -^^-
  4. *    时间: 2019/05/28 12:22
  5. *    说明:
  6. ************************************************************/
  7. #include <ESP8266WiFi.h>
  8. #include <ESP8266WiFiMesh.h>
  9. #include <TypeConversionFunctions.h>
  10. #include <assert.h>

  11. const char exampleMeshName[] PROGMEM = "MeshNode_";
  12. const char exampleWiFiPassword[] PROGMEM = "123456789";//ChangeThisWiFiPassword_TODO

  13. unsigned int requestNumber = 0;
  14. unsigned int responseNumber = 0;

  15. String manageRequest(const String &request, ESP8266WiFiMesh &meshInstance);
  16. transmission_status_t manageResponse(const String &response, ESP8266WiFiMesh &meshInstance);
  17. void networkFilter(int numberOfNetworks, ESP8266WiFiMesh &meshInstance);

  18. /* Create the mesh node object */
  19. ESP8266WiFiMesh meshNode = ESP8266WiFiMesh(manageRequest, manageResponse, networkFilter, FPSTR(exampleWiFiPassword), FPSTR(exampleMeshName), "", true);

  20. /**
  21.    Callback for when other nodes send you a request

  22.    @param request The request string received from another node in the mesh
  23.    @param meshInstance The ESP8266WiFiMesh instance that called the function.
  24.    @returns The string to send back to the other node
  25. */
  26. String manageRequest(const String &request, ESP8266WiFiMesh &meshInstance) {
  27.   // We do not store strings in flash (via F()) in this function.
  28.   // The reason is that the other node will be waiting for our response,
  29.   // so keeping the strings in RAM will give a (small) improvement in response time.
  30.   // Of course, it is advised to adjust this approach based on RAM requirements.

  31.   /* Print out received message */
  32.   Serial.print("Request received: ");
  33.   Serial.println(request);

  34.   /* return a string to send back */
  35.   return ("Hello world response #" + String(responseNumber++) + " from " + meshInstance.getMeshName() + meshInstance.getNodeID() + ".");
  36. }

  37. /**
  38.    Callback for when you get a response from other nodes

  39.    @param response The response string received from another node in the mesh
  40.    @param meshInstance The ESP8266WiFiMesh instance that called the function.
  41.    @returns The status code resulting from the response, as an int
  42. */
  43. transmission_status_t manageResponse(const String &response, ESP8266WiFiMesh &meshInstance) {
  44.   transmission_status_t statusCode = TS_TRANSMISSION_COMPLETE;

  45.   /* Print out received message */
  46.   Serial.print(F("Request sent: "));
  47.   Serial.println(meshInstance.getMessage());
  48.   Serial.print(F("Response received: "));
  49.   Serial.println(response);

  50.   // Our last request got a response, so time to create a new request.
  51.   meshInstance.setMessage(String(F("Hello world request #")) + String(++requestNumber) + String(F(" from "))
  52.                           + meshInstance.getMeshName() + meshInstance.getNodeID() + String(F(".")));

  53.   // (void)meshInstance; // This is useful to remove a "unused parameter" compiler warning. Does nothing else.
  54.   return statusCode;
  55. }

  56. /**
  57.    Callback used to decide which networks to connect to once a WiFi scan has been completed.

  58.    @param numberOfNetworks The number of networks found in the WiFi scan.
  59.    @param meshInstance The ESP8266WiFiMesh instance that called the function.
  60. */
  61. void networkFilter(int numberOfNetworks, ESP8266WiFiMesh &meshInstance) {
  62.   for (int networkIndex = 0; networkIndex < numberOfNetworks; ++networkIndex) {
  63.     String currentSSID = WiFi.SSID(networkIndex);
  64.     int meshNameIndex = currentSSID.indexOf(meshInstance.getMeshName());

  65.     /* Connect to any _suitable_ APs which contain meshInstance.getMeshName() */
  66.     if (meshNameIndex >= 0) {
  67.       uint64_t targetNodeID = stringToUint64(currentSSID.substring(meshNameIndex + meshInstance.getMeshName().length()));

  68.       if (targetNodeID < stringToUint64(meshInstance.getNodeID())) {
  69.         ESP8266WiFiMesh::connectionQueue.push_back(NetworkInfo(networkIndex));
  70.       }
  71.     }
  72.   }
  73. }

  74. void setup() {
  75.   // Prevents the flash memory from being worn out, see: https://github.com/esp8266/Arduino/issues/1054 .
  76.   // This will however delay node WiFi start-up by about 700 ms. The delay is 900 ms if we otherwise would have stored the WiFi network we want to connect to.
  77.   WiFi.persistent(false);

  78.   Serial.begin(115200);
  79.   delay(50); // Wait for Serial.

  80.   //yield(); // Use this if you don't want to wait for Serial.

  81.   // The WiFi.disconnect() ensures that the WiFi is working correctly. If this is not done before receiving WiFi connections,
  82.   // those WiFi connections will take a long time to make or sometimes will not work at all.
  83.   WiFi.disconnect();

  84.   Serial.println();
  85.   Serial.println();

  86.   Serial.println(F("Note that this library can use static IP:s for the nodes to speed up connection times.\n"
  87.                    "Use the setStaticIP method as shown in this example to enable this.\n"
  88.                    "Ensure that nodes connecting to the same AP have distinct static IP:s.\n"
  89.                    "Also, remember to change the default mesh network password!\n\n"));

  90.   Serial.println(F("Setting up mesh node..."));

  91.   /* Initialise the mesh node */
  92.   meshNode.begin();
  93.   meshNode.activateAP(); // Each AP requires a separate server port.
  94. //  meshNode.setStaticIP(IPAddress(192, 168, 4, 22)); // Activate static IP mode to speed up connection times.
  95. }

  96. int32_t timeOfLastScan = -10000;
  97. void loop() {
  98.   if (millis() - timeOfLastScan > 3000 // Give other nodes some time to connect between data transfers.
  99.       || (WiFi.status() != WL_CONNECTED && millis() - timeOfLastScan > 2000)) { // Scan for networks with two second intervals when not already connected.
  100.     String request = String(F("Hello world request #")) + String(requestNumber) + String(F(" from ")) + meshNode.getMeshName() + meshNode.getNodeID() + String(F("."));
  101.     meshNode.attemptTransmission(request, false);
  102.     timeOfLastScan = millis();

  103.     // One way to check how attemptTransmission worked out
  104.     if (ESP8266WiFiMesh::latestTransmissionSuccessful()) {
  105.       Serial.println(F("Transmission successful."));
  106.     }

  107.     // Another way to check how attemptTransmission worked out
  108.     if (ESP8266WiFiMesh::latestTransmissionOutcomes.empty()) {
  109.       Serial.println(F("No mesh AP found."));
  110.     } else {
  111.       for (TransmissionResult &transmissionResult : ESP8266WiFiMesh::latestTransmissionOutcomes) {
  112.         if (transmissionResult.transmissionStatus == TS_TRANSMISSION_FAILED) {
  113.           Serial.println(String(F("Transmission failed to mesh AP ")) + transmissionResult.SSID);
  114.         } else if (transmissionResult.transmissionStatus == TS_CONNECTION_FAILED) {
  115.           Serial.println(String(F("Connection failed to mesh AP ")) + transmissionResult.SSID);
  116.         } else if (transmissionResult.transmissionStatus == TS_TRANSMISSION_COMPLETE) {
  117.           // No need to do anything, transmission was successful.
  118.         } else {
  119.           Serial.println(String(F("Invalid transmission status for ")) + transmissionResult.SSID + String(F("!")));
  120.           assert(F("Invalid transmission status returned from responseHandler!") && false);
  121.         }
  122.       }
  123.     }
  124.     Serial.println();
  125.   } else {
  126.     /* Accept any incoming connections */
  127.     meshNode.acceptRequest();
  128.   }
  129. }
复制代码

(2)验证并上传上述代码到零知-ESP8266开发板;

(3)测试:分别把上述代码上传到两个零知-ESP8266开发板,然后分别连接两个板子的串口调试窗口,然后就可以看到两个节点数据传输信息了:

更多详细资料可到零知实验室免费获取。


本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

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

本版积分规则

APP|手机版|小黑屋|关于我们|联系我们|法律条款|技术知识分享平台

闽公网安备35020502000485号

闽ICP备2021002735号-2

GMT+8, 2024-4-25 01:00 , Processed in 0.109200 second(s), 11 queries , Redis On.

Powered by Discuz!

© 2006-2023 smzj.net

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