commit 1360daaab0c01432a8d067bd827cfc59c3629c8c Author: 编码猿 Date: Fri Sep 27 01:22:07 2024 +0800 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..403adbc --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +.DS_Store +node_modules +/dist + + +# local env files +.env.local +.env.*.local + +# Log files +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* + +# Editor directories and files +.idea +.vscode +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/.pydio b/.pydio new file mode 100644 index 0000000..1e16884 --- /dev/null +++ b/.pydio @@ -0,0 +1 @@ +f514e88e-15a7-4d52-932a-3990a9ab9911 \ No newline at end of file diff --git a/CP2102固件烧录AT/.pydio b/CP2102固件烧录AT/.pydio new file mode 100644 index 0000000..22d3361 --- /dev/null +++ b/CP2102固件烧录AT/.pydio @@ -0,0 +1 @@ +b2370607-8f41-4bf8-af7e-0c1ffbc33310 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266下载程序说明/.pydio b/CP2102固件烧录AT/ESP8266下载程序说明/.pydio new file mode 100644 index 0000000..b4f0df6 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266下载程序说明/.pydio @@ -0,0 +1 @@ +5eeca6e4-dcd3-40e9-b689-9523b7edc1a3 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266下载程序说明/ESP8266 下载程序说明.pdf b/CP2102固件烧录AT/ESP8266下载程序说明/ESP8266 下载程序说明.pdf new file mode 100755 index 0000000..d8dd6ef Binary files /dev/null and b/CP2102固件烧录AT/ESP8266下载程序说明/ESP8266 下载程序说明.pdf differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/.pydio new file mode 100644 index 0000000..751a11a --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/.pydio @@ -0,0 +1 @@ +b1caca24-8abd-42fd-9d13-bc01a9153bbb \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/.pydio new file mode 100644 index 0000000..a8b8b3a --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/.pydio @@ -0,0 +1 @@ +f67ce668-61cd-473f-8934-7d2c57c4d166 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/.pydio new file mode 100644 index 0000000..036cf8e --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/.pydio @@ -0,0 +1 @@ +40f3b6ea-a67b-4d68-8a50-4186ac07e00b \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/.pydio new file mode 100644 index 0000000..483276b --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/.pydio @@ -0,0 +1 @@ +35c7b582-c314-4134-acb7-ebef9e0dc4f7 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/_temp_by_dltool/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/_temp_by_dltool/.pydio new file mode 100644 index 0000000..63286e9 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/_temp_by_dltool/.pydio @@ -0,0 +1 @@ +ee36451d-af5f-44f5-96e4-e8f362dc759e \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/_temp_by_dltool/downloadPanel1/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/_temp_by_dltool/downloadPanel1/.pydio new file mode 100644 index 0000000..77d5b8a --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/_temp_by_dltool/downloadPanel1/.pydio @@ -0,0 +1 @@ +c923a24d-88be-4fa8-a604-512fa29a8e2f \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/_temp_by_dltool/downloadPanel1/v0.9.5.6 AT Firmware.bin_rep b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/_temp_by_dltool/downloadPanel1/v0.9.5.6 AT Firmware.bin_rep new file mode 100755 index 0000000..96c955a Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/_temp_by_dltool/downloadPanel1/v0.9.5.6 AT Firmware.bin_rep differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/v0.9.5.6 AT Firmware.bin b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/v0.9.5.6 AT Firmware.bin new file mode 100755 index 0000000..9d1a980 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/AT 固件/v0.9.5.6 AT Firmware.bin differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/烧录工具/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/烧录工具/.pydio new file mode 100644 index 0000000..58a9935 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/烧录工具/.pydio @@ -0,0 +1 @@ +4c21b5c2-5677-43f4-ab12-358bd5bb9016 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/烧录工具/AT-Espressif AT 指令集_AIThinkerMod_v021.pdf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/烧录工具/AT-Espressif AT 指令集_AIThinkerMod_v021.pdf new file mode 100755 index 0000000..acd4ee2 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/烧录工具/AT-Espressif AT 指令集_AIThinkerMod_v021.pdf differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/烧录工具/flash_download_tools_v3.6.2.2.zip b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/烧录工具/flash_download_tools_v3.6.2.2.zip new file mode 100755 index 0000000..a04419c Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/ESP8266 AT固件/烧录工具/flash_download_tools_v3.6.2.2.zip differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/.pydio new file mode 100644 index 0000000..bf6f831 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/.pydio @@ -0,0 +1 @@ +7c2f3b15-aade-4065-a82c-4eba004f2096 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/.pydio new file mode 100644 index 0000000..07ddf91 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/.pydio @@ -0,0 +1 @@ +5bd37d6d-4247-4ad3-86ee-bdf553de469d \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/AiThinker Serial Tool V1.2.3.exe b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/AiThinker Serial Tool V1.2.3.exe new file mode 100755 index 0000000..3cda510 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/AiThinker Serial Tool V1.2.3.exe differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/aithinker_serial_tool.cfg b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/aithinker_serial_tool.cfg new file mode 100755 index 0000000..78fa7fd --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/aithinker_serial_tool.cfg @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/en/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/en/.pydio new file mode 100644 index 0000000..a2b99a7 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/en/.pydio @@ -0,0 +1 @@ +e7c49728-cd91-4d7f-808e-6383a44bbb3e \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/en/AiThinker_Serial_Tool.resources.dll b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/en/AiThinker_Serial_Tool.resources.dll new file mode 100755 index 0000000..4891286 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/AiThinker_Serial_Tool_V1.2.3/en/AiThinker_Serial_Tool.resources.dll differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/.pydio new file mode 100644 index 0000000..713fb3d --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/.pydio @@ -0,0 +1 @@ +362bb72b-ce5f-444c-9ee7-c386f98dbd2e \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/DownloadTool_release_note.txt b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/DownloadTool_release_note.txt new file mode 100755 index 0000000..a2f924a --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/DownloadTool_release_note.txt @@ -0,0 +1,5 @@ +Vers: 3.6.4 +Time: 20180130 +Desc: + 1. Add new GPIO config page in the tool + 2. Able to change bootloader of ESP8266 to change GPIO level when power on \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/ESPFlashDownloadTool_v3.6.4.exe b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/ESPFlashDownloadTool_v3.6.4.exe new file mode 100755 index 0000000..c8d63dd Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/ESPFlashDownloadTool_v3.6.4.exe differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/.pydio new file mode 100644 index 0000000..348c2b2 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/.pydio @@ -0,0 +1 @@ +914a7907-0476-4bef-941b-a0110b73458b \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/CON_ERROR.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/CON_ERROR.bmp new file mode 100755 index 0000000..f2c1cb2 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/CON_ERROR.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/CON_ERROR_S.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/CON_ERROR_S.bmp new file mode 100755 index 0000000..4600fd5 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/CON_ERROR_S.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/DEVKEY_ERROR.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/DEVKEY_ERROR.bmp new file mode 100755 index 0000000..1eacc19 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/DEVKEY_ERROR.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/DEVKEY_ERROR_S.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/DEVKEY_ERROR_S.bmp new file mode 100755 index 0000000..2bc687c Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/DEVKEY_ERROR_S.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/DOWNLOAD.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/DOWNLOAD.bmp new file mode 100755 index 0000000..c42f8df Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/DOWNLOAD.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/DOWNLOAD_S.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/DOWNLOAD_S.bmp new file mode 100755 index 0000000..461e9b2 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/DOWNLOAD_S.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/EFUSE_ERROR.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/EFUSE_ERROR.bmp new file mode 100755 index 0000000..86d702a Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/EFUSE_ERROR.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/EFUSE_ERROR_S.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/EFUSE_ERROR_S.bmp new file mode 100755 index 0000000..0318d34 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/EFUSE_ERROR_S.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/ERROR.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/ERROR.bmp new file mode 100755 index 0000000..7fc8b7c Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/ERROR.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/ERROR_S.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/ERROR_S.bmp new file mode 100755 index 0000000..34aa9d6 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/ERROR_S.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FAIL.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FAIL.bmp new file mode 100755 index 0000000..a5d5feb Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FAIL.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FAIL_S.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FAIL_S.bmp new file mode 100755 index 0000000..75f3dfa Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FAIL_S.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FINISH.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FINISH.bmp new file mode 100755 index 0000000..63a35dc Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FINISH.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FINISH_RESTART.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FINISH_RESTART.bmp new file mode 100755 index 0000000..ac15d1a Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FINISH_RESTART.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FINISH_RESTART_S.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FINISH_RESTART_S.bmp new file mode 100755 index 0000000..f527027 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FINISH_RESTART_S.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FINISH_S.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FINISH_S.bmp new file mode 100755 index 0000000..489cf3f Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/FINISH_S.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/IDLE.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/IDLE.bmp new file mode 100755 index 0000000..c7a8c26 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/IDLE.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/IDLE_S.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/IDLE_S.bmp new file mode 100755 index 0000000..b7028cb Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/IDLE_S.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/STOP.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/STOP.bmp new file mode 100755 index 0000000..beedfe3 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/STOP.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/STOP_S.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/STOP_S.bmp new file mode 100755 index 0000000..dbf6e45 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/STOP_S.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/SYNC.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/SYNC.bmp new file mode 100755 index 0000000..c04517c Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/SYNC.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/SYNC_S.bmp b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/SYNC_S.bmp new file mode 100755 index 0000000..a4397aa Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/SYNC_S.bmp differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/Thumbs.db b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/Thumbs.db new file mode 100755 index 0000000..03ed567 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/Thumbs.db differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/logo.ico b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/logo.ico new file mode 100755 index 0000000..3f3522e Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/RESOURCE/logo.ico differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/Readme.pdf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/Readme.pdf new file mode 100755 index 0000000..c93fbf5 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/Readme.pdf differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/.pydio new file mode 100644 index 0000000..6c78595 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/.pydio @@ -0,0 +1 @@ +ac58ebf4-e8cd-45a3-b49b-ee5c53655628 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel1/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel1/.pydio new file mode 100644 index 0000000..582673f --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel1/.pydio @@ -0,0 +1 @@ +a132342d-7e7b-4a30-8770-ae462dff76ce \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel1/v0.9.5.6 AT Firmware.bin_rep b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel1/v0.9.5.6 AT Firmware.bin_rep new file mode 100755 index 0000000..96c955a Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel1/v0.9.5.6 AT Firmware.bin_rep differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel2/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel2/.pydio new file mode 100644 index 0000000..be189cd --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel2/.pydio @@ -0,0 +1 @@ +cf4b4563-d5c9-4119-af37-adea3610eab5 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel2/HW-629自动连WIFI.bin_rep b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel2/HW-629自动连WIFI.bin_rep new file mode 100755 index 0000000..337025a Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel2/HW-629自动连WIFI.bin_rep differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel3/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel3/.pydio new file mode 100644 index 0000000..894aaef --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel3/.pydio @@ -0,0 +1 @@ +5cd8667c-2e25-4eee-9c08-80177f6556f6 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel3/HW-629自动连WIFI.bin_rep b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel3/HW-629自动连WIFI.bin_rep new file mode 100755 index 0000000..337025a Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel3/HW-629自动连WIFI.bin_rep differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel4/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel4/.pydio new file mode 100644 index 0000000..b251c72 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel4/.pydio @@ -0,0 +1 @@ +464a5d89-6b9b-4d31-b19c-6e90cc7baa92 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel4/HW-629自动连WIFI.bin_rep b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel4/HW-629自动连WIFI.bin_rep new file mode 100755 index 0000000..337025a Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel4/HW-629自动连WIFI.bin_rep differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel5/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel5/.pydio new file mode 100644 index 0000000..c763be1 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel5/.pydio @@ -0,0 +1 @@ +586625f2-02f0-4c02-aa66-17eb52e78d00 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel5/HW-629自动连WIFI.bin_rep b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel5/HW-629自动连WIFI.bin_rep new file mode 100755 index 0000000..337025a Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel5/HW-629自动连WIFI.bin_rep differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel6/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel6/.pydio new file mode 100644 index 0000000..177cb8a --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel6/.pydio @@ -0,0 +1 @@ +db39fae0-8cc7-44ee-a66c-13901bf33725 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel6/HW-629自动连WIFI.bin_rep b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel6/HW-629自动连WIFI.bin_rep new file mode 100755 index 0000000..337025a Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel6/HW-629自动连WIFI.bin_rep differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel7/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel7/.pydio new file mode 100644 index 0000000..ea31eea --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel7/.pydio @@ -0,0 +1 @@ +0d0993c5-8ec9-408d-9d01-41e278f1e84b \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel7/HW-629自动连WIFI.bin_rep b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel7/HW-629自动连WIFI.bin_rep new file mode 100755 index 0000000..337025a Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel7/HW-629自动连WIFI.bin_rep differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel8/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel8/.pydio new file mode 100644 index 0000000..7378c38 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel8/.pydio @@ -0,0 +1 @@ +e683b403-54de-44ce-839e-8c142cac8a31 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel8/HW-629自动连WIFI.bin_rep b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel8/HW-629自动连WIFI.bin_rep new file mode 100755 index 0000000..337025a Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/bin_tmp/downloadPanel8/HW-629自动连WIFI.bin_rep differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/combine/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/combine/.pydio new file mode 100644 index 0000000..240aa06 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/combine/.pydio @@ -0,0 +1 @@ +cae8973b-df92-4c45-b1df-173c5904ee73 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/.pydio new file mode 100644 index 0000000..02482bd --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/.pydio @@ -0,0 +1 @@ +49cc0a68-eca4-41db-997d-2cfe3e9bb953 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/.pydio new file mode 100644 index 0000000..80d257a --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/.pydio @@ -0,0 +1 @@ +e68adcc5-0d1c-4c0a-8a40-4be40698cab9 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/hspi_download.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/hspi_download.conf new file mode 100755 index 0000000..cea175f --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/hspi_download.conf @@ -0,0 +1,62 @@ +[EFUSE CHECK] +efuse_mode = 1 +efuse_err_halt = 1 +mac_save = 0 + +[DOWNLOAD PATH] +file_sel0 = 0 +file_path0 = +file_offset0 = +file_sel1 = 0 +file_path1 = +file_offset1 = +file_sel2 = 0 +file_path2 = +file_offset2 = +file_sel3 = 0 +file_path3 = +file_offset3 = +file_sel4 = 0 +file_path4 = +file_offset4 = +file_sel5 = 0 +file_path5 = +file_offset5 = +file_sel6 = 0 +file_path6 = +file_offset6 = +file_sel7 = 0 +file_path7 = +file_offset7 = +file_sel8 = 0 +file_path8 = +file_offset8 = +file_sel9 = 0 +file_path9 = +file_offset9 = +file_sel10 = 0 +file_path10 = +file_offset10 = +file_sel11 = 0 +file_path11 = +file_offset11 = +default_path = C:\Users\panfeng\Desktop\FLASH_DOWNLOAD_TOOLS_V3.6.4 + +[LOCK] +id_bind_en = 0 +lock_settings = 0 + +[FLASH_CRYSTAL] +crystal = 0 +spiautoset = 0 +spicfgdis = 0 +spispeed = 0 +spimode = 2 +flashsize = 2 + +[DOWNLOAD] +autostart1 = 0 +com_port1 = COM1 +baudrate1 = 0 +checkmac1 = 1 + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/multi_download.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/multi_download.conf new file mode 100755 index 0000000..6f9f05d --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/multi_download.conf @@ -0,0 +1,90 @@ +[EFUSE CHECK] +efuse_mode = 1 +efuse_err_halt = 1 +mac_save = 0 + +[DOWNLOAD PATH] +file_sel0 = 0 +file_path0 = +file_offset0 = +file_sel1 = 0 +file_path1 = +file_offset1 = +file_sel2 = 0 +file_path2 = +file_offset2 = +file_sel3 = 0 +file_path3 = +file_offset3 = +file_sel4 = 0 +file_path4 = +file_offset4 = +file_sel5 = 0 +file_path5 = +file_offset5 = +file_sel6 = 0 +file_path6 = +file_offset6 = +file_sel7 = 0 +file_path7 = +file_offset7 = +file_sel8 = 0 +file_path8 = +file_offset8 = +file_sel9 = 0 +file_path9 = +file_offset9 = +file_sel10 = 0 +file_path10 = +file_offset10 = +file_sel11 = 0 +file_path11 = +file_offset11 = +default_path = C:\Users\panfeng\Desktop\FLASH_DOWNLOAD_TOOLS_V3.6.4 + +[LOCK] +id_bind_en = 0 +lock_settings = 0 + +[FLASH_CRYSTAL] +crystal = 0 +spiautoset = 0 +spicfgdis = 0 +spispeed = 0 +spimode = 2 +flashsize = 2 + +[DOWNLOAD] +autostart1 = 0 +com_port1 = COM1 +baudrate1 = 0 +checkmac1 = 1 +autostart2 = 0 +com_port2 = COM1 +baudrate2 = 0 +checkmac2 = 1 +autostart3 = 0 +com_port3 = COM1 +baudrate3 = 0 +checkmac3 = 1 +autostart4 = 0 +com_port4 = COM1 +baudrate4 = 0 +checkmac4 = 1 +autostart5 = 0 +com_port5 = COM1 +baudrate5 = 0 +checkmac5 = 1 +autostart6 = 0 +com_port6 = COM1 +baudrate6 = 0 +checkmac6 = 1 +autostart7 = 0 +com_port7 = COM1 +baudrate7 = 0 +checkmac7 = 1 +autostart8 = 0 +com_port8 = COM1 +baudrate8 = 0 +checkmac8 = 1 + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/security.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/security.conf new file mode 100755 index 0000000..f357485 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/security.conf @@ -0,0 +1,26 @@ +[DEBUG MODE] +debug_enable = True +debug_pem_path = + +[SECURE BOOT] +secure_boot_en = False +burn_secure_boot_key = False +secure_boot_force_write = False +secure_boot_rw_protect = False + +[FLASH ENCRYPTION] +flash_encryption_en = False +burn_flash_encryption_key = False +flash_encrypt_force_write = False +flash_encrypt_rw_protect = False + +[AES KEY] +aes_key_en = False +burn_aes_key = False + +[DISABLE FUNC] +jtag_disable = False +dl_encrypt_disable = False +dl_decrypt_disable = False +dl_cache_disable = False + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/spi_download.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/spi_download.conf new file mode 100755 index 0000000..7805048 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/spi_download.conf @@ -0,0 +1,83 @@ +[EFUSE CHECK] +efuse_mode = 1 +efuse_err_halt = 1 +mac_save = 0 + +[DOWNLOAD PATH] +file_sel0 = 1 +file_path0 = G:\άƷ\ESP-32ͨ¼\ESP-32ͨ¼.bin +file_offset0 = 0X00000 +file_sel1 = 0 +file_path1 = +file_offset1 = +file_sel2 = 0 +file_path2 = +file_offset2 = +file_sel3 = 0 +file_path3 = +file_offset3 = +file_sel4 = 0 +file_path4 = +file_offset4 = +file_sel5 = 0 +file_path5 = +file_offset5 = +file_sel6 = 0 +file_path6 = +file_offset6 = +file_sel7 = 0 +file_path7 = +file_offset7 = +file_sel8 = 0 +file_path8 = +file_offset8 = +file_sel9 = 0 +file_path9 = +file_offset9 = +file_sel10 = 0 +file_path10 = +file_offset10 = +file_sel11 = 0 +file_path11 = +file_offset11 = +default_path = G:\άƷ\ESP-32ͨ¼ + +[LOCK] +id_bind_en = 0 +lock_settings = 0 + +[FLASH_CRYSTAL] +crystal = 1 +spiautoset = 0 +spicfgdis = 1 +spispeed = 0 +spimode = 0 +flashsize = 0 + +[DOWNLOAD] +autostart1 = 0 +com_port1 = COM42 +baudrate1 = 4 +checkmac1 = 1 +erase_flash_en = True +new_status = 0 +num_bytes = 0 +non_volatile = False + +[ESPTOOL_PARAM] +after = hard_reset +baud = 115200 +before = default_reset +chip = auto +compress = 0 +flash_freq = keep +flash_mode = keep +flash_size = keep +no_compress = False +no_progress = False +no_stub = False +operation = write_flash +port = /dev/cu.SLAB_USBtoUART +spi_connection = 0 +verify = False + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/utility.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/utility.conf new file mode 100755 index 0000000..aa7535d --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32/utility.conf @@ -0,0 +1,30 @@ +[LOG_LEVEL] +utility_log_level = ERROR +multi_log_level = ERROR +spi_log_level = ERROR +hspi_log_level = ERROR + +[RF_INIT] +autocalen = 0 +toutvdd = 1 +targetlowpower = 12.000000 +limitval = 20.500000 +vdd = 3.3 +toutadc = 0 +backoffen = 0 +freqoffset = 50 +setfreqen = 0 +cryfreq = 3 +rfgain = 0 +targetpower6 = 14.000000 +targetpower4 = 17.000000 +targetpower5 = 16.000000 +targetpower2 = 19.500000 +targetpower3 = 18.500000 +lowpoweren = 0 +targetpower1 = 20.500000 +rfinitmode = 0 +backoffval = 0.000000 +digitalgain = 0 +limiten = 0 + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/.pydio new file mode 100644 index 0000000..ae731fa --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/.pydio @@ -0,0 +1 @@ +79a5f7b2-eb7f-4eba-a438-cc7de92209d9 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/hspi_download.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/hspi_download.conf new file mode 100755 index 0000000..b79650b --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/hspi_download.conf @@ -0,0 +1,62 @@ +[EFUSE CHECK] +efuse_mode = 1 +efuse_err_halt = 1 +mac_save = 0 + +[DOWNLOAD PATH] +file_sel0 = 0 +file_path0 = +file_offset0 = +file_sel1 = 0 +file_path1 = +file_offset1 = +file_sel2 = 0 +file_path2 = +file_offset2 = +file_sel3 = 0 +file_path3 = +file_offset3 = +file_sel4 = 0 +file_path4 = +file_offset4 = +file_sel5 = 0 +file_path5 = +file_offset5 = +file_sel6 = 0 +file_path6 = +file_offset6 = +file_sel7 = 0 +file_path7 = +file_offset7 = +file_sel8 = 0 +file_path8 = +file_offset8 = +file_sel9 = 0 +file_path9 = +file_offset9 = +file_sel10 = 0 +file_path10 = +file_offset10 = +file_sel11 = 0 +file_path11 = +file_offset11 = +default_path = C:\Users\panfeng\Desktop\FLASH_DOWNLOAD_TOOLS_V3.6.4 + +[LOCK] +id_bind_en = 0 +lock_settings = 0 + +[FLASH_CRYSTAL] +crystal = 0 +spiautoset = 0 +spicfgdis = 0 +spispeed = 0 +spimode = 2 +flashsize = 1 + +[DOWNLOAD] +autostart1 = 0 +com_port1 = COM1 +baudrate1 = 4 +checkmac1 = 1 + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/multi_download.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/multi_download.conf new file mode 100755 index 0000000..0881741 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/multi_download.conf @@ -0,0 +1,90 @@ +[EFUSE CHECK] +efuse_mode = 1 +efuse_err_halt = 1 +mac_save = 0 + +[DOWNLOAD PATH] +file_sel0 = 0 +file_path0 = +file_offset0 = +file_sel1 = 0 +file_path1 = +file_offset1 = +file_sel2 = 0 +file_path2 = +file_offset2 = +file_sel3 = 0 +file_path3 = +file_offset3 = +file_sel4 = 0 +file_path4 = +file_offset4 = +file_sel5 = 0 +file_path5 = +file_offset5 = +file_sel6 = 0 +file_path6 = +file_offset6 = +file_sel7 = 0 +file_path7 = +file_offset7 = +file_sel8 = 0 +file_path8 = +file_offset8 = +file_sel9 = 0 +file_path9 = +file_offset9 = +file_sel10 = 0 +file_path10 = +file_offset10 = +file_sel11 = 0 +file_path11 = +file_offset11 = +default_path = C:\Users\panfeng\Desktop\FLASH_DOWNLOAD_TOOLS_V3.6.4 + +[LOCK] +id_bind_en = 0 +lock_settings = 0 + +[FLASH_CRYSTAL] +crystal = 0 +spiautoset = 0 +spicfgdis = 0 +spispeed = 0 +spimode = 2 +flashsize = 1 + +[DOWNLOAD] +autostart1 = 0 +com_port1 = COM1 +baudrate1 = 0 +checkmac1 = 1 +autostart2 = 0 +com_port2 = COM1 +baudrate2 = 0 +checkmac2 = 1 +autostart3 = 0 +com_port3 = COM1 +baudrate3 = 0 +checkmac3 = 1 +autostart4 = 0 +com_port4 = COM1 +baudrate4 = 0 +checkmac4 = 1 +autostart5 = 0 +com_port5 = COM1 +baudrate5 = 0 +checkmac5 = 1 +autostart6 = 0 +com_port6 = COM1 +baudrate6 = 0 +checkmac6 = 1 +autostart7 = 0 +com_port7 = COM1 +baudrate7 = 0 +checkmac7 = 1 +autostart8 = 0 +com_port8 = COM1 +baudrate8 = 0 +checkmac8 = 1 + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/security.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/security.conf new file mode 100755 index 0000000..f357485 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/security.conf @@ -0,0 +1,26 @@ +[DEBUG MODE] +debug_enable = True +debug_pem_path = + +[SECURE BOOT] +secure_boot_en = False +burn_secure_boot_key = False +secure_boot_force_write = False +secure_boot_rw_protect = False + +[FLASH ENCRYPTION] +flash_encryption_en = False +burn_flash_encryption_key = False +flash_encrypt_force_write = False +flash_encrypt_rw_protect = False + +[AES KEY] +aes_key_en = False +burn_aes_key = False + +[DISABLE FUNC] +jtag_disable = False +dl_encrypt_disable = False +dl_decrypt_disable = False +dl_cache_disable = False + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/spi_download.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/spi_download.conf new file mode 100755 index 0000000..229a91e --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/spi_download.conf @@ -0,0 +1,83 @@ +[EFUSE CHECK] +efuse_mode = 1 +efuse_err_halt = 1 +mac_save = 0 + +[DOWNLOAD PATH] +file_sel0 = 1 +file_path0 = G:\άƷ\ESP-32ͨ¼\ESP-32ͨ¼.bin +file_offset0 = 0X00000 +file_sel1 = 0 +file_path1 = +file_offset1 = +file_sel2 = 0 +file_path2 = +file_offset2 = +file_sel3 = 0 +file_path3 = +file_offset3 = +file_sel4 = 0 +file_path4 = +file_offset4 = +file_sel5 = 0 +file_path5 = +file_offset5 = +file_sel6 = 0 +file_path6 = +file_offset6 = +file_sel7 = 0 +file_path7 = +file_offset7 = +file_sel8 = 0 +file_path8 = +file_offset8 = +file_sel9 = 0 +file_path9 = +file_offset9 = +file_sel10 = 0 +file_path10 = +file_offset10 = +file_sel11 = 0 +file_path11 = +file_offset11 = +default_path = G:\άƷ\ESP-32ͨ¼ + +[LOCK] +id_bind_en = 0 +lock_settings = 0 + +[FLASH_CRYSTAL] +crystal = 1 +spiautoset = 0 +spicfgdis = 0 +spispeed = 1 +spimode = 2 +flashsize = 2 + +[DOWNLOAD] +autostart1 = 0 +com_port1 = COM8 +baudrate1 = 0 +checkmac1 = 1 +erase_flash_en = True +new_status = 0 +num_bytes = 0 +non_volatile = False + +[ESPTOOL_PARAM] +after = hard_reset +baud = 115200 +before = default_reset +chip = auto +compress = 0 +flash_freq = keep +flash_mode = keep +flash_size = keep +no_compress = False +no_progress = False +no_stub = False +operation = write_flash +port = /dev/cu.SLAB_USBtoUART +spi_connection = 0 +verify = False + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/utility.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/utility.conf new file mode 100755 index 0000000..93a9172 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp32d2wd/utility.conf @@ -0,0 +1,30 @@ +[LOG_LEVEL] +multi_log_level = ERROR +utility_log_level = ERROR +spi_log_level = ERROR +hspi_log_level = ERROR + +[RF_INIT] +autocalen = 0 +toutvdd = 1 +targetlowpower = 12.000000 +limitval = 20.500000 +vdd = 3.3 +toutadc = 0 +backoffen = 0 +freqoffset = 50 +setfreqen = 0 +cryfreq = 3 +rfgain = 0 +targetpower6 = 14.000000 +targetpower4 = 17.000000 +targetpower5 = 16.000000 +targetpower2 = 19.500000 +targetpower3 = 18.500000 +lowpoweren = 0 +targetpower1 = 20.500000 +rfinitmode = 0 +backoffval = 0.000000 +digitalgain = 0 +limiten = 0 + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/.pydio new file mode 100644 index 0000000..20db22b --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/.pydio @@ -0,0 +1 @@ +765720ea-060d-4ed3-8fcf-8e0bcd5649f3 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/hspi_download.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/hspi_download.conf new file mode 100755 index 0000000..82e2312 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/hspi_download.conf @@ -0,0 +1,62 @@ +[EFUSE CHECK] +efuse_mode = 1 +efuse_err_halt = 1 +mac_save = 0 + +[DOWNLOAD PATH] +file_sel0 = 0 +file_path0 = +file_offset0 = +file_sel1 = 0 +file_path1 = +file_offset1 = +file_sel2 = 0 +file_path2 = +file_offset2 = +file_sel3 = 0 +file_path3 = +file_offset3 = +file_sel4 = 0 +file_path4 = +file_offset4 = +file_sel5 = 0 +file_path5 = +file_offset5 = +file_sel6 = 0 +file_path6 = +file_offset6 = +file_sel7 = 0 +file_path7 = +file_offset7 = +file_sel8 = 0 +file_path8 = +file_offset8 = +file_sel9 = 0 +file_path9 = +file_offset9 = +file_sel10 = 0 +file_path10 = +file_offset10 = +file_sel11 = 0 +file_path11 = +file_offset11 = +default_path = C:\Users\panfeng\Desktop\FLASH_DOWNLOAD_TOOLS_V3.6.4 + +[LOCK] +id_bind_en = 0 +lock_settings = 0 + +[FLASH_CRYSTAL] +crystal = 1 +spiautoset = 0 +spicfgdis = 0 +spispeed = 0 +spimode = 0 +flashsize = 3 + +[DOWNLOAD] +autostart1 = 0 +com_port1 = COM1 +baudrate1 = 3 +checkmac1 = 1 + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/multi_download.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/multi_download.conf new file mode 100755 index 0000000..7fc5c8f --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/multi_download.conf @@ -0,0 +1,107 @@ +[EFUSE CHECK] +efuse_mode = 1 +efuse_err_halt = 1 +mac_save = 0 + +[DOWNLOAD PATH] +file_sel0 = 1 +file_path0 = D:\ESP8266ͨ\HW-629ԶWIFI.bin +file_offset0 = 0x00000 +file_sel1 = 0 +file_path1 = +file_offset1 = +file_sel2 = 0 +file_path2 = +file_offset2 = +file_sel3 = 0 +file_path3 = +file_offset3 = +file_sel4 = 0 +file_path4 = +file_offset4 = +file_sel5 = 0 +file_path5 = +file_offset5 = +file_sel6 = 0 +file_path6 = +file_offset6 = +file_sel7 = 0 +file_path7 = +file_offset7 = +file_sel8 = 0 +file_path8 = +file_offset8 = +file_sel9 = 0 +file_path9 = +file_offset9 = +file_sel10 = 0 +file_path10 = +file_offset10 = +file_sel11 = 0 +file_path11 = +file_offset11 = +default_path = D:\ESP8266ͨ + +[LOCK] +id_bind_en = 0 +lock_settings = 0 + +[FLASH_CRYSTAL] +crystal = 1 +spiautoset = 0 +spicfgdis = 0 +spispeed = 0 +spimode = 0 +flashsize = 3 + +[DOWNLOAD] +autostart1 = 0 +com_port1 = COM1 +baudrate1 = 3 +checkmac1 = 1 +autostart2 = 0 +com_port2 = COM1 +baudrate2 = 3 +checkmac2 = 1 +autostart3 = 0 +com_port3 = COM1 +baudrate3 = 4 +checkmac3 = 1 +autostart4 = 0 +com_port4 = COM1 +baudrate4 = 0 +checkmac4 = 1 +autostart5 = 0 +com_port5 = COM1 +baudrate5 = 0 +checkmac5 = 1 +autostart6 = 0 +com_port6 = COM1 +baudrate6 = 0 +checkmac6 = 1 +autostart7 = 0 +com_port7 = COM1 +baudrate7 = 0 +checkmac7 = 1 +autostart8 = 0 +com_port8 = COM1 +baudrate8 = 0 +checkmac8 = 1 + +[ESPTOOL_PARAM] +after = hard_reset +baud = 115200 +before = default_reset +chip = auto +compress = 0 +flash_freq = keep +flash_mode = keep +flash_size = keep +no_compress = False +no_progress = False +no_stub = False +operation = write_flash +port = /dev/cu.SLAB_USBtoUART +spi_connection = 0 +verify = False + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/spi_download.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/spi_download.conf new file mode 100755 index 0000000..de93c46 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/spi_download.conf @@ -0,0 +1,83 @@ +[EFUSE CHECK] +efuse_mode = 1 +efuse_err_halt = 1 +mac_save = 0 + +[DOWNLOAD PATH] +file_sel0 = 1 +file_path0 = C:\Users\mayn\Desktop\ESP8266 AT̼\AT ̼\v0.9.5.6 AT Firmware.bin +file_offset0 = 0x00000 +file_sel1 = 0 +file_path1 = +file_offset1 = +file_sel2 = 0 +file_path2 = +file_offset2 = +file_sel3 = 0 +file_path3 = +file_offset3 = +file_sel4 = 0 +file_path4 = +file_offset4 = +file_sel5 = 0 +file_path5 = +file_offset5 = +file_sel6 = 0 +file_path6 = +file_offset6 = +file_sel7 = 0 +file_path7 = +file_offset7 = +file_sel8 = 0 +file_path8 = +file_offset8 = +file_sel9 = 0 +file_path9 = +file_offset9 = +file_sel10 = 0 +file_path10 = +file_offset10 = +file_sel11 = 0 +file_path11 = +file_offset11 = +default_path = C:\Users\mayn\Desktop\ESP8266 AT̼\AT ̼ + +[LOCK] +id_bind_en = 0 +lock_settings = 0 + +[FLASH_CRYSTAL] +crystal = 1 +spiautoset = 1 +spicfgdis = 0 +spispeed = 0 +spimode = 0 +flashsize = 4 + +[DOWNLOAD] +autostart1 = 0 +com_port1 = COM5 +baudrate1 = 4 +checkmac1 = 1 +erase_flash_en = True +new_status = 0 +num_bytes = 0 +non_volatile = False + +[ESPTOOL_PARAM] +after = hard_reset +baud = 115200 +before = default_reset +chip = auto +compress = 0 +flash_freq = keep +flash_mode = keep +flash_size = keep +no_compress = False +no_progress = False +no_stub = False +operation = write_flash +port = /dev/cu.SLAB_USBtoUART +spi_connection = 0 +verify = False + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/utility.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/utility.conf new file mode 100755 index 0000000..9cc1df7 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8266/utility.conf @@ -0,0 +1,49 @@ +[LOG_LEVEL] +utility_log_level = ERROR +multi_log_level = ERROR +spi_log_level = ERROR +hspi_log_level = ERROR + +[RF_INIT] +autocalen = 0 +toutvdd = 1 +targetlowpower = 12.000000 +limitval = 20.500000 +vdd = 3.3 +toutadc = 0 +backoffen = 0 +freqoffset = 50 +setfreqen = 0 +cryfreq = 1 +rfgain = 0 +targetpower6 = 14.000000 +targetpower4 = 17.000000 +targetpower5 = 16.000000 +targetpower2 = 19.500000 +targetpower3 = 18.500000 +lowpoweren = 0 +targetpower1 = 20.500000 +rfinitmode = 0 +backoffval = 0.000000 +digitalgain = 0 +limiten = 0 + +[GPIO_INIT] +gpio10_status = 2 +gpio5_status = 2 +gpio14_status = 2 +gpio1_status = 2 +gpio12_status = 2 +gpio7_status = 2 +gpio8_status = 2 +gpio3_status = 2 +gpio6_status = 2 +gpio13_status = 2 +gpio4_status = 2 +gpio11_status = 2 +gpio2_status = 2 +gpio0_status = 2 +gpio15_status = 2 +gpio16_status = 2 +gpio9_status = 2 + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/.pydio new file mode 100644 index 0000000..3754d6f --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/.pydio @@ -0,0 +1 @@ +e70f8692-4909-454c-acf2-c1bde4ee6861 \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/hspi_download.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/hspi_download.conf new file mode 100755 index 0000000..f1c0f6d --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/hspi_download.conf @@ -0,0 +1,62 @@ +[EFUSE CHECK] +efuse_mode = 1 +efuse_err_halt = 1 +mac_save = 0 + +[DOWNLOAD PATH] +file_sel0 = 0 +file_path0 = +file_offset0 = +file_sel1 = 0 +file_path1 = +file_offset1 = +file_sel2 = 0 +file_path2 = +file_offset2 = +file_sel3 = 0 +file_path3 = +file_offset3 = +file_sel4 = 0 +file_path4 = +file_offset4 = +file_sel5 = 0 +file_path5 = +file_offset5 = +file_sel6 = 0 +file_path6 = +file_offset6 = +file_sel7 = 0 +file_path7 = +file_offset7 = +file_sel8 = 0 +file_path8 = +file_offset8 = +file_sel9 = 0 +file_path9 = +file_offset9 = +file_sel10 = 0 +file_path10 = +file_offset10 = +file_sel11 = 0 +file_path11 = +file_offset11 = +default_path = C:\Users\panfeng\Desktop\FLASH_DOWNLOAD_TOOLS_V3.6.4 + +[LOCK] +id_bind_en = 0 +lock_settings = 0 + +[FLASH_CRYSTAL] +crystal = 1 +spiautoset = 0 +spicfgdis = 0 +spispeed = 0 +spimode = 3 +flashsize = 2 + +[DOWNLOAD] +autostart1 = 0 +com_port1 = COM1 +baudrate1 = 3 +checkmac1 = 1 + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/multi_download.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/multi_download.conf new file mode 100755 index 0000000..121d9a3 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/multi_download.conf @@ -0,0 +1,90 @@ +[EFUSE CHECK] +efuse_mode = 1 +efuse_err_halt = 1 +mac_save = 0 + +[DOWNLOAD PATH] +file_sel0 = 0 +file_path0 = +file_offset0 = +file_sel1 = 0 +file_path1 = +file_offset1 = +file_sel2 = 0 +file_path2 = +file_offset2 = +file_sel3 = 0 +file_path3 = +file_offset3 = +file_sel4 = 0 +file_path4 = +file_offset4 = +file_sel5 = 0 +file_path5 = +file_offset5 = +file_sel6 = 0 +file_path6 = +file_offset6 = +file_sel7 = 0 +file_path7 = +file_offset7 = +file_sel8 = 0 +file_path8 = +file_offset8 = +file_sel9 = 0 +file_path9 = +file_offset9 = +file_sel10 = 0 +file_path10 = +file_offset10 = +file_sel11 = 0 +file_path11 = +file_offset11 = +default_path = C:\Users\panfeng\Desktop\FLASH_DOWNLOAD_TOOLS_V3.6.4 + +[LOCK] +id_bind_en = 0 +lock_settings = 0 + +[FLASH_CRYSTAL] +crystal = 1 +spiautoset = 0 +spicfgdis = 0 +spispeed = 0 +spimode = 3 +flashsize = 2 + +[DOWNLOAD] +autostart1 = 0 +com_port1 = COM1 +baudrate1 = 0 +checkmac1 = 1 +autostart2 = 0 +com_port2 = COM1 +baudrate2 = 0 +checkmac2 = 1 +autostart3 = 0 +com_port3 = COM1 +baudrate3 = 0 +checkmac3 = 1 +autostart4 = 0 +com_port4 = COM1 +baudrate4 = 0 +checkmac4 = 1 +autostart5 = 0 +com_port5 = COM1 +baudrate5 = 0 +checkmac5 = 1 +autostart6 = 0 +com_port6 = COM1 +baudrate6 = 0 +checkmac6 = 1 +autostart7 = 0 +com_port7 = COM1 +baudrate7 = 0 +checkmac7 = 1 +autostart8 = 0 +com_port8 = COM1 +baudrate8 = 0 +checkmac8 = 1 + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/spi_download.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/spi_download.conf new file mode 100755 index 0000000..f1c0f6d --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/spi_download.conf @@ -0,0 +1,62 @@ +[EFUSE CHECK] +efuse_mode = 1 +efuse_err_halt = 1 +mac_save = 0 + +[DOWNLOAD PATH] +file_sel0 = 0 +file_path0 = +file_offset0 = +file_sel1 = 0 +file_path1 = +file_offset1 = +file_sel2 = 0 +file_path2 = +file_offset2 = +file_sel3 = 0 +file_path3 = +file_offset3 = +file_sel4 = 0 +file_path4 = +file_offset4 = +file_sel5 = 0 +file_path5 = +file_offset5 = +file_sel6 = 0 +file_path6 = +file_offset6 = +file_sel7 = 0 +file_path7 = +file_offset7 = +file_sel8 = 0 +file_path8 = +file_offset8 = +file_sel9 = 0 +file_path9 = +file_offset9 = +file_sel10 = 0 +file_path10 = +file_offset10 = +file_sel11 = 0 +file_path11 = +file_offset11 = +default_path = C:\Users\panfeng\Desktop\FLASH_DOWNLOAD_TOOLS_V3.6.4 + +[LOCK] +id_bind_en = 0 +lock_settings = 0 + +[FLASH_CRYSTAL] +crystal = 1 +spiautoset = 0 +spicfgdis = 0 +spispeed = 0 +spimode = 3 +flashsize = 2 + +[DOWNLOAD] +autostart1 = 0 +com_port1 = COM1 +baudrate1 = 3 +checkmac1 = 1 + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/utility.conf b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/utility.conf new file mode 100755 index 0000000..977e319 --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/configure/esp8285/utility.conf @@ -0,0 +1,30 @@ +[LOG_LEVEL] +multi_log_level = ERROR +utility_log_level = ERROR +spi_log_level = ERROR +hspi_log_level = ERROR + +[RF_INIT] +autocalen = 0 +toutvdd = 1 +targetlowpower = 12.000000 +limitval = 20.500000 +vdd = 3.3 +toutadc = 0 +backoffen = 0 +freqoffset = 50 +setfreqen = 0 +cryfreq = 1 +rfgain = 0 +targetpower6 = 14.000000 +targetpower4 = 17.000000 +targetpower5 = 16.000000 +targetpower2 = 19.500000 +targetpower3 = 18.500000 +lowpoweren = 0 +targetpower1 = 20.500000 +rfinitmode = 0 +backoffval = 0.000000 +digitalgain = 0 +limiten = 0 + diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/.pydio b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/.pydio new file mode 100644 index 0000000..484071e --- /dev/null +++ b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/.pydio @@ -0,0 +1 @@ +dd074ef7-403b-4acb-a0b7-958b17d238cc \ No newline at end of file diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/ESP32_RF_INIT.xlsx b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/ESP32_RF_INIT.xlsx new file mode 100755 index 0000000..861ebf8 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/ESP32_RF_INIT.xlsx differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/ESP8266_RF_init.xls b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/ESP8266_RF_init.xls new file mode 100755 index 0000000..9e8a8a9 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/ESP8266_RF_init.xls differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/ESP8266_RF_init.xlsx b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/ESP8266_RF_init.xlsx new file mode 100755 index 0000000..625c861 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/ESP8266_RF_init.xlsx differ diff --git a/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/esp32_init_data_setting.bin b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/esp32_init_data_setting.bin new file mode 100755 index 0000000..2daa077 Binary files /dev/null and b/CP2102固件烧录AT/ESP8266开发板烧录AT固件说明/ESP8266开发板烧录AT固件说明/工具/FLASH_DOWNLOAD_TOOLS_V3.6.4/init_data/esp32_init_data_setting.bin differ diff --git a/Untitled Sketch.fzz b/Untitled Sketch.fzz new file mode 100644 index 0000000..44a715f Binary files /dev/null and b/Untitled Sketch.fzz differ diff --git a/blinker-library/.gitattributes b/blinker-library/.gitattributes new file mode 100644 index 0000000..b19e83b --- /dev/null +++ b/blinker-library/.gitattributes @@ -0,0 +1,3 @@ +.gitattributes export-ignore +.gitignore export-ignore +.github export-ignore \ No newline at end of file diff --git a/blinker-library/.gitignore b/blinker-library/.gitignore new file mode 100644 index 0000000..a92cf5e --- /dev/null +++ b/blinker-library/.gitignore @@ -0,0 +1,16 @@ +__vm/ +Debug/ +*.vcxproj +*.filters +.vs/ +*.sln +.vscode/ +src/BlinkerSimpleSerialBLE.h +src/BlinkerSimpleESP8266_WS.h +src/BlinkerSimpleESP8266_PRO.h +src/BlinkerSimpleESP8266_MQTT.h +src/BlinkerSimpleESP32_WS.h +src/BlinkerSimpleESP32_PRO.h +src/BlinkerSimpleESP32_MQTT.h +src/BlinkerSimpleESP32_BLE.h +src/Adapters/BlinkerArduinoWS.h diff --git a/blinker-library/.pydio b/blinker-library/.pydio new file mode 100644 index 0000000..89c2dbb --- /dev/null +++ b/blinker-library/.pydio @@ -0,0 +1 @@ +17c69772-b5bc-4553-b32a-a390cc15315d \ No newline at end of file diff --git a/blinker-library/ISSUE_TEMPLATE.md b/blinker-library/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..669df9a --- /dev/null +++ b/blinker-library/ISSUE_TEMPLATE.md @@ -0,0 +1,64 @@ + +----------------------------- 删除下面的内容 ----------------------------- + +提问指南 +============= +请按如下说明描述您的问题,以便您的问题能够得到解决。 + +1. 对照下方的 基本信息 表,在[]中填入x。 +2. 对照下发的 设备信息 表,在[]中填入您的设备信息。 +3. 检查是否使用最新的库及APP,因为这个问题可能在最新的版本中已修复。 +4. 描述您的问题。 +5. 如果有设备端串口LOG信息,请提供LOG信息(建议DEBUG ALL下查看LOG信息)。 +6. 一个能正常运行的描述您问题的最小示例代码。不要提供您的整个项目代码。 +7. 如果编译报错,请提供完整的报错信息。 +8. 如果使用串口蓝牙模块或者blinker AT固件, 请提供接线电路示意。 +9. 提交您的问题前请将该提问指南删除。 + +----------------------------- 删除上面的内容 ----------------------------- + +== 提问请到论坛 https://www.arduino.cn/forum-132-1.html == + +## 基本信息 +- [] 这个问题满足提问指南 +- [] 我阅读了开发文档 +- [] 我使用了最新的库及APP进行测试,但是问题仍然存在 +- [] 我搜索过类似问题的解决方法但是仍然无法解决 +- [] 有设备端的LOG信息 +- [] 有编译报错信息 +- [] 我已填写基本信息 + +## 设备信息 +- 硬件: [ESP-12|wifiduino|Arduino UNO] +- 接入方式: [BLE|WIFI] +- package版本: [esp8266-arduino-2.5.0dev|esp32-1.0.1-rc3] +- blinker库版本: [arduino 0.3.0|py 0.2.0] +- 开发环境: [Arduino|linux] +- 操作系统: [Windows|Ubuntu|MacOS] + +## IDE 中的设置 +- Module: [Generic ESP8266 Module|Wemos D1 mini r2|Nodemcu|other] +- Flash Mode: [qio|dio|other] +- Flash Size: [4MB/1MB] +- lwip Variant: [v1.4|v2 Lower Memory|Higher Bandwidth] +- Reset Method: [ck|nodemcu] +- Flash Frequency: [40Mhz] +- CPU Frequency: [80Mhz|160MHz] +- Upload Using: [OTA|SERIAL] +- Upload Speed: [115200|other] (serial upload only) +## 手机信息及APP信息 +- 手机品牌及型号 +- android系统版本(请注意是android系统版本,不是厂商自己的版本号) +- blinker App版本 + +## 问题描述 +在这里填写您的问题 + +## 代码 +在这里填写您出现问题的最小示例代码 + +## LOG信息 +在这里填写您设备串口输出的LOG信息 + +## 编译信息 +在这里填写您IDE编译报错信息 \ No newline at end of file diff --git a/blinker-library/LICENSE b/blinker-library/LICENSE new file mode 100644 index 0000000..c74ade1 --- /dev/null +++ b/blinker-library/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2017 i3water + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/blinker-library/README.md b/blinker-library/README.md new file mode 100644 index 0000000..b31bd73 --- /dev/null +++ b/blinker-library/README.md @@ -0,0 +1,44 @@ +# blinker-library +Blinker library for embedded hardware. Works with Arduino, ESP8266, ESP32. + +# Why named blinker +When we learn a new embedded hardware, we usually started with the sketch **Blink**. +We think **Blink** is the **hello world** of embedded hardware. +We aim to build a easy learn IoT solution project, which like **Blink** a led. +So we named this project **blinker** with this inspiration. + +# 为什么叫 blinker +当我们接触学习一个新的嵌入式硬件平台时, 我们通常是从 **Blink** 点亮一颗LED开始的。 +我们把 **Blink** 当作硬件开发第一课的 **hello world** 。 +我们期望做像 **Blink** 点亮一颗LED 那样简单的物联网解决方案。 +根据这个灵感, 我们将这个项目命名为 **blinker** 。 + +# What's blinker +[blinker](https://blinker.app/) is a cross-hardware, cross-platform solution for the IoT. It provides APP, device and server support, and uses public cloud services for data transmission and storage. It can be used in smart home, data monitoring and other fields to help users build Internet of Things projects better and faster. + +[blinker](https://blinker.app/) 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + +# Reference/参考 +* [EN-英文](https://github.com/blinker-iot/blinker-doc/wiki/Blinker-Arduino-library-reference) +* [CN-中文](https://github.com/blinker-iot/blinker-doc/wiki/Blinker-Arduino-%E5%BA%93%E4%BD%BF%E7%94%A8%E6%89%8B%E5%86%8C) +* [CN-中文/官网](https://diandeng.tech/doc) + +# Thanks +[WebSockets](https://github.com/Links2004/arduinoWebSockets) - for Blinker to build up a websocket server +[Adafruit_MQTT_Library](https://github.com/adafruit/Adafruit_MQTT_Library) - for Blinker to build up a mqtt client +[ArduinoJson](https://github.com/bblanchon/ArduinoJson) - for Blinker to format Json data +[OneButton](https://github.com/mathertel/OneButton) - for Blinker to manage button +[painlessMesh](https://gitlab.com/painlessMesh/painlessMesh/tree/master) - for Blinker to build up a mesh network +[Blynk](https://github.com/blynkkk/blynk-library) + +Due to frequent updates of versions, individual items may not be added in time. We hope to understand. If you find out, please let us know. + +# 感谢 +[WebSockets](https://github.com/Links2004/arduinoWebSockets) - Blinker 用这个库建立了一个 websocket 服务器 +[Adafruit_MQTT_Library](https://github.com/adafruit/Adafruit_MQTT_Library) - Blinker 用这个库建立了一个 MQTT 客户端 +[ArduinoJson](https://github.com/bblanchon/ArduinoJson) - Blinker 用这个库解析 Json +[OneButton](https://github.com/mathertel/OneButton) - Blinker 用这个库管理按键 +[painlessMesh](https://gitlab.com/painlessMesh/painlessMesh/tree/master) - Blinker 用这个库建立mesh网络 +[Blynk](https://github.com/blynkkk/blynk-library) + +由于版本更新频繁,个别项目可能没有及时添加,望理解,如有发现可告知我们 diff --git a/blinker-library/appveyor.yml b/blinker-library/appveyor.yml new file mode 100644 index 0000000..9259797 --- /dev/null +++ b/blinker-library/appveyor.yml @@ -0,0 +1,51 @@ +image: Ubuntu1804 + +environment: + BUILD_HOME: "/home/appveyor" + + TARGET_LIB: "$BUILD_HOME/Arduino/libraries/blinker-library" + OTHER_LIB: "https://github.com/adafruit/Adafruit_NeoPixel.git,https://github.com/adafruit/DHT-sensor-library.git,https://github.com/adafruit/Adafruit_Sensor.git,https://github.com/adafruit/Adafruit-BMP085-Library.git" + + ARDUINO_VER: "arduino-1.8.9" + ARDUINO_URL: "https://downloads.arduino.cc/arduino-1.8.9-linux64.tar.xz" + + ARDUINO_PATH: "$BUILD_HOME/$ARDUINO_VER" + + matrix: + + - TARGET: "ESP32" + LIB_VER: "arduino-esp32-1.0.4" + LIB_URL: "https://github.com/espressif/arduino-esp32/archive/1.0.4.zip" + + HWLIB_PATH: "$BUILD_HOME/Arduino/hardware/espressif" + TOOL_PATH: "$HWLIB_PATH/esp32/tools" + + BOARD_CONF: "espressif:esp32:nodemcu-32s:FlashFreq=80" + BUILD_CONF: "build.warn_data_percentage=75,runtime.tools.xtensa-esp32-elf-gcc.path=$HWLIB_PATH/esp32/tools/xtensa-esp32-elf,runtime.tools.xtensa-esp32-elf-gcc-1.22.0-80-g6c4433a-5.2.0.path=$HWLIB_PATH/esp32/tools/xtensa-esp32-elf,runtime.tools.esptool_py.path=$HWLIB_PATH/esp32/tools/esptool_py/2.6.1,runtime.tools.esptool_py-2.6.1.path=$HWLIB_PATH/esp32/tools/esptool_py/2.6.1,runtime.tools.mkspiffs.path=$HWLIB_PATH/esp32/tools/mkspiffs/0.2.3,runtime.tools.mkspiffs-0.2.3.path=$HWLIB_PATH/esp32/tools/mkspiffs/0.2.3" + + - TARGET: "UNO" + BOARD_CONF: "arduino:avr:uno" + + - TARGET: "ESP8266" + LIB_VER: "esp8266-2.5.2" + LIB_URL: "https://github.com/esp8266/Arduino/releases/download/2.5.2/esp8266-2.5.2.zip" + + HWLIB_PATH: "$BUILD_HOME/Arduino/hardware/esp8266com" + TOOL_PATH: "$HWLIB_PATH/esp8266/tools" + + BOARD_CONF: "esp8266com:esp8266:wifiduino:xtal=80,vt=flash,exception=disabled,ssl=all,eesz=4M,ip=lm2f,dbg=Disabled,lvl=None____,wipe=none,baud=921600" + BUILD_CONF: "build.warn_data_percentage=75,runtime.tools.xtensa-lx106-elf-gcc.path=$HWLIB_PATH/esp8266/tools/xtensa-lx106-elf,runtime.tools.xtensa-lx106-elf-gcc-2.5.0-3-20ed2b9.path=$HWLIB_PATH/esp8266/tools/xtensa-lx106-elf,runtime.tools.mkspiffs.path=$HWLIB_PATH/esp8266/tools/mkspiffs,runtime.tools.mkspiffs-2.5.0-3-20ed2b9.path=$HWLIB_PATH/esp8266/tools/mkspiffs,runtime.tools.python.path=$HWLIB_PATH/esp8266/tools/python,runtime.tools.python-3.7.2-post1.path=$HWLIB_PATH/esp8266/tools/python" + +init: +- mkdir -p $BUILD_HOME/Arduino/libraries +- mkdir -p $BUILD_HOME/Arduino/hardware +- mkdir -p $BUILD_HOME/build_cache +clone_folder: $TARGET_LIB + +install: +- chmod +x $TARGET_LIB/test/install.sh +- chmod +x $TARGET_LIB/test/build.sh +- $TARGET_LIB/test/install.sh + +build_script: +- $TARGET_LIB/test/build.sh diff --git a/blinker-library/examples/.pydio b/blinker-library/examples/.pydio new file mode 100644 index 0000000..1b54737 --- /dev/null +++ b/blinker-library/examples/.pydio @@ -0,0 +1 @@ +9b049167-3861-4c6c-8f9d-1c25bd4db82d \ No newline at end of file diff --git a/blinker-library/examples/Blinker_AT_Firmware/.pydio b/blinker-library/examples/Blinker_AT_Firmware/.pydio new file mode 100644 index 0000000..59db08a --- /dev/null +++ b/blinker-library/examples/Blinker_AT_Firmware/.pydio @@ -0,0 +1 @@ +99d5c867-b417-41db-aabd-18079af026f8 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_AT_Firmware/AT_Firmware_WiFi/.pydio b/blinker-library/examples/Blinker_AT_Firmware/AT_Firmware_WiFi/.pydio new file mode 100644 index 0000000..e9d2380 --- /dev/null +++ b/blinker-library/examples/Blinker_AT_Firmware/AT_Firmware_WiFi/.pydio @@ -0,0 +1 @@ +b47b4b4a-42f8-4523-b8b4-5e2d1a0c25ec \ No newline at end of file diff --git a/blinker-library/examples/Blinker_AT_Firmware/AT_Firmware_WiFi/AT_Firmware_WiFi.ino b/blinker-library/examples/Blinker_AT_Firmware/AT_Firmware_WiFi/AT_Firmware_WiFi.ino new file mode 100644 index 0000000..d1bab7b --- /dev/null +++ b/blinker-library/examples/Blinker_AT_Firmware/AT_Firmware_WiFi/AT_Firmware_WiFi.ino @@ -0,0 +1,58 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_AT_MQTT + +#include + +void setup() +{ + Blinker.begin(); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_ArduinoJson/.pydio b/blinker-library/examples/Blinker_ArduinoJson/.pydio new file mode 100644 index 0000000..738f14c --- /dev/null +++ b/blinker-library/examples/Blinker_ArduinoJson/.pydio @@ -0,0 +1 @@ +460dd916-2bf0-4bc1-a6f4-33b76b9e1c36 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_ArduinoJson/ArduinoJson_WiFi/.pydio b/blinker-library/examples/Blinker_ArduinoJson/ArduinoJson_WiFi/.pydio new file mode 100644 index 0000000..8e36bed --- /dev/null +++ b/blinker-library/examples/Blinker_ArduinoJson/ArduinoJson_WiFi/.pydio @@ -0,0 +1 @@ +e70730c2-0822-43ad-a318-9ceee3c997a3 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_ArduinoJson/ArduinoJson_WiFi/ArduinoJson_WiFi.ino b/blinker-library/examples/Blinker_ArduinoJson/ArduinoJson_WiFi/ArduinoJson_WiFi.ino new file mode 100644 index 0000000..fbdf823 --- /dev/null +++ b/blinker-library/examples/Blinker_ArduinoJson/ArduinoJson_WiFi/ArduinoJson_WiFi.ino @@ -0,0 +1,104 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void weatherData(const String & data) +{ + BLINKER_LOG("weather: ", data); + + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject weather = jsonBuffer.as(); + + if (error) + { + BLINKER_LOG(data, " , not a Json buffer!"); + } + + String weather_text = weather["cond_txt"]; + int8_t weather_temp = weather["tmp"]; + + BLINKER_LOG("Local weather is: ", weather_text, " ,temperature is: ", weather_temp, "℃"); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + uint32_t BlinkerTime = millis(); + + Blinker.vibrate(); + Blinker.print("millis", BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + Blinker.weather(); + + Blinker.delay(60000); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + Blinker.attachWeather(weatherData); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Bridge/.pydio b/blinker-library/examples/Blinker_Bridge/.pydio new file mode 100644 index 0000000..e912c1a --- /dev/null +++ b/blinker-library/examples/Blinker_Bridge/.pydio @@ -0,0 +1 @@ +7a053fba-686a-4575-b461-0c8531aef540 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Bridge/Bridge_WiFi/.pydio b/blinker-library/examples/Blinker_Bridge/Bridge_WiFi/.pydio new file mode 100644 index 0000000..6460f53 --- /dev/null +++ b/blinker-library/examples/Blinker_Bridge/Bridge_WiFi/.pydio @@ -0,0 +1 @@ +982e6392-796a-413a-ba03-deb6d6c052e5 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Bridge/Bridge_WiFi/Bridge_WiFi.ino b/blinker-library/examples/Blinker_Bridge/Bridge_WiFi/Bridge_WiFi.ino new file mode 100644 index 0000000..4ab3c4c --- /dev/null +++ b/blinker-library/examples/Blinker_Bridge/Bridge_WiFi/Bridge_WiFi.ino @@ -0,0 +1,87 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +#define BRIDGE_1 "Your Device Secret Key of bridge to device" + +BlinkerBridge BridgeDevice1(BRIDGE_1); + +void bridge1Read(const String & data) +{ + BLINKER_LOG("BridgeDevice1 readString: ", data); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + // must print Json data + BridgeDevice1.print("{\"hello\":\"bridge\"}"); +} + +void setup() { + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BridgeDevice1.attach(bridge1Read); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Cloud/.pydio b/blinker-library/examples/Blinker_Cloud/.pydio new file mode 100644 index 0000000..295205b --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/.pydio @@ -0,0 +1 @@ +909a51d1-27d9-4f31-a904-698210707b78 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_CLOUDDATA/.pydio b/blinker-library/examples/Blinker_Cloud/Blinker_CLOUDDATA/.pydio new file mode 100644 index 0000000..0a4e60f --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_CLOUDDATA/.pydio @@ -0,0 +1 @@ +eca17031-b486-474c-9c22-337162f04dd0 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_CLOUDDATA/CLOUDDATA_WiFi/.pydio b/blinker-library/examples/Blinker_Cloud/Blinker_CLOUDDATA/CLOUDDATA_WiFi/.pydio new file mode 100644 index 0000000..021f85e --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_CLOUDDATA/CLOUDDATA_WiFi/.pydio @@ -0,0 +1 @@ +9aa96af5-4ab8-4339-a246-229e31e2ea10 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_CLOUDDATA/CLOUDDATA_WiFi/CLOUDDATA_WiFi.ino b/blinker-library/examples/Blinker_Cloud/Blinker_CLOUDDATA/CLOUDDATA_WiFi/CLOUDDATA_WiFi.ino new file mode 100644 index 0000000..6b90a50 --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_CLOUDDATA/CLOUDDATA_WiFi/CLOUDDATA_WiFi.ino @@ -0,0 +1,88 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + uint32_t BlinkerTime = millis(); + + Blinker.vibrate(); + Blinker.print("millis", BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +void dataStorage() +{ + Blinker.dataStorage("data1", random(0,120)); + Blinker.dataStorage("data2", random(0,120)/2.0); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + Blinker.attachDataStorage(dataStorage); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_Coordinate/.pydio b/blinker-library/examples/Blinker_Cloud/Blinker_Coordinate/.pydio new file mode 100644 index 0000000..006b669 --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_Coordinate/.pydio @@ -0,0 +1 @@ +112f8898-7da6-4376-b94e-f5adeaeb857a \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_Coordinate/Coordinate_WiFi/.pydio b/blinker-library/examples/Blinker_Cloud/Blinker_Coordinate/Coordinate_WiFi/.pydio new file mode 100644 index 0000000..3fa3f6d --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_Coordinate/Coordinate_WiFi/.pydio @@ -0,0 +1 @@ +165af3c1-550f-4643-9cab-c4383600250e \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_Coordinate/Coordinate_WiFi/Coordinate_WiFi.ino b/blinker-library/examples/Blinker_Cloud/Blinker_Coordinate/Coordinate_WiFi/Coordinate_WiFi.ino new file mode 100644 index 0000000..7894910 --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_Coordinate/Coordinate_WiFi/Coordinate_WiFi.ino @@ -0,0 +1,91 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + + Blinker.coordinate(104.0667, 30.6667); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + counter++; + Number1.print(counter); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, HIGH); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + Button1.attach(button1_callback); +} + +void loop() { + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/.pydio b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/.pydio new file mode 100644 index 0000000..84884bf --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/.pydio @@ -0,0 +1 @@ +76e1bb29-64e0-4191-934c-00e6818bb04d \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_ConfigData/.pydio b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_ConfigData/.pydio new file mode 100644 index 0000000..9c020fd --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_ConfigData/.pydio @@ -0,0 +1 @@ +b53f9e64-c60f-4683-8914-d4362a78362e \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_ConfigData/Blinker_ConfigData.ino b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_ConfigData/Blinker_ConfigData.ino new file mode 100644 index 0000000..5a88217 --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_ConfigData/Blinker_ConfigData.ino @@ -0,0 +1,93 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void configGet(const String & data) +{ + BLINKER_LOG("config get: ", data); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + uint32_t BlinkerTime = millis(); + + Blinker.vibrate(); + Blinker.print("millis", BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + + // update data must be Json + if (Blinker.configUpdate("{\"Hello\":\"blinker\"}")) + { + Blinker.configGet(); + } +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + Blinker.attachConfigGet(configGet); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_TextData/.pydio b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_TextData/.pydio new file mode 100644 index 0000000..f763b1f --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_TextData/.pydio @@ -0,0 +1 @@ +53bb5ac5-ca06-4f16-984e-0a89570099a7 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_TextData/Blinker_TextData.ino b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_TextData/Blinker_TextData.ino new file mode 100644 index 0000000..591a896 --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_TextData/Blinker_TextData.ino @@ -0,0 +1,80 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + uint32_t BlinkerTime = millis(); + + Blinker.textData("text data"); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_TimeSlotData/.pydio b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_TimeSlotData/.pydio new file mode 100644 index 0000000..2732cb5 --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_TimeSlotData/.pydio @@ -0,0 +1 @@ +6d1dc563-cc11-40f4-bd29-83dcbd14ad09 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_TimeSlotData/Blinker_TimeSlotData.ino b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_TimeSlotData/Blinker_TimeSlotData.ino new file mode 100644 index 0000000..6b096d9 --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_DataStorage/Blinker_TimeSlotData/Blinker_TimeSlotData.ino @@ -0,0 +1,88 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + uint32_t BlinkerTime = millis(); + + Blinker.vibrate(); + Blinker.print("millis", BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +void dataStorage() +{ + Blinker.timeSlotData("data1", (int32_t)random(0,120)); + Blinker.timeSlotData("data2", random(0,120)/(float)1.5); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + Blinker.attachDataStorage(dataStorage); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_GPSData/.pydio b/blinker-library/examples/Blinker_Cloud/Blinker_GPSData/.pydio new file mode 100644 index 0000000..56fc829 --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_GPSData/.pydio @@ -0,0 +1 @@ +c3944b91-6da6-4ad5-9b24-a2471ebeb5aa \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_GPSData/GPSData_WiFi/.pydio b/blinker-library/examples/Blinker_Cloud/Blinker_GPSData/GPSData_WiFi/.pydio new file mode 100644 index 0000000..d64e01b --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_GPSData/GPSData_WiFi/.pydio @@ -0,0 +1 @@ +256c575b-c5dd-428c-bcd4-838298bd505a \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_GPSData/GPSData_WiFi/GPSData_WiFi.ino b/blinker-library/examples/Blinker_Cloud/Blinker_GPSData/GPSData_WiFi/GPSData_WiFi.ino new file mode 100644 index 0000000..c577f8d --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_GPSData/GPSData_WiFi/GPSData_WiFi.ino @@ -0,0 +1,95 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +// 新建组件对象 +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +// 按下按键即会执行该函数 +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +// 如果未绑定的组件被触发,则会执行其中内容 +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + counter++; + Number1.print(counter); + + Blinker.gps(30.6573130504,104.0661831040); +} + +void setup() +{ + // 初始化串口 + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + // 初始化有LED的IO + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, HIGH); + // 初始化blinker + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + Button1.attach(button1_callback); +} + +void loop() { + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_LOG/.pydio b/blinker-library/examples/Blinker_Cloud/Blinker_LOG/.pydio new file mode 100644 index 0000000..9fa955f --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_LOG/.pydio @@ -0,0 +1 @@ +1f46c0e6-cf43-491d-937e-b9c72a57ccce \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_LOG/LOG_WiFi/.pydio b/blinker-library/examples/Blinker_Cloud/Blinker_LOG/LOG_WiFi/.pydio new file mode 100644 index 0000000..9a100dc --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_LOG/LOG_WiFi/.pydio @@ -0,0 +1 @@ +7d840479-015c-4b33-bfc0-20c2917a48c5 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Cloud/Blinker_LOG/LOG_WiFi/LOG_WiFi.ino b/blinker-library/examples/Blinker_Cloud/Blinker_LOG/LOG_WiFi/LOG_WiFi.ino new file mode 100644 index 0000000..e5930b8 --- /dev/null +++ b/blinker-library/examples/Blinker_Cloud/Blinker_LOG/LOG_WiFi/LOG_WiFi.ino @@ -0,0 +1,91 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + + Blinker.log("button pressed"); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + counter++; + Number1.print(counter); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, HIGH); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + Button1.attach(button1_callback); +} + +void loop() { + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_ESP32_CAM/.pydio b/blinker-library/examples/Blinker_ESP32_CAM/.pydio new file mode 100644 index 0000000..62a9d7e --- /dev/null +++ b/blinker-library/examples/Blinker_ESP32_CAM/.pydio @@ -0,0 +1 @@ +c1a2e691-f8d8-4fb3-b915-e53c75028567 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_ESP32_CAM/Blinker_ESP32_CAM.ino b/blinker-library/examples/Blinker_ESP32_CAM/Blinker_ESP32_CAM.ino new file mode 100644 index 0000000..591ba1b --- /dev/null +++ b/blinker-library/examples/Blinker_ESP32_CAM/Blinker_ESP32_CAM.ino @@ -0,0 +1,89 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_ESP_SMARTCONFIG + +#include +#include "ESP32_CAM_SERVER.h" + +char auth[] = "Your Device Secret Key"; +bool setup_camera = false; + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); + + if (Blinker.connected() && !setup_camera) + { + setupCamera(); + setup_camera = true; + + Blinker.printObject("video", "{\"str\":\"mjpg\",\"url\":\"http://"+ WiFi.localIP().toString() + "\"}"); + } +} diff --git a/blinker-library/examples/Blinker_ESP32_CAM/ESP32_CAM_SERVER.h b/blinker-library/examples/Blinker_ESP32_CAM/ESP32_CAM_SERVER.h new file mode 100644 index 0000000..5dd9cf6 --- /dev/null +++ b/blinker-library/examples/Blinker_ESP32_CAM/ESP32_CAM_SERVER.h @@ -0,0 +1,256 @@ +#ifndef ESP_CAM_SERVER_H +#define ESP_CAM_SERVER_H + +#include "esp_camera.h" +#include +#include "esp_timer.h" +#include "img_converters.h" +#include "Arduino.h" +#include "fb_gfx.h" +#include "soc/soc.h" //disable brownout problems +#include "soc/rtc_cntl_reg.h" //disable brownout problems +#include "esp_http_server.h" + + +#define PART_BOUNDARY "123456789000000000000987654321" + +// This project was tested with the AI Thinker Model, M5STACK PSRAM Model and M5STACK WITHOUT PSRAM +#define CAMERA_MODEL_AI_THINKER +//#define CAMERA_MODEL_M5STACK_PSRAM +//#define CAMERA_MODEL_M5STACK_WITHOUT_PSRAM + +// Not tested with this model +//#define CAMERA_MODEL_WROVER_KIT + +#if defined(CAMERA_MODEL_WROVER_KIT) + #define PWDN_GPIO_NUM -1 + #define RESET_GPIO_NUM -1 + #define XCLK_GPIO_NUM 21 + #define SIOD_GPIO_NUM 26 + #define SIOC_GPIO_NUM 27 + + #define Y9_GPIO_NUM 35 + #define Y8_GPIO_NUM 34 + #define Y7_GPIO_NUM 39 + #define Y6_GPIO_NUM 36 + #define Y5_GPIO_NUM 19 + #define Y4_GPIO_NUM 18 + #define Y3_GPIO_NUM 5 + #define Y2_GPIO_NUM 4 + #define VSYNC_GPIO_NUM 25 + #define HREF_GPIO_NUM 23 + #define PCLK_GPIO_NUM 22 + +#elif defined(CAMERA_MODEL_M5STACK_PSRAM) + #define PWDN_GPIO_NUM -1 + #define RESET_GPIO_NUM 15 + #define XCLK_GPIO_NUM 27 + #define SIOD_GPIO_NUM 25 + #define SIOC_GPIO_NUM 23 + + #define Y9_GPIO_NUM 19 + #define Y8_GPIO_NUM 36 + #define Y7_GPIO_NUM 18 + #define Y6_GPIO_NUM 39 + #define Y5_GPIO_NUM 5 + #define Y4_GPIO_NUM 34 + #define Y3_GPIO_NUM 35 + #define Y2_GPIO_NUM 32 + #define VSYNC_GPIO_NUM 22 + #define HREF_GPIO_NUM 26 + #define PCLK_GPIO_NUM 21 + +#elif defined(CAMERA_MODEL_M5STACK_WITHOUT_PSRAM) + #define PWDN_GPIO_NUM -1 + #define RESET_GPIO_NUM 15 + #define XCLK_GPIO_NUM 27 + #define SIOD_GPIO_NUM 25 + #define SIOC_GPIO_NUM 23 + + #define Y9_GPIO_NUM 19 + #define Y8_GPIO_NUM 36 + #define Y7_GPIO_NUM 18 + #define Y6_GPIO_NUM 39 + #define Y5_GPIO_NUM 5 + #define Y4_GPIO_NUM 34 + #define Y3_GPIO_NUM 35 + #define Y2_GPIO_NUM 17 + #define VSYNC_GPIO_NUM 22 + #define HREF_GPIO_NUM 26 + #define PCLK_GPIO_NUM 21 + +#elif defined(CAMERA_MODEL_AI_THINKER) + #define PWDN_GPIO_NUM 32 + #define RESET_GPIO_NUM -1 + #define XCLK_GPIO_NUM 0 + #define SIOD_GPIO_NUM 26 + #define SIOC_GPIO_NUM 27 + + #define Y9_GPIO_NUM 35 + #define Y8_GPIO_NUM 34 + #define Y7_GPIO_NUM 39 + #define Y6_GPIO_NUM 36 + #define Y5_GPIO_NUM 21 + #define Y4_GPIO_NUM 19 + #define Y3_GPIO_NUM 18 + #define Y2_GPIO_NUM 5 + #define VSYNC_GPIO_NUM 25 + #define HREF_GPIO_NUM 23 + #define PCLK_GPIO_NUM 22 +#else + #error "Camera model not selected" +#endif + +static const char* _STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY; +static const char* _STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n"; +static const char* _STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n"; + +httpd_handle_t stream_httpd = NULL; + +static esp_err_t stream_handler(httpd_req_t *req){ + camera_fb_t * fb = NULL; + esp_err_t res = ESP_OK; + size_t _jpg_buf_len = 0; + uint8_t * _jpg_buf = NULL; + char * part_buf[64]; + + res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE); + if(res != ESP_OK){ + return res; + } + + while(true){ + fb = esp_camera_fb_get(); + if (!fb) { + Serial.println("Camera capture failed"); + res = ESP_FAIL; + } else { + if(fb->width > 400){ + if(fb->format != PIXFORMAT_JPEG){ + bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len); + esp_camera_fb_return(fb); + fb = NULL; + if(!jpeg_converted){ + Serial.println("JPEG compression failed"); + res = ESP_FAIL; + } + } else { + _jpg_buf_len = fb->len; + _jpg_buf = fb->buf; + } + } + else { + if (fb->format != PIXFORMAT_JPEG){ + esp_camera_fb_return(fb); + fb = NULL; + } else { + _jpg_buf = fb->buf; + _jpg_buf_len = fb->len; + } + } + } + if(res == ESP_OK){ + size_t hlen = snprintf((char *)part_buf, 64, _STREAM_PART, _jpg_buf_len); + res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen); + } + if(res == ESP_OK){ + res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len); + } + if(res == ESP_OK){ + res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY)); + } + if(fb){ + esp_camera_fb_return(fb); + fb = NULL; + _jpg_buf = NULL; + } else if(_jpg_buf){ + free(_jpg_buf); + _jpg_buf = NULL; + } + if(res != ESP_OK){ + break; + } + //Serial.printf("MJPG: %uB\n",(uint32_t)(_jpg_buf_len)); + } + return res; +} + +void startCameraServer(){ + httpd_config_t config = HTTPD_DEFAULT_CONFIG(); + config.server_port = 80; + + httpd_uri_t index_uri = { + .uri = "/", + .method = HTTP_GET, + .handler = stream_handler, + .user_ctx = NULL + }; + + //Serial.printf("Starting web server on port: '%d'\n", config.server_port); + if (httpd_start(&stream_httpd, &config) == ESP_OK) { + httpd_register_uri_handler(stream_httpd, &index_uri); + } +} + +void setupCamera() +{ + WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector + + // Serial.begin(115200); + // Serial.setDebugOutput(false); + + camera_config_t config; + config.ledc_channel = LEDC_CHANNEL_0; + config.ledc_timer = LEDC_TIMER_0; + config.pin_d0 = Y2_GPIO_NUM; + config.pin_d1 = Y3_GPIO_NUM; + config.pin_d2 = Y4_GPIO_NUM; + config.pin_d3 = Y5_GPIO_NUM; + config.pin_d4 = Y6_GPIO_NUM; + config.pin_d5 = Y7_GPIO_NUM; + config.pin_d6 = Y8_GPIO_NUM; + config.pin_d7 = Y9_GPIO_NUM; + config.pin_xclk = XCLK_GPIO_NUM; + config.pin_pclk = PCLK_GPIO_NUM; + config.pin_vsync = VSYNC_GPIO_NUM; + config.pin_href = HREF_GPIO_NUM; + config.pin_sscb_sda = SIOD_GPIO_NUM; + config.pin_sscb_scl = SIOC_GPIO_NUM; + config.pin_pwdn = PWDN_GPIO_NUM; + config.pin_reset = RESET_GPIO_NUM; + config.xclk_freq_hz = 20000000; + config.pixel_format = PIXFORMAT_JPEG; + + if(psramFound()){ + config.frame_size = FRAMESIZE_QVGA; + config.jpeg_quality = 10; + config.fb_count = 2; + } else { + config.frame_size = FRAMESIZE_QVGA; + config.jpeg_quality = 10; + config.fb_count = 2; + } + + // Camera init + esp_err_t err = esp_camera_init(&config); + if (err != ESP_OK) { + Serial.printf("Camera init failed with error 0x%x", err); + return; + } + // Wi-Fi connection + // WiFi.begin(ssid, password); + // while (WiFi.status() != WL_CONNECTED) { + // delay(500); + // Serial.print("."); + // } + // Serial.println(""); + // Serial.println("WiFi connected"); + + // Serial.print("Camera Stream Ready! Go to: http://"); + // Serial.println(WiFi.localIP()); + + // Start streaming web server + startCameraServer(); +} + +#endif \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Hello/.pydio b/blinker-library/examples/Blinker_Hello/.pydio new file mode 100644 index 0000000..c5d43b5 --- /dev/null +++ b/blinker-library/examples/Blinker_Hello/.pydio @@ -0,0 +1 @@ +8c7f1d82-a68a-4a2e-9f0e-f521d25e5a75 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Hello/Blinker_HTTP/.pydio b/blinker-library/examples/Blinker_Hello/Blinker_HTTP/.pydio new file mode 100644 index 0000000..05b020f --- /dev/null +++ b/blinker-library/examples/Blinker_Hello/Blinker_HTTP/.pydio @@ -0,0 +1 @@ +30498214-1fb0-46ad-8117-93fc292d57cd \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Hello/Blinker_HTTP/Blinker_HTTP.ino b/blinker-library/examples/Blinker_Hello/Blinker_HTTP/Blinker_HTTP.ino new file mode 100644 index 0000000..bdaf95f --- /dev/null +++ b/blinker-library/examples/Blinker_Hello/Blinker_HTTP/Blinker_HTTP.ino @@ -0,0 +1,102 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_HTTP + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +// 新建组件对象 +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +// 按下按键即会执行该函数 +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +// 如果未绑定的组件被触发,则会执行其中内容 +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + counter++; + Number1.print(counter); +} + +void setup() +{ + // 初始化串口 + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + // 初始化有LED的IO + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, HIGH); + // 初始化blinker + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + Button1.attach(button1_callback); +} + +uint32_t time_os_run = 0; + +void loop() { + Blinker.run(); + + if ((millis() - time_os_run) >= 60000) + { + Blinker.subscribe(); + time_os_run += 60000; + } +} diff --git a/blinker-library/examples/Blinker_Hello/Hello_BLE/.pydio b/blinker-library/examples/Blinker_Hello/Hello_BLE/.pydio new file mode 100644 index 0000000..5712122 --- /dev/null +++ b/blinker-library/examples/Blinker_Hello/Hello_BLE/.pydio @@ -0,0 +1 @@ +cd484f7c-f6c3-4807-88b9-fb56461debbe \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Hello/Hello_BLE/Hello_BLE.ino b/blinker-library/examples/Blinker_Hello/Hello_BLE/Hello_BLE.ino new file mode 100644 index 0000000..e16caf2 --- /dev/null +++ b/blinker-library/examples/Blinker_Hello/Hello_BLE/Hello_BLE.ino @@ -0,0 +1,85 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_BLE + +#include + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + counter++; + Number1.print(counter); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, HIGH); + + Blinker.begin(); + Blinker.attachData(dataRead); + + Button1.attach(button1_callback); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Hello/Hello_WiFi/.pydio b/blinker-library/examples/Blinker_Hello/Hello_WiFi/.pydio new file mode 100644 index 0000000..a977fea --- /dev/null +++ b/blinker-library/examples/Blinker_Hello/Hello_WiFi/.pydio @@ -0,0 +1 @@ +3807e855-a36b-4668-ae1d-ce752af5e7c1 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Hello/Hello_WiFi/Hello_WiFi.ino b/blinker-library/examples/Blinker_Hello/Hello_WiFi/Hello_WiFi.ino new file mode 100644 index 0000000..692fbe4 --- /dev/null +++ b/blinker-library/examples/Blinker_Hello/Hello_WiFi/Hello_WiFi.ino @@ -0,0 +1,94 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +// 新建组件对象 +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +// 按下按键即会执行该函数 +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +// 如果未绑定的组件被触发,则会执行其中内容 +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + counter++; + Number1.print(counter); +} + +void setup() +{ + // 初始化串口 + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + // 初始化有LED的IO + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, HIGH); + // 初始化blinker + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + Button1.attach(button1_callback); +} + +void loop() { + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Hello/Hello_WiFi_Without_SSL/.pydio b/blinker-library/examples/Blinker_Hello/Hello_WiFi_Without_SSL/.pydio new file mode 100644 index 0000000..db478e6 --- /dev/null +++ b/blinker-library/examples/Blinker_Hello/Hello_WiFi_Without_SSL/.pydio @@ -0,0 +1 @@ +4ae01131-ba92-4681-bb04-10aa23efd89d \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Hello/Hello_WiFi_Without_SSL/Hello_WiFi_Without_SSL.ino b/blinker-library/examples/Blinker_Hello/Hello_WiFi_Without_SSL/Hello_WiFi_Without_SSL.ino new file mode 100644 index 0000000..1843157 --- /dev/null +++ b/blinker-library/examples/Blinker_Hello/Hello_WiFi_Without_SSL/Hello_WiFi_Without_SSL.ino @@ -0,0 +1,95 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_WITHOUT_SSL + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +// 新建组件对象 +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +// 按下按键即会执行该函数 +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +// 如果未绑定的组件被触发,则会执行其中内容 +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + counter++; + Number1.print(counter); +} + +void setup() +{ + // 初始化串口 + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + // 初始化有LED的IO + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, HIGH); + // 初始化blinker + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + Button1.attach(button1_callback); +} + +void loop() { + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_MQTT/.pydio b/blinker-library/examples/Blinker_MQTT/.pydio new file mode 100644 index 0000000..8133e6d --- /dev/null +++ b/blinker-library/examples/Blinker_MQTT/.pydio @@ -0,0 +1 @@ +c1b16c8c-f934-4def-bbe9-92a4877aeddf \ No newline at end of file diff --git a/blinker-library/examples/Blinker_MQTT/MQTT_PUB/.pydio b/blinker-library/examples/Blinker_MQTT/MQTT_PUB/.pydio new file mode 100644 index 0000000..eba6751 --- /dev/null +++ b/blinker-library/examples/Blinker_MQTT/MQTT_PUB/.pydio @@ -0,0 +1 @@ +4732c82b-59fc-40b9-b6f5-ba8eb850e712 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_MQTT/MQTT_PUB/MQTT_PUB.ino b/blinker-library/examples/Blinker_MQTT/MQTT_PUB/MQTT_PUB.ino new file mode 100644 index 0000000..e20abd1 --- /dev/null +++ b/blinker-library/examples/Blinker_MQTT/MQTT_PUB/MQTT_PUB.ino @@ -0,0 +1,100 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +// 新建组件对象 +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +// 按下按键即会执行该函数 +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +// 如果未绑定的组件被触发,则会执行其中内容 +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + counter++; + Number1.print(counter); + + if (BLINKER_PROTOCOL_MQTT != NULL) { + String pub_topic = "/device/" + Blinker.deviceName() + "/s"; + String pub_data = "{\"toDevice\":\"the device name you need pub to\",\"data\":{\"hello\":\"blinker\"}}"; + BLINKER_PROTOCOL_MQTT->publish(pub_topic.c_str(), pub_data.c_str()); + } +} + +void setup() +{ + // 初始化串口 + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + // 初始化有LED的IO + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, HIGH); + // 初始化blinker + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + Button1.attach(button1_callback); +} + +void loop() { + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_PRO/.pydio b/blinker-library/examples/Blinker_PRO/.pydio new file mode 100644 index 0000000..fcbbf5a --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/.pydio @@ -0,0 +1 @@ +65284a9e-4a26-4140-8e2f-8d008aa8d552 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_AIR202/.pydio b/blinker-library/examples/Blinker_PRO/Blinker_PRO_AIR202/.pydio new file mode 100644 index 0000000..34a29b0 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_AIR202/.pydio @@ -0,0 +1 @@ +5832cbcf-f223-4242-abf3-3f272f70feb3 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_AIR202/Blinker_PRO_AIR202.ino b/blinker-library/examples/Blinker_PRO/Blinker_PRO_AIR202/Blinker_PRO_AIR202.ino new file mode 100644 index 0000000..d47161f --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_AIR202/Blinker_PRO_AIR202.ino @@ -0,0 +1,163 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +/* + * BLINKER_PRO is use for professional device + * + * Please make sure you have permission to modify professional device! + * Please read usermanual first! Thanks! + * https://diandeng.tech/doc + * + * Written by i3water for blinker. + * Learn more:https://blinker.app/ + */ + +#define BLINKER_PRO_AIR202 +// #define BLINKER_BUTTON +// #define BLINKER_BUTTON_PIN D7 + +#define BLINKER_OTA_VERSION_CODE "0.1.1" + +#include + +/* + * Add your command parse code in this function + * + * When get a command and device not parsed this command, device will call this function + */ +bool dataParse(const JsonObject & data) +{ + String getData; + + serializeJson(data, getData); + + BLINKER_LOG("Get user command: ", getData); + return true; +} + +/* + * Add your heartbeat message detail in this function + * + * When get heartbeat command {"get": "state"}, device will call this function + * For example, you can print message back + * + * Every 30s will get a heartbeat command from app + */ +void heartbeat() +{ + // Blinker.print("hello", "blinker"); + BLINKER_LOG("heartbeat!"); +} + +#if defined(BLINKER_BUTTON) +/* + * Blinker provide a button parse function for user if you defined BLINKER_BUTTON + * + * Blinker button can detect singal click/ double click/ long press + * + * Blinker.tick() will run by default, use interrupt will be better + */ +ICACHE_RAM_ATTR void buttonTick() +{ + Blinker.tick(); +} + +/* + * Add your code in this function + * + * When button clicked, device will call this function + */ +void singleClick() +{ + BLINKER_LOG("Button clicked!"); +} + +/* + * Add your code in this function + * + * When button double clicked, device will call this function + */ +void doubleClick() +{ + BLINKER_LOG("Button double clicked!"); +} +#endif + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + Blinker.print(BlinkerTime); + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + Blinker.attachData(dataRead); + Blinker.attachParse(dataParse); + Blinker.attachHeartbeat(heartbeat); + +#if defined(BLINKER_BUTTON) + Blinker.attachClick(singleClick); + Blinker.attachDoubleClick(doubleClick); + attachInterrupt(BLINKER_BUTTON_PIN, buttonTick, CHANGE); +#endif +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_Change_Server/.pydio b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Change_Server/.pydio new file mode 100644 index 0000000..9ebe86b --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Change_Server/.pydio @@ -0,0 +1 @@ +c565f625-fbb7-488a-b4e4-1688adcbc7fa \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_Change_Server/Blinker_Pro_Change_Server.ino b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Change_Server/Blinker_Pro_Change_Server.ino new file mode 100644 index 0000000..812ada0 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Change_Server/Blinker_Pro_Change_Server.ino @@ -0,0 +1,174 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_PRO_ESP +#define BLINKER_BUTTON +#if defined(ESP32) + #define BLINKER_BUTTON_PIN 4 +#else + #define BLINKER_BUTTON_PIN D7 +#endif + +#define BLINKER_OTA_VERSION_CODE "0.1.1" + +#define BLINKER_SERVER_HTTPS "https://iot.diandeng.tech" + +#define BLINKER_SERVER_HOST "iot.diandeng.tech" + +#include + +char type[] = "Your Device Type"; +char auth[] = "Your Device Secret Key"; + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +/* + * Add your command parse code in this function + * + * When get a command and device not parsed this command, device will call this function + */ +bool dataParse(const JsonObject & data) +{ + String getData; + + serializeJson(data, getData); + + BLINKER_LOG("Get user command: ", getData); + + // if you parsed this data, return TRUE. + // return true; + return false; +} + +/* + * Add your heartbeat message detail in this function + * + * When get heartbeat command {"get": "state"}, device will call this function + * For example, you can print message back + * + * Every 30s will get a heartbeat command from app + */ +void heartbeat() +{ + BLINKER_LOG("heartbeat!"); +} + +#if defined(BLINKER_BUTTON) +/* + * Blinker provide a button parse function for user if you defined BLINKER_BUTTON + * + * Blinker button can detect singal click/ double click/ long press + * + * Blinker.tick() will run by default, use interrupt will be better + */ +ICACHE_RAM_ATTR void buttonTick() +{ + Blinker.tick(); +} + +/* + * Add your code in this function + * + * When button clicked, device will call this function + */ +void singleClick() +{ + BLINKER_LOG("Button clicked!"); +} + +/* + * Add your code in this function + * + * When button double clicked, device will call this function + */ +void doubleClick() +{ + BLINKER_LOG("Button double clicked!"); +} +#endif + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + counter++; + Number1.print(counter); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, type); + Blinker.attachData(dataRead); + Blinker.attachParse(dataParse); + Blinker.attachHeartbeat(heartbeat); + Button1.attach(button1_callback); + +#if defined(BLINKER_BUTTON) + Blinker.attachClick(singleClick); + Blinker.attachDoubleClick(doubleClick); + attachInterrupt(BLINKER_BUTTON_PIN, buttonTick, CHANGE); +#endif +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_ESP/.pydio b/blinker-library/examples/Blinker_PRO/Blinker_PRO_ESP/.pydio new file mode 100644 index 0000000..9ea6c5d --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_ESP/.pydio @@ -0,0 +1 @@ +2a3c9f01-f4ac-4d9d-82e8-0daa3210ddd3 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_ESP/Blinker_PRO_ESP.ino b/blinker-library/examples/Blinker_PRO/Blinker_PRO_ESP/Blinker_PRO_ESP.ino new file mode 100644 index 0000000..cec57fc --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_ESP/Blinker_PRO_ESP.ino @@ -0,0 +1,170 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_PRO_ESP +#define BLINKER_BUTTON +#if defined(ESP32) + #define BLINKER_BUTTON_PIN 4 +#else + #define BLINKER_BUTTON_PIN D7 +#endif + +#define BLINKER_OTA_VERSION_CODE "0.1.1" + +#include + +char type[] = "Your Device Type"; +char auth[] = "Your Device Secret Key"; + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +/* + * Add your command parse code in this function + * + * When get a command and device not parsed this command, device will call this function + */ +bool dataParse(const JsonObject & data) +{ + String getData; + + serializeJson(data, getData); + + BLINKER_LOG("Get user command: ", getData); + + // if you parsed this data, return TRUE. + // return true; + return false; +} + +/* + * Add your heartbeat message detail in this function + * + * When get heartbeat command {"get": "state"}, device will call this function + * For example, you can print message back + * + * Every 30s will get a heartbeat command from app + */ +void heartbeat() +{ + BLINKER_LOG("heartbeat!"); +} + +#if defined(BLINKER_BUTTON) +/* + * Blinker provide a button parse function for user if you defined BLINKER_BUTTON + * + * Blinker button can detect singal click/ double click/ long press + * + * Blinker.tick() will run by default, use interrupt will be better + */ +ICACHE_RAM_ATTR void buttonTick() +{ + Blinker.tick(); +} + +/* + * Add your code in this function + * + * When button clicked, device will call this function + */ +void singleClick() +{ + BLINKER_LOG("Button clicked!"); +} + +/* + * Add your code in this function + * + * When button double clicked, device will call this function + */ +void doubleClick() +{ + BLINKER_LOG("Button double clicked!"); +} +#endif + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + counter++; + Number1.print(counter); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, type); + Blinker.attachData(dataRead); + Blinker.attachParse(dataParse); + Blinker.attachHeartbeat(heartbeat); + Button1.attach(button1_callback); + +#if defined(BLINKER_BUTTON) + Blinker.attachClick(singleClick); + Blinker.attachDoubleClick(doubleClick); + attachInterrupt(BLINKER_BUTTON_PIN, buttonTick, CHANGE); +#endif +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_ESP_APCONFIG/.pydio b/blinker-library/examples/Blinker_PRO/Blinker_PRO_ESP_APCONFIG/.pydio new file mode 100644 index 0000000..6a28066 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_ESP_APCONFIG/.pydio @@ -0,0 +1 @@ +65108938-a1a1-4f8c-b2ea-347220a70890 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_ESP_APCONFIG/Blinker_PRO_ESP_APCONFIG.ino b/blinker-library/examples/Blinker_PRO/Blinker_PRO_ESP_APCONFIG/Blinker_PRO_ESP_APCONFIG.ino new file mode 100644 index 0000000..cd9d58f --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_ESP_APCONFIG/Blinker_PRO_ESP_APCONFIG.ino @@ -0,0 +1,182 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +/* + * BLINKER_PRO is use for professional device + * + * Please make sure you have permission to modify professional device! + * Please read usermanual first! Thanks! + * https://diandeng.tech/doc + * + * Written by i3water for blinker. + * Learn more:https://blinker.app/ + */ + +#define BLINKER_PRO_ESP +#define BLINKER_BUTTON +#if defined(ESP32) + #define BLINKER_BUTTON_PIN 4 +#else + #define BLINKER_BUTTON_PIN D7 +#endif + +#define BLINKER_OTA_VERSION_CODE "0.1.1" + +#include + +char type[] = "Your Device Type"; +char auth[] = "Your Device Secret Key"; + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +/* + * Add your command parse code in this function + * + * When get a command and device not parsed this command, device will call this function + */ +bool dataParse(const JsonObject & data) +{ + String getData; + + serializeJson(data, getData); + + BLINKER_LOG("Get user command: ", getData); + + // if you parsed this data, return TRUE. + // return true; + return false; +} + +/* + * Add your heartbeat message detail in this function + * + * When get heartbeat command {"get": "state"}, device will call this function + * For example, you can print message back + * + * Every 30s will get a heartbeat command from app + */ +void heartbeat() +{ + BLINKER_LOG("heartbeat!"); +} + +#if defined(BLINKER_BUTTON) +/* + * Blinker provide a button parse function for user if you defined BLINKER_BUTTON + * + * Blinker button can detect singal click/ double click/ long press + * + * Blinker.tick() will run by default, use interrupt will be better + */ +ICACHE_RAM_ATTR void buttonTick() +{ + Blinker.tick(); +} + +/* + * Add your code in this function + * + * When button clicked, device will call this function + */ +void singleClick() +{ + BLINKER_LOG("Button clicked!"); +} + +/* + * Add your code in this function + * + * When button double clicked, device will call this function + */ +void doubleClick() +{ + BLINKER_LOG("Button double clicked!"); +} +#endif + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + counter++; + Number1.print(counter); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, type); + Blinker.apConfigInit(); + Blinker.attachData(dataRead); + Blinker.attachParse(dataParse); + Blinker.attachHeartbeat(heartbeat); + Button1.attach(button1_callback); + +#if defined(BLINKER_BUTTON) + Blinker.attachClick(singleClick); + Blinker.attachDoubleClick(doubleClick); + attachInterrupt(BLINKER_BUTTON_PIN, buttonTick, CHANGE); +#endif +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/.pydio b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/.pydio new file mode 100644 index 0000000..65a53a5 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/.pydio @@ -0,0 +1 @@ +2d7ca55d-a1e0-4482-976a-f0a264dc80e6 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Error/.pydio b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Error/.pydio new file mode 100644 index 0000000..e7959c5 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Error/.pydio @@ -0,0 +1 @@ +aa7dbde7-4224-4429-8056-55a4db17f013 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Error/Event_Error.ino b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Error/Event_Error.ino new file mode 100644 index 0000000..a0edf67 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Error/Event_Error.ino @@ -0,0 +1,181 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +/* + * BLINKER_PRO is use for professional device + * + * Please make sure you have permission to modify professional device! + * Please read usermanual first! Thanks! + * https://diandeng.tech/doc + * + * Written by i3water for blinker. + * Learn more:https://blinker.app/ + */ + +#define BLINKER_PRO_ESP +#define BLINKER_BUTTON +#if defined(ESP32) + #define BLINKER_BUTTON_PIN 4 +#else + #define BLINKER_BUTTON_PIN D7 +#endif + +#include + +char type[] = "Your Device Type"; +char auth[] = "Your Device Secret Key"; + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +/* + * Add your command parse code in this function + * + * When get a command and device not parsed this command, device will call this function + */ +bool dataParse(const JsonObject & data) +{ + String getData; + + serializeJson(data, getData); + + BLINKER_LOG("Get user command: ", getData); + + // if you parsed this data, return TRUE. + // return true; + return false; +} + +/* + * Add your heartbeat message detail in this function + * + * When get heartbeat command {"get": "state"}, device will call this function + * For example, you can print message back + * + * Every 30s will get a heartbeat command from app + */ +void heartbeat() +{ + BLINKER_LOG("heartbeat!"); +} + +#if defined(BLINKER_BUTTON) +/* + * Blinker provide a button parse function for user if you defined BLINKER_BUTTON + * + * Blinker button can detect singal click/ double click/ long press + * + * Blinker.tick() will run by default, use interrupt will be better + */ +ICACHE_RAM_ATTR void buttonTick() +{ + Blinker.tick(); +} + +/* + * Add your code in this function + * + * When button clicked, device will call this function + */ +void singleClick() +{ + BLINKER_LOG("Button clicked!"); +} + +/* + * Add your code in this function + * + * When button double clicked, device will call this function + */ +void doubleClick() +{ + BLINKER_LOG("Button double clicked!"); +} +#endif + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + counter++; + Number1.print(counter); + + BlinkerEvent.warning("button click!"); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, type); + Blinker.attachData(dataRead); + Blinker.attachParse(dataParse); + Blinker.attachHeartbeat(heartbeat); + Button1.attach(button1_callback); + +#if defined(BLINKER_BUTTON) + Blinker.attachClick(singleClick); + Blinker.attachDoubleClick(doubleClick); + attachInterrupt(BLINKER_BUTTON_PIN, buttonTick, CHANGE); +#endif +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Message/.pydio b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Message/.pydio new file mode 100644 index 0000000..a13ad86 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Message/.pydio @@ -0,0 +1 @@ +25c1101c-e164-4fd7-93f7-46691f20f843 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Message/Event_Message.ino b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Message/Event_Message.ino new file mode 100644 index 0000000..c31f5ea --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Message/Event_Message.ino @@ -0,0 +1,181 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +/* + * BLINKER_PRO is use for professional device + * + * Please make sure you have permission to modify professional device! + * Please read usermanual first! Thanks! + * https://diandeng.tech/doc + * + * Written by i3water for blinker. + * Learn more:https://blinker.app/ + */ + +#define BLINKER_PRO_ESP +#define BLINKER_BUTTON +#if defined(ESP32) + #define BLINKER_BUTTON_PIN 4 +#else + #define BLINKER_BUTTON_PIN D7 +#endif + +#include + +char type[] = "Your Device Type"; +char auth[] = "Your Device Secret Key"; + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +/* + * Add your command parse code in this function + * + * When get a command and device not parsed this command, device will call this function + */ +bool dataParse(const JsonObject & data) +{ + String getData; + + serializeJson(data, getData); + + BLINKER_LOG("Get user command: ", getData); + + // if you parsed this data, return TRUE. + // return true; + return false; +} + +/* + * Add your heartbeat message detail in this function + * + * When get heartbeat command {"get": "state"}, device will call this function + * For example, you can print message back + * + * Every 30s will get a heartbeat command from app + */ +void heartbeat() +{ + BLINKER_LOG("heartbeat!"); +} + +#if defined(BLINKER_BUTTON) +/* + * Blinker provide a button parse function for user if you defined BLINKER_BUTTON + * + * Blinker button can detect singal click/ double click/ long press + * + * Blinker.tick() will run by default, use interrupt will be better + */ +ICACHE_RAM_ATTR void buttonTick() +{ + Blinker.tick(); +} + +/* + * Add your code in this function + * + * When button clicked, device will call this function + */ +void singleClick() +{ + BLINKER_LOG("Button clicked!"); +} + +/* + * Add your code in this function + * + * When button double clicked, device will call this function + */ +void doubleClick() +{ + BLINKER_LOG("Button double clicked!"); +} +#endif + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + counter++; + Number1.print(counter); + + BlinkerEvent.message("button click!"); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, type); + Blinker.attachData(dataRead); + Blinker.attachParse(dataParse); + Blinker.attachHeartbeat(heartbeat); + Button1.attach(button1_callback); + +#if defined(BLINKER_BUTTON) + Blinker.attachClick(singleClick); + Blinker.attachDoubleClick(doubleClick); + attachInterrupt(BLINKER_BUTTON_PIN, buttonTick, CHANGE); +#endif +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Warning/.pydio b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Warning/.pydio new file mode 100644 index 0000000..7a53f7f --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Warning/.pydio @@ -0,0 +1 @@ +3dfce2de-e679-404d-9843-bcd4d6d62040 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Warning/Event_Warning.ino b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Warning/Event_Warning.ino new file mode 100644 index 0000000..a0edf67 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Event/Event_Warning/Event_Warning.ino @@ -0,0 +1,181 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +/* + * BLINKER_PRO is use for professional device + * + * Please make sure you have permission to modify professional device! + * Please read usermanual first! Thanks! + * https://diandeng.tech/doc + * + * Written by i3water for blinker. + * Learn more:https://blinker.app/ + */ + +#define BLINKER_PRO_ESP +#define BLINKER_BUTTON +#if defined(ESP32) + #define BLINKER_BUTTON_PIN 4 +#else + #define BLINKER_BUTTON_PIN D7 +#endif + +#include + +char type[] = "Your Device Type"; +char auth[] = "Your Device Secret Key"; + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +/* + * Add your command parse code in this function + * + * When get a command and device not parsed this command, device will call this function + */ +bool dataParse(const JsonObject & data) +{ + String getData; + + serializeJson(data, getData); + + BLINKER_LOG("Get user command: ", getData); + + // if you parsed this data, return TRUE. + // return true; + return false; +} + +/* + * Add your heartbeat message detail in this function + * + * When get heartbeat command {"get": "state"}, device will call this function + * For example, you can print message back + * + * Every 30s will get a heartbeat command from app + */ +void heartbeat() +{ + BLINKER_LOG("heartbeat!"); +} + +#if defined(BLINKER_BUTTON) +/* + * Blinker provide a button parse function for user if you defined BLINKER_BUTTON + * + * Blinker button can detect singal click/ double click/ long press + * + * Blinker.tick() will run by default, use interrupt will be better + */ +ICACHE_RAM_ATTR void buttonTick() +{ + Blinker.tick(); +} + +/* + * Add your code in this function + * + * When button clicked, device will call this function + */ +void singleClick() +{ + BLINKER_LOG("Button clicked!"); +} + +/* + * Add your code in this function + * + * When button double clicked, device will call this function + */ +void doubleClick() +{ + BLINKER_LOG("Button double clicked!"); +} +#endif + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + counter++; + Number1.print(counter); + + BlinkerEvent.warning("button click!"); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, type); + Blinker.attachData(dataRead); + Blinker.attachParse(dataParse); + Blinker.attachHeartbeat(heartbeat); + Button1.attach(button1_callback); + +#if defined(BLINKER_BUTTON) + Blinker.attachClick(singleClick); + Blinker.attachDoubleClick(doubleClick); + attachInterrupt(BLINKER_BUTTON_PIN, buttonTick, CHANGE); +#endif +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_OTA/.pydio b/blinker-library/examples/Blinker_PRO/Blinker_PRO_OTA/.pydio new file mode 100644 index 0000000..fe806b5 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_OTA/.pydio @@ -0,0 +1 @@ +640c8e68-17e4-4cca-84c8-8440336f5a31 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_OTA/OTA_PRO/.pydio b/blinker-library/examples/Blinker_PRO/Blinker_PRO_OTA/OTA_PRO/.pydio new file mode 100644 index 0000000..d0aa574 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_OTA/OTA_PRO/.pydio @@ -0,0 +1 @@ +18c5bb91-c842-49e7-b323-6fde537b99cd \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_OTA/OTA_PRO/OTA_PRO.ino b/blinker-library/examples/Blinker_PRO/Blinker_PRO_OTA/OTA_PRO/OTA_PRO.ino new file mode 100644 index 0000000..df2350e --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_OTA/OTA_PRO/OTA_PRO.ino @@ -0,0 +1,184 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_PRO_ESP +#define BLINKER_BUTTON +#if defined(ESP32) + #define BLINKER_BUTTON_PIN 4 +#else + #define BLINKER_BUTTON_PIN D7 +#endif + +#define BLINKER_OTA_VERSION_CODE "0.1.1" + +#include + +char type[] = "Your Device Type"; +char auth[] = "Your Device Secret Key"; + +#define BLINKER_OTA_BLINK_TIME 500 + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +uint32_t os_time; +int counter = 0; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +/* + * Add your command parse code in this function + * + * When get a command and device not parsed this command, device will call this function + */ +bool dataParse(const JsonObject & data) +{ + String getData; + + serializeJson(data, getData); + + BLINKER_LOG("Get user command: ", getData); + + // if you parsed this data, return TRUE. + // return true; + return false; +} + +/* + * Add your heartbeat message detail in this function + * + * When get heartbeat command {"get": "state"}, device will call this function + * For example, you can print message back + * + * Every 30s will get a heartbeat command from app + */ +void heartbeat() +{ + BLINKER_LOG("heartbeat!"); +} + +#if defined(BLINKER_BUTTON) +/* + * Blinker provide a button parse function for user if you defined BLINKER_BUTTON + * + * Blinker button can detect singal click/ double click/ long press + * + * Blinker.tick() will run by default, use interrupt will be better + */ +ICACHE_RAM_ATTR void buttonTick() +{ + Blinker.tick(); +} + +/* + * Add your code in this function + * + * When button clicked, device will call this function + */ +void singleClick() +{ + BLINKER_LOG("Button clicked!"); +} + +/* + * Add your code in this function + * + * When button double clicked, device will call this function + */ +void doubleClick() +{ + BLINKER_LOG("Button double clicked!"); +} +#endif + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + counter++; + Number1.print(counter); +} + +// void otaStatus(uint32_t load_size, uint32_t total_size) +// { +// if (millis() - os_time >= BLINKER_OTA_BLINK_TIME) +// { +// os_time = millis(); + +// digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +// } +// } + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, type); + Blinker.attachData(dataRead); + Blinker.attachParse(dataParse); + Blinker.attachHeartbeat(heartbeat); + Button1.attach(button1_callback); + +#if defined(BLINKER_BUTTON) + Blinker.attachClick(singleClick); + Blinker.attachDoubleClick(doubleClick); + attachInterrupt(BLINKER_BUTTON_PIN, buttonTick, CHANGE); +#endif + // BlinkerUpdater.onProgress(otaStatus); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_SIM7020/.pydio b/blinker-library/examples/Blinker_PRO/Blinker_PRO_SIM7020/.pydio new file mode 100644 index 0000000..2faa931 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_SIM7020/.pydio @@ -0,0 +1 @@ +072d0936-ad7e-45a2-ab83-8f8d59a88c2c \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_SIM7020/Blinker_PRO_SIM7020.ino b/blinker-library/examples/Blinker_PRO/Blinker_PRO_SIM7020/Blinker_PRO_SIM7020.ino new file mode 100644 index 0000000..60677a4 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_SIM7020/Blinker_PRO_SIM7020.ino @@ -0,0 +1,163 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +/* + * BLINKER_PRO is use for professional device + * + * Please make sure you have permission to modify professional device! + * Please read usermanual first! Thanks! + * https://diandeng.tech/doc + * + * Written by i3water for blinker. + * Learn more:https://blinker.app/ + */ + +#define BLINKER_PRO_SIM7020 +// #define BLINKER_BUTTON +// #define BLINKER_BUTTON_PIN D7 + +#define BLINKER_OTA_VERSION_CODE "0.1.1" + +#include + +/* + * Add your command parse code in this function + * + * When get a command and device not parsed this command, device will call this function + */ +bool dataParse(const JsonObject & data) +{ + String getData; + + serializeJson(data, getData); + + BLINKER_LOG("Get user command: ", getData); + return true; +} + +/* + * Add your heartbeat message detail in this function + * + * When get heartbeat command {"get": "state"}, device will call this function + * For example, you can print message back + * + * Every 30s will get a heartbeat command from app + */ +void heartbeat() +{ + // Blinker.print("hello", "blinker"); + BLINKER_LOG("heartbeat!"); +} + +#if defined(BLINKER_BUTTON) +/* + * Blinker provide a button parse function for user if you defined BLINKER_BUTTON + * + * Blinker button can detect singal click/ double click/ long press + * + * Blinker.tick() will run by default, use interrupt will be better + */ +ICACHE_RAM_ATTR void buttonTick() +{ + Blinker.tick(); +} + +/* + * Add your code in this function + * + * When button clicked, device will call this function + */ +void singleClick() +{ + BLINKER_LOG("Button clicked!"); +} + +/* + * Add your code in this function + * + * When button double clicked, device will call this function + */ +void doubleClick() +{ + BLINKER_LOG("Button double clicked!"); +} +#endif + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + Blinker.print(BlinkerTime); + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + Blinker.attachData(dataRead); + Blinker.attachParse(dataParse); + Blinker.attachHeartbeat(heartbeat); + +#if defined(BLINKER_BUTTON) + Blinker.attachClick(singleClick); + Blinker.attachDoubleClick(doubleClick); + attachInterrupt(BLINKER_BUTTON_PIN, buttonTick, CHANGE); +#endif +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_Wlan_Config/.pydio b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Wlan_Config/.pydio new file mode 100644 index 0000000..dc164e5 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Wlan_Config/.pydio @@ -0,0 +1 @@ +362b3899-6d40-4d91-9147-1525e76adf96 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO/Blinker_PRO_Wlan_Config/Blinker_PRO_Wlan_Config.ino b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Wlan_Config/Blinker_PRO_Wlan_Config.ino new file mode 100644 index 0000000..2197b40 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO/Blinker_PRO_Wlan_Config/Blinker_PRO_Wlan_Config.ino @@ -0,0 +1,211 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +/* + * BLINKER_PRO is use for professional device + * + * Please make sure you have permission to modify professional device! + * Please read usermanual first! Thanks! + * https://diandeng.tech/doc + * + * Written by i3water for blinker. + * Learn more:https://blinker.app/ + */ + +#define BLINKER_PRO_ESP +#define BLINKER_BUTTON +#define BLINKER_BUTTON_LONGPRESS_POWERDOWN +#if defined(ESP32) + #define BLINKER_BUTTON_PIN 4 +#else + #define BLINKER_BUTTON_PIN D7 +#endif + +#define BLINKER_OTA_VERSION_CODE "0.1.1" + +#include + +char type[] = "Your Device Type"; +char auth[] = "Your Device Secret Key"; + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +/* + * Add your command parse code in this function + * + * When get a command and device not parsed this command, device will call this function + */ +bool dataParse(const JsonObject & data) +{ + String getData; + + serializeJson(data, getData); + + BLINKER_LOG("Get user command: ", getData); + + // if you parsed this data, return TRUE. + // return true; + return false; +} + +/* + * Add your heartbeat message detail in this function + * + * When get heartbeat command {"get": "state"}, device will call this function + * For example, you can print message back + * + * Every 30s will get a heartbeat command from app + */ +void heartbeat() +{ + BLINKER_LOG("heartbeat!"); +} + +#if defined(BLINKER_BUTTON) +/* + * Blinker provide a button parse function for user if you defined BLINKER_BUTTON + * + * Blinker button can detect singal click/ double click/ long press + * + * Blinker.tick() will run by default, use interrupt will be better + */ +ICACHE_RAM_ATTR void buttonTick() +{ + Blinker.tick(); +} + +/* + * Add your code in this function + * + * When button clicked, device will call this function + */ +void singleClick() +{ + BLINKER_LOG("Button clicked!"); +} + +/* + * Add your code in this function + * + * When button double clicked, device will call this function + */ +void doubleClick() +{ + BLINKER_LOG("Button double clicked!"); +} + +/* + * Add your code in this function + * + * When long press start, device will call this function + */ +void longPressStart() +{ + BLINKER_LOG("Button long press start!"); +} + +/* + * Add your code in this function + * + * When during long press, device will call this function + */ +void duringLongPress() +{ + // BLINKER_LOG("During button long press!"); + + uint16_t pressed_time = Blinker.pressedTime(); + + if (pressed_time >= 5000 && Blinker.configType() != BLINKER_AP_CONFIG) + { + Blinker.esptouchInit(); + } +} +#endif + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + counter++; + Number1.print(counter); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, type); + Blinker.attachData(dataRead); + Blinker.attachParse(dataParse); + Blinker.attachHeartbeat(heartbeat); + Button1.attach(button1_callback); + +#if defined(BLINKER_BUTTON) + Blinker.attachClick(singleClick); + Blinker.attachDoubleClick(doubleClick); + Blinker.attachLongPressStart(longPressStart); + Blinker.attachDuringLongPress(duringLongPress); + attachInterrupt(BLINKER_BUTTON_PIN, buttonTick, CHANGE); +#endif +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO_Device/.pydio b/blinker-library/examples/Blinker_PRO_Device/.pydio new file mode 100644 index 0000000..2f7ab1a --- /dev/null +++ b/blinker-library/examples/Blinker_PRO_Device/.pydio @@ -0,0 +1 @@ +a6e4b4fc-4683-4945-a1ab-942dda7e9ad0 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO_Device/Blinker_PRO_Plug/.pydio b/blinker-library/examples/Blinker_PRO_Device/Blinker_PRO_Plug/.pydio new file mode 100644 index 0000000..e0541b8 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO_Device/Blinker_PRO_Plug/.pydio @@ -0,0 +1 @@ +b791ff96-f4ec-47cd-874e-38d286635607 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_PRO_Device/Blinker_PRO_Plug/Blinker_PRO_Plug.ino b/blinker-library/examples/Blinker_PRO_Device/Blinker_PRO_Plug/Blinker_PRO_Plug.ino new file mode 100644 index 0000000..08ce957 --- /dev/null +++ b/blinker-library/examples/Blinker_PRO_Device/Blinker_PRO_Plug/Blinker_PRO_Plug.ino @@ -0,0 +1,209 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +/* + * BLINKER_PRO is use for professional device + * + * Please make sure you have permission to modify professional device! + * Please read usermanual first! Thanks! + * https://diandeng.tech/doc + * + * Written by i3water for blinker. + * Learn more:https://blinker.app/ + */ + +#define BLINKER_PRO_ESP +#define BLINKER_BUTTON +#if defined(ESP32) + #define BLINKER_BUTTON_PIN 4 +#else + #define BLINKER_BUTTON_PIN D7 +#endif + +#define BLINKER_OTA_VERSION_CODE "0.1.1" + +#include + +char type[] = "Your Device Type"; +char auth[] = "Your Device Secret Key"; + +#define powerKey "power" + +bool sw_state = false; + +float power_read() +{ + return sw_state ? random(0, 10)/2.0 : 0.0; +} + +void switch_callback(const String & state) +{ + BLINKER_LOG("get switch state: ", state); + + if (state == BLINKER_CMD_ON) { + sw_state = true; + digitalWrite(LED_BUILTIN, HIGH); + BUILTIN_SWITCH.print("on"); + Blinker.print(powerKey, power_read()); + } + else { + sw_state = false; + digitalWrite(LED_BUILTIN, LOW); + BUILTIN_SWITCH.print("off"); + Blinker.print(powerKey, power_read()); + } +} + +/* + * Add your command parse code in this function + * + * When get a command and device not parsed this command, device will call this function + */ +bool dataParse(const JsonObject & data) +{ + String getData; + + serializeJson(data, getData); + + BLINKER_LOG("Get user command: ", getData); + + // if you parsed this data, return TRUE. + // return true; + return false; +} + +/* + * Add your heartbeat message detail in this function + * + * When get heartbeat command {"get": "state"}, device will call this function + * For example, you can print message back + * + * Every 30s will get a heartbeat command from app + */ +void heartbeat() +{ + BUILTIN_SWITCH.print(sw_state ? "on" : "off"); + Blinker.print(powerKey, power_read()); + + BLINKER_LOG("heartbeat!"); +} + +#if defined(BLINKER_BUTTON) +/* + * Blinker provide a button parse function for user if you defined BLINKER_BUTTON + * + * Blinker button can detect singal click/ double click/ long press + * + * Blinker.tick() will run by default, use interrupt will be better + */ +ICACHE_RAM_ATTR void buttonTick() +{ + Blinker.tick(); +} + +/* + * Add your code in this function + * + * When button clicked, device will call this function + */ +void singleClick() +{ + BLINKER_LOG("Button clicked!"); +} + +/* + * Add your code in this function + * + * When button double clicked, device will call this function + */ +void doubleClick() +{ + BLINKER_LOG("Button double clicked!"); +} +#endif + +void dataStorage() +{ + Blinker.dataStorage("power", power_read()); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, type); + Blinker.attachData(dataRead); + Blinker.attachParse(dataParse); + Blinker.attachHeartbeat(heartbeat); + +#if defined(BLINKER_BUTTON) + Blinker.attachClick(singleClick); + Blinker.attachDoubleClick(doubleClick); + attachInterrupt(BLINKER_BUTTON_PIN, buttonTick, CHANGE); +#endif + + BUILTIN_SWITCH.attach(switch_callback); + Blinker.attachDataStorage(dataStorage); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Sensor/.pydio b/blinker-library/examples/Blinker_Sensor/.pydio new file mode 100644 index 0000000..5230458 --- /dev/null +++ b/blinker-library/examples/Blinker_Sensor/.pydio @@ -0,0 +1 @@ +d5733326-3a68-42d6-b463-8caa2265d107 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Sensor/Blinker_BMP180/.pydio b/blinker-library/examples/Blinker_Sensor/Blinker_BMP180/.pydio new file mode 100644 index 0000000..fd1feaf --- /dev/null +++ b/blinker-library/examples/Blinker_Sensor/Blinker_BMP180/.pydio @@ -0,0 +1 @@ +5db05e13-7a56-4f18-ab66-8fefe7996c20 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Sensor/Blinker_BMP180/BMP180_WiFi/.pydio b/blinker-library/examples/Blinker_Sensor/Blinker_BMP180/BMP180_WiFi/.pydio new file mode 100644 index 0000000..7b99f77 --- /dev/null +++ b/blinker-library/examples/Blinker_Sensor/Blinker_BMP180/BMP180_WiFi/.pydio @@ -0,0 +1 @@ +45cd5624-b5ab-4d99-94c1-5bbbca074e7d \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Sensor/Blinker_BMP180/BMP180_WiFi/BMP180_WiFi.ino b/blinker-library/examples/Blinker_Sensor/Blinker_BMP180/BMP180_WiFi/BMP180_WiFi.ino new file mode 100644 index 0000000..d330c4a --- /dev/null +++ b/blinker-library/examples/Blinker_Sensor/Blinker_BMP180/BMP180_WiFi/BMP180_WiFi.ino @@ -0,0 +1,104 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +BlinkerNumber TEMP("temp"); // Temperature +BlinkerNumber PRES("pres"); // Pressure +BlinkerNumber ALTI("alti"); // Altitude + +// Download Adafruit-BMP085-Library library here: +// https://github.com/adafruit/Adafruit-BMP085-Library +#include +#include + +Adafruit_BMP085 bmp; + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void heartbeat() +{ + TEMP.print(bmp.readTemperature()); + PRES.print(bmp.readPressure()); + ALTI.print(bmp.readAltitude()); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + Blinker.attachHeartbeat(heartbeat); + + if (!bmp.begin()) { + BLINKER_LOG("Could not find a valid BMP085 sensor, check wiring!"); + while (1) {delay(100);} + } +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Sensor/Blinker_DHT/.pydio b/blinker-library/examples/Blinker_Sensor/Blinker_DHT/.pydio new file mode 100644 index 0000000..f905ec8 --- /dev/null +++ b/blinker-library/examples/Blinker_Sensor/Blinker_DHT/.pydio @@ -0,0 +1 @@ +84c5a792-06d2-43d0-9de0-16fe678d7b7d \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Sensor/Blinker_DHT/DHT_BLE/.pydio b/blinker-library/examples/Blinker_Sensor/Blinker_DHT/DHT_BLE/.pydio new file mode 100644 index 0000000..56797ee --- /dev/null +++ b/blinker-library/examples/Blinker_Sensor/Blinker_DHT/DHT_BLE/.pydio @@ -0,0 +1 @@ +3f7cd58b-408e-424c-b764-d8c8596ec05c \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Sensor/Blinker_DHT/DHT_BLE/DHT_BLE.ino b/blinker-library/examples/Blinker_Sensor/Blinker_DHT/DHT_BLE/DHT_BLE.ino new file mode 100644 index 0000000..1953b92 --- /dev/null +++ b/blinker-library/examples/Blinker_Sensor/Blinker_DHT/DHT_BLE/DHT_BLE.ino @@ -0,0 +1,126 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_BLE + +#include + +BlinkerNumber HUMI("humi"); +BlinkerNumber TEMP("temp"); + +// Download Adafruit DHT-sensor-library library here: +// https://github.com/adafruit/DHT-sensor-library +#include + +#define DHTPIN 2 + +//#define DHTTYPE DHT11 // DHT 11 +#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 +//#define DHTTYPE DHT21 // DHT 21 (AM2301) + +DHT dht(DHTPIN, DHTTYPE); + +uint32_t read_time = 0; + +float humi_read, temp_read; + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void heartbeat() +{ + HUMI.print(humi_read); + TEMP.print(temp_read); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + Blinker.attachData(dataRead); + Blinker.attachHeartbeat(heartbeat); + + dht.begin(); +} + +void loop() +{ + Blinker.run(); + + if (read_time == 0 || (millis() - read_time) >= 2000) + { + read_time = millis(); + + float h = dht.readHumidity(); + float t = dht.readTemperature(); + + if (isnan(h) || isnan(t)) { + BLINKER_LOG("Failed to read from DHT sensor!"); + return; + } + + float hic = dht.computeHeatIndex(t, h, false); + + humi_read = h; + temp_read = t; + + BLINKER_LOG("Humidity: ", h, " %"); + BLINKER_LOG("Temperature: ", t, " *C"); + BLINKER_LOG("Heat index: ", hic, " *C"); + } +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Sensor/Blinker_DHT/DHT_WiFi/.pydio b/blinker-library/examples/Blinker_Sensor/Blinker_DHT/DHT_WiFi/.pydio new file mode 100644 index 0000000..d9281c8 --- /dev/null +++ b/blinker-library/examples/Blinker_Sensor/Blinker_DHT/DHT_WiFi/.pydio @@ -0,0 +1 @@ +56b6e643-3901-4ecb-bacd-622b7946f535 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Sensor/Blinker_DHT/DHT_WiFi/DHT_WiFi.ino b/blinker-library/examples/Blinker_Sensor/Blinker_DHT/DHT_WiFi/DHT_WiFi.ino new file mode 100644 index 0000000..7473a94 --- /dev/null +++ b/blinker-library/examples/Blinker_Sensor/Blinker_DHT/DHT_WiFi/DHT_WiFi.ino @@ -0,0 +1,130 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +BlinkerNumber HUMI("humi"); +BlinkerNumber TEMP("temp"); + +// Download Adafruit DHT-sensor-library library here: +// https://github.com/adafruit/DHT-sensor-library +#include + +#define DHTPIN 2 + +//#define DHTTYPE DHT11 // DHT 11 +#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 +//#define DHTTYPE DHT21 // DHT 21 (AM2301) + +DHT dht(DHTPIN, DHTTYPE); + +uint32_t read_time = 0; + +float humi_read, temp_read; + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void heartbeat() +{ + HUMI.print(humi_read); + TEMP.print(temp_read); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + Blinker.attachHeartbeat(heartbeat); + + dht.begin(); +} + +void loop() +{ + Blinker.run(); + + if (read_time == 0 || (millis() - read_time) >= 2000) + { + read_time = millis(); + + float h = dht.readHumidity(); + float t = dht.readTemperature(); + + if (isnan(h) || isnan(t)) { + BLINKER_LOG("Failed to read from DHT sensor!"); + return; + } + + float hic = dht.computeHeatIndex(t, h, false); + + humi_read = h; + temp_read = t; + + BLINKER_LOG("Humidity: ", h, " %"); + BLINKER_LOG("Temperature: ", t, " *C"); + BLINKER_LOG("Heat index: ", hic, " *C"); + } +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/.pydio new file mode 100644 index 0000000..cae60ee --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/.pydio @@ -0,0 +1 @@ +b7a78739-12a5-455a-9cb5-831065ad4777 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/.pydio new file mode 100644 index 0000000..7b47b39 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/.pydio @@ -0,0 +1 @@ +9e05126e-2393-4584-a9ad-96ca2035e968 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_AIRCONDITION/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_AIRCONDITION/.pydio new file mode 100644 index 0000000..01ee860 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_AIRCONDITION/.pydio @@ -0,0 +1 @@ +77e1d9eb-8980-428a-88fc-fa2fbdb26932 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_AIRCONDITION/AliGenie_AIRCONDITION.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_AIRCONDITION/AliGenie_AIRCONDITION.ino new file mode 100644 index 0000000..e3d4f38 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_AIRCONDITION/AliGenie_AIRCONDITION.ino @@ -0,0 +1,239 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_ALIGENIE_AIRCONDITION + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +bool oState = false; +bool hsState = false; +bool vsState = false; +String setLevel = "auto"; +uint8_t setTemp = 26; + +void aligenieTemp(uint8_t temp) +{ + BLINKER_LOG("need set temp: ", temp); + + setTemp = temp; + + BlinkerAliGenie.temp(temp); + BlinkerAliGenie.print(); +} + +void aligenieRelativeTemp(uint8_t relTemp) +{ + BLINKER_LOG("need set temp: ", relTemp); + + setTemp = setTemp + relTemp; + + BlinkerAliGenie.temp(setTemp); + BlinkerAliGenie.print(); +} + +void aligenieLevel(const String & level) +{ + BLINKER_LOG("need set level: ", level); + // auto 自动风 + // low 低风 + // medium 中风 + // high 高风 + + setLevel = level; + + BlinkerAliGenie.level(level); + BlinkerAliGenie.print(); +} + +void aligenieHSwingState(const String & state) +{ + BLINKER_LOG("need set HSwing state: ", state); + // horizontal-swing + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerAliGenie.hswing("on"); + BlinkerAliGenie.print(); + + hsState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerAliGenie.hswing("off"); + BlinkerAliGenie.print(); + + hsState = false; + } +} + +void aligenieVSwingState(const String & state) +{ + BLINKER_LOG("need set VSwing state: ", state); + // vertical-swing + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerAliGenie.vswing("on"); + BlinkerAliGenie.print(); + + vsState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerAliGenie.vswing("off"); + BlinkerAliGenie.print(); + + vsState = false; + } +} + +void aligenieMode(const String & mode) +{ + BLINKER_LOG("need set mode: ", mode); + + BlinkerAliGenie.mode(mode); + BlinkerAliGenie.print(); +} + +void aligeniePowerState(const String & state) +{ + BLINKER_LOG("need set power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerAliGenie.powerState("on"); + BlinkerAliGenie.print(); + + oState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerAliGenie.powerState("off"); + BlinkerAliGenie.print(); + + oState = false; + } +} + +void aligenieQuery(int32_t queryCode) +{ + BLINKER_LOG("AliGenie Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_ALL_NUMBER : + BLINKER_LOG("AliGenie Query All"); + BlinkerAliGenie.powerState(oState ? "on" : "off"); + BlinkerAliGenie.hswing(hsState ? "on" : "off"); + BlinkerAliGenie.vswing(vsState ? "on" : "off"); + BlinkerAliGenie.level(setLevel); + BlinkerAliGenie.mode("quietWind"); + BlinkerAliGenie.temp(setTemp); + BlinkerAliGenie.print(); + break; + case BLINKER_CMD_QUERY_POWERSTATE_NUMBER : + BLINKER_LOG("AliGenie Query Power State"); + BlinkerAliGenie.powerState(oState ? "on" : "off"); + BlinkerAliGenie.print(); + break; + default : + BlinkerAliGenie.powerState(oState ? "on" : "off"); + BlinkerAliGenie.hswing(hsState ? "on" : "off"); + BlinkerAliGenie.vswing(vsState ? "on" : "off"); + BlinkerAliGenie.level(setLevel); + BlinkerAliGenie.mode("quietWind"); + BlinkerAliGenie.temp(setTemp); + BlinkerAliGenie.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerAliGenie.attachPowerState(aligeniePowerState); + BlinkerAliGenie.attachHSwing(aligenieHSwingState); + BlinkerAliGenie.attachVSwing(aligenieVSwingState); + BlinkerAliGenie.attachLevel(aligenieLevel); + BlinkerAliGenie.attachMode(aligenieMode); + BlinkerAliGenie.attachTemp(aligenieTemp); + BlinkerAliGenie.attachRelativeTemp(aligenieRelativeTemp); + BlinkerAliGenie.attachQuery(aligenieQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_FAN/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_FAN/.pydio new file mode 100644 index 0000000..1ea55b8 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_FAN/.pydio @@ -0,0 +1 @@ +2113466f-7660-4654-a01f-7bc0a7ebabe0 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_FAN/AliGenie_FAN.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_FAN/AliGenie_FAN.ino new file mode 100644 index 0000000..13ce913 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_FAN/AliGenie_FAN.ino @@ -0,0 +1,211 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_ALIGENIE_FAN + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +bool oState = false; +bool hsState = false; +bool vsState = false; +uint8_t setLevel; + +void aligenieLevel(uint8_t level) +{ + BLINKER_LOG("need set level: ", level); + // 0:AUTO MODE, 1-3 LEVEL + + setLevel = level; + + BlinkerAliGenie.level(level); + BlinkerAliGenie.print(); +} + +void aligenieHSwingState(const String & state) +{ + BLINKER_LOG("need set HSwing state: ", state); + // horizontal-swing + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerAliGenie.hswing("on"); + BlinkerAliGenie.print(); + + hsState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerAliGenie.hswing("off"); + BlinkerAliGenie.print(); + + hsState = false; + } +} + +void aligenieVSwingState(const String & state) +{ + BLINKER_LOG("need set VSwing state: ", state); + // vertical-swing + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerAliGenie.vswing("on"); + BlinkerAliGenie.print(); + + vsState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerAliGenie.vswing("off"); + BlinkerAliGenie.print(); + + vsState = false; + } +} + +void aligenieMode(const String & mode) +{ + BLINKER_LOG("need set mode: ", mode); + + BlinkerAliGenie.mode(mode); + BlinkerAliGenie.print(); +} + +void aligeniePowerState(const String & state) +{ + BLINKER_LOG("need set power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerAliGenie.powerState("on"); + BlinkerAliGenie.print(); + + oState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerAliGenie.powerState("off"); + BlinkerAliGenie.print(); + + oState = false; + } +} + +void aligenieQuery(int32_t queryCode) +{ + BLINKER_LOG("AliGenie Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_ALL_NUMBER : + BLINKER_LOG("AliGenie Query All"); + BlinkerAliGenie.powerState(oState ? "on" : "off"); + BlinkerAliGenie.hswing(hsState ? "on" : "off"); + BlinkerAliGenie.vswing(vsState ? "on" : "off"); + BlinkerAliGenie.level(setLevel); + BlinkerAliGenie.mode("quietWind"); + BlinkerAliGenie.print(); + break; + case BLINKER_CMD_QUERY_POWERSTATE_NUMBER : + BLINKER_LOG("AliGenie Query Power State"); + BlinkerAliGenie.powerState(oState ? "on" : "off"); + BlinkerAliGenie.print(); + break; + default : + BlinkerAliGenie.powerState(oState ? "on" : "off"); + BlinkerAliGenie.hswing(hsState ? "on" : "off"); + BlinkerAliGenie.vswing(vsState ? "on" : "off"); + BlinkerAliGenie.level(setLevel); + BlinkerAliGenie.mode("quietWind"); + BlinkerAliGenie.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerAliGenie.attachPowerState(aligeniePowerState); + BlinkerAliGenie.attachHSwing(aligenieHSwingState); + BlinkerAliGenie.attachVSwing(aligenieVSwingState); + BlinkerAliGenie.attachLevel(aligenieLevel); + BlinkerAliGenie.attachMode(aligenieMode); + BlinkerAliGenie.attachQuery(aligenieQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_LIGHT/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_LIGHT/.pydio new file mode 100644 index 0000000..fe876ce --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_LIGHT/.pydio @@ -0,0 +1 @@ +f831f50d-1197-45d5-8250-e202e65be74e \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_LIGHT/AliGenie_LIGHT.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_LIGHT/AliGenie_LIGHT.ino new file mode 100644 index 0000000..bd5f1e4 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_LIGHT/AliGenie_LIGHT.ino @@ -0,0 +1,439 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_ALIGENIE_LIGHT + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +// Download Adafruit_NeoPixel library here: +// https://github.com/adafruit/Adafruit_NeoPixel +#include + +#define PIN 13 +#define NUMPIXELS 24 +Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); + +#define RGB_1 "RGBKey" + +BlinkerRGB WS2812(RGB_1); + +uint8_t colorR, colorG, colorB, colorW; +bool wsState; +String wsMode = BLINKER_CMD_COMMON; + +void pixelShow() +{ + pixels.setBrightness(colorW); + + for(int i = 0; i < NUMPIXELS; i++){ + pixels.setPixelColor(i, colorR, colorG, colorB); + } + pixels.show(); +} + +void ws2812_callback(uint8_t r_value, uint8_t g_value, uint8_t b_value, uint8_t bright_value) +{ + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + BLINKER_LOG("R value: ", r_value); + BLINKER_LOG("G value: ", g_value); + BLINKER_LOG("B value: ", b_value); + BLINKER_LOG("Rrightness value: ", bright_value); + + colorR = r_value; + colorG = g_value; + colorB = b_value; + colorW = bright_value; + + pixelShow(); +} + +String getColor() +{ + uint32_t color = colorR << 16 | colorG << 8 | colorB; + + switch (color) + { + case 0xFF0000 : + return "Red"; + case 0xFFFF00 : + return "Yellow"; + case 0x0000FF : + return "Blue"; + case 0x00FF00 : + return "Green"; + case 0xFFFFFF : + return "White"; + case 0x000000 : + return "Black"; + case 0x00FFFF : + return "Cyan"; + case 0x800080 : + return "Purple"; + case 0xFFA500 : + return "Orange"; + default : + return "White"; + } +} + +void aligeniePowerState(const String & state) +{ + BLINKER_LOG("need set power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerAliGenie.powerState("on"); + BlinkerAliGenie.print(); + + wsState = true; + + if (colorW == 0) colorW = 255; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerAliGenie.powerState("off"); + BlinkerAliGenie.print(); + + wsState = false; + + colorW == 0; + } + + pixelShow(); +} + +void aligenieColor(const String & color) +{ + BLINKER_LOG("need set color: ", color); + + if (color == "Red") { + colorR = 255; + colorG = 0; + colorB = 0; + } + else if (color == "Yellow") { + colorR = 255; + colorG = 255; + colorB = 0; + } + else if (color == "Blue") { + colorR = 0; + colorG = 0; + colorB = 255; + } + else if (color == "Green") { + colorR = 0; + colorG = 255; + colorB = 0; + } + else if (color == "White") { + colorR = 255; + colorG = 255; + colorB = 255; + } + else if (color == "Black") { + colorR = 0; + colorG = 0; + colorB = 0; + } + else if (color == "Cyan") { + colorR = 0; + colorG = 255; + colorB = 255; + } + else if (color == "Purple") { + colorR = 128; + colorG = 0; + colorB = 128; + } + else if (color == "Orange") { + colorR = 255; + colorG = 165; + colorB = 0; + } + + if (wsState == false) { + wsState = true; + colorW = 255; + } + + if (colorW == 0) { + colorW = 255; + } + + pixelShow(); + + BlinkerAliGenie.color(color); + BlinkerAliGenie.print(); +} + +void aligenieMode(const String & mode) +{ + BLINKER_LOG("need set mode: ", mode); + + if (mode == BLINKER_CMD_ALIGENIE_READING) { + // Your mode function + } + else if (mode == BLINKER_CMD_ALIGENIE_MOVIE) { + // Your mode function + } + else if (mode == BLINKER_CMD_ALIGENIE_SLEEP) { + // Your mode function + } + else if (mode == BLINKER_CMD_ALIGENIE_HOLIDAY) { + // Your mode function + } + else if (mode == BLINKER_CMD_ALIGENIE_MUSIC) { + // Your mode function + } + else if (mode == BLINKER_CMD_ALIGENIE_COMMON) { + // Your mode function + } + + wsMode = mode; + + BlinkerAliGenie.mode(mode); + BlinkerAliGenie.print(); +} + +void aligeniecMode(const String & cmode) +{ + BLINKER_LOG("need cancel mode: ", cmode); + + if (cmode == BLINKER_CMD_ALIGENIE_READING) { + // Your mode function + } + else if (cmode == BLINKER_CMD_ALIGENIE_MOVIE) { + // Your mode function + } + else if (cmode == BLINKER_CMD_ALIGENIE_SLEEP) { + // Your mode function + } + else if (cmode == BLINKER_CMD_ALIGENIE_HOLIDAY) { + // Your mode function + } + else if (cmode == BLINKER_CMD_ALIGENIE_MUSIC) { + // Your mode function + } + else if (cmode == BLINKER_CMD_ALIGENIE_COMMON) { + // Your mode function + } + + wsMode = BLINKER_CMD_COMMON; // new mode + + BlinkerAliGenie.mode(wsMode); // must response + BlinkerAliGenie.print(); +} + +void aligenieBright(const String & bright) +{ + BLINKER_LOG("need set brightness: ", bright); + + if (bright == BLINKER_CMD_MAX) { + colorW = 255; + } + else if (bright == BLINKER_CMD_MIN) { + colorW = 0; + } + else { + colorW = bright.toInt(); + } + + BLINKER_LOG("now set brightness: ", colorW); + + pixelShow(); + + BlinkerAliGenie.brightness(colorW); + BlinkerAliGenie.print(); +} + +void aligenieRelativeBright(int32_t bright) +{ + BLINKER_LOG("need set relative brightness: ", bright); + + if (colorW + bright < 255 && colorW + bright >= 0) { + colorW += bright; + } + + BLINKER_LOG("now set brightness: ", colorW); + + pixelShow(); + + BlinkerAliGenie.brightness(bright); + BlinkerAliGenie.print(); +} + +void aligenieColoTemp(int32_t colorTemp) +{ + BLINKER_LOG("need set colorTemperature: ", colorTemp); + + BlinkerAliGenie.colorTemp(colorTemp); + BlinkerAliGenie.print(); +} + +void aligenieRelativeColoTemp(int32_t colorTemp) +{ + BLINKER_LOG("need set relative colorTemperature: ", colorTemp); + + BlinkerAliGenie.colorTemp(colorTemp); + BlinkerAliGenie.print(); +} + +void aligenieQuery(int32_t queryCode) +{ + BLINKER_LOG("AliGenie Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_ALL_NUMBER : + BLINKER_LOG("AliGenie Query All"); + BlinkerAliGenie.powerState(wsState ? "on" : "off"); + BlinkerAliGenie.color(getColor()); + BlinkerAliGenie.mode(wsMode); + BlinkerAliGenie.colorTemp(50); + BlinkerAliGenie.brightness(colorW); + BlinkerAliGenie.print(); + break; + case BLINKER_CMD_QUERY_POWERSTATE_NUMBER : + BLINKER_LOG("AliGenie Query Power State"); + BlinkerAliGenie.powerState(wsState ? "on" : "off"); + BlinkerAliGenie.print(); + break; + case BLINKER_CMD_QUERY_COLOR_NUMBER : + BLINKER_LOG("AliGenie Query Color"); + BlinkerAliGenie.color(getColor()); + BlinkerAliGenie.print(); + break; + case BLINKER_CMD_QUERY_MODE_NUMBER : + BLINKER_LOG("AliGenie Query Mode"); + BlinkerAliGenie.mode(wsMode); + BlinkerAliGenie.print(); + break; + case BLINKER_CMD_QUERY_COLORTEMP_NUMBER : + BLINKER_LOG("AliGenie Query ColorTemperature"); + BlinkerAliGenie.colorTemp(50); + BlinkerAliGenie.print(); + break; + case BLINKER_CMD_QUERY_BRIGHTNESS_NUMBER : + BLINKER_LOG("AliGenie Query Brightness"); + BlinkerAliGenie.brightness(colorW); + BlinkerAliGenie.print(); + break; + default : + BlinkerAliGenie.powerState(wsState ? "on" : "off"); + BlinkerAliGenie.color(getColor()); + BlinkerAliGenie.mode(wsMode); + BlinkerAliGenie.colorTemp(50); + BlinkerAliGenie.brightness(colorW); + BlinkerAliGenie.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerAliGenie.attachPowerState(aligeniePowerState); + BlinkerAliGenie.attachColor(aligenieColor); + BlinkerAliGenie.attachMode(aligenieMode); + BlinkerAliGenie.attachCancelMode(aligeniecMode); + BlinkerAliGenie.attachBrightness(aligenieBright); + BlinkerAliGenie.attachRelativeBrightness(aligenieRelativeBright); + BlinkerAliGenie.attachColorTemperature(aligenieColoTemp); + BlinkerAliGenie.attachRelativeColorTemperature(aligenieRelativeColoTemp); + BlinkerAliGenie.attachQuery(aligenieQuery); + + pinMode(14, OUTPUT); + digitalWrite(14, HIGH); + pinMode(15, OUTPUT); + digitalWrite(15, HIGH); + + colorR = 255; + colorG = 255; + colorB = 255; + colorW = 0; + wsState = true; + + pixels.begin(); + pixels.setBrightness(colorW); + WS2812.attach(ws2812_callback); + pixelShow(); +} + +void loop() +{ + Blinker.run(); + + for(int i = 0; i < NUMPIXELS; i++){ + pixels.setPixelColor(i, colorR, colorG, colorB); + } + pixels.show(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_MULTI_OUTLET/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_MULTI_OUTLET/.pydio new file mode 100644 index 0000000..b25c6c3 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_MULTI_OUTLET/.pydio @@ -0,0 +1 @@ +bf20fa62-e30e-4f08-8f26-29139386248a \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_MULTI_OUTLET/AliGenie_MULTI_OUTLET.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_MULTI_OUTLET/AliGenie_MULTI_OUTLET.ino new file mode 100644 index 0000000..4ce78dd --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_MULTI_OUTLET/AliGenie_MULTI_OUTLET.ino @@ -0,0 +1,139 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_ALIGENIE_MULTI_OUTLET + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +bool oState[5] = { false }; + +void aligeniePowerState(const String & state, uint8_t num) +{ + BLINKER_LOG("need set outlet: ", num, ", power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerAliGenie.powerState("on", num); + BlinkerAliGenie.print(); + + oState[num] = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerAliGenie.powerState("off", num); + BlinkerAliGenie.print(); + + oState[num] = true; + + if (num == 0) + { + for (uint8_t o_num = 0; o_num < 5; o_num++) + { + oState[o_num] = false; + } + } + } +} + +void aligenieQuery(int32_t queryCode, uint8_t num) +{ + BLINKER_LOG("AliGenie Query outlet: ", num,", codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_ALL_NUMBER : + BLINKER_LOG("AliGenie Query All"); + BlinkerAliGenie.powerState(oState[num] ? "on" : "off", num); + BlinkerAliGenie.print(); + break; + case BLINKER_CMD_QUERY_POWERSTATE_NUMBER : + BLINKER_LOG("AliGenie Query Power State"); + BlinkerAliGenie.powerState(oState[num] ? "on" : "off", num); + BlinkerAliGenie.print(); + break; + default : + BlinkerAliGenie.powerState(oState[num] ? "on" : "off", num); + BlinkerAliGenie.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerAliGenie.attachPowerState(aligeniePowerState); + BlinkerAliGenie.attachQuery(aligenieQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_OUTLET/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_OUTLET/.pydio new file mode 100644 index 0000000..cb24404 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_OUTLET/.pydio @@ -0,0 +1 @@ +ae9b53b1-cca5-484e-9896-64034e6846d0 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_OUTLET/AliGenie_OUTLET.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_OUTLET/AliGenie_OUTLET.ino new file mode 100644 index 0000000..306ebf5 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_OUTLET/AliGenie_OUTLET.ino @@ -0,0 +1,131 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_ALIGENIE_OUTLET + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +bool oState = false; + +void aligeniePowerState(const String & state) +{ + BLINKER_LOG("need set power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerAliGenie.powerState("on"); + BlinkerAliGenie.print(); + + oState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerAliGenie.powerState("off"); + BlinkerAliGenie.print(); + + oState = false; + } +} + +void aligenieQuery(int32_t queryCode) +{ + BLINKER_LOG("AliGenie Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_ALL_NUMBER : + BLINKER_LOG("AliGenie Query All"); + BlinkerAliGenie.powerState(oState ? "on" : "off"); + BlinkerAliGenie.print(); + break; + case BLINKER_CMD_QUERY_POWERSTATE_NUMBER : + BLINKER_LOG("AliGenie Query Power State"); + BlinkerAliGenie.powerState(oState ? "on" : "off"); + BlinkerAliGenie.print(); + break; + default : + BlinkerAliGenie.powerState(oState ? "on" : "off"); + BlinkerAliGenie.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerAliGenie.attachPowerState(aligeniePowerState); + BlinkerAliGenie.attachQuery(aligenieQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_SENSOR/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_SENSOR/.pydio new file mode 100644 index 0000000..7f2ef14 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_SENSOR/.pydio @@ -0,0 +1 @@ +d463a16b-b238-4d61-a351-c93965263fde \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_SENSOR/AliGenie_SENSOR.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_SENSOR/AliGenie_SENSOR.ino new file mode 100644 index 0000000..f06bc0a --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_AliGenie/AliGenie_SENSOR/AliGenie_SENSOR.ino @@ -0,0 +1,105 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_ALIGENIE_SENSOR + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void aligenieQuery(int32_t queryCode) +{ + BLINKER_LOG("AliGenie Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_ALL_NUMBER : + BLINKER_LOG("AliGenie Query All"); + BlinkerAliGenie.temp(20); + BlinkerAliGenie.humi(20); + BlinkerAliGenie.pm25(20); + BlinkerAliGenie.print(); + break; + default : + BlinkerAliGenie.temp(20); + BlinkerAliGenie.humi(20); + BlinkerAliGenie.pm25(20); + BlinkerAliGenie.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerAliGenie.attachQuery(aligenieQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/.pydio new file mode 100644 index 0000000..e34cf64 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/.pydio @@ -0,0 +1 @@ +f35e0edb-4e9c-4d34-b784-e3df40001fa3 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_AIRCONDITION/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_AIRCONDITION/.pydio new file mode 100644 index 0000000..0f34aa3 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_AIRCONDITION/.pydio @@ -0,0 +1 @@ +a6ca2f94-7b22-452e-8f25-b6940c14bf98 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_AIRCONDITION/DuerOS_AIRCONDITION.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_AIRCONDITION/DuerOS_AIRCONDITION.ino new file mode 100644 index 0000000..040abff --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_AIRCONDITION/DuerOS_AIRCONDITION.ino @@ -0,0 +1,251 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_DUEROS_AIRCONDITION + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +#define BUTTON_1 "ButtonKey" + +BlinkerButton Button1(BUTTON_1); + +bool oState = false; +bool hsState = false; +bool vsState = false; +uint8_t setLevel; +uint8_t setTemp; +String wsMode = "AUTO"; + +void duerLevel(uint8_t level) +{ + BLINKER_LOG("need set level: ", level); + // 0:AUTO MODE, 1-3 LEVEL + + setLevel = level; + + BlinkerDuerOS.level(level); + BlinkerDuerOS.print(); +} + +void duerRelativeLevel(int32_t level) +{ + BLINKER_LOG("need set relative level: ", level); + // 0:AUTO MODE, 1-3 LEVEL + + setLevel += level; + + BlinkerDuerOS.level(setLevel); + BlinkerDuerOS.print(); +} + +void duerTemp(uint8_t temp) +{ + BLINKER_LOG("need set temp: ", temp); + + setTemp = temp; + + BlinkerDuerOS.temp(temp); + BlinkerDuerOS.print(); +} + +void duerRelativeTemp(int32_t temp) +{ + BLINKER_LOG("need set relative temp: ", temp); + + setTemp += temp; + + BlinkerDuerOS.temp(setTemp); + BlinkerDuerOS.print(); +} + +void duerMode(const String & mode) +{ + BLINKER_LOG("need set mode: ", mode); + // COOL:制冷 + // HEAT:制热 + // AUTO:自动 + // FAN:送风 + // DEHUMIDIFICATION:除湿 + // SLEEP:睡眠 + // CLEAN:净化 + // NAI:负离子 + // NO_WIND_FEELING: 无风感 + // NO_UP_WIND_FEELING: 上无风感 + // NO_DOWN_WIND_FEELING: 下无风感 + // UP_DOWN_SWING: 上下摆风 + // LEFT_RIGHT_SWING: 左右摆风 + + wsMode = mode; + + BlinkerDuerOS.mode(mode); + BlinkerDuerOS.print(); +} + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + + if (state == BLINKER_CMD_ON) { + BLINKER_LOG("Toggle on!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + Button1.print("on"); + + oState = true; + } + else if (state == BLINKER_CMD_OFF) { + BLINKER_LOG("Toggle off!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + Button1.print("off"); + + oState = false; + } + + BlinkerDuerOS.powerState(oState ? "on" : "off"); + BlinkerDuerOS.report(); + + digitalWrite(LED_BUILTIN, oState); +} + +void duerPowerState(const String & state) +{ + BLINKER_LOG("need set power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerDuerOS.powerState("on"); + BlinkerDuerOS.print(); + + oState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerDuerOS.powerState("off"); + BlinkerDuerOS.print(); + + oState = false; + } +} + +void duerQuery(int32_t queryCode) +{ + BLINKER_LOG("DuerOS Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_POWERSTATE_NUMBER : + BLINKER_LOG("DuerOS Query power state"); + BlinkerDuerOS.powerState(oState ? "on" : "off"); + BlinkerDuerOS.level(setLevel); + BlinkerDuerOS.temp(setTemp); + BlinkerDuerOS.mode(wsMode); + BlinkerDuerOS.print(); + break; + case BLINKER_CMD_QUERY_TIME_NUMBER : + BLINKER_LOG("DuerOS Query time"); + BlinkerDuerOS.time(millis()); + BlinkerDuerOS.print(); + break; + default : + BlinkerDuerOS.powerState(oState ? "on" : "off"); + BlinkerDuerOS.level(setLevel); + BlinkerDuerOS.temp(setTemp); + BlinkerDuerOS.mode(wsMode); + BlinkerDuerOS.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + // Blinker.vibrate(); + + // uint32_t BlinkerTime = millis(); + + // Blinker.print("millis", BlinkerTime); + + BlinkerDuerOS.powerState("off"); + BlinkerDuerOS.report(); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerDuerOS.attachPowerState(duerPowerState); + BlinkerDuerOS.attachLevel(duerLevel); + BlinkerDuerOS.attachRelativeLevel(duerRelativeLevel); + BlinkerDuerOS.attachTemp(duerTemp); + BlinkerDuerOS.attachRelativeTemp(duerRelativeTemp); + BlinkerDuerOS.attachMode(duerMode); + BlinkerDuerOS.attachQuery(duerQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_FAN/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_FAN/.pydio new file mode 100644 index 0000000..97d943e --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_FAN/.pydio @@ -0,0 +1 @@ +858ff0e8-610f-4ea2-a903-286097de9233 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_FAN/DuerOS_FAN.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_FAN/DuerOS_FAN.ino new file mode 100644 index 0000000..9425f2b --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_FAN/DuerOS_FAN.ino @@ -0,0 +1,225 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_DUEROS_FAN + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +#define BUTTON_1 "ButtonKey" + +BlinkerButton Button1(BUTTON_1); + +bool oState = false; +bool hsState = false; +bool vsState = false; +uint8_t setLevel; +String wsMode = "NIGHT"; + +void duerLevel(uint8_t level) +{ + BLINKER_LOG("need set level: ", level); + // 0:AUTO MODE, 1-3 LEVEL + + setLevel = level; + + BlinkerDuerOS.level(level); + BlinkerDuerOS.print(); +} + +void duerRelativeLevel(int32_t level) +{ + BLINKER_LOG("need set relative level: ", level); + // 0:AUTO MODE, 1-3 LEVEL + + setLevel += level; + + BlinkerDuerOS.level(setLevel); + BlinkerDuerOS.print(); +} + +void duerMode(const String & mode) +{ + BLINKER_LOG("need set mode: ", mode); + // NIGHT:夜间 + // SWING:摆动/摆风 + // SINGLE:单人 + // MULTI:多人 + // SPURT:喷射 + // SPREAD:扩散 + // QUIET:安静 + // NORMAL:正常风速/适中风速/一般风速 + // POWERFUL:强效 + // MUTE:静音风速 + // NATURAL:自然风速 + // BABY:无感风速/轻微风速 + // COMFORTABLE:舒适风速 + // FEEL:人感风速 + + wsMode = mode; + + BlinkerDuerOS.mode(mode); + BlinkerDuerOS.print(); +} + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + + if (state == BLINKER_CMD_ON) { + BLINKER_LOG("Toggle on!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + Button1.print("on"); + + oState = true; + } + else if (state == BLINKER_CMD_OFF) { + BLINKER_LOG("Toggle off!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + Button1.print("off"); + + oState = false; + } + + BlinkerDuerOS.powerState(oState ? "on" : "off"); + BlinkerDuerOS.report(); + + digitalWrite(LED_BUILTIN, oState); +} + +void duerPowerState(const String & state) +{ + BLINKER_LOG("need set power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerDuerOS.powerState("on"); + BlinkerDuerOS.print(); + + oState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerDuerOS.powerState("off"); + BlinkerDuerOS.print(); + + oState = false; + } +} + +void duerQuery(int32_t queryCode) +{ + BLINKER_LOG("DuerOS Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_POWERSTATE_NUMBER : + BLINKER_LOG("DuerOS Query power state"); + BlinkerDuerOS.powerState(oState ? "on" : "off"); + BlinkerDuerOS.level(setLevel); + BlinkerDuerOS.print(); + break; + case BLINKER_CMD_QUERY_TIME_NUMBER : + BLINKER_LOG("DuerOS Query time"); + BlinkerDuerOS.time(millis()); + BlinkerDuerOS.print(); + break; + default : + BlinkerDuerOS.powerState(oState ? "on" : "off"); + BlinkerDuerOS.level(setLevel); + BlinkerDuerOS.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + // Blinker.vibrate(); + + // uint32_t BlinkerTime = millis(); + + // Blinker.print("millis", BlinkerTime); + + BlinkerDuerOS.powerState("off"); + BlinkerDuerOS.report(); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerDuerOS.attachPowerState(duerPowerState); + BlinkerDuerOS.attachLevel(duerLevel); + BlinkerDuerOS.attachRelativeLevel(duerRelativeLevel); + BlinkerDuerOS.attachMode(duerMode); + BlinkerDuerOS.attachQuery(duerQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_LIGHT/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_LIGHT/.pydio new file mode 100644 index 0000000..576c804 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_LIGHT/.pydio @@ -0,0 +1 @@ +e4b6dc09-72a5-444e-8579-2a9941dd078e \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_LIGHT/DuerOS_LIGHT.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_LIGHT/DuerOS_LIGHT.ino new file mode 100644 index 0000000..498284a --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_LIGHT/DuerOS_LIGHT.ino @@ -0,0 +1,333 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_DUEROS_LIGHT + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +// Download Adafruit_NeoPixel library here: +// https://github.com/adafruit/Adafruit_NeoPixel +#include + +#define PIN 13 +#define NUMPIXELS 24 +Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); + +#define RGB_1 "RGBKey" + +BlinkerRGB WS2812(RGB_1); + +uint8_t colorR, colorG, colorB, colorW; +bool wsState; +String wsMode = BLINKER_CMD_COMMON; + +void pixelShow() +{ + pixels.setBrightness(colorW); + + for(int i = 0; i < NUMPIXELS; i++){ + pixels.setPixelColor(i, colorR, colorG, colorB); + } + pixels.show(); +} + +void ws2812_callback(uint8_t r_value, uint8_t g_value, uint8_t b_value, uint8_t bright_value) +{ + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + BLINKER_LOG("R value: ", r_value); + BLINKER_LOG("G value: ", g_value); + BLINKER_LOG("B value: ", b_value); + BLINKER_LOG("Rrightness value: ", bright_value); + + colorR = r_value; + colorG = g_value; + colorB = b_value; + colorW = bright_value; + + pixelShow(); +} + +String getColor() +{ + uint32_t color = colorR << 16 | colorG << 8 | colorB; + + switch (color) + { + case 0xFF0000 : + return "Red"; + case 0xFFFF00 : + return "Yellow"; + case 0x0000FF : + return "Blue"; + case 0x00FF00 : + return "Green"; + case 0xFFFFFF : + return "White"; + case 0x000000 : + return "Black"; + case 0x00FFFF : + return "Cyan"; + case 0x800080 : + return "Purple"; + case 0xFFA500 : + return "Orange"; + default : + return "White"; + } +} + +void duerPowerState(const String & state) +{ + BLINKER_LOG("need set power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerDuerOS.powerState("on"); + BlinkerDuerOS.print(); + + wsState = true; + + if (colorW == 0) colorW = 255; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerDuerOS.powerState("off"); + BlinkerDuerOS.print(); + + wsState = false; + + colorW == 0; + } + + pixelShow(); +} + +void duerColor(int32_t color) +{ + BLINKER_LOG("need set color: ", color); + + colorR = color >> 16 & 0xFF; + colorG = color >> 8 & 0xFF; + colorB = color & 0xFF; + + BLINKER_LOG("colorR: ", colorR, ", colorG: ", colorG, ", colorB: ", colorB); + + pixelShow(); + + BlinkerDuerOS.color(color); + BlinkerDuerOS.print(); +} + +void duerMode(const String & mode) +{ + BLINKER_LOG("need set mode: ", mode); + // READING:阅读 + // SLEEP:睡眠 + // ALARM:报警 + // NIGHT_LIGHT:夜灯 + // ROMANTIC:浪漫 + // SUNDOWN:日落 + // SUNRISE:日出 + // RELAX :休闲/放松 + // LIGHTING :照明 + // SUN :太阳 + // STAR :星星 + // ENERGY_SAVING:节能 + // MOON:月亮 + // JUDI:蹦迪 + + wsMode = mode; + + BlinkerDuerOS.mode(mode); + BlinkerDuerOS.print(); +} + +void duercMode(const String & cmode) +{ + BLINKER_LOG("need cancel mode: ", cmode); + + wsMode = BLINKER_CMD_COMMON; // new mode + + BlinkerDuerOS.mode(wsMode); // must response + BlinkerDuerOS.print(); +} + +void duerBright(const String & bright) +{ + BLINKER_LOG("need set brightness: ", bright); + + if (bright == BLINKER_CMD_MAX) { + colorW = 255; + } + else if (bright == BLINKER_CMD_MIN) { + colorW = 0; + } + else { + colorW = bright.toInt(); + } + + BLINKER_LOG("now set brightness: ", colorW); + + pixelShow(); + + BlinkerDuerOS.brightness(colorW); + BlinkerDuerOS.print(); +} + +void duerRelativeBright(int32_t bright) +{ + BLINKER_LOG("need set relative brightness: ", bright); + + if (colorW + bright < 255 && colorW + bright >= 0) { + colorW += bright; + } + + BLINKER_LOG("now set brightness: ", colorW); + + pixelShow(); + + BlinkerDuerOS.brightness(bright); + BlinkerDuerOS.print(); +} + +void duerColoTemp(int32_t colorTemp) +{ + BLINKER_LOG("need set colorTemperature: ", colorTemp); + + BlinkerDuerOS.colorTemp(colorTemp); + BlinkerDuerOS.print(); +} + +void duerRelativeColoTemp(int32_t colorTemp) +{ + BLINKER_LOG("need set relative colorTemperature: ", colorTemp); + + BlinkerDuerOS.colorTemp(colorTemp); + BlinkerDuerOS.print(); +} + +void duerQuery(int32_t queryCode) +{ + BLINKER_LOG("DuerOS Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_TIME_NUMBER : + BLINKER_LOG("DuerOS Query time"); + BlinkerDuerOS.time(millis()); + BlinkerDuerOS.print(); + break; + default : + BlinkerDuerOS.time(millis()); + BlinkerDuerOS.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerDuerOS.attachPowerState(duerPowerState); + BlinkerDuerOS.attachColor(duerColor); + BlinkerDuerOS.attachMode(duerMode); + BlinkerDuerOS.attachCancelMode(duercMode); + BlinkerDuerOS.attachBrightness(duerBright); + BlinkerDuerOS.attachRelativeBrightness(duerRelativeBright); + BlinkerDuerOS.attachColorTemperature(duerColoTemp); + BlinkerDuerOS.attachRelativeColorTemperature(duerRelativeColoTemp); + BlinkerDuerOS.attachQuery(duerQuery); + + pinMode(14, OUTPUT); + digitalWrite(14, HIGH); + pinMode(15, OUTPUT); + digitalWrite(15, HIGH); + + colorR = 255; + colorG = 255; + colorB = 255; + colorW = 0; + wsState = true; + + pixels.begin(); + pixels.setBrightness(colorW); + WS2812.attach(ws2812_callback); + pixelShow(); +} + +void loop() +{ + Blinker.run(); + + for(int i = 0; i < NUMPIXELS; i++){ + pixels.setPixelColor(i, colorR, colorG, colorB); + } + pixels.show(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_MULTI_OUTLET/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_MULTI_OUTLET/.pydio new file mode 100644 index 0000000..1133fbb --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_MULTI_OUTLET/.pydio @@ -0,0 +1 @@ +01e7be96-5f25-4ecb-b98a-f0a26a81aff8 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_MULTI_OUTLET/DuerOS_MULTI_OUTLET.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_MULTI_OUTLET/DuerOS_MULTI_OUTLET.ino new file mode 100644 index 0000000..2f49c30 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_MULTI_OUTLET/DuerOS_MULTI_OUTLET.ino @@ -0,0 +1,115 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_DUEROS_MULTI_OUTLET + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +bool oState[5] = { false }; + +void duerPowerState(const String & state, uint8_t num) +{ + BLINKER_LOG("need set outlet: ", num, ", power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerDuerOS.powerState("on", num); + BlinkerDuerOS.print(); + + oState[num] = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerDuerOS.powerState("off", num); + BlinkerDuerOS.print(); + + oState[num] = false; + + if (num == 0) + { + for (uint8_t o_num = 0; o_num < 5; o_num++) + { + oState[o_num] = false; + } + } + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerDuerOS.attachPowerState(duerPowerState); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_OUTLET/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_OUTLET/.pydio new file mode 100644 index 0000000..92cc32a --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_OUTLET/.pydio @@ -0,0 +1 @@ +546f7793-494d-4eda-a793-0db02e615eef \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_OUTLET/DuerOS_OUTLET.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_OUTLET/DuerOS_OUTLET.ino new file mode 100644 index 0000000..8cb6703 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_OUTLET/DuerOS_OUTLET.ino @@ -0,0 +1,170 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_DUEROS_OUTLET + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +#define BUTTON_1 "ButtonKey" + +BlinkerButton Button1(BUTTON_1); + +bool oState = false; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + + if (state == BLINKER_CMD_ON) { + BLINKER_LOG("Toggle on!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + Button1.print("on"); + + oState = true; + } + else if (state == BLINKER_CMD_OFF) { + BLINKER_LOG("Toggle off!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + Button1.print("off"); + + oState = false; + } + + BlinkerDuerOS.powerState(oState ? "on" : "off"); + BlinkerDuerOS.report(); + + digitalWrite(LED_BUILTIN, oState); +} + +void duerPowerState(const String & state) +{ + BLINKER_LOG("need set power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerDuerOS.powerState("on"); + BlinkerDuerOS.print(); + + oState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerDuerOS.powerState("off"); + BlinkerDuerOS.print(); + + oState = false; + } +} + +void duerQuery(int32_t queryCode) +{ + BLINKER_LOG("DuerOS Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_POWERSTATE_NUMBER : + BLINKER_LOG("DuerOS Query power state"); + BlinkerDuerOS.powerState(oState ? "on" : "off"); + BlinkerDuerOS.print(); + break; + case BLINKER_CMD_QUERY_TIME_NUMBER : + BLINKER_LOG("DuerOS Query time"); + BlinkerDuerOS.time(millis()); + BlinkerDuerOS.print(); + break; + default : + BlinkerDuerOS.powerState(oState ? "on" : "off"); + BlinkerDuerOS.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + // Blinker.vibrate(); + + // uint32_t BlinkerTime = millis(); + + // Blinker.print("millis", BlinkerTime); + + BlinkerDuerOS.powerState("off"); + BlinkerDuerOS.report(); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerDuerOS.attachPowerState(duerPowerState); + BlinkerDuerOS.attachQuery(duerQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_SENSOR/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_SENSOR/.pydio new file mode 100644 index 0000000..73f8e43 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_SENSOR/.pydio @@ -0,0 +1 @@ +3a423ac6-3b31-4f04-826a-1308e66d5bc7 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_SENSOR/DuerOS_SENSOR.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_SENSOR/DuerOS_SENSOR.ino new file mode 100644 index 0000000..ddefb31 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_DuerOS/DuerOS_SENSOR/DuerOS_SENSOR.ino @@ -0,0 +1,137 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_DUEROS_SENSOR + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void duerQuery(int32_t queryCode) +{ + BLINKER_LOG("DuerOS Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_AQI_NUMBER : + BLINKER_LOG("DuerOS Query AQI"); + BlinkerDuerOS.aqi(20); + BlinkerDuerOS.print(); + break; + case BLINKER_CMD_QUERY_CO2_NUMBER : + BLINKER_LOG("DuerOS Query CO2"); + BlinkerDuerOS.co2(20); + BlinkerDuerOS.print(); + break; + case BLINKER_CMD_QUERY_PM10_NUMBER : + BLINKER_LOG("DuerOS Query PM10"); + BlinkerDuerOS.pm10(20); + BlinkerDuerOS.print(); + break; + case BLINKER_CMD_QUERY_PM25_NUMBER : + BLINKER_LOG("DuerOS Query PM25"); + BlinkerDuerOS.pm25(20); + BlinkerDuerOS.print(); + break; + case BLINKER_CMD_QUERY_HUMI_NUMBER : + BLINKER_LOG("DuerOS Query HUMI"); + BlinkerDuerOS.humi(20); + BlinkerDuerOS.print(); + break; + case BLINKER_CMD_QUERY_TEMP_NUMBER : + BLINKER_LOG("DuerOS Query TEMP"); + BlinkerDuerOS.temp(20); + BlinkerDuerOS.print(); + break; + case BLINKER_CMD_QUERY_TIME_NUMBER : + BLINKER_LOG("DuerOS Query time"); + BlinkerDuerOS.time(millis()); + BlinkerDuerOS.print(); + break; + default : + BlinkerDuerOS.temp(20); + BlinkerDuerOS.humi(20); + BlinkerDuerOS.pm25(20); + BlinkerDuerOS.pm10(20); + BlinkerDuerOS.co2(20); + BlinkerDuerOS.aqi(20); + BlinkerDuerOS.time(millis()); + BlinkerDuerOS.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerDuerOS.attachQuery(duerQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/.pydio new file mode 100644 index 0000000..88749a9 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/.pydio @@ -0,0 +1 @@ +81efbb48-6f26-4632-be15-bdcd55699f9a \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_AIRCONDITION/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_AIRCONDITION/.pydio new file mode 100644 index 0000000..058f3f2 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_AIRCONDITION/.pydio @@ -0,0 +1 @@ +8c706e83-35e0-4e83-bdd1-6f162092fab1 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_AIRCONDITION/MIOT_AIRCONDITION.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_AIRCONDITION/MIOT_AIRCONDITION.ino new file mode 100644 index 0000000..c113d94 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_AIRCONDITION/MIOT_AIRCONDITION.ino @@ -0,0 +1,256 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_MIOT_AIRCONDITION + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +bool oState = false; +bool hsState = false; +bool vsState = false; +uint8_t setLevel; + +void miotLevel(uint8_t level) +{ + BLINKER_LOG("need set level: ", level); + // 0:AUTO MODE, 1-3 LEVEL + + setLevel = level; + + BlinkerMIOT.level(level); + BlinkerMIOT.print(); +} + +void miotTemp(uint8_t temp) +{ + BLINKER_LOG("need set temp: ", temp); + + BlinkerMIOT.temp(temp); + BlinkerMIOT.print(); +} + +void miotHumi(uint8_t humi) +{ + BLINKER_LOG("need set humi: ", humi); + + BlinkerMIOT.humi(humi); + BlinkerMIOT.print(); +} + +void miotMode(const String & mode, const String & state) +{ + // eco ECO节能模式 + // anion 负离子 + // heater 辅热功能 + // dryer 干燥功能 + // sleep 睡眠模式 + // soft 柔风功能 + // uv UV杀菌 + // unsb un-straight-blowing 防直吹 + + BLINKER_LOG("need set mode: ", mode, ", state:", state); + + BlinkerMIOT.mode(mode, state); + BlinkerMIOT.print(); +} + +void miotHSwingState(const String & state) +{ + BLINKER_LOG("need set HSwing state: ", state); + // horizontal-swing + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerMIOT.hswing("on"); + BlinkerMIOT.print(); + + hsState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerMIOT.hswing("off"); + BlinkerMIOT.print(); + + hsState = false; + } +} + +void miotVSwingState(const String & state) +{ + BLINKER_LOG("need set VSwing state: ", state); + // vertical-swing + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerMIOT.vswing("on"); + BlinkerMIOT.print(); + + vsState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerMIOT.vswing("off"); + BlinkerMIOT.print(); + + vsState = false; + } +} + +void miotPowerState(const String & state) +{ + BLINKER_LOG("need set power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerMIOT.powerState("on"); + BlinkerMIOT.print(); + + oState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerMIOT.powerState("off"); + BlinkerMIOT.print(); + + oState = false; + } +} + +void miotQuery(int32_t queryCode) +{ + BLINKER_LOG("MIOT Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_ALL_NUMBER : + BLINKER_LOG("MIOT Query All"); + BlinkerMIOT.powerState(oState ? "on" : "off"); + BlinkerMIOT.hswing(hsState ? "on" : "off"); + BlinkerMIOT.vswing(vsState ? "on" : "off"); + BlinkerMIOT.eco("off"); + BlinkerMIOT.anion("off"); + BlinkerMIOT.heater("off"); + BlinkerMIOT.dryer("off"); + BlinkerMIOT.sleep("off"); + BlinkerMIOT.soft("off"); + BlinkerMIOT.uv("off"); + BlinkerMIOT.unStraightBlow("off"); + BlinkerMIOT.level(setLevel); + BlinkerMIOT.temp(16); + BlinkerMIOT.humi(20); + BlinkerMIOT.print(); + break; + case BLINKER_CMD_QUERY_POWERSTATE_NUMBER : + BLINKER_LOG("MIOT Query Power State"); + BlinkerMIOT.powerState(oState ? "on" : "off"); + BlinkerMIOT.print(); + break; + default : + BlinkerMIOT.powerState(oState ? "on" : "off"); + BlinkerMIOT.hswing(hsState ? "on" : "off"); + BlinkerMIOT.vswing(vsState ? "on" : "off"); + BlinkerMIOT.eco("off"); + BlinkerMIOT.anion("off"); + BlinkerMIOT.heater("off"); + BlinkerMIOT.dryer("off"); + BlinkerMIOT.sleep("off"); + BlinkerMIOT.soft("off"); + BlinkerMIOT.uv("off"); + BlinkerMIOT.unStraightBlow("off"); + BlinkerMIOT.level(setLevel); + BlinkerMIOT.temp(16); + BlinkerMIOT.humi(20); + BlinkerMIOT.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerMIOT.attachPowerState(miotPowerState); + BlinkerMIOT.attachHSwing(miotHSwingState); + BlinkerMIOT.attachVSwing(miotVSwingState); + BlinkerMIOT.attachLevel(miotLevel); + BlinkerMIOT.attachMode(miotMode); + BlinkerMIOT.attachTemp(miotTemp); + BlinkerMIOT.attachHumi(miotHumi); + BlinkerMIOT.attachQuery(miotQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_FAN/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_FAN/.pydio new file mode 100644 index 0000000..d42b47e --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_FAN/.pydio @@ -0,0 +1 @@ +c5863779-0188-42ca-ba9c-c7ae6658298e \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_FAN/MIOT_FAN.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_FAN/MIOT_FAN.ino new file mode 100644 index 0000000..a074bd2 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_FAN/MIOT_FAN.ino @@ -0,0 +1,200 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.4 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_MIOT_FAN + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +bool oState = false; +bool hsState = false; +bool vsState = false; +uint8_t setLevel; + +void miotLevel(uint8_t level) +{ + BLINKER_LOG("need set level: ", level); + // 0:AUTO MODE, 1-3 LEVEL + + setLevel = level; + + BlinkerMIOT.level(level); + BlinkerMIOT.print(); +} + +void miotHSwingState(const String & state) +{ + BLINKER_LOG("need set HSwing state: ", state); + // horizontal-swing + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerMIOT.hswing("on"); + BlinkerMIOT.print(); + + hsState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerMIOT.hswing("off"); + BlinkerMIOT.print(); + + hsState = false; + } +} + +void miotVSwingState(const String & state) +{ + BLINKER_LOG("need set VSwing state: ", state); + // vertical-swing + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerMIOT.vswing("on"); + BlinkerMIOT.print(); + + vsState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerMIOT.vswing("off"); + BlinkerMIOT.print(); + + vsState = false; + } +} + +void miotPowerState(const String & state) +{ + BLINKER_LOG("need set power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerMIOT.powerState("on"); + BlinkerMIOT.print(); + + oState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerMIOT.powerState("off"); + BlinkerMIOT.print(); + + oState = false; + } +} + +void miotQuery(int32_t queryCode) +{ + BLINKER_LOG("MIOT Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_ALL_NUMBER : + BLINKER_LOG("MIOT Query All"); + BlinkerMIOT.powerState(oState ? "on" : "off"); + BlinkerMIOT.hswing(hsState ? "on" : "off"); + BlinkerMIOT.vswing(vsState ? "on" : "off"); + BlinkerMIOT.level(setLevel); + BlinkerMIOT.print(); + break; + case BLINKER_CMD_QUERY_POWERSTATE_NUMBER : + BLINKER_LOG("MIOT Query Power State"); + BlinkerMIOT.powerState(oState ? "on" : "off"); + BlinkerMIOT.print(); + break; + default : + BlinkerMIOT.powerState(oState ? "on" : "off"); + BlinkerMIOT.hswing(hsState ? "on" : "off"); + BlinkerMIOT.vswing(vsState ? "on" : "off"); + BlinkerMIOT.level(setLevel); + BlinkerMIOT.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerMIOT.attachPowerState(miotPowerState); + BlinkerMIOT.attachHSwing(miotHSwingState); + BlinkerMIOT.attachVSwing(miotVSwingState); + BlinkerMIOT.attachLevel(miotLevel); + BlinkerMIOT.attachQuery(miotQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_LIGHT/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_LIGHT/.pydio new file mode 100644 index 0000000..d6d9d22 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_LIGHT/.pydio @@ -0,0 +1 @@ +059aba4b-80fc-4175-9dbc-6bec0a349729 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_LIGHT/MIOT_LIGHT.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_LIGHT/MIOT_LIGHT.ino new file mode 100644 index 0000000..0fb5417 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_LIGHT/MIOT_LIGHT.ino @@ -0,0 +1,308 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_MIOT_LIGHT + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +// Download Adafruit_NeoPixel library here: +// https://github.com/adafruit/Adafruit_NeoPixel +#include + +#define PIN 2 +#define NUMPIXELS 24 +Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); + +#define RGB_1 "RGBKey" + +BlinkerRGB WS2812(RGB_1); + +uint8_t colorR, colorG, colorB, colorW; +bool wsState; +uint8_t wsMode = BLINKER_CMD_MIOT_DAY; + +void pixelShow() +{ + pixels.setBrightness(colorW); + + for(int i = 0; i < NUMPIXELS; i++){ + pixels.setPixelColor(i, colorR, colorG, colorB); + } + pixels.show(); +} + +void ws2812_callback(uint8_t r_value, uint8_t g_value, uint8_t b_value, uint8_t bright_value) +{ + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + BLINKER_LOG("R value: ", r_value); + BLINKER_LOG("G value: ", g_value); + BLINKER_LOG("B value: ", b_value); + BLINKER_LOG("Rrightness value: ", bright_value); + + colorR = r_value; + colorG = g_value; + colorB = b_value; + colorW = bright_value; + + pixelShow(); +} + +uint32_t getColor() +{ + uint32_t color = colorR << 16 | colorG << 8 | colorB; + + return color; +} + +void miotPowerState(const String & state) +{ + BLINKER_LOG("need set power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerMIOT.powerState("on"); + BlinkerMIOT.print(); + + wsState = true; + + if (colorW == 0) colorW = 255; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerMIOT.powerState("off"); + BlinkerMIOT.print(); + + wsState = false; + + colorW = 0; + } + + pixelShow(); +} + +void miotColor(int32_t color) +{ + BLINKER_LOG("need set color: ", color); + + colorR = color >> 16 & 0xFF; + colorG = color >> 8 & 0xFF; + colorB = color & 0xFF; + + BLINKER_LOG("colorR: ", colorR, ", colorG: ", colorG, ", colorB: ", colorB); + + pixelShow(); + + BlinkerMIOT.color(color); + BlinkerMIOT.print(); +} + +void miotMode(uint8_t mode) +{ + BLINKER_LOG("need set mode: ", mode); + + if (mode == BLINKER_CMD_MIOT_DAY) { + // Your mode function + } + else if (mode == BLINKER_CMD_MIOT_NIGHT) { + // Your mode function + } + else if (mode == BLINKER_CMD_MIOT_COLOR) { + // Your mode function + } + else if (mode == BLINKER_CMD_MIOT_WARMTH) { + // Your mode function + } + else if (mode == BLINKER_CMD_MIOT_TV) { + // Your mode function + } + else if (mode == BLINKER_CMD_MIOT_READING) { + // Your mode function + } + else if (mode == BLINKER_CMD_MIOT_COMPUTER) { + // Your mode function + } + + wsMode = mode; + + BlinkerMIOT.mode(mode); + BlinkerMIOT.print(); +} + +void miotBright(const String & bright) +{ + BLINKER_LOG("need set brightness: ", bright); + + colorW = bright.toInt(); + + BLINKER_LOG("now set brightness: ", colorW); + + pixelShow(); + + BlinkerMIOT.brightness(colorW); + BlinkerMIOT.print(); +} + +void miotColoTemp(int32_t colorTemp) +{ + BLINKER_LOG("need set colorTemperature: ", colorTemp); + + BlinkerMIOT.colorTemp(colorTemp); + BlinkerMIOT.print(); +} + +void miotQuery(int32_t queryCode) +{ + BLINKER_LOG("MIOT Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_ALL_NUMBER : + BLINKER_LOG("MIOT Query All"); + BlinkerMIOT.powerState(wsState ? "on" : "off"); + BlinkerMIOT.color(0); + BlinkerMIOT.mode(0); + BlinkerMIOT.colorTemp(1000); + BlinkerMIOT.brightness(1); + BlinkerMIOT.print(); + break; + case BLINKER_CMD_QUERY_POWERSTATE_NUMBER : + BLINKER_LOG("MIOT Query Power State"); + BlinkerMIOT.powerState(wsState ? "on" : "off"); + BlinkerMIOT.print(); + break; + case BLINKER_CMD_QUERY_COLOR_NUMBER : + BLINKER_LOG("MIOT Query Color"); + BlinkerMIOT.color(0); + BlinkerMIOT.print(); + break; + case BLINKER_CMD_QUERY_MODE_NUMBER : + BLINKER_LOG("MIOT Query Mode"); + BlinkerMIOT.mode(0); + BlinkerMIOT.print(); + break; + case BLINKER_CMD_QUERY_COLORTEMP_NUMBER : + BLINKER_LOG("MIOT Query ColorTemperature"); + BlinkerMIOT.colorTemp(1000); + BlinkerMIOT.print(); + break; + case BLINKER_CMD_QUERY_BRIGHTNESS_NUMBER : + BLINKER_LOG("MIOT Query Brightness"); + BlinkerMIOT.brightness(1); + BlinkerMIOT.print(); + break; + default : + BlinkerMIOT.powerState(wsState ? "on" : "off"); + BlinkerMIOT.color(0); + BlinkerMIOT.mode(0); + BlinkerMIOT.colorTemp(1000); + BlinkerMIOT.brightness(1); + BlinkerMIOT.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerMIOT.attachPowerState(miotPowerState); + BlinkerMIOT.attachColor(miotColor); + BlinkerMIOT.attachMode(miotMode); + BlinkerMIOT.attachBrightness(miotBright); + BlinkerMIOT.attachColorTemperature(miotColoTemp); + BlinkerMIOT.attachQuery(miotQuery); + + pinMode(14, OUTPUT); + digitalWrite(14, HIGH); + pinMode(15, OUTPUT); + digitalWrite(15, HIGH); + + colorR = 255; + colorG = 255; + colorB = 255; + colorW = 0; + wsState = true; + + pixels.begin(); + pixels.setBrightness(colorW); + WS2812.attach(ws2812_callback); + pixelShow(); +} + +void loop() +{ + Blinker.run(); + + for(int i = 0; i < NUMPIXELS; i++){ + pixels.setPixelColor(i, colorR, colorG, colorB); + } + pixels.show(); +} diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_MULTI_OUTLET/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_MULTI_OUTLET/.pydio new file mode 100644 index 0000000..673c3f3 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_MULTI_OUTLET/.pydio @@ -0,0 +1 @@ +d4785423-73ec-4e7d-a7ce-14b49f8c4b30 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_MULTI_OUTLET/MIOT_MULTI_OUTLET.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_MULTI_OUTLET/MIOT_MULTI_OUTLET.ino new file mode 100644 index 0000000..959a1f2 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_MULTI_OUTLET/MIOT_MULTI_OUTLET.ino @@ -0,0 +1,139 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_MIOT_MULTI_OUTLET + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +bool oState[5] = { false }; + +void miotPowerState(const String & state, uint8_t num) +{ + BLINKER_LOG("need set outlet: ", num, ", power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerMIOT.powerState("on", num); + BlinkerMIOT.print(); + + oState[num] = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerMIOT.powerState("off", num); + BlinkerMIOT.print(); + + oState[num] = false; + + if (num == 0) + { + for (uint8_t o_num = 0; o_num < 5; o_num++) + { + oState[o_num] = false; + } + } + } +} + +void miotQuery(int32_t queryCode, uint8_t num) +{ + BLINKER_LOG("MIOT Query outlet: ", num,", codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_ALL_NUMBER : + BLINKER_LOG("MIOT Query All"); + BlinkerMIOT.powerState(oState[num] ? "on" : "off", num); + BlinkerMIOT.print(); + break; + case BLINKER_CMD_QUERY_POWERSTATE_NUMBER : + BLINKER_LOG("MIOT Query Power State"); + BlinkerMIOT.powerState(oState[num] ? "on" : "off", num); + BlinkerMIOT.print(); + break; + default : + BlinkerMIOT.powerState(oState[num] ? "on" : "off", num); + BlinkerMIOT.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerMIOT.attachPowerState(miotPowerState); + BlinkerMIOT.attachQuery(miotQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_OUTLET/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_OUTLET/.pydio new file mode 100644 index 0000000..58255ca --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_OUTLET/.pydio @@ -0,0 +1 @@ +0f12acc0-deae-4786-b9f3-5395b1885530 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_OUTLET/MIOT_OUTLET.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_OUTLET/MIOT_OUTLET.ino new file mode 100644 index 0000000..6452cb3 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_OUTLET/MIOT_OUTLET.ino @@ -0,0 +1,131 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_MIOT_OUTLET + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +bool oState = false; + +void miotPowerState(const String & state) +{ + BLINKER_LOG("need set power state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + + BlinkerMIOT.powerState("on"); + BlinkerMIOT.print(); + + oState = true; + } + else if (state == BLINKER_CMD_OFF) { + digitalWrite(LED_BUILTIN, LOW); + + BlinkerMIOT.powerState("off"); + BlinkerMIOT.print(); + + oState = false; + } +} + +void miotQuery(int32_t queryCode) +{ + BLINKER_LOG("MIOT Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_ALL_NUMBER : + BLINKER_LOG("MIOT Query All"); + BlinkerMIOT.powerState(oState ? "on" : "off"); + BlinkerMIOT.print(); + break; + case BLINKER_CMD_QUERY_POWERSTATE_NUMBER : + BLINKER_LOG("MIOT Query Power State"); + BlinkerMIOT.powerState(oState ? "on" : "off"); + BlinkerMIOT.print(); + break; + default : + BlinkerMIOT.powerState(oState ? "on" : "off"); + BlinkerMIOT.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerMIOT.attachPowerState(miotPowerState); + BlinkerMIOT.attachQuery(miotQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_SENSOR/.pydio b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_SENSOR/.pydio new file mode 100644 index 0000000..e6f9a41 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_SENSOR/.pydio @@ -0,0 +1 @@ +66954d9f-6687-48b7-9a9e-03ce9b41ea8d \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_SENSOR/MIOT_SENSOR.ino b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_SENSOR/MIOT_SENSOR.ino new file mode 100644 index 0000000..ca1e163 --- /dev/null +++ b/blinker-library/examples/Blinker_Voice_Assistant/Blinker_MIOT/MIOT_SENSOR/MIOT_SENSOR.ino @@ -0,0 +1,107 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_MIOT_SENSOR + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void miotQuery(int32_t queryCode) +{ + BLINKER_LOG("MIOT Query codes: ", queryCode); + + switch (queryCode) + { + case BLINKER_CMD_QUERY_ALL_NUMBER : + BLINKER_LOG("MIOT Query All"); + BlinkerMIOT.temp(20); + BlinkerMIOT.humi(20); + BlinkerMIOT.pm25(20); + BlinkerMIOT.co2(20); + BlinkerMIOT.print(); + break; + default : + BlinkerMIOT.temp(20); + BlinkerMIOT.humi(20); + BlinkerMIOT.pm25(20); + BlinkerMIOT.co2(20); + BlinkerMIOT.print(); + break; + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + BlinkerMIOT.attachQuery(miotQuery); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Weathers/.pydio b/blinker-library/examples/Blinker_Weathers/.pydio new file mode 100644 index 0000000..869c339 --- /dev/null +++ b/blinker-library/examples/Blinker_Weathers/.pydio @@ -0,0 +1 @@ +d319415d-aaab-49b2-a17d-37b892d19b43 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Weathers/Blinker_Air/.pydio b/blinker-library/examples/Blinker_Weathers/Blinker_Air/.pydio new file mode 100644 index 0000000..bfbe639 --- /dev/null +++ b/blinker-library/examples/Blinker_Weathers/Blinker_Air/.pydio @@ -0,0 +1 @@ +0e45be6a-68ec-40f2-b9ed-dae4f58e0777 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Weathers/Blinker_Air/Air_WiFi/.pydio b/blinker-library/examples/Blinker_Weathers/Blinker_Air/Air_WiFi/.pydio new file mode 100644 index 0000000..50e0bca --- /dev/null +++ b/blinker-library/examples/Blinker_Weathers/Blinker_Air/Air_WiFi/.pydio @@ -0,0 +1 @@ +bfaf20a8-7dc2-4112-8e19-4fa8aeb0eb70 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Weathers/Blinker_Air/Air_WiFi/Air_WiFi.ino b/blinker-library/examples/Blinker_Weathers/Blinker_Air/Air_WiFi/Air_WiFi.ino new file mode 100644 index 0000000..c1e6c87 --- /dev/null +++ b/blinker-library/examples/Blinker_Weathers/Blinker_Air/Air_WiFi/Air_WiFi.ino @@ -0,0 +1,90 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.5.0 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.2 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.5.0 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.2 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void airData(const String & data) +{ + BLINKER_LOG("air: ", data); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + uint32_t BlinkerTime = millis(); + + Blinker.vibrate(); + Blinker.print("millis", BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + Blinker.air(); + + Blinker.delay(60000); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + Blinker.attachAir(airData); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Weathers/Blinker_Weather/.pydio b/blinker-library/examples/Blinker_Weathers/Blinker_Weather/.pydio new file mode 100644 index 0000000..65dd877 --- /dev/null +++ b/blinker-library/examples/Blinker_Weathers/Blinker_Weather/.pydio @@ -0,0 +1 @@ +abf5d5f4-383b-469c-b1cb-08d027f8a957 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Weathers/Blinker_Weather/Weather_WiFi/.pydio b/blinker-library/examples/Blinker_Weathers/Blinker_Weather/Weather_WiFi/.pydio new file mode 100644 index 0000000..7e63a65 --- /dev/null +++ b/blinker-library/examples/Blinker_Weathers/Blinker_Weather/Weather_WiFi/.pydio @@ -0,0 +1 @@ +a4a40a1f-f94e-4ed3-83f5-c4ef06742b89 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Weathers/Blinker_Weather/Weather_WiFi/Weather_WiFi.ino b/blinker-library/examples/Blinker_Weathers/Blinker_Weather/Weather_WiFi/Weather_WiFi.ino new file mode 100644 index 0000000..47fc74b --- /dev/null +++ b/blinker-library/examples/Blinker_Weathers/Blinker_Weather/Weather_WiFi/Weather_WiFi.ino @@ -0,0 +1,97 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void weatherData(const String & data) +{ + BLINKER_LOG("weather: ", data); +} + +void weatherForecastData(const String & data) +{ + BLINKER_LOG("weather: ", data); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + uint32_t BlinkerTime = millis(); + + Blinker.vibrate(); + Blinker.print("millis", BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + Blinker.weather(); + Blinker.weatherForecast(); + + Blinker.delay(60000); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + Blinker.attachWeather(weatherData); + Blinker.attachWeatherForecast(weatherForecastData); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_WiFi_Config/.pydio b/blinker-library/examples/Blinker_WiFi_Config/.pydio new file mode 100644 index 0000000..c3d7fe9 --- /dev/null +++ b/blinker-library/examples/Blinker_WiFi_Config/.pydio @@ -0,0 +1 @@ +a82084d3-a1c2-4076-bd53-0f09396eb433 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_WiFi_Config/Blinker_APCONFIG/.pydio b/blinker-library/examples/Blinker_WiFi_Config/Blinker_APCONFIG/.pydio new file mode 100644 index 0000000..b5ccea4 --- /dev/null +++ b/blinker-library/examples/Blinker_WiFi_Config/Blinker_APCONFIG/.pydio @@ -0,0 +1 @@ +e4e3cb77-b577-4658-ac4f-c680d0d88cdb \ No newline at end of file diff --git a/blinker-library/examples/Blinker_WiFi_Config/Blinker_APCONFIG/APCONFIG_WiFi/.pydio b/blinker-library/examples/Blinker_WiFi_Config/Blinker_APCONFIG/APCONFIG_WiFi/.pydio new file mode 100644 index 0000000..b67cf79 --- /dev/null +++ b/blinker-library/examples/Blinker_WiFi_Config/Blinker_APCONFIG/APCONFIG_WiFi/.pydio @@ -0,0 +1 @@ +31c95e38-f475-4d27-94b8-cce9503e7e7c \ No newline at end of file diff --git a/blinker-library/examples/Blinker_WiFi_Config/Blinker_APCONFIG/APCONFIG_WiFi/APCONFIG_WiFi.ino b/blinker-library/examples/Blinker_WiFi_Config/Blinker_APCONFIG/APCONFIG_WiFi/APCONFIG_WiFi.ino new file mode 100644 index 0000000..32e95c8 --- /dev/null +++ b/blinker-library/examples/Blinker_WiFi_Config/Blinker_APCONFIG/APCONFIG_WiFi/APCONFIG_WiFi.ino @@ -0,0 +1,99 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_APCONFIG + +#include + +// Download OneButton library here: +// https://github.com/mathertel/OneButton +#include "OneButton.h" + +#if defined(ESP32) + #define BLINKER_BUTTON_PIN 4 +#else + #define BLINKER_BUTTON_PIN D7 +#endif +// button trigged when pin input level is LOW +OneButton button(BLINKER_BUTTON_PIN, true); + +char auth[] = "Your Device Secret Key"; + +void deviceReset() +{ + // Reset device ,erase WiFi config. + Blinker.reset(); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth); + Blinker.attachData(dataRead); + button.attachLongPressStop(deviceReset); +} + +void loop() +{ + Blinker.run(); + button.tick(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_WiFi_Config/Blinker_ESPTOUCH/.pydio b/blinker-library/examples/Blinker_WiFi_Config/Blinker_ESPTOUCH/.pydio new file mode 100644 index 0000000..a6a30cf --- /dev/null +++ b/blinker-library/examples/Blinker_WiFi_Config/Blinker_ESPTOUCH/.pydio @@ -0,0 +1 @@ +052e8ed4-77af-4da5-8f87-e39f1177ac4d \ No newline at end of file diff --git a/blinker-library/examples/Blinker_WiFi_Config/Blinker_ESPTOUCH/ESPTOUCH_WiFi/.pydio b/blinker-library/examples/Blinker_WiFi_Config/Blinker_ESPTOUCH/ESPTOUCH_WiFi/.pydio new file mode 100644 index 0000000..1183d88 --- /dev/null +++ b/blinker-library/examples/Blinker_WiFi_Config/Blinker_ESPTOUCH/ESPTOUCH_WiFi/.pydio @@ -0,0 +1 @@ +68dffc3d-8db6-4798-8fd7-ae42b53cc58a \ No newline at end of file diff --git a/blinker-library/examples/Blinker_WiFi_Config/Blinker_ESPTOUCH/ESPTOUCH_WiFi/ESPTOUCH_WiFi.ino b/blinker-library/examples/Blinker_WiFi_Config/Blinker_ESPTOUCH/ESPTOUCH_WiFi/ESPTOUCH_WiFi.ino new file mode 100644 index 0000000..de1f8d3 --- /dev/null +++ b/blinker-library/examples/Blinker_WiFi_Config/Blinker_ESPTOUCH/ESPTOUCH_WiFi/ESPTOUCH_WiFi.ino @@ -0,0 +1,99 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_ESP_SMARTCONFIG + +#include + +// Download OneButton library here: +// https://github.com/mathertel/OneButton +#include "OneButton.h" + +#if defined(ESP32) + #define BLINKER_BUTTON_PIN 4 +#else + #define BLINKER_BUTTON_PIN D7 +#endif +// button trigged when pin input level is LOW +OneButton button(BLINKER_BUTTON_PIN, true); + +char auth[] = "Your Device Secret Key"; + +void deviceReset() +{ + // Reset device ,erase WiFi config. + Blinker.reset(); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth); + Blinker.attachData(dataRead); + button.attachLongPressStop(deviceReset); +} + +void loop() +{ + Blinker.run(); + button.tick(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_WiFi_Config/Blinker_Multi_WiFi/.pydio b/blinker-library/examples/Blinker_WiFi_Config/Blinker_Multi_WiFi/.pydio new file mode 100644 index 0000000..52206ab --- /dev/null +++ b/blinker-library/examples/Blinker_WiFi_Config/Blinker_Multi_WiFi/.pydio @@ -0,0 +1 @@ +5f903ae6-d2eb-489b-aac9-33cc9a9dc720 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_WiFi_Config/Blinker_Multi_WiFi/Multi_WiFi/.pydio b/blinker-library/examples/Blinker_WiFi_Config/Blinker_Multi_WiFi/Multi_WiFi/.pydio new file mode 100644 index 0000000..8f34304 --- /dev/null +++ b/blinker-library/examples/Blinker_WiFi_Config/Blinker_Multi_WiFi/Multi_WiFi/.pydio @@ -0,0 +1 @@ +86c6d757-d203-4221-a6de-07371400bb37 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_WiFi_Config/Blinker_Multi_WiFi/Multi_WiFi/Multi_WiFi.ino b/blinker-library/examples/Blinker_WiFi_Config/Blinker_Multi_WiFi/Multi_WiFi/Multi_WiFi.ino new file mode 100644 index 0000000..aa93f48 --- /dev/null +++ b/blinker-library/examples/Blinker_WiFi_Config/Blinker_Multi_WiFi/Multi_WiFi/Multi_WiFi.ino @@ -0,0 +1,104 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI +#define BLINKER_WIFI_MULTI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + + +char ssid1[] = "Your WiFi network SSID or name"; +char pswd1[] = "Your WiFi network WPA password or WEP key"; + +char ssid2[] = "Your WiFi network SSID or name"; +char pswd2[] = "Your WiFi network WPA password or WEP key"; + +// 新建组件对象 +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +// 按下按键即会执行该函数 +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +// 如果未绑定的组件被触发,则会执行其中内容 +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + counter++; + Number1.print(counter); +} + +void setup() +{ + // 初始化串口 + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + // 初始化有LED的IO + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, HIGH); + // 初始化blinker + Blinker.addAP(ssid2, pswd2); + Blinker.addAP(ssid1, pswd1); + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + Button1.attach(button1_callback); +} + +void loop() { + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/.pydio b/blinker-library/examples/Blinker_Widgets/.pydio new file mode 100644 index 0000000..5eff843 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/.pydio @@ -0,0 +1 @@ +a6317ef1-793c-4190-81cb-b1c71275a7e6 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/.pydio new file mode 100644 index 0000000..5cccc70 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/.pydio @@ -0,0 +1 @@ +bc810c34-c7c2-4daa-875a-3ae3e0a1bca0 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/AUTO_Pro/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/AUTO_Pro/.pydio new file mode 100644 index 0000000..6b73b02 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/AUTO_Pro/.pydio @@ -0,0 +1 @@ +5d398941-60e0-4992-b7b4-8abc56876991 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/AUTO_Pro/AUTO_Pro.ino b/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/AUTO_Pro/AUTO_Pro.ino new file mode 100644 index 0000000..63e41b5 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/AUTO_Pro/AUTO_Pro.ino @@ -0,0 +1,190 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_PRO_ESP +#define BLINKER_BUTTON +#if defined(ESP32) + #define BLINKER_BUTTON_PIN 4 +#else + #define BLINKER_BUTTON_PIN D7 +#endif + +#define BLINKER_OTA_VERSION_CODE "0.1.1" + +#include + +char type[] = "Your Device Type"; +char auth[] = "Your Device Secret Key"; + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +/* + * Add your command parse code in this function + * + * When get a command and device not parsed this command, device will call this function + */ +bool dataParse(const JsonObject & data) +{ + String getData; + + serializeJson(data, getData); + + BLINKER_LOG("Get user command: ", getData); + + // if you parsed this data, return TRUE. + // return true; + return false; +} + +/* + * Add your heartbeat message detail in this function + * + * When get heartbeat command {"get": "state"}, device will call this function + * For example, you can print message back + * + * Every 30s will get a heartbeat command from app + */ +void heartbeat() +{ + BLINKER_LOG("heartbeat!"); +} + +#if defined(BLINKER_BUTTON) +/* + * Blinker provide a button parse function for user if you defined BLINKER_BUTTON + * + * Blinker button can detect singal click/ double click/ long press + * + * Blinker.tick() will run by default, use interrupt will be better + */ +ICACHE_RAM_ATTR void buttonTick() +{ + Blinker.tick(); +} + +/* + * Add your code in this function + * + * When button clicked, device will call this function + */ +void singleClick() +{ + BLINKER_LOG("Button clicked!"); +} + +/* + * Add your code in this function + * + * When button double clicked, device will call this function + */ +void doubleClick() +{ + BLINKER_LOG("Button double clicked!"); +} +#endif + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + counter++; + Number1.print(counter); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, type); + Blinker.attachData(dataRead); + Blinker.attachParse(dataParse); + Blinker.attachHeartbeat(heartbeat); + + Button1.attach(button1_callback); + +#if defined(BLINKER_BUTTON) + Blinker.attachClick(singleClick); + Blinker.attachDoubleClick(doubleClick); + attachInterrupt(BLINKER_BUTTON_PIN, buttonTick, CHANGE); +#endif +} + +uint32_t run_time = millis(); + +uint8_t humis[10] = {19,18,17,18,21,20,19,18,17,16}; +uint8_t humi_num = 0; + +void auto_check() +{ + if (millis() - run_time >= 10000) + { + run_time = millis(); + + Blinker.autoInput("num-abc", humis[humi_num]); + Blinker.autoRun(); + + humi_num = (humi_num + 1) % 10; + } +} + +void loop() +{ + Blinker.run(); + auto_check(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/AUTO_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/AUTO_WiFi/.pydio new file mode 100644 index 0000000..f79d725 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/AUTO_WiFi/.pydio @@ -0,0 +1 @@ +20f66ae3-e10e-42c9-8ff9-aba9498aa738 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/AUTO_WiFi/AUTO_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/AUTO_WiFi/AUTO_WiFi.ino new file mode 100644 index 0000000..7e8a706 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_AUTO/AUTO_WiFi/AUTO_WiFi.ino @@ -0,0 +1,135 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +/* + * + * This example not complete at all, TODO. + * + */ + +#define BLINKER_PRINT Serial +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +bool switch_state = false; +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); + +int counter = 0; + +bool switch_state = false; + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + counter++; + Number1.print(counter); +} + +void switch_callback(const String & state) +{ + BLINKER_LOG("get switch state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + switch_state = true; + BUILTIN_SWITCH.print("on"); + } + else { + digitalWrite(LED_BUILTIN, LOW); + switch_state = false; + BUILTIN_SWITCH.print("off"); + } + + Blinker.autoInput("switch", switch_state ? 1.0 : 0.0); + Blinker.autoRun(); +} + +void heartbeat() +{ + if (switch_state) BUILTIN_SWITCH.print("on"); + else BUILTIN_SWITCH.print("off"); + + Number1.print(counter); +} + +void setup() { + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + Blinker.attachHeartbeat(heartbeat); + + Button1.attach(button1_callback); + + BUILTIN_SWITCH.attach(switch_callback); +} + +void loop() +{ + Blinker.run(); + Blinker.autoRun(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Button/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Button/.pydio new file mode 100644 index 0000000..0023020 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Button/.pydio @@ -0,0 +1 @@ +de928d72-2aef-40a3-8cd0-55ab97548ab4 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Button/Button_BLE/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Button/Button_BLE/.pydio new file mode 100644 index 0000000..25f236f --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Button/Button_BLE/.pydio @@ -0,0 +1 @@ +da9977da-f928-4033-bfe2-276205660c50 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Button/Button_BLE/Button_BLE.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Button/Button_BLE/Button_BLE.ino new file mode 100644 index 0000000..61a7c00 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Button/Button_BLE/Button_BLE.ino @@ -0,0 +1,141 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_BLE + +#include + +#define BUTTON_1 "ButtonKey" + +BlinkerButton Button1(BUTTON_1); + +void button1_callback(const String & state) +{ + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + BLINKER_LOG("get button state: ", state); + + if (state == BLINKER_CMD_BUTTON_TAP) { + BLINKER_LOG("Button tap!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + // Button1.text("Your button name", "describe"); + Button1.print(); + } + else if (state == BLINKER_CMD_BUTTON_PRESSED) { + BLINKER_LOG("Button pressed!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + // Button1.text("Your button name", "describe"); + Button1.print(); + } + else if (state == BLINKER_CMD_BUTTON_RELEASED) { + BLINKER_LOG("Button released!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + // Button1.text("Your button name", "describe"); + Button1.print(); + } + else if (state == BLINKER_CMD_ON) { + BLINKER_LOG("Toggle on!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + // Button1.text("Your button name", "describe"); + Button1.print("on"); + } + else if (state == BLINKER_CMD_OFF) { + BLINKER_LOG("Toggle off!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + // Button1.text("Your button name", "describe"); + Button1.print("off"); + } + else { + BLINKER_LOG("Get user setting: ", state); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + Button1.print(); + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + Button1.attach(button1_callback); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Button/Button_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Button/Button_WiFi/.pydio new file mode 100644 index 0000000..710783c --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Button/Button_WiFi/.pydio @@ -0,0 +1 @@ +22551a63-d6fb-49c7-9e63-265f1d4a28ac \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Button/Button_WiFi/Button_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Button/Button_WiFi/Button_WiFi.ino new file mode 100644 index 0000000..397d592 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Button/Button_WiFi/Button_WiFi.ino @@ -0,0 +1,144 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +#define BUTTON_1 "ButtonKey" + +BlinkerButton Button1(BUTTON_1); + +void button1_callback(const String & state) +{ + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + BLINKER_LOG("get button state: ", state); + + if (state == BLINKER_CMD_BUTTON_TAP) { + BLINKER_LOG("Button tap!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + Button1.print(); + } + else if (state == BLINKER_CMD_BUTTON_PRESSED) { + BLINKER_LOG("Button pressed!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + Button1.print(); + } + else if (state == BLINKER_CMD_BUTTON_RELEASED) { + BLINKER_LOG("Button released!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + // Button1.text("Your button name", "describe"); + Button1.print(); + } + else if (state == BLINKER_CMD_ON) { + BLINKER_LOG("Toggle on!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + // Button1.text("Your button name", "describe"); + Button1.print("on"); + } + else if (state == BLINKER_CMD_OFF) { + BLINKER_LOG("Toggle off!"); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + // Button1.text("Your button name", "describe"); + Button1.print("off"); + } + else { + BLINKER_LOG("Get user setting: ", state); + + Button1.icon("icon_1"); + Button1.color("#FFFFFF"); + Button1.text("Your button name or describe"); + // Button1.text("Your button name", "describe"); + Button1.print(); + } +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + Button1.attach(button1_callback); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/.pydio new file mode 100644 index 0000000..d4f42d1 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/.pydio @@ -0,0 +1 @@ +4bb70b7f-2fe3-4ada-8305-1ba4cde56603 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/Heartbeat_BLE/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/Heartbeat_BLE/.pydio new file mode 100644 index 0000000..049f59b --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/Heartbeat_BLE/.pydio @@ -0,0 +1 @@ +a9365339-1ed8-4e9f-9cff-df2d70f628c6 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/Heartbeat_BLE/Heartbeat_BLE.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/Heartbeat_BLE/Heartbeat_BLE.ino new file mode 100644 index 0000000..1393c56 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/Heartbeat_BLE/Heartbeat_BLE.ino @@ -0,0 +1,105 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_BLE + +#include + +bool switch_state = false; + +void switch_callback(const String & state) +{ + BLINKER_LOG("get switch state: ", state); + + if (state == BLINKER_CMD_ON) { + switch_state = true; + digitalWrite(LED_BUILTIN, HIGH); + + BUILTIN_SWITCH.print("on"); + } + else if (state == BLINKER_CMD_OFF) { + switch_state = false; + digitalWrite(LED_BUILTIN, LOW); + + BUILTIN_SWITCH.print("off"); + } +} + +void heartbeat() +{ + if (switch_state) BUILTIN_SWITCH.print("on"); + else BUILTIN_SWITCH.print("off"); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + Blinker.attachData(dataRead); + Blinker.attachHeartbeat(heartbeat); + + BUILTIN_SWITCH.attach(switch_callback); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/Heartbeat_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/Heartbeat_WiFi/.pydio new file mode 100644 index 0000000..efe51d1 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/Heartbeat_WiFi/.pydio @@ -0,0 +1 @@ +0b0d6565-06fc-4889-975c-48354a866b63 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/Heartbeat_WiFi/Heartbeat_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/Heartbeat_WiFi/Heartbeat_WiFi.ino new file mode 100644 index 0000000..e7318fd --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Heartbeat/Heartbeat_WiFi/Heartbeat_WiFi.ino @@ -0,0 +1,117 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +bool switch_state = false; + +void switch_callback(const String & state) +{ + BLINKER_LOG("get switch state: ", state); + + if (state == BLINKER_CMD_ON) { + switch_state = true; + digitalWrite(LED_BUILTIN, HIGH); + + BUILTIN_SWITCH.print("on"); + } + else if (state == BLINKER_CMD_OFF) { + switch_state = false; + digitalWrite(LED_BUILTIN, LOW); + + BUILTIN_SWITCH.print("off"); + } +} + +void heartbeat() +{ + if (switch_state) BUILTIN_SWITCH.print("on"); + else BUILTIN_SWITCH.print("off"); +} + +String summary() +{ + String data = "online, switch: " + STRING_format(switch_state ? "on" : "off"); + + return data; +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + Blinker.attachHeartbeat(heartbeat); + Blinker.attachSummary(summary); + + BUILTIN_SWITCH.attach(switch_callback); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Image/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Image/.pydio new file mode 100644 index 0000000..35d0b3f --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Image/.pydio @@ -0,0 +1 @@ +ad4bd18b-9d6a-4f4c-b96e-27171151a9b3 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Image/Image_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Image/Image_WiFi/.pydio new file mode 100644 index 0000000..d2ae843 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Image/Image_WiFi/.pydio @@ -0,0 +1 @@ +69df66d9-e9fb-4cdd-86c4-67f54c569e32 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Image/Image_WiFi/Image_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Image/Image_WiFi/Image_WiFi.ino new file mode 100644 index 0000000..11591b6 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Image/Image_WiFi/Image_WiFi.ino @@ -0,0 +1,98 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +BlinkerButton Button1("btn-abc"); +BlinkerNumber Number1("num-abc"); +BlinkerImage Image1("img_abc"); + +int counter = 0; + +void image1_callback(int32_t num) +{ + BLINKER_LOG("image is tapped, number is : ", num); +} + +void button1_callback(const String & state) +{ + BLINKER_LOG("get button state: ", state); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + + Image1.print(digitalRead(LED_BUILTIN) ? 1 : 0); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + counter++; + Number1.print(counter); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + BLINKER_DEBUG.debugAll(); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, HIGH); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + Button1.attach(button1_callback); + Image1.attach(image1_callback); +} + +void loop() { + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/.pydio new file mode 100644 index 0000000..dd996e0 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/.pydio @@ -0,0 +1 @@ +eddab941-e867-4741-a0ce-e7f768f8cd1c \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/Joystick_BLE/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/Joystick_BLE/.pydio new file mode 100644 index 0000000..a3c02da --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/Joystick_BLE/.pydio @@ -0,0 +1 @@ +b2c3f65d-8396-4680-aa5c-4b25372b70e4 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/Joystick_BLE/Joystick_BLE.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/Joystick_BLE/Joystick_BLE.ino new file mode 100644 index 0000000..01562ab --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/Joystick_BLE/Joystick_BLE.ino @@ -0,0 +1,88 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_BLE + +#include + +#define JOY_1 "JOYKey" + +BlinkerJoystick JOY1(JOY_1); + +void joystick1_callback(uint8_t xAxis, uint8_t yAxis) +{ + BLINKER_LOG("Joystick1 X axis: ", xAxis); + BLINKER_LOG("Joystick1 Y axis: ", yAxis); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + Blinker.attachData(dataRead); + + JOY1.attach(joystick1_callback); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/Joystick_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/Joystick_WiFi/.pydio new file mode 100644 index 0000000..325fa05 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/Joystick_WiFi/.pydio @@ -0,0 +1 @@ +1c84d01e-1af0-436c-bf54-de96e2c9e233 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/Joystick_WiFi/Joystick_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/Joystick_WiFi/Joystick_WiFi.ino new file mode 100644 index 0000000..fa12710 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Joystick/Joystick_WiFi/Joystick_WiFi.ino @@ -0,0 +1,92 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.5.0 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.2 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.5.0 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.2 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +#define JOY_1 "JOYKey" + +BlinkerJoystick JOY1(JOY_1); + +void joystick1_callback(uint8_t xAxis, uint8_t yAxis) +{ + BLINKER_LOG("Joystick1 X axis: ", xAxis); + BLINKER_LOG("Joystick1 Y axis: ", yAxis); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + JOY1.attach(joystick1_callback); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Notify/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Notify/.pydio new file mode 100644 index 0000000..01fea2f --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Notify/.pydio @@ -0,0 +1 @@ +9bede9c3-0705-4800-852c-bf4fccdbe660 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Notify/Notify_BLE/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Notify/Notify_BLE/.pydio new file mode 100644 index 0000000..46d16f4 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Notify/Notify_BLE/.pydio @@ -0,0 +1 @@ +d3cfabad-7ec7-40aa-909b-7907c774e9b5 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Notify/Notify_BLE/Notify_BLE.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Notify/Notify_BLE/Notify_BLE.ino new file mode 100644 index 0000000..a5cc6fa --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Notify/Notify_BLE/Notify_BLE.ino @@ -0,0 +1,79 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_BLE + +#include + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); + + Blinker.notify("!Button Pressed!"); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Notify/Notify_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Notify/Notify_WiFi/.pydio new file mode 100644 index 0000000..889edfb --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Notify/Notify_WiFi/.pydio @@ -0,0 +1 @@ +1803fc9d-3f80-4115-b6ea-4f754b65d16c \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Notify/Notify_WiFi/Notify_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Notify/Notify_WiFi/Notify_WiFi.ino new file mode 100644 index 0000000..6e5cbc2 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Notify/Notify_WiFi/Notify_WiFi.ino @@ -0,0 +1,83 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); + + Blinker.notify("!Button Pressed!"); + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Number/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Number/.pydio new file mode 100644 index 0000000..4ce27b4 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Number/.pydio @@ -0,0 +1 @@ +52d719ae-4b9b-4244-8648-e76091684385 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Number/Number_BLE/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Number/Number_BLE/.pydio new file mode 100644 index 0000000..29ec796 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Number/Number_BLE/.pydio @@ -0,0 +1 @@ +e23f2cf0-4e09-41e6-9652-728a9826bbf1 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Number/Number_BLE/Number_BLE.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Number/Number_BLE/Number_BLE.ino new file mode 100644 index 0000000..4495ed5 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Number/Number_BLE/Number_BLE.ino @@ -0,0 +1,87 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_BLE + +#include + +#define Number_1 "NUMKey" + +BlinkerNumber Number1(Number_1); + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); + + Number1.icon("icon_1"); + Number1.color("#FFFFFF"); + Number1.unit("ms"); + Number1.print(BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Number/Number_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Number/Number_WiFi/.pydio new file mode 100644 index 0000000..190f6e6 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Number/Number_WiFi/.pydio @@ -0,0 +1 @@ +acf60423-2192-440d-91c4-0a2b1d4e71ee \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Number/Number_WiFi/Number_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Number/Number_WiFi/Number_WiFi.ino new file mode 100644 index 0000000..e8a23d3 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Number/Number_WiFi/Number_WiFi.ino @@ -0,0 +1,91 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +#define Number_1 "NUMKey" + +BlinkerNumber Number1(Number_1); + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); + + Number1.icon("icon_1"); + Number1.color("#FFFFFF"); + Number1.unit("ms"); + Number1.print(BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_PUSH/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_PUSH/.pydio new file mode 100644 index 0000000..e57ceac --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_PUSH/.pydio @@ -0,0 +1 @@ +6d3b4100-f2bc-4167-b49f-83889a43bfa4 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_PUSH/PUSH_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_PUSH/PUSH_WiFi/.pydio new file mode 100644 index 0000000..e7af5ac --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_PUSH/PUSH_WiFi/.pydio @@ -0,0 +1 @@ +9f4203b9-75d2-44b7-bfac-366fb6620671 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_PUSH/PUSH_WiFi/PUSH_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_PUSH/PUSH_WiFi/PUSH_WiFi.ino new file mode 100644 index 0000000..fa94831 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_PUSH/PUSH_WiFi/PUSH_WiFi.ino @@ -0,0 +1,84 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + uint32_t BlinkerTime = millis(); + + Blinker.vibrate(); + Blinker.print("millis", BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + Blinker.push("Hello blinker!"); + + Blinker.delay(60000); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Print/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Print/.pydio new file mode 100644 index 0000000..41a7f3a --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Print/.pydio @@ -0,0 +1 @@ +5a36d1c1-cd4a-4e92-84df-25b56a9b5e8f \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Print/Print_BLE/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Print/Print_BLE/.pydio new file mode 100644 index 0000000..0711507 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Print/Print_BLE/.pydio @@ -0,0 +1 @@ +9f405f54-2093-4765-80be-aaea191174ed \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Print/Print_BLE/Print_BLE.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Print/Print_BLE/Print_BLE.ino new file mode 100644 index 0000000..1522e96 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Print/Print_BLE/Print_BLE.ino @@ -0,0 +1,76 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_BLE + +#include + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Print/Print_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Print/Print_WiFi/.pydio new file mode 100644 index 0000000..450f0db --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Print/Print_WiFi/.pydio @@ -0,0 +1 @@ +f5dc7b8d-d857-406b-a157-da52d4a31f77 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Print/Print_WiFi/Print_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Print/Print_WiFi/Print_WiFi.ino new file mode 100644 index 0000000..3a76cc3 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Print/Print_WiFi/Print_WiFi.ino @@ -0,0 +1,80 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_RGB/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_RGB/.pydio new file mode 100644 index 0000000..68615ff --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_RGB/.pydio @@ -0,0 +1 @@ +8402ce33-caa6-4689-9444-0d8c625ee4cb \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_RGB/RGB_BLE/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_RGB/RGB_BLE/.pydio new file mode 100644 index 0000000..6d14dc3 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_RGB/RGB_BLE/.pydio @@ -0,0 +1 @@ +b7653192-6ca9-4076-8e97-3efe1c46333c \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_RGB/RGB_BLE/RGB_BLE.ino b/blinker-library/examples/Blinker_Widgets/Blinker_RGB/RGB_BLE/RGB_BLE.ino new file mode 100644 index 0000000..338d981 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_RGB/RGB_BLE/RGB_BLE.ino @@ -0,0 +1,94 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_BLE + +#include + +#define RGB_1 "RGBKey" + +BlinkerRGB RGB1(RGB_1); + +void rgb1_callback(uint8_t r_value, uint8_t g_value, uint8_t b_value, uint8_t bright_value) +{ + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + BLINKER_LOG("R value: ", r_value); + BLINKER_LOG("G value: ", g_value); + BLINKER_LOG("B value: ", b_value); + BLINKER_LOG("Rrightness value: ", bright_value); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); + + RGB1.brightness(random(0, 255)); + RGB1.print(random(0, 255), random(0, 255), random(0, 255)); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + Blinker.attachData(dataRead); + + RGB1.attach(rgb1_callback); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_RGB/RGB_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_RGB/RGB_WiFi/.pydio new file mode 100644 index 0000000..00af92a --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_RGB/RGB_WiFi/.pydio @@ -0,0 +1 @@ +633e5c3c-8dd1-4ae6-952c-a1ba0402fe22 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_RGB/RGB_WiFi/RGB_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_RGB/RGB_WiFi/RGB_WiFi.ino new file mode 100644 index 0000000..8b79f67 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_RGB/RGB_WiFi/RGB_WiFi.ino @@ -0,0 +1,98 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +#define RGB_1 "RGBKey" + +BlinkerRGB RGB1(RGB_1); + +void rgb1_callback(uint8_t r_value, uint8_t g_value, uint8_t b_value, uint8_t bright_value) +{ + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + BLINKER_LOG("R value: ", r_value); + BLINKER_LOG("G value: ", g_value); + BLINKER_LOG("B value: ", b_value); + BLINKER_LOG("Rrightness value: ", bright_value); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); + + RGB1.brightness(random(0, 255)); + RGB1.print(random(0, 255), random(0, 255), random(0, 255)); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + RGB1.attach(rgb1_callback); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_SMS/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_SMS/.pydio new file mode 100644 index 0000000..96c3397 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_SMS/.pydio @@ -0,0 +1 @@ +8cece48d-70ba-42a6-977a-f84d8fbaf72e \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_SMS/SMS_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_SMS/SMS_WiFi/.pydio new file mode 100644 index 0000000..74b5f91 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_SMS/SMS_WiFi/.pydio @@ -0,0 +1 @@ +bcfbeea9-9afe-40f0-989b-ea990aef7701 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_SMS/SMS_WiFi/SMS_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_SMS/SMS_WiFi/SMS_WiFi.ino new file mode 100644 index 0000000..f706bcc --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_SMS/SMS_WiFi/SMS_WiFi.ino @@ -0,0 +1,84 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + uint32_t BlinkerTime = millis(); + + Blinker.vibrate(); + Blinker.print("millis", BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + Blinker.sms("Hello blinker!"); + + Blinker.delay(60000); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Slider/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Slider/.pydio new file mode 100644 index 0000000..a81d107 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Slider/.pydio @@ -0,0 +1 @@ +66cd9e53-ff04-4b96-8a8f-3988ba85545f \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Slider/Slider_BLE/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Slider/Slider_BLE/.pydio new file mode 100644 index 0000000..d1166f3 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Slider/Slider_BLE/.pydio @@ -0,0 +1 @@ +f557fe02-b140-4bb0-a1e0-a1f69a6cbf5e \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Slider/Slider_BLE/Slider_BLE.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Slider/Slider_BLE/Slider_BLE.ino new file mode 100644 index 0000000..c2e6ca3 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Slider/Slider_BLE/Slider_BLE.ino @@ -0,0 +1,91 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_BLE + +#include + +#define Slider_1 "SliderKey" + +BlinkerSlider Slider1(Slider_1); + +void slider1_callback(int32_t value) +{ + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + BLINKER_LOG("get slider value: ", value); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); + + Slider1.color("#FFFFFF"); + Slider1.print(random(0, 128)); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + Blinker.attachData(dataRead); + + Slider1.attach(slider1_callback); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Slider/Slider_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Slider/Slider_WiFi/.pydio new file mode 100644 index 0000000..9488da7 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Slider/Slider_WiFi/.pydio @@ -0,0 +1 @@ +aeaafdd3-f5b0-47f0-ab8a-64b5969b3eeb \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Slider/Slider_WiFi/Slider_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Slider/Slider_WiFi/Slider_WiFi.ino new file mode 100644 index 0000000..caaa204 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Slider/Slider_WiFi/Slider_WiFi.ino @@ -0,0 +1,95 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +#define Slider_1 "SliderKey" + +BlinkerSlider Slider1(Slider_1); + +void slider1_callback(int32_t value) +{ + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + BLINKER_LOG("get slider value: ", value); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); + + Slider1.color("#FFFFFF"); + Slider1.print(random(0, 128)); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + Slider1.attach(slider1_callback); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Summary/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Summary/.pydio new file mode 100644 index 0000000..c504174 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Summary/.pydio @@ -0,0 +1 @@ +ca57f600-425e-444b-921b-f4f6048fe20d \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Summary/Summary_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Summary/Summary_WiFi/.pydio new file mode 100644 index 0000000..1a4148f --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Summary/Summary_WiFi/.pydio @@ -0,0 +1 @@ +3047277e-9894-4b6f-a4d8-b518690e9946 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Summary/Summary_WiFi/Summary_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Summary/Summary_WiFi/Summary_WiFi.ino new file mode 100644 index 0000000..e7318fd --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Summary/Summary_WiFi/Summary_WiFi.ino @@ -0,0 +1,117 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +bool switch_state = false; + +void switch_callback(const String & state) +{ + BLINKER_LOG("get switch state: ", state); + + if (state == BLINKER_CMD_ON) { + switch_state = true; + digitalWrite(LED_BUILTIN, HIGH); + + BUILTIN_SWITCH.print("on"); + } + else if (state == BLINKER_CMD_OFF) { + switch_state = false; + digitalWrite(LED_BUILTIN, LOW); + + BUILTIN_SWITCH.print("off"); + } +} + +void heartbeat() +{ + if (switch_state) BUILTIN_SWITCH.print("on"); + else BUILTIN_SWITCH.print("off"); +} + +String summary() +{ + String data = "online, switch: " + STRING_format(switch_state ? "on" : "off"); + + return data; +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + Blinker.attachHeartbeat(heartbeat); + Blinker.attachSummary(summary); + + BUILTIN_SWITCH.attach(switch_callback); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Switch/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Switch/.pydio new file mode 100644 index 0000000..7517461 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Switch/.pydio @@ -0,0 +1 @@ +af737a0a-58ca-45cd-8bf8-21d17bdbf29d \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Switch/Switch_BLE/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Switch/Switch_BLE/.pydio new file mode 100644 index 0000000..a61a864 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Switch/Switch_BLE/.pydio @@ -0,0 +1 @@ +aafbc814-eb00-4eb3-857f-d82289d7539b \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Switch/Switch_BLE/Switch_BLE.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Switch/Switch_BLE/Switch_BLE.ino new file mode 100644 index 0000000..906653b --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Switch/Switch_BLE/Switch_BLE.ino @@ -0,0 +1,80 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_BLE + +#include + +void switch_callback(const String & state) +{ + BLINKER_LOG("get switch state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + BUILTIN_SWITCH.print("on"); + } + else { + digitalWrite(LED_BUILTIN, LOW); + BUILTIN_SWITCH.print("off"); + } +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + + BUILTIN_SWITCH.attach(switch_callback); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Switch/Switch_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Switch/Switch_WiFi/.pydio new file mode 100644 index 0000000..248ba6c --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Switch/Switch_WiFi/.pydio @@ -0,0 +1 @@ +61db7881-c65d-4e20-851f-7ab47bb2d317 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Switch/Switch_WiFi/Switch_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Switch/Switch_WiFi/Switch_WiFi.ino new file mode 100644 index 0000000..1a2d39b --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Switch/Switch_WiFi/Switch_WiFi.ino @@ -0,0 +1,84 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void switch_callback(const String & state) +{ + BLINKER_LOG("get switch state: ", state); + + if (state == BLINKER_CMD_ON) { + digitalWrite(LED_BUILTIN, HIGH); + BUILTIN_SWITCH.print("on"); + } + else { + digitalWrite(LED_BUILTIN, LOW); + BUILTIN_SWITCH.print("off"); + } +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + + BUILTIN_SWITCH.attach(switch_callback); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/.pydio new file mode 100644 index 0000000..35336f3 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/.pydio @@ -0,0 +1 @@ +404433bd-cade-4004-8d0f-e66946375751 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/TEXT_BLE/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/TEXT_BLE/.pydio new file mode 100644 index 0000000..b8e0ea2 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/TEXT_BLE/.pydio @@ -0,0 +1 @@ +73927cea-abd6-4268-8345-07ec6d84891f \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/TEXT_BLE/TEXT_BLE.ino b/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/TEXT_BLE/TEXT_BLE.ino new file mode 100644 index 0000000..bfc598a --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/TEXT_BLE/TEXT_BLE.ino @@ -0,0 +1,84 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_BLE + +#include + +#define TEXTE_1 "TextKey" + +BlinkerText Text1(TEXTE_1); + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); + + Text1.print("os time", BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/TEXT_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/TEXT_WiFi/.pydio new file mode 100644 index 0000000..b42af7e --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/TEXT_WiFi/.pydio @@ -0,0 +1 @@ +18a52050-1859-435f-8186-9158e6a4c3a6 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/TEXT_WiFi/TEXT_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/TEXT_WiFi/TEXT_WiFi.ino new file mode 100644 index 0000000..18ec590 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_TEXT/TEXT_WiFi/TEXT_WiFi.ino @@ -0,0 +1,88 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +#define TEXTE_1 "TextKey" + +BlinkerText Text1(TEXTE_1); + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); + + Text1.print("os time", BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Tab/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Tab/.pydio new file mode 100644 index 0000000..719495c --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Tab/.pydio @@ -0,0 +1 @@ +cfbb5f44-7168-446b-b6fc-3af656dcf082 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Tab/Tab_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Tab/Tab_WiFi/.pydio new file mode 100644 index 0000000..10709c9 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Tab/Tab_WiFi/.pydio @@ -0,0 +1 @@ +07345ac7-d8e5-4d27-81b6-a71b4f556bf5 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Tab/Tab_WiFi/Tab_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Tab/Tab_WiFi/Tab_WiFi.ino new file mode 100644 index 0000000..6e4e38e --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Tab/Tab_WiFi/Tab_WiFi.ino @@ -0,0 +1,133 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +#define Tab_1 "TabKey" + +BlinkerTab Tab1(Tab_1); + +bool tab[5] = { false }; + +void tab1_callback(uint8_t tab_set) +{ + BLINKER_LOG("get tab set: ", tab_set); + + switch (tab_set) + { + case BLINKER_CMD_TAB_0 : + tab[0] = true; + BLINKER_LOG("tab 0 set"); + break; + case BLINKER_CMD_TAB_1 : + tab[1] = true; + BLINKER_LOG("tab 1 set"); + break; + case BLINKER_CMD_TAB_2 : + tab[2] = true; + BLINKER_LOG("tab 2 set"); + break; + case BLINKER_CMD_TAB_3 : + tab[3] = true; + BLINKER_LOG("tab 3 set"); + break; + case BLINKER_CMD_TAB_4 : + tab[4] = true; + BLINKER_LOG("tab 4 set"); + break; + default: + break; + } +} + +void tab1_feedback() +{ + for(uint8_t num = 0; num < 5; num++) + { + if (tab[num]) + { + Tab1.tab(num); + tab[num] = false; + } + } + Tab1.print(); +} + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + Tab1.attach(tab1_callback, tab1_feedback); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Time/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Time/.pydio new file mode 100644 index 0000000..0e92cf1 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Time/.pydio @@ -0,0 +1 @@ +845bce52-a65b-4be3-b00a-a3c977ffc0b1 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Time/Time_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_Time/Time_WiFi/.pydio new file mode 100644 index 0000000..af7196f --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Time/Time_WiFi/.pydio @@ -0,0 +1 @@ +5ac90d11-4d5f-4164-802d-ca8b8567d876 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_Time/Time_WiFi/Time_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_Time/Time_WiFi/Time_WiFi.ino new file mode 100644 index 0000000..de23908 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_Time/Time_WiFi/Time_WiFi.ino @@ -0,0 +1,94 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + Blinker.vibrate(); + + uint32_t BlinkerTime = millis(); + + Blinker.print("millis", BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + + BLINKER_LOG("Now second: ", Blinker.second()); + BLINKER_LOG("Now minute: ", Blinker.minute()); + BLINKER_LOG("Now hour: ", Blinker.hour()); + BLINKER_LOG("Now wday: ", Blinker.wday()); + BLINKER_LOG("Now month: ", Blinker.month()); + BLINKER_LOG("Now mday: ", Blinker.mday()); + BLINKER_LOG("Now year: ", Blinker.year()); + BLINKER_LOG("Now yday: ", Blinker.yday()); + BLINKER_LOG("Now ntp time: ", Blinker.time()); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); + + Blinker.setTimezone(8.0); +} + +void loop() +{ + Blinker.run(); +} diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_WECHAT/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_WECHAT/.pydio new file mode 100644 index 0000000..7a59b9c --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_WECHAT/.pydio @@ -0,0 +1 @@ +8928836c-0f97-4887-b3c0-357044913d1b \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_WECHAT/WECHAT_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_WECHAT/WECHAT_WiFi/.pydio new file mode 100644 index 0000000..e602ea5 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_WECHAT/WECHAT_WiFi/.pydio @@ -0,0 +1 @@ +bad0a8e5-d8e6-48a6-8f30-bb11149604ac \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_WECHAT/WECHAT_WiFi/WECHAT_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_WECHAT/WECHAT_WiFi/WECHAT_WiFi.ino new file mode 100644 index 0000000..4e3ea7f --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_WECHAT/WECHAT_WiFi/WECHAT_WiFi.ino @@ -0,0 +1,84 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +void dataRead(const String & data) +{ + BLINKER_LOG("Blinker readString: ", data); + + uint32_t BlinkerTime = millis(); + + Blinker.vibrate(); + Blinker.print("millis", BlinkerTime); + + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + Blinker.wechat("Hello blinker!","state","message"); + + Blinker.delay(60000); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + Blinker.attachData(dataRead); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/.pydio new file mode 100644 index 0000000..9a51ad5 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/.pydio @@ -0,0 +1 @@ +dd9126d7-6388-4a28-a8a2-d88763fb9062 \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/WS2812_BLE/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/WS2812_BLE/.pydio new file mode 100644 index 0000000..99cda1f --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/WS2812_BLE/.pydio @@ -0,0 +1 @@ +2fe1a7ac-f5f7-427f-9149-3425d067cd8f \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/WS2812_BLE/WS2812_BLE.ino b/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/WS2812_BLE/WS2812_BLE.ino new file mode 100644 index 0000000..c873d15 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/WS2812_BLE/WS2812_BLE.ino @@ -0,0 +1,99 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_BLE + +#include + +// Download Adafruit_NeoPixel library here: +// https://github.com/adafruit/Adafruit_NeoPixel +#include +#ifdef __AVR__ + #include +#endif + +#define PIN 13 +#define NUMPIXELS 9 +Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); + +#define RGB_1 "RGBKey" + +BlinkerRGB WS2812(RGB_1); + +void ws2812_callback(uint8_t r_value, uint8_t g_value, uint8_t b_value, uint8_t bright_value) +{ + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + BLINKER_LOG("R value: ", r_value); + BLINKER_LOG("G value: ", g_value); + BLINKER_LOG("B value: ", b_value); + BLINKER_LOG("Rrightness value: ", bright_value); + + pixels.setBrightness(bright_value); + + for(int i = 0; i < NUMPIXELS; i++){ + pixels.setPixelColor(i, r_value, g_value, b_value); + } + pixels.show(); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(); + + pixels.begin(); + + WS2812.attach(ws2812_callback); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/WS2812_WiFi/.pydio b/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/WS2812_WiFi/.pydio new file mode 100644 index 0000000..19b9956 --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/WS2812_WiFi/.pydio @@ -0,0 +1 @@ +a14c9bb3-c3d4-4d4d-8fd2-7bb5d402afaa \ No newline at end of file diff --git a/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/WS2812_WiFi/WS2812_WiFi.ino b/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/WS2812_WiFi/WS2812_WiFi.ino new file mode 100644 index 0000000..1126e7d --- /dev/null +++ b/blinker-library/examples/Blinker_Widgets/Blinker_WS2812/WS2812_WiFi/WS2812_WiFi.ino @@ -0,0 +1,103 @@ +/* ***************************************************************** + * + * Download latest Blinker library here: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * + * Blinker is a cross-hardware, cross-platform solution for the IoT. + * It provides APP, device and server support, + * and uses public cloud services for data transmission and storage. + * It can be used in smart home, data monitoring and other fields + * to help users build Internet of Things projects better and faster. + * + * Make sure installed 2.7.4 or later ESP8266/Arduino package, + * if use ESP8266 with Blinker. + * https://github.com/esp8266/Arduino/releases + * + * Make sure installed 1.0.5 or later ESP32/Arduino package, + * if use ESP32 with Blinker. + * https://github.com/espressif/arduino-esp32/releases + * + * Docs: https://diandeng.tech/doc + * + * + * ***************************************************************** + * + * Blinker 库下载地址: + * https://github.com/blinker-iot/blinker-library/archive/master.zip + * + * Blinker 是一套跨硬件、跨平台的物联网解决方案,提供APP端、设备端、 + * 服务器端支持,使用公有云服务进行数据传输存储。可用于智能家居、 + * 数据监测等领域,可以帮助用户更好更快地搭建物联网项目。 + * + * 如果使用 ESP8266 接入 Blinker, + * 请确保安装了 2.7.4 或更新的 ESP8266/Arduino 支持包。 + * https://github.com/esp8266/Arduino/releases + * + * 如果使用 ESP32 接入 Blinker, + * 请确保安装了 1.0.5 或更新的 ESP32/Arduino 支持包。 + * https://github.com/espressif/arduino-esp32/releases + * + * 文档: https://diandeng.tech/doc + * + * + * *****************************************************************/ + +#define BLINKER_WIFI + +#include + +char auth[] = "Your Device Secret Key"; +char ssid[] = "Your WiFi network SSID or name"; +char pswd[] = "Your WiFi network WPA password or WEP key"; + +// Download Adafruit_NeoPixel library here: +// https://github.com/adafruit/Adafruit_NeoPixel +#include +#ifdef __AVR__ + #include +#endif + +#define PIN 13 +#define NUMPIXELS 9 +Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); + +#define RGB_1 "RGBKey" + +BlinkerRGB WS2812(RGB_1); + +void ws2812_callback(uint8_t r_value, uint8_t g_value, uint8_t b_value, uint8_t bright_value) +{ + digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); + BLINKER_LOG("R value: ", r_value); + BLINKER_LOG("G value: ", g_value); + BLINKER_LOG("B value: ", b_value); + BLINKER_LOG("Rrightness value: ", bright_value); + + pixels.setBrightness(bright_value); + + for(int i = 0; i < NUMPIXELS; i++){ + pixels.setPixelColor(i, r_value, g_value, b_value); + } + pixels.show(); +} + +void setup() +{ + Serial.begin(115200); + BLINKER_DEBUG.stream(Serial); + + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + + Blinker.begin(auth, ssid, pswd); + + pixels.begin(); + + WS2812.attach(ws2812_callback); +} + +void loop() +{ + Blinker.run(); +} \ No newline at end of file diff --git a/blinker-library/keywords.txt b/blinker-library/keywords.txt new file mode 100644 index 0000000..a47e115 --- /dev/null +++ b/blinker-library/keywords.txt @@ -0,0 +1,344 @@ +####################################### +# Data types (KEYWORD1) +####################################### +Blinker KEYWORD1 +BlinkerButton KEYWORD1 +BlinkerRGB KEYWORD1 +BlinkerSlider KEYWORD1 +BlinkerNumber KEYWORD1 +BlinkerImage KEYWORD1 +BlinkerTab KEYWORD1 +BlinkerText KEYWORD1 +BlinkerJoystick KEYWORD1 +BlinkerBridge KEYWORD1 +BUILTIN_SWITCH KEYWORD1 +BLINKER_DEBUG KEYWORD1 +BlinkerTimer KEYWORD1 +BlinkerTicker KEYWORD1 + +BlinkerAliGenie KEYWORD1 +BlinkerDuerOS KEYWORD1 +BlinkerMIOT KEYWORD1 +BlinkerUpdater KEYWORD1 +BlinkerEvent KEYWORD1 +BLINKER_PROTOCOL_MQTT KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +BLINKER_TAST_INIT KEYWORD2 +deviceName KEYWORD2 + +auth KEYWORD2 +ssid KEYWORD2 +pswd KEYWORD2 +begin KEYWORD2 +connect KEYWORD2 +disconnect KEYWORD2 +connected KEYWORD2 +connected KEYWORD2 +available KEYWORD2 +readString KEYWORD2 +print KEYWORD2 +printObject KEYWORD2 +delay KEYWORD2 +notify KEYWORD2 +attachDataStorage KEYWORD2 +attachHeartbeat KEYWORD2 +attachParse KEYWORD2 +attachClick KEYWORD2 +attachDoubleClick KEYWORD2 +attachLongPressStart KEYWORD2 +attachLongPressStop KEYWORD2 +attachDuringLongPress KEYWORD2 +attachLongPressPowerdown KEYWORD2 +attachLongPressReset KEYWORD2 +attachNoButtonReset KEYWORD2 +attachAQI KEYWORD2 +attachAir KEYWORD2 +attachWeather KEYWORD2 +attachWeatherForecast KEYWORD2 +attachConfigGet KEYWORD2 +attachDataGet KEYWORD2 +pressedTime KEYWORD2 +attach KEYWORD2 +icon KEYWORD2 +color KEYWORD2 +text KEYWORD2 +brightness KEYWORD2 +unit KEYWORD2 +ahrs KEYWORD2 +attachAhrs KEYWORD2 +detachAhrs KEYWORD2 +gps KEYWORD2 +event KEYWORD2 +vibrate KEYWORD2 +timingState KEYWORD2 +loopState KEYWORD2 +countdownState KEYWORD2 +deleteTiming KEYWORD2 +deleteLoop KEYWORD2 +deleteCountdown KEYWORD2 +deleteTimer KEYWORD2 +setTimezone KEYWORD2 +time KEYWORD2 +second KEYWORD2 +minute KEYWORD2 +hour KEYWORD2 +wday KEYWORD2 +mday KEYWORD2 +yday KEYWORD2 +month KEYWORD2 +year KEYWORD2 +bridge KEYWORD2 +bridgeAvailable KEYWORD2 +bridgeRead KEYWORD2 +bridgePrint KEYWORD2 +bridgeBeginFormat KEYWORD2 +bridgeEndFormat KEYWORD2 +configUpdate KEYWORD2 +configGet KEYWORD2 +configDelete KEYWORD2 +timeSlotData KEYWORD2 +textData KEYWORD2 +jsonData KEYWORD2 +dataStorage KEYWORD2 +dataUpdate KEYWORD2 +dataGet KEYWORD2 +dataDelete KEYWORD2 +sms KEYWORD2 +push KEYWORD2 +wechat KEYWORD2 +weather KEYWORD2 +weatherForecast KEYWORD2 +aqi KEYWORD2 +air KEYWORD2 +status KEYWORD2 +flush KEYWORD2 +init KEYWORD2 +beginAuto KEYWORD2 +autoInput KEYWORD2 +autoInput KEYWORD2 +autoRun KEYWORD2 +setType KEYWORD2 +type KEYWORD2 +reset KEYWORD2 +tick KEYWORD2 +lang KEYWORD2 +lat KEYWORD2 +warning KEYWORD2 +error KEYWORD2 +message KEYWORD2 +BLINKER_LOG KEYWORD2 +BLINKER_LOG KEYWORD2 +BLINKER_LOG KEYWORD2 +BLINKER_LOG KEYWORD2 +BLINKER_LOG KEYWORD2 +BLINKER_LOG KEYWORD2 +BLINKER_LOG KEYWORD2 +BLINKER_ERR_LOG KEYWORD2 +BLINKER_LOG_FreeHeap KEYWORD2 +BLINKER_LOG_FreeHeap_ALL KEYWORD2 +BLINKER_F KEYWORD2 +BLINKER_PRINT KEYWORD2 +BLINKER_DEBUG_ALL KEYWORD2 +BLINKER_ESP_SMARTCONFIG KEYWORD2 +BLINKER_APCONFIG KEYWORD2 +BLINKER_WIFI_MULTI KEYWORD2 +BLINKER_BLE KEYWORD2 +BLINKER_WIFI KEYWORD2 +BLINKER_WITHOUT_SSL KEYWORD2 +BLINKER_WIFI_AUTO KEYWORD2 +BLINKER_LOWPOWER KEYWORD2 +BLINKER_LOWPOWER_AIR202 KEYWORD2 +BLINKER_MQTT KEYWORD2 +BLINKER_MQTT_AUTO KEYWORD2 +BLINKER_WIFI_GATEWAY KEYWORD2 +BLINKER_WIFI_SUBDEVICE KEYWORD2 +BLINKER_PRO KEYWORD2 +BLINKER_PRO_ESP KEYWORD2 +BLINKER_ESP_TASK KEYWORD2 +BLINKER_AT_MQTT KEYWORD2 +BLINKER_AT_PRO KEYWORD2 +BLINKER_NBIOT_WH KEYWORD2 +BLINKER_GPRS_AIR202 KEYWORD2 +BLINKER_GPRS KEYWORD2 +BLINKER_NBIOT_SIM7020 KEYWORD2 +BLINKER_NBIOT_SIM7000 KEYWORD2 +BLINKER_QRCODE_NBIOT_SIM7020 KEYWORD2 +BLINKER_QRCODE_NBIOT_SIM7000 KEYWORD2 +BLINKER_PRO_SIM7020 KEYWORD2 +BLINKER_PRO_AIR202 KEYWORD2 +BLINKER_ESP_AT KEYWORD2 +BLINKER_NO_BUTTON KEYWORD2 +BLINKER_BUTTON KEYWORD2 +BLINKER_BUTTON_PIN KEYWORD2 +BLINKER_BUTTON_PULLDOWN KEYWORD2 +BLINKER_BUTTON_LONGPRESS_POWERDOWN KEYWORD2 + +BLINKER_MAX_SEND_SIZE KEYWORD2 +BLINKER_MAX_READ_SIZE KEYWORD2 + +BLINKER_ALIGENIE_LIGHT KEYWORD2 +BLINKER_ALIGENIE_OUTLET KEYWORD2 +BLINKER_ALIGENIE_MULTI_OUTLET KEYWORD2 +BLINKER_ALIGENIE_SWITCH KEYWORD2 +BLINKER_ALIGENIE_SENSOR KEYWORD2 +BLINKER_ALIGENIE_FAN KEYWORD2 +BLINKER_ALIGENIE_AIRCONDITION KEYWORD2 + +BLINKER_DUEROS_LIGHT KEYWORD2 +BLINKER_DUEROS_OUTLET KEYWORD2 +BLINKER_DUEROS_MULTI_OUTLET KEYWORD2 +BLINKER_DUEROS_SWITCH KEYWORD2 +BLINKER_DUEROS_SENSOR KEYWORD2 +BLINKER_DUEROS_FAN KEYWORD2 +BLINKER_DUEROS_AIRCONDITION KEYWORD2 + +BLINKER_MIOT_LIGHT KEYWORD2 +BLINKER_MIOT_OUTLET KEYWORD2 +BLINKER_MIOT_MULTI_OUTLET KEYWORD2 +BLINKER_MIOT_SWITCH KEYWORD2 +BLINKER_MIOT_SENSOR KEYWORD2 +BLINKER_MIOT_FAN KEYWORD2 +BLINKER_MIOT_AIRCONDITION KEYWORD2 + +BLINKER_CMD_READING KEYWORD2 +BLINKER_CMD_MOVIE KEYWORD2 +BLINKER_CMD_SLEEP KEYWORD2 +BLINKER_CMD_HOLIDAY KEYWORD2 +BLINKER_CMD_MUSIC KEYWORD2 +BLINKER_CMD_COMMON KEYWORD2 + +BLINKER_CMD_ON KEYWORD2 +BLINKER_CMD_OFF KEYWORD2 + +BLINKER_CMD_QUERY_ALL_NUMBER KEYWORD2 +BLINKER_CMD_QUERY_POWERSTATE_NUMBER KEYWORD2 +BLINKER_CMD_QUERY_COLOR_NUMBER KEYWORD2 +BLINKER_CMD_QUERY_MODE_NUMBER KEYWORD2 +BLINKER_CMD_QUERY_COLORTEMP_NUMBER KEYWORD2 +BLINKER_CMD_QUERY_BRIGHTNESS_NUMBER KEYWORD2 +BLINKER_CMD_QUERY_TEMP_NUMBER KEYWORD2 +BLINKER_CMD_QUERY_HUMI_NUMBER KEYWORD2 +BLINKER_CMD_QUERY_PM25_NUMBER KEYWORD2 +BLINKER_CMD_QUERY_PM10_NUMBER KEYWORD2 +BLINKER_CMD_QUERY_CO2_NUMBER KEYWORD2 +BLINKER_CMD_QUERY_AQI_NUMBER KEYWORD2 + +BLINKER_CMD_TAB_0 KEYWORD2 +BLINKER_CMD_TAB_1 KEYWORD2 +BLINKER_CMD_TAB_2 KEYWORD2 +BLINKER_CMD_TAB_3 KEYWORD2 +BLINKER_CMD_TAB_4 KEYWORD2 + +BLINKER_CMD_ALIGENIE_READING KEYWORD2 +BLINKER_CMD_ALIGENIE_MOVIE KEYWORD2 +BLINKER_CMD_ALIGENIE_SLEEP KEYWORD2 +BLINKER_CMD_ALIGENIE_HOLIDAY KEYWORD2 +BLINKER_CMD_ALIGENIE_MUSIC KEYWORD2 +BLINKER_CMD_ALIGENIE_COMMON KEYWORD2 + +BLINKER_CMD_DUEROS_READING KEYWORD2 +BLINKER_CMD_DUEROS_SLEEP KEYWORD2 +BLINKER_CMD_DUEROS_ALARM KEYWORD2 +BLINKER_CMD_DUEROS_NIGHT_LIGHT KEYWORD2 +BLINKER_CMD_DUEROS_ROMANTIC KEYWORD2 +BLINKER_CMD_DUEROS_SUNDOWN KEYWORD2 +BLINKER_CMD_DUEROS_SUNRISE KEYWORD2 +BLINKER_CMD_DUEROS_RELAX KEYWORD2 +BLINKER_CMD_DUEROS_LIGHTING KEYWORD2 +BLINKER_CMD_DUEROS_SUN KEYWORD2 +BLINKER_CMD_DUEROS_STAR KEYWORD2 +BLINKER_CMD_DUEROS_ENERGY_SAVING KEYWORD2 +BLINKER_CMD_DUEROS_MOON KEYWORD2 +BLINKER_CMD_DUEROS_JUDI KEYWORD2 + +BLINKER_CMD_MIOT_DAY KEYWORD2 +BLINKER_CMD_MIOT_NIGHT KEYWORD2 +BLINKER_CMD_MIOT_COLOR KEYWORD2 +BLINKER_CMD_MIOT_WARMTH KEYWORD2 +BLINKER_CMD_MIOT_TV KEYWORD2 +BLINKER_CMD_MIOT_READING KEYWORD2 +BLINKER_CMD_MIOT_COMPUTER KEYWORD2 + +attachPowerState KEYWORD2 +attachColor KEYWORD2 +attachMode KEYWORD2 +attachCancelMode KEYWORD2 +attachBrightness KEYWORD2 +attachRelativeBrightness KEYWORD2 +attachColorTemperature KEYWORD2 +attachRelativeColorTemperature KEYWORD2 +attachQuery KEYWORD2 +attachSummary KEYWORD2 +attachData KEYWORD2 +attachAir202Reset KEYWORD2 +attachSIM7020Reset KEYWORD2 +attachSleep KEYWORD2 +attachLowPower KEYWORD2 +attachHSwing KEYWORD2 +attachVSwing KEYWORD2 +attachLevel KEYWORD2 +attachRelativeLevel KEYWORD2 +attachTemp KEYWORD2 +attachRelativeTemp KEYWORD2 +attachECO KEYWORD2 +attachAnion KEYWORD2 +attachHeater KEYWORD2 +attachDryer KEYWORD2 +attachSleep KEYWORD2 +attachSoft KEYWORD2 +attachUV KEYWORD2 +attachUnStraightBlow KEYWORD2 +attachHumi KEYWORD2 +hswing KEYWORD2 +vswing KEYWORD2 +eco KEYWORD2 +anion KEYWORD2 +heater KEYWORD2 +dryer KEYWORD2 +sleep KEYWORD2 +soft KEYWORD2 +uv KEYWORD2 +unStraightBlow KEYWORD2 +level KEYWORD2 +STRING_format KEYWORD2 +powerState KEYWORD2 +colorTemp KEYWORD2 +temp KEYWORD2 +humi KEYWORD2 +pm25 KEYWORD2 +pm10 KEYWORD2 +ppm KEYWORD2 +co2 KEYWORD2 +mode KEYWORD2 +tab KEYWORD2 +report KEYWORD2 + +stream KEYWORD2 +debugAll KEYWORD2 +BLINKER_OTA_VERSION_CODE KEYWORD2 + +attachGatewayAvailable KEYWORD2 +attachGatewayRead KEYWORD2 +attachGatewayPrint KEYWORD2 + +attachSubAvailable KEYWORD2 +attachSubRead KEYWORD2 +attachSubPrint KEYWORD2 + +configType KEYWORD2 +apConfigInit KEYWORD2 +esptouchInit KEYWORD2 + +####################################### +# Literals (LITERAL1) +####################################### +Yaw LITERAL1 +Roll LITERAL1 +Pitch LITERAL1 +LONG LITERAL1 +LAT LITERAL1 +BLINKER_AP_CONFIG LITERAL1 +BLINKER_SMART_CONFIG LITERAL1 diff --git a/blinker-library/library.json b/blinker-library/library.json new file mode 100644 index 0000000..59e096c --- /dev/null +++ b/blinker-library/library.json @@ -0,0 +1,28 @@ +{ + "name": "Blinker", + "description": "Build a easy way for your IoT project. Blinker library for embedded hardware. Works with Arduino, ESP8266, ESP32.", + "keywords": "wifi, websocket, Bluetooth, mqtt", + "authors": [ + { + "name": "i3water", + "url": "https://github.com/i3water", + "maintainer": true + } + ], + "repository": { + "type": "git", + "url": "https://github.com/blinker-iot/blinker-library.git" + }, + "version": "0.3.80210803", + "homepage": "https://diandeng.tech/home", + "export": { + "exclude": [ + "tests" + ] + }, + "frameworks": "arduino", + "platforms": "*", + "examples": [ + "examples/*/*/*.ino" + ] +} diff --git a/blinker-library/library.properties b/blinker-library/library.properties new file mode 100644 index 0000000..d4cb968 --- /dev/null +++ b/blinker-library/library.properties @@ -0,0 +1,9 @@ +name=Blinker +version=0.3.80210803 +author=i3water +maintainer=i3wawter +sentence=Build a easy way for your IoT project. +paragraph=Blinker library for embedded hardware. Support Arduino, ESP8266, ESP32, WiFi, BLE, MQTT. +category=Communication +url=https://diandeng.tech/home +architectures=* diff --git a/blinker-library/src/.pydio b/blinker-library/src/.pydio new file mode 100644 index 0000000..4971b75 --- /dev/null +++ b/blinker-library/src/.pydio @@ -0,0 +1 @@ +d08c8d20-3c08-489a-8bb2-41941fab5f08 \ No newline at end of file diff --git a/blinker-library/src/Adapters/.pydio b/blinker-library/src/Adapters/.pydio new file mode 100644 index 0000000..c50378c --- /dev/null +++ b/blinker-library/src/Adapters/.pydio @@ -0,0 +1 @@ +e9f64442-df63-4f37-aeb4-073788d04005 \ No newline at end of file diff --git a/blinker-library/src/Adapters/BlinkerAIR202LP.h b/blinker-library/src/Adapters/BlinkerAIR202LP.h new file mode 100644 index 0000000..6dc3d11 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerAIR202LP.h @@ -0,0 +1,370 @@ +#ifndef BLINKER_AIR202_LP_H +#define BLINKER_AIR202_LP_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" +#include "../Functions/BlinkerAIR202.h" +#include "../Functions/BlinkerHTTPAIR202.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif + +class BlinkerAIR202LP : public BlinkerStream +{ + public : + BlinkerAIR202LP() + : stream(NULL), isConnect(false) + {} + + int connect() { return isGPRSinit ? true : false; } + int connected() { return isGPRSinit ? true : false; } + void disconnect() { delay(1); } + void ping() { delay(1); } + int available() + { + dataGet(); + if (isAvail) + { + isAvail = false; return true; + } + else return false; + } + char * lastRead() { if (isFresh) return msgBuf; return ""; } + void flush() { if (isFresh) { free(msgBuf); isFresh = false; isAvail = false; } } + void dataGet(); + int print(char * data, bool needCheck = true); + void begin(const char* _key, const char* _deviceType, String _imei); + void initStream(Stream& s, bool state, blinker_callback_t func); + char * deviceName() { return _deviceName; } + char * authKey() { return _authKey; } + char * token() { if (!isGPRSinit) return ""; else return _authKey; } + int init() { return isGPRSinit; } + int deviceRegister() { return connectServer(); } + + private : + bool isGPRSinit = false; + int connectServer(); + + protected : + Stream* stream; + char* msgBuf; + bool isConnect; + bool isHWS = false; + char* imei; + bool isAvail = false; + bool isFresh = false; + bool _isAuthKey = false; + const char* _vipKey; + const char* _deviceType; + char* _authKey; + char* _deviceName; + + blinker_callback_t listenFunc = NULL; +}; + +int BlinkerAIR202LP::print(char * data, bool needCheck) +{ + String msg = BLINKER_F("{\"deviceName\":\""); + msg += _deviceName; + msg += BLINKER_F("\",\"key\":\""); + msg += _authKey; + msg += BLINKER_F("\",\"data\":"); + msg += data; + msg += BLINKER_F("}"); + + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + String url_iot = BLINKER_F("/api/v1/user/device/lowpower/data"); + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host + url_iot); + + BlinkerHTTPAIR202 http(*stream, isHWS, listenFunc); + + String conType = BLINKER_F("Content-Type"); + String application = BLINKER_F("application/json;charset=utf-8"); + + http.begin(host, url_iot); + + String payload; + + if (http.POST(msg, conType, application)) + { + BLINKER_LOG(BLINKER_F("[HTTP] ... success")); + + payload = http.getString(); + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed")); + + return false; + } + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& data_rp = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject data_rp = jsonBuffer.as(); + + // if (data_rp.success()) + if (!error) + { + uint16_t msg_code = data_rp[BLINKER_CMD_MESSAGE]; + if (msg_code != 1000) + { + String _detail = data_rp[BLINKER_CMD_DETAIL]; + BLINKER_ERR_LOG(_detail); + } + else + { + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DATA].as(); + } + } + + BLINKER_LOG_ALL(BLINKER_F("payload: "), payload); + + return true; +} + +void BlinkerAIR202LP::dataGet() +{ + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + String uri = ""; + uri += BLINKER_F("/api/v1/user/device/lowpower/data?deviceName="); + uri += _deviceName; + uri += BLINKER_F("&key="); + uri += _authKey; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host + uri); + + BlinkerHTTPAIR202 http(*stream, isHWS, listenFunc); + + http.begin(host, uri); + + String payload; + + if (http.GET()) + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... success")); + + payload = http.getString(); + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed")); + + return; + } + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& data_rp = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject data_rp = jsonBuffer.as(); + + // if (data_rp.success()) + if (!error) + { + uint16_t msg_code = data_rp[BLINKER_CMD_MESSAGE]; + if (msg_code != 1000) + { + String _detail = data_rp[BLINKER_CMD_DETAIL]; + BLINKER_ERR_LOG(_detail); + } + else + { + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DATA].as(); + if (isFresh) free(msgBuf); + + if (payload != "{}") + { + msgBuf = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(msgBuf, payload.c_str()); + isFresh = true; + isAvail = true; + + BLINKER_LOG_ALL(BLINKER_F("isAvail")); + } + } + } + + BLINKER_LOG_ALL(BLINKER_F("payload: "), payload); +} + +void BlinkerAIR202LP::begin(const char* _key, const char* _type, String _imei) +{ + _vipKey = _key; + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + imei = (char*)malloc((_imei.length() + 1)*sizeof(char)); + strcpy(imei, _imei.c_str()); + + // authKey = (char*)malloc((strlen(_deviceType) + 1)*sizeof(char)); + // strcpy(authKey, _deviceType); +} + +void BlinkerAIR202LP::initStream(Stream& s, bool state, blinker_callback_t func) +{ + stream = &s; + stream->setTimeout(BLINKER_STREAM_TIMEOUT); + isHWS = state; + + listenFunc = func; +} + +int BlinkerAIR202LP::connectServer() +{ + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + String uri = ""; + if (!_isAuthKey) + { + // uri += BLINKER_F("/api/v1/user/device/register?deviceType="); + // uri += _deviceType; + // uri += BLINKER_F("&deviceName="); + // uri += imei; + uri += BLINKER_F("/api/v1/user/device/pro/lowpower/auth/get?deviceType="); + uri += _deviceType; + uri += BLINKER_F("&vipKey="); + uri += _vipKey; + uri += BLINKER_F("&deviceName="); + uri += imei; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host + uri); + + BlinkerHTTPAIR202 http(*stream, isHWS, listenFunc); + + http.begin(host, uri); + + String payload; + + if (http.GET()) + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... success")); + + payload = http.getString(); + + // return true; + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed")); + + return false; + } + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_AUTHKEY)) { + // while(1) { + BLINKER_ERR_LOG(("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + String _getAuthKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_AUTHKEY]; + + _authKey = (char*)malloc((_getAuthKey.length()+1)*sizeof(char)); + strcpy(_authKey, _getAuthKey.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("_authKey: "), _authKey); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + _isAuthKey = true; + } + + String url_iot = BLINKER_F("/api/v1/user/device/pro/lowpower/auth?authKey="); + url_iot += _authKey; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host + url_iot); + + BlinkerHTTPAIR202 http(*stream, isHWS, listenFunc); + + http.begin(host, url_iot); + + String payload; + + if (http.GET()) + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... success")); + + payload = http.getString(); + + // return true; + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed")); + + return false; + } + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_DEVICENAME)) { + // while(1) { + BLINKER_ERR_LOG(("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + String _device_name = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + + if (isGPRSinit) + { + free(_deviceName); + + isGPRSinit = false; + } + + _deviceName = (char*)malloc((_device_name.length()+1)*sizeof(char)); + strcpy(_deviceName, _device_name.c_str()); + isGPRSinit = true; + + return true; +} + +#endif diff --git a/blinker-library/src/Adapters/BlinkerBLE.h b/blinker-library/src/Adapters/BlinkerBLE.h new file mode 100644 index 0000000..bf29af5 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerBLE.h @@ -0,0 +1,343 @@ +#ifndef BLINKER_BLE_H +#define BLINKER_BLE_H + +#if defined(ESP32) + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include +#include +#include +#include + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +class BlinkerBLE : public BlinkerStream, public BLEServerCallbacks, public BLECharacteristicCallbacks +{ + public : + BlinkerBLE() + : deviceConnected(false), isAvail(false) + {} + + void begin(); + int available(); + int read(); + int timedRead(); + char * lastRead();// { return _isFresh ? BLEBuf : ""; } + void flush(); + // bool print(String s, bool needCheck = true); + int print(char * data, bool needCheck = true); + int connect() { return deviceConnected; } + void disconnect() { deviceConnected = false; } + int connected() { return deviceConnected; } + + private : + bool deviceConnected; + char* BLEBuf;//[BLINKER_MAX_READ_SIZE]; + bool _isFresh = false; + bool isAvail; + bool isFresh; + uint32_t _bufLen; + uint32_t freshTime; + BLEServer *pServer; + BLEService *pService; + BLECharacteristic *pCharacteristic; + BLEAdvertising *pAdvertising; + BLEAdvertisementData pAdvertisementData; + uint8_t respTimes = 0; + uint32_t respTime = 0; + + + // bool isAvailBLE = false; + // uint8_t* bleReadBuf;//[20]; + // uint32_t bleReadBufLen = 0; + // uint32_t getNum = 0; + // bool isNewLine = false; + + void onConnect(BLEServer* pServer); + void onDisconnect(BLEServer* pServer); + void onWrite(BLECharacteristic *pCharacteristic); + int checkTimeOut(); + int checkPrintSpan(); +}; + +void BlinkerBLE::begin() +{ + BLEDevice::init("Blinker"); + pServer = BLEDevice::createServer(); + + pService = pServer->createService(BLEUUID((uint16_t)0xffe0));//SERVICE_UUID + pServer->setCallbacks(this); + + pCharacteristic = pService->createCharacteristic( + BLEUUID((uint16_t)0xffe1),//CHARACTERISTIC_UUID, + BLECharacteristic::PROPERTY_READ | + BLECharacteristic::PROPERTY_NOTIFY | + BLECharacteristic::PROPERTY_WRITE_NR + ); + + pCharacteristic->setCallbacks(this); + + pCharacteristic->addDescriptor(new BLE2902()); + + pCharacteristic->setValue("Blinker"); + pService->start(); + + pAdvertising = pServer->getAdvertising(); + + BLEAddress otherAddress = BLEDevice::getAddress(); + + esp_bd_addr_t ble_m_address; + memcpy(ble_m_address, otherAddress.getNative(), ESP_BD_ADDR_LEN); + char macStr[9] = { 0 }; + macStr[0] = 0x48; + macStr[1] = 0X4d; + for (uint8_t cpynum = 0; cpynum < 6; cpynum++) { + macStr[cpynum+2] = (char)ble_m_address[cpynum]; + } + + pAdvertisementData.setManufacturerData(macStr); + pAdvertising->setAdvertisementData(pAdvertisementData); + pAdvertising->addServiceUUID(BLEUUID((uint16_t)0xffe0)); + pAdvertising->start(); + + _bufLen = 0; +} + +int BlinkerBLE::available() +{ + // checkTimeOut(); + + if (_bufLen) + { + bool isNewLine = false; + + for (uint8_t num = 0; num < _bufLen; num++) + { + if (BLEBuf[num] == '\n') + { + BLEBuf[num] = '\0'; + isNewLine = true; + } + } + + if (isNewLine) + { + BLINKER_LOG_ALL(BLINKER_F("GET1: "), BLEBuf); + isAvail = true; + _isFresh = true; + + // for (uint8_t num = 0; num < _bufLen; num++) + // { + // Serial.print(BLEBuf[num]); + // } + // Serial.println(); + } + else + { + if (checkTimeOut()) + { + BLEBuf[_bufLen] = '\0'; + BLINKER_LOG_ALL(BLINKER_F("GET: "), BLEBuf); + isAvail = true; + _isFresh = true; + } + } + } + + if (isAvail) + { + BLINKER_LOG_ALL(BLINKER_F("handleBLE: "), BLEBuf); + + BLINKER_LOG_FreeHeap_ALL(); + + isAvail = false; + + return true; + } + else { + return false; + } + + return false; +} + +// int BlinkerBLE::read() +// { +// uint32_t num = getNum; +// if (num < bleReadBufLen) +// { +// getNum++; +// return bleReadBuf[num]; +// } +// else +// { +// return -1; +// } +// } + +// int BlinkerBLE::timedRead() +// { +// int c; +// uint32_t _startMillis = millis(); +// do { +// c = read(); +// if (c >= 0) return c; +// } while(millis() - _startMillis < 1000); +// return -1; +// } + +char * BlinkerBLE::lastRead() +{ + if (_isFresh) return BLEBuf; + else return ""; +} + +void BlinkerBLE::flush() +{ + if (_isFresh || _bufLen) + { + BLINKER_LOG_ALL(BLINKER_F("flush")); + free(BLEBuf); //isFresh = false; + isAvail = false; _isFresh = false; + _bufLen = 0; //isNewLine = false; + } +} + +// bool BlinkerBLE::print(String s, bool needCheck) +int BlinkerBLE::print(char * data, bool needCheck) +{ + if (needCheck) + { + if (!checkPrintSpan()) + { + respTime = millis(); + return false; + } + } + + String s = data; + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("Response: "), s); + + if (connected()) + { + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + s += BLINKER_CMD_NEWLINE; + + String s_send; + uint8_t parts = s.length()/20 + 1; + for (uint8_t num = 0; num < parts; num++) + { + if ((num + 1) == parts) + s_send = s.substring(num*(20), s.length()); + else + s_send = s.substring(num*(20), (num+1)*20); + // BLINKER_LOG_ALL("s_send: ", s_send); + pCharacteristic->setValue(s_send.c_str()); + pCharacteristic->notify(); + delay(5); + } + return true; + } + else + { + BLINKER_LOG_ALL(BLINKER_F("Faile... Disconnected")); + return false; + } +} + +void BlinkerBLE::onConnect(BLEServer* pServer) +{ + deviceConnected = true; + BLINKER_LOG_ALL("BLE connect"); +} + +void BlinkerBLE::onDisconnect(BLEServer* pServer) +{ + deviceConnected = false; + BLINKER_LOG_ALL("BLE disconnect"); + pServer->startAdvertising(); +} + +void BlinkerBLE::onWrite(BLECharacteristic *pCharacteristic) +{ + std::string value = pCharacteristic->getValue(); + int vlen = value.length(); + + if (vlen > 0) + { + int data; + uint8_t num; + + if (!_bufLen) BLEBuf = (char*)malloc(BLINKER_MAX_READ_SIZE*sizeof(char)); + + for (num = 0; num < vlen; num++) + { + data = value[num]; + if (data == '\n') + { + BLEBuf[_bufLen+num] = data; + num++; + BLINKER_LOG_ALL(BLINKER_F("GET \\n")); + break; + } + BLEBuf[_bufLen+num] = (char)data; + } + + if (_bufLen) _bufLen += num; + else _bufLen = num; + + freshTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("vlen: "), vlen); + BLINKER_LOG_ALL(BLINKER_F("_bufLen: "), _bufLen); + } +} + +int BlinkerBLE::checkTimeOut() +{ + ::delay(10); + + uint32_t timeout_ms = millis() - freshTime; + + // BLINKER_LOG_ALL(BLINKER_F("timeout_ms: "), timeout_ms); + + return timeout_ms > 1000; +} + +int BlinkerBLE::checkPrintSpan() +{ + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) + { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG("DEVICE NOT CONNECT OR MSG LIMIT"); + return false; + } + else + { + respTimes++; + return true; + } + } + else + { + respTimes = 0; + return true; + } +} + +#endif + +#endif diff --git a/blinker-library/src/Adapters/BlinkerGateway.h b/blinker-library/src/Adapters/BlinkerGateway.h new file mode 100644 index 0000000..8e218fa --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerGateway.h @@ -0,0 +1,4736 @@ +#ifndef BLINKER_GATEWAY_H +#define BLINKER_GATEWAY_H + +#if (defined(ESP8266) || defined(ESP32)) + +#if defined(ESP8266) + #include + #include + #include +#elif defined(ESP32) + #include + #include + #include +#endif + +#include + +#include "../modules/painlessMesh/painlessMesh.h" + +#include "../modules/WebSockets/WebSocketsServer.h" +#include "../modules/mqtt/Adafruit_MQTT.h" +#include "../modules/mqtt/Adafruit_MQTT_Client.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +// #include "Adapters/BlinkerGateway.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +char* MQTT_HOST_PRO; +char* MQTT_ID_PRO; +char* MQTT_NAME_PRO; +char* MQTT_KEY_PRO; +char* MQTT_PRODUCTINFO_PRO; +char* UUID_PRO; +char* AUTHKEY_PRO; +char* MQTT_DEVICEID_PRO; +// char* DEVICE_NAME; +char* BLINKER_PUB_TOPIC_PRO; +char* BLINKER_SUB_TOPIC_PRO; +uint16_t MQTT_PORT_PRO; + +painlessMesh mesh; + +#ifndef BLINKER_MESH_SSID + #define BLINKER_MESH_SSID "blinkerMesh" +#endif + +#ifndef BLINKER_MESH_PSWD + #define BLINKER_MESH_PSWD "blinkerMesh" +#endif + +#ifndef BLINKER_MESH_PORT + #define BLINKER_MESH_PORT 5555 +#endif + +char* meshBuf; +bool isFresh_mesh = false; +bool isAvail_gate = false; +bool isAvail_ctrl = false; +uint32_t msgFrom; + +BlinkerMeshSub *_subDevices[BLINKER_MAX_SUB_DEVICE_NUM]; +uint8_t _subCount = 0; +bool _newSub = false; + +int16_t _checkIdAlive(uint32_t nodeId) +{ + for (uint8_t num = 0; num < _subCount; num++) + { + if (_subDevices[num]->id() == nodeId) + { + return num; + } + } + + return -1; +} + +int16_t _checkIdAlive(const String & name) +{ + for (uint8_t num = 0; num < _subCount; num++) + { + if (_subDevices[num]->isAuth()) + { + if (_subDevices[num]->deviceName() == name) + { + return num; + } + } + } + + return -1; +} + +void _receivedCallback(uint32_t from, String &msg) +{ + BLINKER_LOG_ALL("bridge: Received from: ", from, ", msg: ",msg); + msgFrom = from; + + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, msg); + JsonObject root = jsonBuffer.as(); + + if (error) + { + BLINKER_ERR_LOG_ALL("msg not Json!"); + return; + } + + if (root.containsKey(BLINKER_CMD_GATE)) + { + BLINKER_LOG_ALL("gate data"); + + String _data = root[BLINKER_CMD_GATE]; + meshBuf = (char*)malloc((_data.length()+1)*sizeof(char)); + strcpy(meshBuf, _data.c_str()); + + isAvail_gate = true; + } + else if (root.containsKey(BLINKER_CMD_CONTROL)) + { + BLINKER_LOG_ALL("control data"); + + String _data = root[BLINKER_CMD_CONTROL]; + meshBuf = (char*)malloc((_data.length()+1)*sizeof(char)); + strcpy(meshBuf, _data.c_str()); + + isAvail_ctrl = true; + } + + + int checkId = _checkIdAlive(from); + if (checkId == -1) + { + _subDevices[_subCount] = new BlinkerMeshSub(from); + _subCount++; + } + else + { + _subDevices[checkId]->state(true); + BLINKER_LOG_ALL("fresh new"); + } + // _newSub = true; +} + +void _newConnectionCallback(uint32_t nodeId) +{ + BLINKER_LOG_ALL("--> startHere: New Connection, nodeId = ", nodeId); + BLINKER_LOG_ALL("--> startHere: New Connection, ", mesh.subConnectionJson(true)); + + int checkId = _checkIdAlive(nodeId); + if (checkId == -1) + { + _subDevices[_subCount] = new BlinkerMeshSub(nodeId); + _subCount++; + } + else + { + _subDevices[checkId]->state(true); + BLINKER_LOG_ALL("fresh new"); + } + _newSub = true; +} + +void _changedConnectionCallback() +{ + BLINKER_LOG_ALL("Changed connections"); +} + +enum b_config_t { + BLINKER_SMART_CONFIG, + BLINKER_AP_CONFIG +}; + +b_config_t _configType = BLINKER_SMART_CONFIG; + +class BlinkerGateway : public BlinkerStream +{ + public : + BlinkerGateway(); + + void setSmartConfig() { _configType = BLINKER_SMART_CONFIG; BLINKER_LOG_ALL(BLINKER_F("SmartConfig")); } + void setApConfig() { _configType = BLINKER_AP_CONFIG; BLINKER_LOG_ALL(BLINKER_F("ApConfig")); } + bool checkSmartConfig() { return _configType == BLINKER_SMART_CONFIG; } + int connect(); + int connected(); + int mConnected();// { if (!isMQTTinit) return false; else return mqtt->connected(); } + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + int miAvail(); + // bool extraAvailable(); + void subscribe(); + char * lastRead(); + void flush(); + int print(char * data, bool needCheck = true); + int toServer(char * data); + int subPrint(const String & data, const String & toDevice, const String & subDevice); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int subAliPrint(const String & data, const String & subDevice); + int duerPrint(const String & data, bool report = false); + int subDuerPrint(const String & data, const String & subDevice); + int miPrint(const String & data); + int subMiPrint(const String & data, const String & subDevice); + // void aliType(const String & type); + void begin(const char* _key, const char* _type); + int autoPrint(unsigned long id); + // bool autoPrint(char *name, char *type, char *data); + // bool autoPrint(char *name1, char *type1, char *data1, \ + // char *name2, char *type2, char *data2); + char * deviceName(); + char * authKey() { return AUTHKEY_PRO; } + int init() { return isMQTTinit; } + int reRegister() { return connectServer(); } + int deviceRegister() { return connectServer(); } + int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + void setTimezone(float tz) { _timezone = tz; } + + private : + bool isMQTTinit = false; + bool isWSinit = false; + + int connectServer(); + void mDNSInit(String name = macDeviceName()); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkMIOTKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + int checkMIOTPrintSpan(); + int pubHello(); + String vasDecode(uint16_t num); + bool meshInit(); + void meshCheck(); + void sendBroadcast(String msg); + bool sendSingle(uint32_t toId, String msg); + String gateFormat(const String & msg); + bool subRegister(uint32_t num); + time_t time(); + String blinkerServer(uint8_t _type, const String & msg); + + protected : + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + const char* _vipKey; + const char* _deviceType; + // char* _authKey; + // char* _aliType; + bool* isHandle;// = &isConnect; + // bool* isHandle = &isConnect_PRO; + bool isAlive = false; + bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + uint8_t respMIOTTimes = 0; + uint32_t respMIOTTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + uint32_t miKaTime = 0; + bool isMIOTAlive = false; + bool isMIOTAvail = false; + + bool isNew = false; + bool isAuth = false; + bool isFirst = false; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; + uint32_t _reRegister_time = 0; + uint8_t _reRegister_times = 0; + + bool _isAuthKey = false; + bool _isMeshInit = false; + uint32_t _meshCheckTime = 0; + float _timezone = 8.0; +}; + +// #if defined(ESP8266) +// extern BearSSL::WiFiClientSecure client_mqtt; +// // WiFiClientSecure client_mqtt; +// #elif defined(ESP32) +// extern WiFiClientSecure client_s; +// #endif + +// extern WiFiClient client; + + +#if defined(ESP8266) + BearSSL::WiFiClientSecure client_mqtt; + // WiFiClientSecure client_mqtt; +#elif defined(ESP32) + WiFiClientSecure client_s; +#endif + +// WiFiClient client; +Adafruit_MQTT_Client* mqtt_PRO; +// Adafruit_MQTT_Publish *iotPub; +Adafruit_MQTT_Subscribe* iotSub_PRO; + +#define WS_SERVERPORT 81 +WebSocketsServer webSocket_PRO = WebSocketsServer(WS_SERVERPORT); + +char* msgBuf_PRO; +bool isFresh_PRO = false; +bool isConnect_PRO = false; +bool isAvail_PRO = false; +bool isApCfg = false; +uint8_t ws_num_PRO = 0; +uint8_t dataFrom_PRO = BLINKER_MSG_FROM_MQTT; + +void webSocketEvent_PRO(uint8_t num, WStype_t type, \ + uint8_t * payload, size_t length) +{ + + switch(type) + { + case WStype_DISCONNECTED: + BLINKER_LOG_ALL(BLINKER_F("Disconnected! "), num); + + isConnect_PRO = false; + break; + case WStype_CONNECTED: + { + IPAddress ip = webSocket_PRO.remoteIP(num); + + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", Connected from: "), ip, + BLINKER_F(", url: "), (char *)payload); + + // send message to client + webSocket_PRO.sendTXT(num, "{\"state\":\"connected\"}\n"); + + ws_num_PRO = num; + + if (!isApCfg) isConnect_PRO = true; + } + break; + case WStype_TEXT: + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", get Text: "), (char *)payload, \ + BLINKER_F(", length: "), length); + + if (length < BLINKER_MAX_READ_SIZE) { + if (isFresh_PRO) free(msgBuf_PRO); + msgBuf_PRO = (char*)malloc((length+1)*sizeof(char)); + strcpy(msgBuf_PRO, (char*)payload); + isAvail_PRO = true; + isFresh_PRO = true; + } + + if (!isApCfg) dataFrom_PRO = BLINKER_MSG_FROM_WS; + + ws_num_PRO = num; + + // send message to client + // webSocket_PRO.sendTXT(num, "message here"); + + // send data to all connected clients + // webSocket_PRO.broadcastTXT("message here"); + break; + case WStype_BIN: + // BLINKER_LOG("num: ", num, " get binary length: ", length); + // hexdump(payload, length); + + // send message to client + // webSocket_PRO.sendBIN(num, payload, length); + break; + } +} + +BlinkerGateway::BlinkerGateway() { isHandle = &isConnect_PRO; } + +int BlinkerGateway::connect() +{ + int8_t ret; + + webSocket_PRO.loop(); + + if (!isMQTTinit) { + return *isHandle; + } + + if (mqtt_PRO->connected()) + { + return true; + } + + disconnect(); + + if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + { + yield(); + return false; + } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + #if defined(ESP8266) + client_mqtt.setInsecure(); + ::delay(10); + #endif + + BLINKER_LOG_FreeHeap_ALL(); + + if ((ret = mqtt_PRO->connect()) != 0) + { + BLINKER_LOG(mqtt_PRO->connectErrorString(ret)); + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + if (ret == 4) + { + if (_reRegister_times < BLINKER_SERVER_CONNECT_LIMIT) + { + if (reRegister()) + { + _reRegister_times = 0; + } + else + { + _reRegister_times++; + _reRegister_time = millis(); + } + } + else + { + if (millis() - _reRegister_time >= 60000 * 5) _reRegister_times = 0; + } + + BLINKER_LOG_ALL(BLINKER_F("_reRegister_times: "), _reRegister_times); + } + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + if (_reRegister_times < BLINKER_SERVER_CONNECT_LIMIT) + { + if (reRegister()) + { + _reRegister_times = 0; + } + else + { + _reRegister_times++; + _reRegister_time = millis(); + } + } + else + { + if (millis() - _reRegister_time >= 60000 * 5) _reRegister_times = 0; + } + + reconnect_time = 0; + + BLINKER_LOG_ALL(BLINKER_F("_reRegister_times: "), _reRegister_times); + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + if (isNew) + { + if (pubHello()) { + isNew = false; + } + } + + this->latestTime = millis(); + + return true; +} + +int BlinkerGateway::connected() +{ + if (!isMQTTinit) + { + return *isHandle; + } + + return mqtt_PRO->connected() || *isHandle; +} + +int BlinkerGateway::mConnected() +{ + if (!isMQTTinit) return false; + else return mqtt_PRO->connected(); +} + +void BlinkerGateway::disconnect() +{ + if (isMQTTinit) mqtt_PRO->disconnect(); + + if (*isHandle) webSocket_PRO.disconnect(); +} + +void BlinkerGateway::ping() +{ + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!isMQTTinit) return; + + if (!mqtt_PRO->ping()) + { + disconnect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } +} + +int BlinkerGateway::available() +{ + // meshCheck(); + +#if defined(ESP8266) + MDNS.update(); +#endif + + webSocket_PRO.loop(); + + if (isMQTTinit) { + checkKA(); + + // if (!mqtt_PRO->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + { + ping(); + } + else + { + subscribe(); + } + } + + if (isAvail_PRO) + { + isAvail_PRO = false; + return true; + } + else { + return false; + } +} + +int BlinkerGateway::aligenieAvail() +{ + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerGateway::duerAvail() +{ + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerGateway::miAvail() +{ + if (isMIOTAvail) + { + isMIOTAvail = false; + return true; + } + else { + return false; + } +} + +// bool BlinkerGateway::extraAvailable() +// { +// if (isBavail) +// { +// isBavail = false; +// return true; +// } +// else +// { +// return false; +// } +// } + +void BlinkerGateway::subscribe() +{ + if (!isMQTTinit) return; + + Adafruit_MQTT_Subscribe *subscription; + while ((subscription = mqtt_PRO->readSubscription(10))) + { + if (subscription == iotSub_PRO) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), (char *)iotSub_PRO->lastread); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(String((char *)iotSub_PRO->lastread)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, String((char *)iotSub_PRO->lastread)); + JsonObject root = jsonBuffer.as(); + + if (root.containsKey("subDevice")) + { + String _sub = root["subDevice"]; + + int checkId = _checkIdAlive(_sub); + if (checkId != -1) + { + sendSingle(_subDevices[checkId]->id(), (char *)iotSub_PRO->lastread); + } + + this->latestTime = millis(); + } + else + { + String _uuid = root["fromDevice"]; + String dataGet = root["data"]; + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_PRO) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_PRO = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT) + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_PRO = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found," + "check is from bridge/share device," + "data: "), dataGet); + + _needCheckShare = true; + } + } + } + + // { + // dataGet = String((char *)iotSub_PRO->lastread); + // root.printTo(dataGet); + serializeJson(root, dataGet); + + // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + // check is from bridge/share device, \ + // data: "), dataGet); + + // // return; + + // // isBavail = true; + + // _needCheckShare = true; + // } + + isAvail_PRO = true; + isAlive = true; + } + + // memset(msgBuf_PRO, 0, BLINKER_MAX_READ_SIZE); + // memcpy(msgBuf_PRO, dataGet.c_str(), dataGet.length()); + + if (isFresh_PRO) free(msgBuf_PRO); + msgBuf_PRO = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_PRO, dataGet.c_str()); + isFresh_PRO = true; + + this->latestTime = millis(); + + dataFrom_PRO = BLINKER_MSG_FROM_MQTT; + } + } + } +} + +char * BlinkerGateway::lastRead() +{ + if (isFresh_PRO) return msgBuf_PRO; + return ""; +} + +void BlinkerGateway::flush() +{ + if (isFresh_PRO) + { + free(msgBuf_PRO); isFresh_PRO = false; isAvail_PRO = false; + isAliAvail = false; isDuerAvail = false; isMIOTAvail = false;//isBavail = false; + } +} + +int BlinkerGateway::print(char * data, bool needCheck) +{ + // BLINKER_LOG_FreeHeap(); + if (*isHandle && dataFrom_PRO == BLINKER_MSG_FROM_WS) + { + if (needCheck) + { + if (!checkPrintSpan()) + { + respTime = millis(); + return false; + } + } + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("WS response: ")); + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + strcat(data, BLINKER_CMD_NEWLINE); + + webSocket_PRO.sendTXT(ws_num_PRO, data); + + return true; + } + else + { + // // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // uint8_t num = strlen(data) - 1; + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data.substring(0, data.length() - 1); + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_DEVICEID_PRO; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_PRO; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + // else + // { + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data; + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_DEVICEID_PRO; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_PRO; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + + uint16_t num = strlen(data); + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+7] = data[c_num-1]; + } + + data[num+8] = '\0'; + + String data_add = BLINKER_F("{\"data\":"); + + for(uint16_t c_num = 0; c_num < 8; c_num++) + { + data[c_num] = data_add[c_num]; + } + + data_add = BLINKER_F(",\"fromDevice\":\""); + strcat(data, data_add.c_str()); + strcat(data, MQTT_DEVICEID_PRO); + data_add = BLINKER_F("\",\"toDevice\":\""); + strcat(data, data_add.c_str()); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + strcat(data, _sharers[_sharerFrom]->uuid()); + } + else + { + strcat(data, UUID_PRO); + } + data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + strcat(data, data_add.c_str()); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + if (!isJson(STRING_format(data))) return false; + + // String data_add = BLINKER_F("{\"data\":"); + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_DEVICEID_PRO; + // data_add += BLINKER_F("\",\"toDevice\":\""); + // if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + // { + // data_add += _sharers[_sharerFrom]->uuid(); + // } + // else + // { + // data_add += UUID_PRO; + // } + + // data_add += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + // if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (mqtt_PRO->connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } + } +} + +int BlinkerGateway::toServer(char * data) +{ + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish to server...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (mqtt_PRO->connected()) + { + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_MQTT, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerGateway::subPrint(const String & data, const String & toDevice, const String & subDevice) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\""); + data_add += toDevice; + data_add += BLINKER_F("\",\"subDevice\":\""); + data_add += subDevice; + data_add += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + if (!isJson(data)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerGateway::bPrint(char * name, const String & data) +{ + // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data.substring(0, data.length() - 1); + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_DEVICEID_PRO; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + // else + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data; + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_DEVICEID_PRO; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + + String data_add = BLINKER_F("{\"data\":"); + // for(uint8_t c_num = 0; c_num < 8; c_num++) + // { + // data[c_num] = data_add[c_num]; + // } + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\""); + data_add += name; + data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, MQTT_DEVICEID_PRO); + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, name); + // data_add = BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // strcat(data, data_add.c_str()); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_PRO->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + + // if (! iotPub.publish(payload.c_str())) { + + // String bPubTopic = BLINKER_F(""); + + // if (mqtt_broker == BLINKER_MQTT_BORKER_ONENET) + // { + // bPubTopic = MQTT_PRODUCTINFO_PRO; + // bPubTopic += BLINKER_F("/"); + // bPubTopic += name; + // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // bPubTopic = BLINKER_PUB_TOPIC_PRO; + // } + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerGateway::aliPrint(const String & data) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerGateway::subAliPrint(const String & data, const String & subDevice) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F(",\"subDevice\":\""); + data_add += subDevice; + data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerGateway::duerPrint(const String & data, bool report) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerGateway::subDuerPrint(const String & data, const String & subDevice) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F(",\"subDevice\":\""); + data_add += subDevice; + data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerGateway::miPrint(const String & data) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\"MIOT_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT MIOT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + if (!checkMIOTKA()) + { + return false; + } + + if (!checkMIOTPrintSpan()) + { + respMIOTTime = millis(); + return false; + } + respMIOTTime = millis(); + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isMIOTAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isMIOTAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerGateway::subMiPrint(const String & data, const String & subDevice) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F(",\"subDevice\":\""); + data_add += subDevice; + data_add += BLINKER_F("\",\"toDevice\":\"MIOT_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT MIOT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// void BlinkerGateway::aliType(const String & type) +// { +// _aliType = (char*)malloc((type.length()+1)*sizeof(char)); +// strcpy(_aliType, type.c_str()); +// BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +// } + +void BlinkerGateway::begin(const char* _key, const char* _type) +{ + _vipKey = _key; + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + mDNSInit(); +} + +int BlinkerGateway::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"trigged\":true,\"autoData\":{"); + payload += BLINKER_F("\"autoId\":"); + payload += STRING_format(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(MQTT_DEVICEID_PRO); + payload += BLINKER_F("\",\"toDevice\":\"autoManager\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_PRO->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// bool BlinkerGateway::autoPrint(char *name, char *type, char *data) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_PRO); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_PRO->connected()) { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +// bool BlinkerGateway::autoPrint(char *name1, char *type1, char *data1 +// , char *name2, char *type2, char *data2) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data1); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_PRO); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name1; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type1; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_PRO->connected()) +// { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data2); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_PRO); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name2; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type2; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else +// { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +char * BlinkerGateway::deviceName() { return MQTT_DEVICEID_PRO;/*MQTT_ID_PRO;*/ } + +void BlinkerGateway::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (_sharerCount; _sharerCount > 0; _sharerCount--) + { + delete _sharers[_sharerCount - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerGateway::authCheck() +{ + uint8_t _authCheck; + + BLINKER_LOG_ALL(BLINKER_F("authCheck start")); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck == BLINKER_AUTH_CHECK_DATA) + { + EEPROM.commit(); + EEPROM.end(); + isAuth = true; + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return true; + } + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return false; +} + +int BlinkerGateway::connectServer() { + const int httpsPort = 443; + #if defined(ESP8266) + String host = BLINKER_F(BLINKER_SERVER_HOST); + client_mqtt.stop(); + #elif defined(ESP32) + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + #endif + if (!_isAuthKey) + { + #if defined(ESP8266) + // String host = BLINKER_F(BLINKER_SERVER_HOST); + String fingerprint = BLINKER_F("84 5f a4 8a 70 5e 79 7e f5 b3 b4 20 45 c8 35 55 72 f6 85 5a"); + + // WiFiClientSecure client_s; + + // BearSSL::WiFiClientSecure *client_s; + + // client_s = new BearSSL::WiFiClientSecure(); + + // client_mqtt.stop(); + + // BLINKER_LOG_ALL(BLINKER_F("connecting to "), host); + + // // BLINKER_LOG_FreeHeap(); + + // uint8_t connet_times = 0; + // // client_s.stop(); + // ::delay(100); + + // bool mfln = client_s->probeMaxFragmentLength(host, httpsPort, 1024); + // if (mfln) { + // client_s->setBufferSizes(1024, 1024); + // } + // // client_s.setFingerprint(fingerprint.c_str()); + + // client_s->setInsecure(); + + // // while (1) { + // bool cl_connected = false; + // if (!client_s->connect(host, httpsPort)) { + // BLINKER_ERR_LOG(BLINKER_F("server connection failed")); + // // connet_times++; + + // ::delay(1000); + // } + // else { + // BLINKER_LOG_ALL(BLINKER_F("connection succeed")); + // cl_connected = true; + + // // break; + // } + + // // if (connet_times >= 4 && !cl_connected) return BLINKER_CMD_FALSE; + // // } + + // String client_msg; + + // String url_iot = BLINKER_F("/api/v1/user/device/register?deviceType="); + // url_iot += _deviceType; + // url_iot += BLINKER_F("&deviceName="); + // url_iot += macDeviceName(); + + // if (_deviceType == BLINKER_SMART_LAMP) { + // url_iot += BLINKER_F("&aliType=light"); + // url_iot += BLINKER_F("&duerType=LIGHT"); + // } + // else if (_deviceType == BLINKER_SMART_PLUGIN) { + // url_iot += BLINKER_F("&aliType=outlet"); + // url_iot += BLINKER_F("&duerType=SOCKET"); + // } + // else if (_deviceType == BLINKER_AIR_DETECTOR) { + // url_iot += BLINKER_F("&aliType=sensor"); + // url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + // } + + // // #if defined(BLINKER_ALIGENIE_LIGHT) + // // url_iot += BLINKER_F("&aliType=light"); + // // #elif defined(BLINKER_ALIGENIE_OUTLET) + // // url_iot += BLINKER_F("&aliType=outlet"); + // // #elif defined(BLINKER_ALIGENIE_SWITCH) + // // #elif defined(BLINKER_ALIGENIE_SENSOR) + // // url_iot += BLINKER_F("&aliType=sensor"); + // // #endif + + // BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host, url_iot); + + // client_msg = BLINKER_F("GET "); + // client_msg += url_iot; + // client_msg += BLINKER_F(" HTTP/1.1\r\nHost: "); + // client_msg += host; + // client_msg += BLINKER_F(":"); + // client_msg += STRING_format(httpsPort); + // client_msg += BLINKER_F("\r\nConnection: close\r\n\r\n"); + + // client_s->print(client_msg); + + // BLINKER_LOG_ALL(BLINKER_F("client_msg: "), client_msg); + + // unsigned long timeout = millis(); + // while (client_s->available() == 0) { + // if (millis() - timeout > 5000) { + // BLINKER_LOG_ALL(BLINKER_F(">>> Client Timeout !")); + // client_s->stop(); + // return false; + // } + // } + + // String _dataGet; + // String lastGet; + // String lengthOfJson; + // while (client_s->available()) { + // // String line = client_s.readStringUntil('\r'); + // _dataGet = client_s->readStringUntil('\n'); + + // if (_dataGet.startsWith("Content-Length: ")){ + // int addr_start = _dataGet.indexOf(' '); + // int addr_end = _dataGet.indexOf('\0', addr_start + 1); + // lengthOfJson = _dataGet.substring(addr_start + 1, addr_end); + // } + + // if (_dataGet == "\r") { + // BLINKER_LOG_ALL(BLINKER_F("headers received")); + + // break; + // } + // } + + // for(int i=0;iread(); + // } + + // // BLINKER_LOG_FreeHeap(); + + // client_s->stop(); + // client_s->flush(); + + // free(client_s); + + // // BLINKER_LOG_FreeHeap(); + + // _dataGet = lastGet; + + // BLINKER_LOG_ALL(BLINKER_F("_dataGet: "), _dataGet); + + // String payload = _dataGet; + + + + // client_mqtt.stop(); + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + + String url_iot = BLINKER_F("/api/v1/user/device/auth/get?deviceType="); + url_iot += _deviceType; + url_iot += BLINKER_F("&typeKey="); + url_iot += _vipKey; + url_iot += BLINKER_F("&deviceName="); + url_iot += macDeviceName(); + + url_iot = "https://" + host + url_iot; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + HTTPClient http; + + String payload; + + if (http.begin(*client_s, url_iot)) { // HTTPS + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + + #elif defined(ESP32) + // String host = BLINKER_F(BLINKER_SERVER_HTTPS); + // const char* ca = \ + // "-----BEGIN CERTIFICATE-----\n" \ + // "MIIEgDCCA2igAwIBAgIQDKTfhr9lmWbWUT0hjX36oDANBgkqhkiG9w0BAQsFADBy\n" \ + // "MQswCQYDVQQGEwJDTjElMCMGA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywg\n" \ + // "SW5jLjEdMBsGA1UECxMURG9tYWluIFZhbGlkYXRlZCBTU0wxHTAbBgNVBAMTFFRy\n" \ + // "dXN0QXNpYSBUTFMgUlNBIENBMB4XDTE4MDEwNDAwMDAwMFoXDTE5MDEwNDEyMDAw\n" \ + // "MFowGDEWMBQGA1UEAxMNaW90ZGV2LmNsei5tZTCCASIwDQYJKoZIhvcNAQEBBQAD\n" \ + // "ggEPADCCAQoCggEBALbOFn7cJ2I/FKMJqIaEr38n4kCuJCCeNf1bWdWvOizmU2A8\n" \ + // "QeTAr5e6Q3GKeJRdPnc8xXhqkTm4LOhgdZB8KzuVZARtu23D4vj4sVzxgC/zwJlZ\n" \ + // "MRMxN+cqI37kXE8gGKW46l2H9vcukylJX+cx/tjWDfS2YuyXdFuS/RjhCxLgXzbS\n" \ + // "cve1W0oBZnBPRSMV0kgxTWj7hEGZNWKIzK95BSCiMN59b+XEu3NWGRb/VzSAiJEy\n" \ + // "Hy9DcDPBC9TEg+p5itHtdMhy2gq1OwsPgl9HUT0xmDATSNEV2RB3vwviNfu9/Eif\n" \ + // "ObhsV078zf30TqdiESqISEB68gJ0Otru67ePoTkCAwEAAaOCAWowggFmMB8GA1Ud\n" \ + // "IwQYMBaAFH/TmfOgRw4xAFZWIo63zJ7dygGKMB0GA1UdDgQWBBR/KLqnke61779P\n" \ + // "xc9htonQwLOxPDAYBgNVHREEETAPgg1pb3RkZXYuY2x6Lm1lMA4GA1UdDwEB/wQE\n" \ + // "AwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTAYDVR0gBEUwQzA3\n" \ + // "BglghkgBhv1sAQIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQu\n" \ + // "Y29tL0NQUzAIBgZngQwBAgEwgYEGCCsGAQUFBwEBBHUwczAlBggrBgEFBQcwAYYZ\n" \ + // "aHR0cDovL29jc3AyLmRpZ2ljZXJ0LmNvbTBKBggrBgEFBQcwAoY+aHR0cDovL2Nh\n" \ + // "Y2VydHMuZGlnaXRhbGNlcnR2YWxpZGF0aW9uLmNvbS9UcnVzdEFzaWFUTFNSU0FD\n" \ + // "QS5jcnQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtM4eyrWB14ajJpQ\n" \ + // "ibZ5FbzVuvv2Le0FOSoss7UFCDJUYiz2LiV8yOhL4KTY+oVVkqHaYtcFS1CYZNzj\n" \ + // "6xWcqYZJ+pgsto3WBEgNEEe0uLSiTW6M10hm0LFW9Det3k8fqwSlljqMha3gkpZ6\n" \ + // "8WB0f2clXOuC+f1SxAOymnGUsSqbU0eFSgevcOIBKR7Hr3YXBXH3jjED76Q52OMS\n" \ + // "ucfOM9/HB3jN8o/ioQbkI7xyd/DUQtzK6hSArEoYRl3p5H2P4fr9XqmpoZV3i3gQ\n" \ + // "oOdVycVtpLunyUoVAB2DcOElfDxxXCvDH3XsgoIU216VY03MCaUZf7kZ2GiNL+UX\n" \ + // "9UBd0Q==\n" \ + // "-----END CERTIFICATE-----\n"; + // #endif + + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/auth/get?deviceType="); + url_iot += _deviceType; + url_iot += BLINKER_F("&typeKey="); + url_iot += _vipKey; + url_iot += BLINKER_F("&deviceName="); + url_iot += macDeviceName(); + + // #if defined(BLINKER_ALIGENIE_LIGHT) + // url_iot += BLINKER_F("&aliType=light"); + // #elif defined(BLINKER_ALIGENIE_OUTLET) + // url_iot += BLINKER_F("&aliType=outlet"); + // #elif defined(BLINKER_ALIGENIE_SWITCH) + // #elif defined(BLINKER_ALIGENIE_SENSOR) + // url_iot += BLINKER_F("&aliType=sensor"); + // #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + // #if defined(ESP8266) + // http.begin(url_iot, fingerprint); //HTTP + // #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); + // #endif + int httpCode = http.GET(); + + String payload; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + #endif + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_AUTHKEY)) { + // while(1) { + BLINKER_ERR_LOG(BLINKER_F("Maybe you have put in the wrong AuthKey!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your request is too frequently!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your network is disconnected!")); + // ::delay(60000); + + return false; + // } + } + + String _getAuthKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_AUTHKEY]; + + AUTHKEY_PRO = (char*)malloc((_getAuthKey.length()+1)*sizeof(char)); + strcpy(AUTHKEY_PRO, _getAuthKey.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_PRO: "), AUTHKEY_PRO); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + _isAuthKey = true; + } + +#if defined(ESP8266) + // client_mqtt.stop(); + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + + String url_iot = BLINKER_F("/api/v1/user/device/auth?authKey="); + url_iot += AUTHKEY_PRO; + // url_iot += _aliType; + // url_iot += _duerType; + + #if defined(BLINKER_ALIGENIE_LIGHT) + url_iot += BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + url_iot += BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + url_iot += BLINKER_F("&aliType=multi_outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + url_iot += BLINKER_F("&aliType=sensor"); + #elif defined(BLINKER_ALIGENIE_TYPE) + url_iot += BLINKER_ALIGENIE_TYPE; + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + url_iot += BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + url_iot += BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_MULTI_OUTLET) + url_iot += BLINKER_F("&duerType=MULTI_SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + #elif defined(BLINKER_DUEROS_TYPE) + url_iot += BLINKER_DUEROS_TYPE; + #endif + + #if defined(BLINKER_MIOT_LIGHT) + url_iot += BLINKER_F("&miType=light"); + #elif defined(BLINKER_MIOT_OUTLET) + url_iot += BLINKER_F("&miType=outlet"); + #elif defined(BLINKER_MIOT_MULTI_OUTLET) + url_iot += BLINKER_F("&miType=multi_outlet"); + #elif defined(BLINKER_MIOT_SENSOR) + url_iot += BLINKER_F("&miType=sensor"); + #elif defined(BLINKER_MIOT_TYPE) + url_iot += BLINKER_MIOT_TYPE; + #endif + + url_iot = "https://" + host + url_iot; + + HTTPClient http; + + String payload = ""; + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] begin: "), url_iot); + + if (http.begin(*client_s, url_iot)) { // HTTPS + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + +#elif defined(ESP32) + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/auth?authKey="); + url_iot += AUTHKEY_PRO; + // url_iot += _aliType; + // url_iot += _duerType; + + #if defined(BLINKER_ALIGENIE_LIGHT) + url_iot += BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + url_iot += BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + url_iot += BLINKER_F("&aliType=multi_outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + url_iot += BLINKER_F("&aliType=sensor"); + #elif defined(BLINKER_ALIGENIE_TYPE) + url_iot += BLINKER_ALIGENIE_TYPE; + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + url_iot += BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + url_iot += BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_MULTI_OUTLET) + url_iot += BLINKER_F("&duerType=MULTI_SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + #elif defined(BLINKER_DUEROS_TYPE) + url_iot += BLINKER_DUEROS_TYPE; + #endif + + #if defined(BLINKER_MIOT_LIGHT) + url_iot += BLINKER_F("&miType=light"); + #elif defined(BLINKER_MIOT_OUTLET) + url_iot += BLINKER_F("&miType=outlet"); + #elif defined(BLINKER_MIOT_MULTI_OUTLET) + url_iot += BLINKER_F("&miType=multi_outlet"); + #elif defined(BLINKER_MIOT_SENSOR) + url_iot += BLINKER_F("&miType=sensor"); + #elif defined(BLINKER_MIOT_TYPE) + url_iot += BLINKER_MIOT_TYPE; + #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + +// #if defined(ESP8266) +// http.begin(url_iot, fingerprint); //HTTP +// #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); +// #endif + int httpCode = http.GET(); + + String payload = ""; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); +#endif + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + // String _userID = STRING_find_string(payload, "deviceName", "\"", 4); + // String _userName = STRING_find_string(payload, "iotId", "\"", 4); + // String _key = STRING_find_string(payload, "iotToken", "\"", 4); + // String _productInfo = STRING_find_string(payload, "productKey", "\"", 4); + // String _broker = STRING_find_string(payload, "broker", "\"", 4); + // String _uuid = STRING_find_string(payload, "uuid", "\"", 4); + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + String _authKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_KEY]; + + if (isMQTTinit) + { + free(MQTT_HOST_PRO); + free(MQTT_ID_PRO); + free(MQTT_NAME_PRO); + free(MQTT_KEY_PRO); + free(MQTT_PRODUCTINFO_PRO); + free(UUID_PRO); + // free(AUTHKEY_PRO); + free(MQTT_DEVICEID_PRO); + free(BLINKER_PUB_TOPIC_PRO); + free(BLINKER_SUB_TOPIC_PRO); + free(mqtt_PRO); + free(iotSub_PRO); + + isMQTTinit = false; + } + + BLINKER_LOG_ALL(("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME, _userID.c_str(), 12); + // String _deviceName = _userID.substring(12, 36); + // MQTT_DEVICEID_PRO = (char*)malloc((_deviceName.length()+1)*sizeof(char)); + // String _deviceName = _userID.substring(12, 36); + MQTT_DEVICEID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _userID.c_str()); + MQTT_ID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_PRO, _userID.c_str()); + MQTT_NAME_PRO = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_PRO, _userName.c_str()); + MQTT_KEY_PRO = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_PRO, _key.c_str()); + MQTT_PRODUCTINFO_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_PRO, _productInfo.c_str()); + MQTT_HOST_PRO = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_PRO, BLINKER_MQTT_ALIYUN_HOST); + // AUTHKEY_PRO = (char*)malloc((_authKey.length()+1)*sizeof(char)); + // strcpy(AUTHKEY_PRO, _authKey.c_str()); + MQTT_PORT_PRO = BLINKER_MQTT_ALIYUN_PORT; + + BLINKER_LOG_ALL(("====================")); + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + // String id2name = _userID.subString(10, _userID.length()); + // memcpy(DEVICE_NAME, _userID.c_str(), 12); + MQTT_DEVICEID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _userID.c_str()); + String IDtest = _productInfo + _userID; + MQTT_ID_PRO = (char*)malloc((IDtest.length()+1)*sizeof(char)); + strcpy(MQTT_ID_PRO, IDtest.c_str()); + String NAMEtest = IDtest + ";" + _userName; + MQTT_NAME_PRO = (char*)malloc((NAMEtest.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_PRO, NAMEtest.c_str()); + MQTT_KEY_PRO = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_PRO, _key.c_str()); + MQTT_PRODUCTINFO_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_PRO, _productInfo.c_str()); + MQTT_HOST_PRO = (char*)malloc((strlen(BLINKER_MQTT_QCLOUD_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_PRO, BLINKER_MQTT_QCLOUD_HOST); + MQTT_PORT_PRO = BLINKER_MQTT_QCLOUD_PORT; + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + // memcpy(DEVICE_NAME, _userID.c_str(), 12); + MQTT_DEVICEID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _userID.c_str()); + MQTT_ID_PRO = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_ID_PRO, _userName.c_str()); + MQTT_NAME_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_PRO, _productInfo.c_str()); + MQTT_KEY_PRO = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_PRO, _key.c_str()); + MQTT_PRODUCTINFO_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_PRO, _productInfo.c_str()); + MQTT_HOST_PRO = (char*)malloc((strlen(BLINKER_MQTT_ONENET_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_PRO, BLINKER_MQTT_ONENET_HOST); + MQTT_PORT_PRO = BLINKER_MQTT_ONENET_PORT; + } + UUID_PRO = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_PRO, _uuid.c_str()); + + char uuid_eeprom[BLINKER_AUUID_SIZE]; + + BLINKER_LOG_ALL(("==========AUTH CHECK==========")); + + if (!isFirst) + { + char _authCheck; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + if (strcmp(uuid_eeprom, _uuid.c_str()) != 0) { + // strcpy(UUID_PRO, _uuid.c_str()); + + strcpy(uuid_eeprom, _uuid.c_str()); + EEPROM.put(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("uuid_eeprom: "), uuid_eeprom); + BLINKER_LOG_ALL(BLINKER_F("_uuid: "), _uuid); + isNew = true; + } + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck != BLINKER_AUTH_CHECK_DATA) { + EEPROM.put(BLINKER_EEP_ADDR_AUTH_CHECK, BLINKER_AUTH_CHECK_DATA); + isAuth = true; + } + EEPROM.commit(); + EEPROM.end(); + + isFirst = true; + } + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME: "), macDeviceName()); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_PRO: "), MQTT_PRODUCTINFO_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_DEVICEID_PRO: "), MQTT_DEVICEID_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_PRO: "), MQTT_ID_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_PRO: "), MQTT_NAME_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_PRO: "), MQTT_KEY_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_PRO); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_PRO); + BLINKER_LOG_ALL(BLINKER_F("UUID_PRO: "), UUID_PRO); + BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_PRO: "), AUTHKEY_PRO); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_PRO; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_DEVICEID_PRO; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_PRO = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_PRO: "), BLINKER_PUB_TOPIC_PRO); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_DEVICEID_PRO; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_PRO = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_PRO: "), BLINKER_SUB_TOPIC_PRO); + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + String PUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += _userID; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_PRO = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_PRO: "), BLINKER_PUB_TOPIC_PRO); + + String SUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += _userID; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_PRO = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_PRO: "), BLINKER_SUB_TOPIC_PRO); + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + uint8_t str_len; + String PUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + PUB_TOPIC_STR += BLINKER_F("/onenet_rule/r"); + // str_len = PUB_TOPIC_STR.length() + 1; + BLINKER_PUB_TOPIC_PRO = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_PRO: "), BLINKER_PUB_TOPIC_PRO); + + String SUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += _userID; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_PRO = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_PRO: "), BLINKER_SUB_TOPIC_PRO); + } + + // BLINKER_LOG_FreeHeap(); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_PRO, MQTT_PORT_PRO, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_PRO = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #elif defined(ESP32) + mqtt_PRO = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #endif + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_PRO, MQTT_PORT_PRO, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_PRO = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #elif defined(ESP32) + mqtt_PRO = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #endif + } + // else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + // mqtt_PRO = new Adafruit_MQTT_Client(&client, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + // } + + // iotPub = new Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + // if (!isMQTTinit) + iotSub_PRO = new Adafruit_MQTT_Subscribe(mqtt_PRO, BLINKER_SUB_TOPIC_PRO); + + // mqtt_broker = (char*)malloc((_broker.length()+1)*sizeof(char)); + // strcpy(mqtt_broker, _broker.c_str()); + // mqtt_broker = _broker; + + MDNS.end(); + webSocket_PRO.close(); + mDNSInit(MQTT_DEVICEID_PRO); + this->latestTime = millis(); + // if (!isMQTTinit) + mqtt_PRO->subscribe(iotSub_PRO); + isMQTTinit = true; + + #if defined(ESP8266) + // client_s->stop(); + client_mqtt.setInsecure(); + #endif + // connect(); + + return true; +} + +void BlinkerGateway::mDNSInit(String name) +{ + delay(1000); + + BLINKER_LOG(BLINKER_F("WiFi.localIP: "), WiFi.localIP()); + +#if defined(ESP8266) + if (!MDNS.begin(name.c_str(), WiFi.localIP())) { +#elif defined(ESP32) + if (!MDNS.begin(name.c_str())) { +#endif + while(1) { + ::delay(100); + } + } + + BLINKER_LOG(BLINKER_F("mDNS responder started")); + + String _service = STRING_format(BLINKER_MDNS_SERVICE_BLINKER) + STRING_format(_deviceType); + + MDNS.addService(BLINKER_MDNS_SERVICE_BLINKER, "tcp", WS_SERVERPORT); + MDNS.addServiceTxt(BLINKER_MDNS_SERVICE_BLINKER, "tcp", "deviceName", name); + + // if (!isWSinit) + // { + webSocket_PRO.begin(); + webSocket_PRO.onEvent(webSocketEvent_PRO); + // } + BLINKER_LOG(BLINKER_F("webSocket_PRO server started")); + BLINKER_LOG(BLINKER_F("ws://"), name, BLINKER_F(".local:"), WS_SERVERPORT); + + // isWSinit = true; + + isApCfg = false; +} + +void BlinkerGateway::checkKA() { + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerGateway::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerGateway::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerGateway::checkMIOTKA() { + if (millis() - miKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerGateway::checkCanPrint() { + if ((millis() - printTime >= BLINKER_PRO_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerGateway::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerGateway::checkMIOTPrintSpan() +{ + if (millis() - respMIOTTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respMIOTTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respMIOTTimes++; + return true; + } + } + else + { + respMIOTTimes = 0; + return true; + } +} + +int BlinkerGateway::checkPrintSpan() { + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) { + BLINKER_ERR_LOG(BLINKER_F("WEBSOCKETS CLIENT NOT ALIVE OR MSG LIMIT")); + + return false; + } + else { + respTimes++; + return true; + } + } + else { + respTimes = 0; + return true; + } +} + +int BlinkerGateway::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerGateway::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerGateway::pubHello() +{ + char stateJsonStr[256] = ("{\"message\":\"Registration successful\"}"); + + BLINKER_LOG_ALL(BLINKER_F("PUB hello: "), stateJsonStr); + + return print(stateJsonStr, false); +} + +int BlinkerGateway::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(STRING_format(data)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG(BLINKER_F("Print data is not Json! "), data); + return false; + } + + return true; +} + +String BlinkerGateway::vasDecode(uint16_t num) +{ + String vas = ""; + + if (num & 0xF) + { + if (num & 0x01) vas += "&aliType=light"; + else if (num >> 1 & 0x01) vas += "&aliType=outlet"; + else if (num >> 2 & 0x01) vas += "&aliType=multi_outlet"; + else if (num >> 3 & 0x01) vas += "&aliType=sensor"; + } + + if (num >> 4 & 0xF) + { + if (num >> 4 & 0x01) vas += "&duerType=light"; + else if (num >> 5 & 0x01) vas += "&duerType=outlet"; + else if (num >> 6 & 0x01) vas += "&duerType=multi_outlet"; + else if (num >> 7 & 0x01) vas += "&duerType=sensor"; + } + + if (num >> 8 & 0xF) + { + if (num >> 8 & 0x01) vas += "&miType=light"; + else if (num >> 9 & 0x01) vas += "&miType=outlet"; + else if (num >> 10 & 0x01) vas += "&miType=multi_outlet"; + else if (num >> 11 & 0x01) vas += "&miType=sensor"; + } + + BLINKER_LOG_ALL("vas: ", vas); + + return vas; +} + +bool BlinkerGateway::meshInit() +{ + if (WiFi.status() != WL_CONNECTED) return false; + + mesh.setDebugMsgTypes( ERROR | STARTUP | CONNECTION ); // set before init() so that you can see startup messages + // Channel set to 6. Make sure to use the same channel for your mesh and for you other + // network (STATION_SSID) + mesh.init(BLINKER_MESH_SSID, BLINKER_MESH_PSWD, BLINKER_MESH_PORT, WIFI_AP_STA, 6); + // mesh.stationManual(STATION_SSID, STATION_PASSWORD, STATION_PORT, station_ip); + // BLINKER_LOG_ALL("SSID: ", WiFi.SSID(), ", PWSD: ", WiFi.psk()); + mesh.stationManual(WiFi.SSID(), WiFi.psk()); + // Bridge node, should (in most cases) be a root node. See [the wiki](https://gitlab.com/painlessMesh/painlessMesh/wikis/Possible-challenges-in-mesh-formation) for some background + mesh.setRoot(true); + // This and all other mesh should ideally now the mesh contains a root + mesh.setContainsRoot(true); + + mesh.onReceive(&_receivedCallback); + mesh.onNewConnection(&_newConnectionCallback); + mesh.onChangedConnections(&_changedConnectionCallback); + + WiFi.reconnect(); + + return true; +} + +void BlinkerGateway::meshCheck() +{ + if (!_isMeshInit) + { + if (meshInit()) _isMeshInit = true; + } + else + { + if (WiFi.status() != WL_CONNECTED) return; + mesh.update(); + + if (isAvail_gate) + { + isAvail_gate = false; + + BLINKER_LOG_ALL("new gate data: ", meshBuf); + + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, meshBuf); + JsonObject root = jsonBuffer.as(); + + if (error) + { + BLINKER_ERR_LOG_ALL("msg not Json!"); + free(meshBuf); + return; + } + + if (root.containsKey(BLINKER_CMD_DEVICEINFO)) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + bool authState = root[BLINKER_CMD_DEVICEINFO]["auth"]; + BLINKER_LOG_ALL("auth state: ", authState); + + _subDevices[checkId]->auth(root[BLINKER_CMD_DEVICEINFO]["name"], + root[BLINKER_CMD_DEVICEINFO]["key"], + root[BLINKER_CMD_DEVICEINFO]["type"], + root[BLINKER_CMD_DEVICEINFO]["vas"].as()); + + vasDecode(root[BLINKER_CMD_DEVICEINFO]["vas"].as()); + + + if (!authState || !_subDevices[checkId]->isAuth()) + { + // TODO + if (subRegister(checkId)) + { + _subDevices[checkId]->freshAuth(true); + } + } + } + } + + free(meshBuf); + } + else if (isAvail_ctrl) + { + isAvail_ctrl = false; + + BLINKER_LOG_ALL("new ctrl data: ", meshBuf); + + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, meshBuf); + JsonObject root = jsonBuffer.as(); + + if (error) + { + BLINKER_ERR_LOG_ALL("msg not Json!"); + free(meshBuf); + return; + } + + if (root.containsKey("user")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + if (_subDevices[checkId]->isAuth()) + { + subPrint(root["user"], root["toDevice"], _subDevices[checkId]->deviceName()); + } + } + } + else if (root.containsKey("ali")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + if (_subDevices[checkId]->isAuth()) + { + subAliPrint(root["ali"], _subDevices[checkId]->deviceName()); + } + } + } + else if (root.containsKey("duer")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + if (_subDevices[checkId]->isAuth()) + { + subDuerPrint(root["duer"], _subDevices[checkId]->deviceName()); + } + } + } + else if (root.containsKey("miot")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + if (_subDevices[checkId]->isAuth()) + { + subMiPrint(root["miot"], _subDevices[checkId]->deviceName()); + } + } + } + else if (root.containsKey("sms")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("{\"deviceName\":\""); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += _subDevices[checkId]->authKey(); + data += BLINKER_F("\",\"msg\":\""); + data += root["sms"].as(); + + if (root.containsKey("cel")) + { + data += BLINKER_F("\",\"cel\":\""); + data += root["cel"].as(); + } + + data += BLINKER_F("\"}"); + + blinkerServer(BLINKER_CMD_SMS_NUMBER, data); + } + } + else if (root.containsKey("push")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("{\"deviceName\":\""); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += _subDevices[checkId]->authKey(); + data += BLINKER_F("\",\"msg\":\""); + data += root["push"].as(); + data += BLINKER_F("\"}"); + + blinkerServer(BLINKER_CMD_PUSH_NUMBER, data); + } + } + else if (root.containsKey("wechat")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("{\"deviceName\":\""); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += _subDevices[checkId]->authKey(); + data += BLINKER_F("\",\"msg\":\""); + data += root["wechat"].as(); + + if (root.containsKey("title")) + { + data += BLINKER_F("\",\"title\":\""); + data += root["title"].as(); + } + + if (root.containsKey("state")) + { + data += BLINKER_F("\",\"state\":\""); + data += root["state"].as(); + } + + data += BLINKER_F("\"}"); + + blinkerServer(BLINKER_CMD_WECHAT_NUMBER, data); + } + } + else if (root.containsKey("weather")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("/weather/now?"); + data += BLINKER_F("deviceName="); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("&key="); + data += _subDevices[checkId]->authKey(); + data += BLINKER_F("&location="); + data += root["weather"].as(); + + // String dataBack = "{\"ctrl\":{\"weather\":" + \ + // blinkerServer(BLINKER_CMD_WEATHER_NUMBER, data) + \ + // "}}"; + String dataBack = blinkerServer(BLINKER_CMD_WEATHER_NUMBER, data); + + if (dataBack == "null") dataBack = "\"null\""; + + dataBack = "{\"ctrl\":{\"weather\":" + dataBack + "}}"; + + sendSingle(_subDevices[checkId]->id(), dataBack); + } + } + else if (root.containsKey("aqi")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("/weather/aqi?"); + data += BLINKER_F("deviceName="); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("&key="); + data += _subDevices[checkId]->authKey(); + data += BLINKER_F("&location="); + data += root["aqi"].as(); + + // String dataBack = "{\"ctrl\":{\"aqi\":" + \ + // blinkerServer(BLINKER_CMD_AQI_NUMBER, data) + \ + // "}}"; + String dataBack = blinkerServer(BLINKER_CMD_AQI_NUMBER, data); + + if (dataBack == "null") dataBack = "\"null\""; + + dataBack = "{\"meshData\":{\"aqi\":" + dataBack + "}}"; + + sendSingle(_subDevices[checkId]->id(), dataBack); + } + } + else if (root.containsKey("freshSharers")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("/share/device?"); + data += BLINKER_F("deviceName="); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("&key="); + data += _subDevices[checkId]->authKey(); + + String dataBack = blinkerServer(BLINKER_CMD_FRESH_SHARERS_NUMBER, data); + + if (dataBack == "null") dataBack = "\"null\""; + + dataBack = "{\"meshData\":{\"freshSharers\":" + dataBack + "}}"; + + sendSingle(_subDevices[checkId]->id(), dataBack); + } + } + else if (root.containsKey("configUpdate")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String _msg = root["configUpdate"].as(); + + if (_msg.length() <= 256) + { + String data = BLINKER_F("{\"deviceName\":\""); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += _subDevices[checkId]->authKey(); + data += BLINKER_F("\",\"config\":\""); + data += _msg; + data += BLINKER_F("\"}"); + + blinkerServer(BLINKER_CMD_CONFIG_UPDATE_NUMBER, data); + } + } + } + else if (root.containsKey("configGet")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("/pull_userconfig?deviceName="); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("&key="); + data += _subDevices[checkId]->authKey(); + + String dataBack = blinkerServer(BLINKER_CMD_CONFIG_GET_NUMBER, data); + + if (dataBack == "null") dataBack = "\"null\""; + + dataBack = "{\"meshData\":{\"configGet\":" + dataBack + "}}"; + + sendSingle(_subDevices[checkId]->id(), dataBack); + } + } + else if (root.containsKey("configDel")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("/delete_userconfig?deviceName="); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("&key="); + data += _subDevices[checkId]->authKey(); + + blinkerServer(BLINKER_CMD_CONFIG_DELETE_NUMBER, data); + } + } + else if (root.containsKey("dataUpdate")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("{\"deviceName\":\""); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += _subDevices[checkId]->authKey(); + data += BLINKER_F("\",\"data\":"); + data += root["dataUpdate"].as(); + data += BLINKER_F("}"); + + blinkerServer(BLINKER_CMD_DATA_STORAGE_NUMBER, data); + } + } + else if (root.containsKey("dataGet")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("/pull_cloudStorage?deviceName="); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("&key="); + data += _subDevices[checkId]->authKey(); + + String _type = root["dataGet"].as(); + if (_type != "") + { + data += BLINKER_F("&dataType="); + data += _type; + } + if (root.containsKey("date")) + { + data += BLINKER_F("&date="); + data += root["date"].as(); + } + + String dataBack = blinkerServer(BLINKER_CMD_DATA_GET_NUMBER, data); + + if (dataBack == "null") dataBack = "\"null\""; + + dataBack = "{\"meshData\":{\"dataGet\":" + dataBack + "}}"; + + sendSingle(_subDevices[checkId]->id(), dataBack); + } + } + else if (root.containsKey("dataDel")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("/delete_cloudStorage?deviceName="); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("&key="); + data += _subDevices[checkId]->authKey(); + + String _type = root["dataDel"].as(); + if (_type != "") + { + data += BLINKER_F("&dataType="); + data += _type; + } + + blinkerServer(BLINKER_CMD_DATA_DELETE_NUMBER, data); + } + } + else if (root.containsKey("eKey")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("{\"deviceName\":\""); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += _subDevices[checkId]->authKey(); + data += BLINKER_F("\",\"eKey\":\""); + data += root["eKey"].as(); + data += BLINKER_F("\",\"date\":\""); + data += root["date"].as(); + data += BLINKER_F("\",\"value\":\""); + data += root["value"].as(); + data += BLINKER_F("\"}"); + + blinkerServer(BLINKER_CMD_EVENT_DATA_NUMBER, data); + } + } + else if (root.containsKey("gpsUpdate")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("{\"deviceName\":\""); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += _subDevices[checkId]->authKey(); + data += BLINKER_F("\",\"data\":["); + data += root["gpsUpdate"][0].as(); + data += BLINKER_F(","); + data += root["gpsUpdate"][1].as(); + data += BLINKER_F(","); + data += root["gpsUpdate"][2].as(); + data += BLINKER_F("]}"); + + blinkerServer(BLINKER_CMD_GPS_DATA_NUMBER, data); + } + } + else if (root.containsKey("autoPull")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("/auto/pull?deviceName="); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("&key="); + data += _subDevices[checkId]->authKey(); + + String dataBack = blinkerServer(BLINKER_CMD_AUTO_PULL_NUMBER, data); + + if (dataBack == "null") dataBack = "\"null\""; + + dataBack = "{\"meshData\":{\"autoPull\":" + dataBack + "}}"; + + sendSingle(_subDevices[checkId]->id(), dataBack); + } + } + else if (root.containsKey("deviceHeartbeat")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("/heartbeat?"); + data += BLINKER_F("deviceName="); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("&key="); + data += _subDevices[checkId]->authKey(); + data += BLINKER_F("&heartbeat="); + data += root["deviceHeartbeat"].as(); + + blinkerServer(BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER, data); + } + } + else if (root.containsKey("eventWarn")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("{\"deviceName\":\""); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += _subDevices[checkId]->authKey(); + data += BLINKER_F("\",\"msgType\":\"warning"); + data += BLINKER_F("\",\"msg\":\""); + data += root["eventWarn"].as(); + data += BLINKER_F("\"}"); + + blinkerServer(BLINKER_CMD_EVENT_WARNING_NUMBER, data); + } + } + else if (root.containsKey("eventError")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("{\"deviceName\":\""); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += _subDevices[checkId]->authKey(); + data += BLINKER_F("\",\"msgType\":\"error"); + data += BLINKER_F("\",\"msg\":\""); + data += root["eventError"].as(); + data += BLINKER_F("\"}"); + + blinkerServer(BLINKER_CMD_EVENT_ERROR_NUMBER, data); + } + } + else if (root.containsKey("eventMsg")) + { + int checkId = _checkIdAlive(msgFrom); + if (checkId != -1) + { + String data = BLINKER_F("{\"deviceName\":\""); + data += _subDevices[checkId]->deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += _subDevices[checkId]->authKey(); + data += BLINKER_F("\",\"msgType\":\"error"); + data += BLINKER_F("\",\"msg\":\""); + data += root["eventMsg"].as(); + data += BLINKER_F("\"}"); + + blinkerServer(BLINKER_CMD_EVENT_MSG_NUMBER, data); + } + } + + free(meshBuf); + } + + if (_newSub) + { + _newSub = false; + + sendBroadcast(gateFormat(STRING_format(BLINKER_CMD_WHOIS))); + + _meshCheckTime = millis(); + } + else if (millis() - _meshCheckTime >= BLINKER_MESH_CHECK_FREQ) + { + sendBroadcast(gateFormat(STRING_format(BLINKER_CMD_WHOIS))); + + _meshCheckTime = millis(); + } + } +} + +void BlinkerGateway::sendBroadcast(String msg) +{ + mesh.sendBroadcast(msg); +} + +bool BlinkerGateway::sendSingle(uint32_t toId, String msg) +{ + BLINKER_LOG_ALL("to id: ", toId, ", msg: ", msg); + if (mesh.isConnected(toId)) + { + return mesh.sendSingle(toId, msg); + } + else + { + BLINKER_ERR_LOG("device disconnected"); + return false; + } +} + +String BlinkerGateway::gateFormat(const String & msg) +{ + return "{\"" + STRING_format(BLINKER_CMD_GATE) + "\":" + msg + \ + ",\"tim\":" + STRING_format(time()) + \ + ",\"tz\":" + STRING_format(_timezone) + "}"; +} + +bool BlinkerGateway::subRegister(uint32_t num) +{ + const int httpsPort = 443; + #if defined(ESP8266) + String host = BLINKER_F(BLINKER_SERVER_HOST); + client_mqtt.stop(); + #elif defined(ESP32) + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + #endif + + #if defined(ESP8266) + String fingerprint = BLINKER_F("84 5f a4 8a 70 5e 79 7e f5 b3 b4 20 45 c8 35 55 72 f6 85 5a"); + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + + String url_iot = BLINKER_F("/api/v1/user/device/auth/get?deviceType="); + url_iot += _subDevices[num]->type(); + url_iot += BLINKER_F("&typeKey="); + url_iot += _subDevices[num]->key(); + url_iot += BLINKER_F("&deviceName="); + url_iot += _subDevices[num]->name(); + + url_iot = "https://" + host + url_iot; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + HTTPClient http; + + String payload; + + if (http.begin(*client_s, url_iot)) { // HTTPS + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + + #elif defined(ESP32) + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/auth/get?deviceType="); + url_iot += _subDevices[num]->type(); + url_iot += BLINKER_F("&typeKey="); + url_iot += _subDevices[num]->key(); + url_iot += BLINKER_F("&deviceName="); + url_iot += _subDevices[num]->name(); + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + http.begin(url_iot); + + int httpCode = http.GET(); + + String payload; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + #endif + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_AUTHKEY)) { + BLINKER_ERR_LOG(BLINKER_F("Maybe you have put in the wrong AuthKey!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your request is too frequently!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your network is disconnected!")); + + return false; + } + + String _getAuthKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_AUTHKEY]; + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("_getAuthKey: "), _getAuthKey); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + #if defined(ESP8266) + // std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setInsecure(); + + url_iot = BLINKER_F("/api/v1/user/device/auth?authKey="); + url_iot += _getAuthKey; + + url_iot = "https://" + host + url_iot; + + // HTTPClient http; + + payload = ""; + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] begin: "), url_iot); + + if (http.begin(*client_s, url_iot)) { // HTTPS + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + + #elif defined(ESP32) + // HTTPClient http; + + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/auth?authKey="); + url_iot += _getAuthKey; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + http.begin(url_iot); + + httpCode = http.GET(); + + payload = ""; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + #endif + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + DynamicJsonDocument _jsonBuffer(1024); + DeserializationError _error = deserializeJson(_jsonBuffer, payload); + JsonObject _root = _jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || _error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + _subDevices[num]->authData(_getAuthKey, _root["detail"]["deviceName"].as()); + // _root["detail"]["authKey"] = _getAuthKey; + JsonObject _detail = _root["detail"].as(); + _detail["authKey"] = _getAuthKey; + String _data; + serializeJson(_detail, _data); + sendSingle(_subDevices[num]->id(), "{\"gate\":{\"auth\":" + _data + "}}"); + + return true; +} + +time_t BlinkerGateway::time() +{ + time_t now_ntp = ::time(nullptr); + BLINKER_LOG_ALL("now_ntp: ", now_ntp); + return now_ntp; +} + +String BlinkerGateway::blinkerServer(uint8_t _type, const String & msg) +{ + switch (_type) + { + case BLINKER_CMD_SMS_NUMBER : + break; + case BLINKER_CMD_PUSH_NUMBER : + break; + case BLINKER_CMD_WECHAT_NUMBER : + break; + case BLINKER_CMD_WEATHER_NUMBER : + break; + case BLINKER_CMD_AQI_NUMBER : + break; + case BLINKER_CMD_BRIDGE_NUMBER : + break; + case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + break; + case BLINKER_CMD_CONFIG_GET_NUMBER : + break; + case BLINKER_CMD_CONFIG_DELETE_NUMBER : + break; + case BLINKER_CMD_DATA_STORAGE_NUMBER : + break; + case BLINKER_CMD_DATA_GET_NUMBER : + break; + case BLINKER_CMD_DATA_DELETE_NUMBER : + break; + case BLINKER_CMD_AUTO_PULL_NUMBER : + break; + case BLINKER_CMD_OTA_NUMBER : + break; + case BLINKER_CMD_OTA_STATUS_NUMBER : + break; + case BLINKER_CMD_FRESH_SHARERS_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_FREQ_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_DATA_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER : + break; + case BLINKER_CMD_EVENT_DATA_NUMBER : + break; + case BLINKER_CMD_GPS_DATA_NUMBER : + break; + case BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER : + break; + case BLINKER_CMD_EVENT_WARNING_NUMBER : + break; + case BLINKER_CMD_EVENT_ERROR_NUMBER : + break; + case BLINKER_CMD_EVENT_MSG_NUMBER : + break; + default : + return BLINKER_CMD_FALSE; + } + + BLINKER_LOG_ALL(BLINKER_F("message: "), msg); + + #ifndef BLINKER_LAN_DEBUG + const int httpsPort = 443; + #elif defined(BLINKER_LAN_DEBUG) + const int httpsPort = 9090; + #endif + + #ifndef BLINKER_LAN_DEBUG + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + #elif defined(BLINKER_LAN_DEBUG) + String host = BLINKER_F("http://192.168.1.121:9090"); + #endif + + #if defined(ESP8266) + extern BearSSL::WiFiClientSecure client_mqtt; + client_mqtt.stop(); + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + #endif + + HTTPClient http; + + String url_iot; + + int httpCode; + + String conType = BLINKER_F("Content-Type"); + String application = BLINKER_F("application/json;charset=utf-8"); + + BLINKER_LOG_ALL(BLINKER_F("blinker server begin")); + BLINKER_LOG_FreeHeap_ALL(); + + switch (_type) { + case BLINKER_CMD_SMS_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/sms"); + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_PUSH_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/push"); + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + // return BLINKER_CMD_FALSE; + case BLINKER_CMD_WECHAT_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/wxMsg/"); + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + // return BLINKER_CMD_FALSE; + case BLINKER_CMD_WEATHER_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_AQI_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_BRIDGE_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/userconfig"); + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_CONFIG_GET_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_CONFIG_DELETE_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_DATA_STORAGE_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/cloudStorage/"); + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_DATA_GET_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_DATA_DELETE_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_AUTO_PULL_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_OTA_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_OTA_STATUS_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/ota/upgrade_status"); + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_FRESH_SHARERS_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_FREQ_GET_NUM : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_DATA_GET_NUM : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/lowpower/data"); + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_EVENT_DATA_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/event"); + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_GPS_DATA_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/gps"); + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_EVENT_WARNING_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/event"); + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_EVENT_ERROR_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/event"); + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_EVENT_MSG_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/event"); + + #if defined(ESP8266) + http.begin(*client_s, url_iot); + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + default : + return BLINKER_CMD_FALSE; + } + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + BLINKER_LOG_ALL(BLINKER_F("HTTPS payload: "), msg); + + if (httpCode > 0) + { + BLINKER_LOG_ALL(BLINKER_F("[HTTP] status... code: "), httpCode); + + String payload; + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + + BLINKER_LOG_ALL(payload); + + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject data_rp = jsonBuffer.as(); + + if (!error) + { + uint16_t msg_code = data_rp[BLINKER_CMD_MESSAGE]; + if (msg_code != 1000) + { + String _detail = data_rp[BLINKER_CMD_DETAIL]; + BLINKER_ERR_LOG(_detail); + } + else + { + if (_type == BLINKER_CMD_BRIDGE_NUMBER) + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME].as(); + else if (_type == BLINKER_CMD_OTA_NUMBER || _type == BLINKER_CMD_FRESH_SHARERS_NUMBER) + payload = data_rp[BLINKER_CMD_DETAIL].as(); + else if (_type == BLINKER_CMD_LOWPOWER_FREQ_GET_NUM) + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_FREQ].as(); + else + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DATA].as(); + } + } + + BLINKER_LOG_ALL(BLINKER_F("payload: "), payload); + + switch (_type) { + case BLINKER_CMD_SMS_NUMBER : + break; + case BLINKER_CMD_PUSH_NUMBER : + break; + case BLINKER_CMD_WECHAT_NUMBER : + break; + case BLINKER_CMD_WEATHER_NUMBER : + break; + case BLINKER_CMD_AQI_NUMBER : + break; + case BLINKER_CMD_BRIDGE_NUMBER : + break; + case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + break; + case BLINKER_CMD_CONFIG_GET_NUMBER : + break; + case BLINKER_CMD_CONFIG_DELETE_NUMBER : + break; + case BLINKER_CMD_DATA_STORAGE_NUMBER : + break; + case BLINKER_CMD_DATA_GET_NUMBER : + break; + case BLINKER_CMD_DATA_DELETE_NUMBER : + break; + case BLINKER_CMD_AUTO_PULL_NUMBER : + break; + case BLINKER_CMD_OTA_NUMBER : + break; + case BLINKER_CMD_OTA_STATUS_NUMBER : + break; + case BLINKER_CMD_FRESH_SHARERS_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_FREQ_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_DATA_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER : + break; + case BLINKER_CMD_EVENT_DATA_NUMBER : + break; + case BLINKER_CMD_GPS_DATA_NUMBER : + break; + case BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER : + break; + case BLINKER_CMD_EVENT_WARNING_NUMBER : + break; + case BLINKER_CMD_EVENT_ERROR_NUMBER : + break; + case BLINKER_CMD_EVENT_MSG_NUMBER : + break; + default : + return BLINKER_CMD_FALSE; + } + } + + http.end(); + + return payload; + } + else { + BLINKER_LOG_ALL(BLINKER_F("[HTTP] ... failed, error: "), http.errorToString(httpCode).c_str()); + String payload = http.getString(); + BLINKER_LOG_ALL(payload); + + http.end(); + return BLINKER_CMD_FALSE; + } +} + +static IPAddress apIP(192, 168, 4, 1); +#if defined(ESP8266) + static IPAddress netMsk(255, 255, 255, 0); +#endif + + +enum bwl_status_t +{ + BWL_CONFIG_CKECK, + BWL_CONFIG_FAIL, + BWL_CONFIG_SUCCESS, + BWL_CONNECTING, + BWL_CONNECTED, + BWL_DISCONNECTED, + BWL_SMARTCONFIG_BEGIN, + BWL_SMARTCONFIG_DONE, + BWL_SMARTCONFIG_TIMEOUT, + BWL_STACONFIG_BEGIN, + BWL_APCONFIG_BEGIN, + BWL_APCONFIG_DONE, + BWL_APCONFIG_TIMEOUT, + BWL_CONNECTED_CHECK, + BWL_RESET +}; + +class BlinkerWlan +{ + public : + BlinkerWlan() + : _status(BWL_CONFIG_CKECK) + {} + + bool checkConfig(); + void loadConfig(char *_ssid, char *_pswd); + void saveConfig(char *_ssid, char *_pswd); + void deleteConfig(); + void smartconfigBegin(uint16_t _time = 15000); + bool smartconfigDone(); + void connect(); + bool connected(); + void disconnect(); + void reset(); + bool run(); + bwl_status_t status() { return _status; } + + void setType(const char* _type) { + _deviceType = _type; + +#ifdef BLINKER_DEBUG_ALL + BLINKER_LOG(BLINKER_F("API deviceType: "), _type); +#endif + } + + void softAPinit(); + void serverClient(); + void parseUrl(String data); + void connectWiFi(String _ssid, String _pswd); + void connectWiFi(const char* _ssid, const char* _pswd); + + // uint8_t status() { return _status; } + + private : + + protected : + char *SSID; + char *PSWD; + const char* _deviceType; + uint32_t connectTime; + uint16_t timeout; + bwl_status_t _status; + uint32_t debugStatusTime; +}; + +bool BlinkerWlan::checkConfig() { + BLINKER_LOG_ALL(BLINKER_F("check wlan config")); + + char ok[2 + 1]; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_WLAN_CHECK, ok); + EEPROM.commit(); + EEPROM.end(); + + if (String(ok) != String("OK")) { + + BLINKER_LOG(BLINKER_F("wlan config check,fail")); + + _status = BWL_CONFIG_FAIL; + return false; + } + else { + + BLINKER_LOG(BLINKER_F("wlan config check,success")); + + _status = BWL_CONFIG_SUCCESS; + return true; + } +} + +void BlinkerWlan::loadConfig(char *_ssid, char *_pswd) { + char loadssid[BLINKER_SSID_SIZE]; + char loadpswd[BLINKER_PSWD_SIZE]; + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_SSID, loadssid); + EEPROM.get(BLINKER_EEP_ADDR_PSWD, loadpswd); + // char ok[2 + 1]; + // EEPROM.get(EEP_ADDR_WIFI_CFG + BLINKER_SSID_SIZE + BLINKER_PSWD_SIZE, ok); + EEPROM.commit(); + EEPROM.end(); + + strcpy(_ssid, loadssid); + strcpy(_pswd, loadpswd); + + BLINKER_LOG(BLINKER_F("SSID: "), _ssid, BLINKER_F(" PASWD: "), _pswd); +} + +void BlinkerWlan::saveConfig(char *_ssid, char *_pswd) { + char loadssid[BLINKER_SSID_SIZE]; + char loadpswd[BLINKER_PSWD_SIZE]; + + memcpy(loadssid, _ssid, BLINKER_SSID_SIZE); + memcpy(loadpswd, _pswd, BLINKER_PSWD_SIZE); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_SSID, loadssid); + EEPROM.put(BLINKER_EEP_ADDR_PSWD, loadpswd); + char ok[2 + 1] = "OK"; + EEPROM.put(BLINKER_EEP_ADDR_WLAN_CHECK, ok); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG(BLINKER_F("Save wlan config")); +} + +void BlinkerWlan::deleteConfig() { + char ok[3] = {0}; + EEPROM.begin(BLINKER_EEP_SIZE); + // for (int i = BLINKER_EEP_ADDR_WLAN_CHECK; i < BLINKER_WLAN_CHECK_SIZE; i++) + // EEPROM.write(i, 0); + EEPROM.put(BLINKER_EEP_ADDR_WLAN_CHECK, ok); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG(BLINKER_F("Erase wlan config")); +} + +void BlinkerWlan::smartconfigBegin(uint16_t _time) { + WiFi.mode(WIFI_STA); + delay(100); + String softAP_ssid = STRING_format(_deviceType) + "_" + macDeviceName(); + +#if defined(ESP8266) + WiFi.hostname(softAP_ssid); +#elif defined(ESP32) + WiFi.setHostname(softAP_ssid.c_str()); +#endif + + WiFi.beginSmartConfig(); + connectTime = millis(); + timeout = _time; + _status = BWL_SMARTCONFIG_BEGIN; + + BLINKER_LOG(BLINKER_F("Wait for Smartconfig")); +} + +bool BlinkerWlan::smartconfigDone() { + if (WiFi.smartConfigDone()) + { + // WiFi.setAutoConnect(true); + // WiFi.setAutoReconnect(true); + connectTime = millis(); + + _status = BWL_SMARTCONFIG_DONE; + + BLINKER_LOG(BLINKER_F("SmartConfig Success")); +#if defined(ESP8266) + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + // WiFi.begin(WiFi.SSID().c_str(), WiFi.psk().c_str()); + connectWiFi(WiFi.SSID().c_str(), WiFi.psk().c_str()); + // connectWiFi("有没有wifi", "i8888888"); +#endif + return true; + } + else { + return false; + } +} + +void BlinkerWlan::connect() { + switch (_status) { + case BWL_CONFIG_SUCCESS : + // WiFi.setAutoConnect(false); + // WiFi.setAutoReconnect(true); + + SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + + loadConfig(SSID, PSWD); + // WiFi.begin(SSID, PSWD); + connectWiFi(SSID, PSWD); + + free(SSID); + free(PSWD); + + _status = BWL_CONNECTING; + break; + case BWL_DISCONNECTED : + if (millis() - connectTime > 30000 && WiFi.status() != WL_CONNECTED) { + BLINKER_LOG(BLINKER_F("status: "), WiFi.status()); + + disconnect(); + // SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + // PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + // WiFi.reconnect(); + + char _ssid_[BLINKER_SSID_SIZE]; + char _pswd_[BLINKER_PSWD_SIZE]; + + loadConfig(_ssid_, _pswd_); + connectWiFi(_ssid_, _pswd_); + + // WiFi.setAutoConnect(false); + // WiFi.setAutoReconnect(true); + + // free(SSID); + // free(PSWD); + connectTime = millis(); + BLINKER_LOG(BLINKER_F("connecting BWL_DISCONNECTED")); + + BLINKER_LOG(BLINKER_F("_ssid_: "), _ssid_, BLINKER_F(" _pswd_: "), _pswd_); + } + else if(WiFi.status() == WL_CONNECTED) { + _status = BWL_CONNECTED; + } + break; + } +} + +bool BlinkerWlan::connected() { + switch (_status) { + case BWL_SMARTCONFIG_DONE : + if (WiFi.status() != WL_CONNECTED) { + if (millis() - connectTime > 15000) + { + BLINKER_LOG(BLINKER_F("smartConfig time out")); + + WiFi.stopSmartConfig(); + _status = BWL_SMARTCONFIG_TIMEOUT; + } + return false; + } + else if (WiFi.status() == WL_CONNECTED) { + // WiFi.stopSmartConfig(); + + IPAddress deviceIP = WiFi.localIP(); + BLINKER_LOG(BLINKER_F("WiFi connected")); + BLINKER_LOG(BLINKER_F("IP address: ")); + BLINKER_LOG(deviceIP); + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + + SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + memcpy(SSID,"\0",BLINKER_SSID_SIZE); + memcpy(SSID,WiFi.SSID().c_str(),BLINKER_SSID_SIZE); + memcpy(PSWD,"\0",BLINKER_PSWD_SIZE); + memcpy(PSWD,WiFi.psk().c_str(),BLINKER_PSWD_SIZE); + saveConfig(SSID, PSWD); + free(SSID); + free(PSWD); + + // WiFi.setAutoConnect(true); + // WiFi.setAutoReconnect(true); + + _status = BWL_CONNECTED_CHECK; + + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + // break; + case BWL_APCONFIG_DONE : + if (WiFi.status() != WL_CONNECTED) { + if (millis() - connectTime > 15000) + { + BLINKER_LOG(BLINKER_F("APConfig time out")); + + // WiFi.stopSmartConfig(); + _status = BWL_APCONFIG_TIMEOUT; + } + return false; + } + else if (WiFi.status() == WL_CONNECTED) { + IPAddress deviceIP = WiFi.localIP(); + BLINKER_LOG(BLINKER_F("WiFi connected")); + BLINKER_LOG(BLINKER_F("IP address: ")); + BLINKER_LOG(deviceIP); + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + + // SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + // PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + // memcpy(SSID,"\0",BLINKER_SSID_SIZE); + // memcpy(SSID,WiFi.SSID().c_str(),BLINKER_SSID_SIZE); + // memcpy(PSWD,"\0",BLINKER_PSWD_SIZE); + // memcpy(PSWD,WiFi.psk().c_str(),BLINKER_PSWD_SIZE); + saveConfig(SSID, PSWD); + free(SSID); + free(PSWD); + + // WiFi.setAutoConnect(true); + // WiFi.setAutoReconnect(true); + + _status = BWL_CONNECTED_CHECK; + return true; + } + break; + case BWL_CONNECTING : + if (WiFi.status() == WL_CONNECTED) { + IPAddress deviceIP = WiFi.localIP(); + BLINKER_LOG(BLINKER_F("WiFi connected")); + BLINKER_LOG(BLINKER_F("IP address: ")); + BLINKER_LOG(deviceIP); + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + + _status = BWL_CONNECTED_CHECK; + return true; + } + else if (WiFi.status() != WL_CONNECTED) { + return false; + } + case BWL_CONNECTED_CHECK : + // if (WiFi.status() != WL_CONNECTED) + // _status = BWL_DISCONNECTED; + if (WiFi.status() == WL_CONNECTED) + { + return true; + } + else + { + _status = BWL_DISCONNECTED; + return false; + } + case BWL_RESET : + return false; + default : + if (WiFi.status() == WL_CONNECTED) { + IPAddress deviceIP = WiFi.localIP(); + BLINKER_LOG(BLINKER_F("WiFi connected")); + BLINKER_LOG(BLINKER_F("IP address: ")); + BLINKER_LOG(deviceIP); + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + + _status = BWL_CONNECTED_CHECK; + return true; + } + return false; + } + return false; +} + +void BlinkerWlan::disconnect() { + WiFi.disconnect(); + delay(100); + _status = BWL_DISCONNECTED; + BLINKER_LOG(BLINKER_F("WiFi disconnected")); +} + +void BlinkerWlan::reset() { + disconnect(); + _status = BWL_RESET; +} + +void BlinkerWlan::softAPinit() { + // _server = new WiFiServer(80); + + WiFi.mode(WIFI_AP); + String softAP_ssid = STRING_format(_deviceType) + "_" + macDeviceName(); + +#if defined(ESP8266) + WiFi.hostname(softAP_ssid); + WiFi.softAPConfig(apIP, apIP, netMsk); +#elif defined(ESP32) + WiFi.setHostname(softAP_ssid.c_str()); + WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); +#endif + + WiFi.softAP(softAP_ssid.c_str(), NULL); + delay(100); + + // _server->begin(); + // BLINKER_LOG(BLINKER_F("AP IP address: "), WiFi.softAPIP()); + // BLINKER_LOG(BLINKER_F("HTTP _server started")); + // BLINKER_LOG(String("URL: http://" + WiFi.softAPIP())); + + #if defined(ESP8266) + if (!MDNS.begin(softAP_ssid.c_str(), WiFi.localIP())) { + #elif defined(ESP32) + if (!MDNS.begin(softAP_ssid.c_str())) { + #endif + while(1) { + ::delay(100); + } + } + + BLINKER_LOG(BLINKER_F("mDNS responder started")); + + MDNS.addService(BLINKER_MDNS_SERVICE_BLINKER, "tcp", WS_SERVERPORT); + MDNS.addServiceTxt(BLINKER_MDNS_SERVICE_BLINKER, "tcp", "deviceName", macDeviceName()); + + webSocket_PRO.begin(); + webSocket_PRO.onEvent(webSocketEvent_PRO); + + _status = BWL_APCONFIG_BEGIN; + + isApCfg = true; + + BLINKER_LOG(BLINKER_F("Wait for APConfig")); +} + +void BlinkerWlan::serverClient() +{ + webSocket_PRO.loop(); + + #if defined(ESP8266) + MDNS.update(); + #endif + + if (isAvail_PRO) + { + BLINKER_LOG(BLINKER_F("checkAPCFG: "), msgBuf_PRO); + + if (STRING_contains_string(msgBuf_PRO, "ssid") && \ + STRING_contains_string(msgBuf_PRO, "pswd")) + { + parseUrl(msgBuf_PRO); + } + isAvail_PRO = false; + } + // if (!_client) + // { + // _client = _server->available(); + // } + // else + // { + // // if (_client.status() == CLOSED) + // if (!_client.connected()) + // { + // _client.stop(); + // BLINKER_LOG(BLINKER_F("Connection closed on _client")); + // } + // else + // { + // if (_client.available()) + // { + // String data = _client.readStringUntil('\r'); + + // // data = data.substring(4, data.length() - 9); + // _client.flush(); + + // // BLINKER_LOG("clientData: ", data); + + // if (STRING_contains_string(data, "ssid") && STRING_contains_string(data, "pswd")) { + + // String msg = BLINKER_F("{\"hello\":\"world\"}"); + + // String s= BLINKER_F("HTTP/1.1 200 OK\r\nContent-Type: application/json;charset=utf-8\r\n"); + // s += BLINKER_F("Content-Length: "); + // s += String(msg.length()); + // s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); + // s += msg; + // s += BLINKER_F("\r\n"); + + // _client.print(s); + + // _client.stop(); + + // parseUrl(data); + // } + // } + // } + // } +} + +void BlinkerWlan::parseUrl(String data) +{ + BLINKER_LOG(BLINKER_F("APCONFIG data: "), data); + // DynamicJsonBuffer jsonBuffer; + // JsonObject& wifi_data = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject wifi_data = jsonBuffer.as(); + + // if (!wifi_data.success()) + if (error) + { + return; + } + + String _ssid = wifi_data["ssid"]; + String _pswd = wifi_data["pswd"]; + + BLINKER_LOG(BLINKER_F("ssid: "), _ssid); + BLINKER_LOG(BLINKER_F("pswd: "), _pswd); + + // free(_server); + MDNS.end(); + webSocket_PRO.close(); + + SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + + strcpy(SSID, _ssid.c_str()); + strcpy(PSWD, _pswd.c_str()); + connectWiFi(_ssid, _pswd); + connectTime = millis(); + _status = BWL_APCONFIG_DONE; + + BLINKER_LOG(BLINKER_F("APConfig Success")); +} + +void BlinkerWlan::connectWiFi(String _ssid, String _pswd) +{ + connectWiFi(_ssid.c_str(), _pswd.c_str()); +} + +void BlinkerWlan::connectWiFi(const char* _ssid, const char* _pswd) +{ + uint32_t connectTime = millis(); + + BLINKER_LOG(BLINKER_F("Connecting to "), _ssid); + + WiFi.mode(WIFI_STA); + String _hostname = STRING_format(_deviceType) + "_" + macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(_hostname); + #elif defined(ESP32) + WiFi.setHostname(_hostname.c_str()); + #endif + + if (_pswd && strlen(_pswd)) { + WiFi.begin(_ssid, _pswd); + } + else { + WiFi.begin(_ssid); + } + + // while (WiFi.status() != WL_CONNECTED) { + // ::delay(50); + + // if (millis() - connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { + // connectTime = millis(); + // BLINKER_LOG(("WiFi connect timeout, please check ssid and pswd!")); + // BLINKER_LOG(("Retring WiFi connect again!")); + // } + // } + // BLINKER_LOG(("Connected")); + + // IPAddress myip = WiFi.localIP(); + // BLINKER_LOG(("Your IP is: "), myip); + + // mDNSInit(); +} + +bool BlinkerWlan::run() +{ + // if (millis() - debugStatusTime > 10000) { + // debugStatusTime = millis(); + + // BLINKER_LOG_ALL("WLAN status: ", _status); + // } + + switch (_status) { + case BWL_CONFIG_CKECK : + checkConfig(); + break; + case BWL_CONFIG_FAIL : + // #if defined(BLINKER_ESP_SMARTCONFIG) + // smartconfigBegin(); + // #elif defined(BLINKER_APCONFIG) + // softAPinit(); + // #endif + if (_configType == BLINKER_SMART_CONFIG) + { + smartconfigBegin(); + } + else + { + softAPinit(); + } + break; + case BWL_CONFIG_SUCCESS : + connect(); + break; + case BWL_CONNECTING : + return connected(); + break; + case BWL_CONNECTED : + return connected(); + break; + case BWL_DISCONNECTED : + connect(); + break; + case BWL_SMARTCONFIG_BEGIN : + smartconfigDone(); + break; + case BWL_SMARTCONFIG_DONE : + return connected(); + break; + case BWL_SMARTCONFIG_TIMEOUT : + _status = BWL_CONFIG_FAIL; + break; + case BWL_STACONFIG_BEGIN : + connect(); + break; + case BWL_APCONFIG_BEGIN : + serverClient(); + break; + case BWL_APCONFIG_DONE : + return connected(); + break; + case BWL_APCONFIG_TIMEOUT : + _status = BWL_CONFIG_FAIL; + break; + case BWL_CONNECTED_CHECK : + return connected(); + break; + case BWL_RESET: + break; + default : + break; + } + return false; +} + +#endif + +#endif diff --git a/blinker-library/src/Adapters/BlinkerHTTP.h b/blinker-library/src/Adapters/BlinkerHTTP.h new file mode 100644 index 0000000..f65539a --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerHTTP.h @@ -0,0 +1,1357 @@ +#ifndef BLINKER_HTTP_H +#define BLINKER_HTTP_H + +#if (defined(ESP8266) || defined(ESP32)) + +#define BLINKER_HTTP + +#if defined(ESP8266) + #include + #include + #include + + #include +#elif defined(ESP32) + #include + #include + #include + + #include +#endif + +// #include + +// #include "../modules/WebSockets/WebSocketsServer.h" +// #include "../modules/mqtt/Adafruit_HTTP.h" +// #include "../modules/mqtt/Adafruit_HTTP_Client.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +// #include "Adapters/BlinkerHTTP.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +enum b_config_t { + COMM, + BLINKER_SMART_CONFIG, + BLINKER_AP_CONFIG +}; + +enum b_configStatus_t { + SMART_BEGIN, + SMART_DONE, + SMART_TIMEOUT, + APCFG_BEGIN, + APCFG_DONE, + APCFG_TIMEOUT +}; + +#if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + BearSSL::WiFiClientSecure client_mqtt; + #else + WiFiClient client_mqtt; + #endif + // WiFiClientSecure client_mqtt; +#elif defined(ESP32) + WiFiClientSecure client_s; +#endif + +WiFiClient client; + +class BlinkerHTTP : public BlinkerStream +{ + public : + // BlinkerHTTP() : {} + + int connect(); + int connected(); + void disconnect(); + int available(); + void subscribe(); + char * lastRead(); + void flush(); + int print(char * data, bool needCheck = true); + void begin(const char* auth); + bool begin(); + // int autoPrint(unsigned long id); // TBD + char * deviceName(); + char * authKey() { return _authKey; } + int init() { if (!isInit) checkInit(); return isInit; } + int reRegister() { return connectServer(); } + + bool checkInit(); + void commonBegin(const char* _ssid, const char* _pswd); + void smartconfigBegin(); + void apconfigBegin(); + bool autoInit(); + void smartconfig(); + #if defined(BLINKER_APCONFIG) + void softAPinit(); + void checkAPCFG(); + bool parseUrl(String data); + #endif + void connectWiFi(String _ssid, String _pswd); + void connectWiFi(const char* _ssid, const char* _pswd); + + private : + bool isInit = false; + + int connectServer(); + void parseData(const char* data); + + protected : + bool _isWiFiInit = false; + bool _isBegin = false; + b_config_t _configType = COMM; + b_configStatus_t _configStatus = SMART_BEGIN; + uint32_t _connectTime = 0; + uint8_t _connectTimes = 0; + + char* _authKey; + + char* MQTT_ID_HTTP; + char* MQTT_NAME_HTTP; + char* MQTT_KEY_HTTP; + char* UUID_HTTP; + char* DEVICE_NAME_HTTP; + + char* msgBuf_HTTP; + bool isFresh_HTTP = false; + bool isConnect_HTTP = false; + bool isAvail_HTTP = false; + uint32_t _reRegister_time = 0; + uint8_t _reRegister_times = 0; +}; + +int BlinkerHTTP::connect() +{ + if (isInit) return true; + + if (begin()) + { + return true; + } + else + { + return false; + } +} + +int BlinkerHTTP::connected() +{ + return isConnect_HTTP; +} + +void BlinkerHTTP::disconnect() +{ + isConnect_HTTP = false; +} + +int BlinkerHTTP::available() +{ + if (!isConnect_HTTP) return false; + + // TBD + + if (isAvail_HTTP) + { + isAvail_HTTP = false; + return true; + } + else { + return false; + } +} + +void BlinkerHTTP::subscribe() +{ + if (!isConnect_HTTP) return; + + // TBD + + + const int httpsPort = 443; +#if defined(ESP8266) + String host = BLINKER_F(BLINKER_SERVER_HOST); + String fingerprint = BLINKER_F("84 5f a4 8a 70 5e 79 7e f5 b3 b4 20 45 c8 35 55 72 f6 85 5a"); + + + + #ifndef BLINKER_WITHOUT_SSL + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + #else + WiFiClient client_s; + #endif + + String url_iot = BLINKER_F("/api/v1/user/device/http/sub?token="); + url_iot += STRING_format(MQTT_KEY_HTTP); + // url_iot += BLINKER_OTA_VERSION_CODE; + + #ifndef BLINKER_WITHOUT_SSL + url_iot = "https://" + host + url_iot; + #else + url_iot = "http://" + host + url_iot; + #endif + HTTPClient http; + + String payload; + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] begin: "), url_iot); + + #ifndef BLINKER_WITHOUT_SSL + if (http.begin(*client_s, url_iot)) { // HTTPS + #else + if (http.begin(client_s, url_iot)) { + #endif + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + +#elif defined(ESP32) + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + // const char* ca = + // "-----BEGIN CERTIFICATE-----\n" + // "MIIEgDCCA2igAwIBAgIQDKTfhr9lmWbWUT0hjX36oDANBgkqhkiG9w0BAQsFADBy\n" + // "MQswCQYDVQQGEwJDTjElMCMGA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywg\n" + // "SW5jLjEdMBsGA1UECxMURG9tYWluIFZhbGlkYXRlZCBTU0wxHTAbBgNVBAMTFFRy\n" + // "dXN0QXNpYSBUTFMgUlNBIENBMB4XDTE4MDEwNDAwMDAwMFoXDTE5MDEwNDEyMDAw\n" + // "MFowGDEWMBQGA1UEAxMNaW90ZGV2LmNsei5tZTCCASIwDQYJKoZIhvcNAQEBBQAD\n" + // "ggEPADCCAQoCggEBALbOFn7cJ2I/FKMJqIaEr38n4kCuJCCeNf1bWdWvOizmU2A8\n" + // "QeTAr5e6Q3GKeJRdPnc8xXhqkTm4LOhgdZB8KzuVZARtu23D4vj4sVzxgC/zwJlZ\n" + // "MRMxN+cqI37kXE8gGKW46l2H9vcukylJX+cx/tjWDfS2YuyXdFuS/RjhCxLgXzbS\n" + // "cve1W0oBZnBPRSMV0kgxTWj7hEGZNWKIzK95BSCiMN59b+XEu3NWGRb/VzSAiJEy\n" + // "Hy9DcDPBC9TEg+p5itHtdMhy2gq1OwsPgl9HUT0xmDATSNEV2RB3vwviNfu9/Eif\n" + // "ObhsV078zf30TqdiESqISEB68gJ0Otru67ePoTkCAwEAAaOCAWowggFmMB8GA1Ud\n" + // "IwQYMBaAFH/TmfOgRw4xAFZWIo63zJ7dygGKMB0GA1UdDgQWBBR/KLqnke61779P\n" + // "xc9htonQwLOxPDAYBgNVHREEETAPgg1pb3RkZXYuY2x6Lm1lMA4GA1UdDwEB/wQE\n" + // "AwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTAYDVR0gBEUwQzA3\n" + // "BglghkgBhv1sAQIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQu\n" + // "Y29tL0NQUzAIBgZngQwBAgEwgYEGCCsGAQUFBwEBBHUwczAlBggrBgEFBQcwAYYZ\n" + // "aHR0cDovL29jc3AyLmRpZ2ljZXJ0LmNvbTBKBggrBgEFBQcwAoY+aHR0cDovL2Nh\n" + // "Y2VydHMuZGlnaXRhbGNlcnR2YWxpZGF0aW9uLmNvbS9UcnVzdEFzaWFUTFNSU0FD\n" + // "QS5jcnQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtM4eyrWB14ajJpQ\n" + // "ibZ5FbzVuvv2Le0FOSoss7UFCDJUYiz2LiV8yOhL4KTY+oVVkqHaYtcFS1CYZNzj\n" + // "6xWcqYZJ+pgsto3WBEgNEEe0uLSiTW6M10hm0LFW9Det3k8fqwSlljqMha3gkpZ6\n" + // "8WB0f2clXOuC+f1SxAOymnGUsSqbU0eFSgevcOIBKR7Hr3YXBXH3jjED76Q52OMS\n" + // "ucfOM9/HB3jN8o/ioQbkI7xyd/DUQtzK6hSArEoYRl3p5H2P4fr9XqmpoZV3i3gQ\n" + // "oOdVycVtpLunyUoVAB2DcOElfDxxXCvDH3XsgoIU216VY03MCaUZf7kZ2GiNL+UX\n" + // "9UBd0Q==\n" + // "-----END CERTIFICATE-----\n"; +// #endif + + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/http/sub?token="); + url_iot += STRING_format(MQTT_KEY_HTTP); + +// #if defined(BLINKER_ALIGENIE_LIGHT) +// url_iot += BLINKER_F("&aliType=light"); +// #elif defined(BLINKER_ALIGENIE_OUTLET) +// url_iot += BLINKER_F("&aliType=outlet"); +// #elif defined(BLINKER_ALIGENIE_SWITCH) +// #elif defined(BLINKER_ALIGENIE_SENSOR) +// url_iot += BLINKER_F("&aliType=sensor"); +// #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + +// #if defined(ESP8266) +// http.begin(url_iot, fingerprint); //HTTP +// #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); +// #endif + int httpCode = http.GET(); + + String payload; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); +#endif + + // payload = ""; + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); +} + +char * BlinkerHTTP::lastRead() +{ + if (isFresh_HTTP) return msgBuf_HTTP; + else return ""; +} + +void BlinkerHTTP::flush() +{ + if (isFresh_HTTP) + { + free(msgBuf_HTTP); + isFresh_HTTP = false; + isAvail_HTTP = false; + } +} + +int BlinkerHTTP::print(char * data, bool needCheck) +{ + if (!isConnect_HTTP) return false; + + // TBD + String msg = BLINKER_F("{\"token\":\""); + msg += STRING_format(MQTT_KEY_HTTP); + msg += BLINKER_F("\",\"toDevice\":\""); + msg += STRING_format(UUID_HTTP); + msg += BLINKER_F("\",\"deviceType\":\"OwnApp\",\"data\":"); + msg += STRING_format(data); + msg += BLINKER_F("}"); + + String conType = BLINKER_F("Content-Type"); + String application = BLINKER_F("application/json;charset=utf-8"); + + const int httpsPort = 443; +#if defined(ESP8266) + String host = BLINKER_F(BLINKER_SERVER_HOST); + String fingerprint = BLINKER_F("84 5f a4 8a 70 5e 79 7e f5 b3 b4 20 45 c8 35 55 72 f6 85 5a"); + + + + #ifndef BLINKER_WITHOUT_SSL + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + #else + WiFiClient client_s; + #endif + + String url_iot = BLINKER_F("/api/v1/user/device/http/pub"); + // url_iot += STRING_format(MQTT_KEY_HTTP); + // url_iot += BLINKER_OTA_VERSION_CODE; + + #ifndef BLINKER_WITHOUT_SSL + url_iot = "https://" + host + url_iot; + #else + url_iot = "http://" + host + url_iot; + #endif + HTTPClient http; + + String payload; + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] begin: "), url_iot); + + #ifndef BLINKER_WITHOUT_SSL + if (http.begin(*client_s, url_iot)) { // HTTPS + #else + if (http.begin(client_s, url_iot)) { + #endif + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + http.addHeader(conType, application); + int httpCode = http.POST(msg); + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] POST: "), msg); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] POST... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] POST... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + +#elif defined(ESP32) + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + // const char* ca = + // "-----BEGIN CERTIFICATE-----\n" + // "MIIEgDCCA2igAwIBAgIQDKTfhr9lmWbWUT0hjX36oDANBgkqhkiG9w0BAQsFADBy\n" + // "MQswCQYDVQQGEwJDTjElMCMGA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywg\n" + // "SW5jLjEdMBsGA1UECxMURG9tYWluIFZhbGlkYXRlZCBTU0wxHTAbBgNVBAMTFFRy\n" + // "dXN0QXNpYSBUTFMgUlNBIENBMB4XDTE4MDEwNDAwMDAwMFoXDTE5MDEwNDEyMDAw\n" + // "MFowGDEWMBQGA1UEAxMNaW90ZGV2LmNsei5tZTCCASIwDQYJKoZIhvcNAQEBBQAD\n" + // "ggEPADCCAQoCggEBALbOFn7cJ2I/FKMJqIaEr38n4kCuJCCeNf1bWdWvOizmU2A8\n" + // "QeTAr5e6Q3GKeJRdPnc8xXhqkTm4LOhgdZB8KzuVZARtu23D4vj4sVzxgC/zwJlZ\n" + // "MRMxN+cqI37kXE8gGKW46l2H9vcukylJX+cx/tjWDfS2YuyXdFuS/RjhCxLgXzbS\n" + // "cve1W0oBZnBPRSMV0kgxTWj7hEGZNWKIzK95BSCiMN59b+XEu3NWGRb/VzSAiJEy\n" + // "Hy9DcDPBC9TEg+p5itHtdMhy2gq1OwsPgl9HUT0xmDATSNEV2RB3vwviNfu9/Eif\n" + // "ObhsV078zf30TqdiESqISEB68gJ0Otru67ePoTkCAwEAAaOCAWowggFmMB8GA1Ud\n" + // "IwQYMBaAFH/TmfOgRw4xAFZWIo63zJ7dygGKMB0GA1UdDgQWBBR/KLqnke61779P\n" + // "xc9htonQwLOxPDAYBgNVHREEETAPgg1pb3RkZXYuY2x6Lm1lMA4GA1UdDwEB/wQE\n" + // "AwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTAYDVR0gBEUwQzA3\n" + // "BglghkgBhv1sAQIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQu\n" + // "Y29tL0NQUzAIBgZngQwBAgEwgYEGCCsGAQUFBwEBBHUwczAlBggrBgEFBQcwAYYZ\n" + // "aHR0cDovL29jc3AyLmRpZ2ljZXJ0LmNvbTBKBggrBgEFBQcwAoY+aHR0cDovL2Nh\n" + // "Y2VydHMuZGlnaXRhbGNlcnR2YWxpZGF0aW9uLmNvbS9UcnVzdEFzaWFUTFNSU0FD\n" + // "QS5jcnQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtM4eyrWB14ajJpQ\n" + // "ibZ5FbzVuvv2Le0FOSoss7UFCDJUYiz2LiV8yOhL4KTY+oVVkqHaYtcFS1CYZNzj\n" + // "6xWcqYZJ+pgsto3WBEgNEEe0uLSiTW6M10hm0LFW9Det3k8fqwSlljqMha3gkpZ6\n" + // "8WB0f2clXOuC+f1SxAOymnGUsSqbU0eFSgevcOIBKR7Hr3YXBXH3jjED76Q52OMS\n" + // "ucfOM9/HB3jN8o/ioQbkI7xyd/DUQtzK6hSArEoYRl3p5H2P4fr9XqmpoZV3i3gQ\n" + // "oOdVycVtpLunyUoVAB2DcOElfDxxXCvDH3XsgoIU216VY03MCaUZf7kZ2GiNL+UX\n" + // "9UBd0Q==\n" + // "-----END CERTIFICATE-----\n"; +// #endif + + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/http/pub"); + url_iot += STRING_format(MQTT_KEY_HTTP); + +// #if defined(BLINKER_ALIGENIE_LIGHT) +// url_iot += BLINKER_F("&aliType=light"); +// #elif defined(BLINKER_ALIGENIE_OUTLET) +// url_iot += BLINKER_F("&aliType=outlet"); +// #elif defined(BLINKER_ALIGENIE_SWITCH) +// #elif defined(BLINKER_ALIGENIE_SENSOR) +// url_iot += BLINKER_F("&aliType=sensor"); +// #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + +// #if defined(ESP8266) +// http.begin(url_iot, fingerprint); //HTTP +// #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); +// #endif + http.addHeader(conType, application); + int httpCode = http.POST(msg); + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] POST: "), msg); + + String payload; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] POST... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] POST... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); +#endif + + // payload = ""; + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); +} + +void BlinkerHTTP::begin(const char* auth) +{ + // if (!checkInit()) return; + // _authKey = auth; + _authKey = (char*)malloc((strlen(auth)+1)*sizeof(char)); + strcpy(_authKey, auth); + + BLINKER_LOG_ALL(BLINKER_F("_authKey: "), auth); +} + +bool BlinkerHTTP::begin() +{ + if (!checkInit()) return false; + + if (reRegister()) + { + return true; + } + else + { + return false; + } +} + +char * BlinkerHTTP::deviceName() { return DEVICE_NAME_HTTP;/*MQTT_ID_HTTP;*/ } + +int BlinkerHTTP::connectServer() +{ + const int httpsPort = 443; +#if defined(ESP8266) + String host = BLINKER_F(BLINKER_SERVER_HOST); + String fingerprint = BLINKER_F("84 5f a4 8a 70 5e 79 7e f5 b3 b4 20 45 c8 35 55 72 f6 85 5a"); + + + + #ifndef BLINKER_WITHOUT_SSL + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + #else + WiFiClient client_s; + #endif + + String url_iot = BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + url_iot += _authKey; + url_iot += BLINKER_F("&version="); + url_iot += BLINKER_OTA_VERSION_CODE; + #ifndef BLINKER_WITHOUT_SSL + url_iot += BLINKER_F("&protocol=https"); + #else + url_iot += BLINKER_F("&protocol=http"); + #endif + // url_iot += BLINKER_OTA_VERSION_CODE; + + #ifndef BLINKER_WITHOUT_SSL + url_iot = "https://" + host + url_iot; + #else + url_iot = "http://" + host + url_iot; + #endif + HTTPClient http; + + String payload; + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] begin: "), url_iot); + + #ifndef BLINKER_WITHOUT_SSL + if (http.begin(*client_s, url_iot)) { // HTTPS + #else + if (http.begin(client_s, url_iot)) { + #endif + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + +#elif defined(ESP32) + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + // const char* ca = + // "-----BEGIN CERTIFICATE-----\n" + // "MIIEgDCCA2igAwIBAgIQDKTfhr9lmWbWUT0hjX36oDANBgkqhkiG9w0BAQsFADBy\n" + // "MQswCQYDVQQGEwJDTjElMCMGA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywg\n" + // "SW5jLjEdMBsGA1UECxMURG9tYWluIFZhbGlkYXRlZCBTU0wxHTAbBgNVBAMTFFRy\n" + // "dXN0QXNpYSBUTFMgUlNBIENBMB4XDTE4MDEwNDAwMDAwMFoXDTE5MDEwNDEyMDAw\n" + // "MFowGDEWMBQGA1UEAxMNaW90ZGV2LmNsei5tZTCCASIwDQYJKoZIhvcNAQEBBQAD\n" + // "ggEPADCCAQoCggEBALbOFn7cJ2I/FKMJqIaEr38n4kCuJCCeNf1bWdWvOizmU2A8\n" + // "QeTAr5e6Q3GKeJRdPnc8xXhqkTm4LOhgdZB8KzuVZARtu23D4vj4sVzxgC/zwJlZ\n" + // "MRMxN+cqI37kXE8gGKW46l2H9vcukylJX+cx/tjWDfS2YuyXdFuS/RjhCxLgXzbS\n" + // "cve1W0oBZnBPRSMV0kgxTWj7hEGZNWKIzK95BSCiMN59b+XEu3NWGRb/VzSAiJEy\n" + // "Hy9DcDPBC9TEg+p5itHtdMhy2gq1OwsPgl9HUT0xmDATSNEV2RB3vwviNfu9/Eif\n" + // "ObhsV078zf30TqdiESqISEB68gJ0Otru67ePoTkCAwEAAaOCAWowggFmMB8GA1Ud\n" + // "IwQYMBaAFH/TmfOgRw4xAFZWIo63zJ7dygGKMB0GA1UdDgQWBBR/KLqnke61779P\n" + // "xc9htonQwLOxPDAYBgNVHREEETAPgg1pb3RkZXYuY2x6Lm1lMA4GA1UdDwEB/wQE\n" + // "AwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTAYDVR0gBEUwQzA3\n" + // "BglghkgBhv1sAQIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQu\n" + // "Y29tL0NQUzAIBgZngQwBAgEwgYEGCCsGAQUFBwEBBHUwczAlBggrBgEFBQcwAYYZ\n" + // "aHR0cDovL29jc3AyLmRpZ2ljZXJ0LmNvbTBKBggrBgEFBQcwAoY+aHR0cDovL2Nh\n" + // "Y2VydHMuZGlnaXRhbGNlcnR2YWxpZGF0aW9uLmNvbS9UcnVzdEFzaWFUTFNSU0FD\n" + // "QS5jcnQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtM4eyrWB14ajJpQ\n" + // "ibZ5FbzVuvv2Le0FOSoss7UFCDJUYiz2LiV8yOhL4KTY+oVVkqHaYtcFS1CYZNzj\n" + // "6xWcqYZJ+pgsto3WBEgNEEe0uLSiTW6M10hm0LFW9Det3k8fqwSlljqMha3gkpZ6\n" + // "8WB0f2clXOuC+f1SxAOymnGUsSqbU0eFSgevcOIBKR7Hr3YXBXH3jjED76Q52OMS\n" + // "ucfOM9/HB3jN8o/ioQbkI7xyd/DUQtzK6hSArEoYRl3p5H2P4fr9XqmpoZV3i3gQ\n" + // "oOdVycVtpLunyUoVAB2DcOElfDxxXCvDH3XsgoIU216VY03MCaUZf7kZ2GiNL+UX\n" + // "9UBd0Q==\n" + // "-----END CERTIFICATE-----\n"; +// #endif + + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + url_iot += _authKey; + url_iot += BLINKER_F("&version="); + url_iot += BLINKER_OTA_VERSION_CODE; + url_iot += BLINKER_F("&protocol=https"); + +// #if defined(BLINKER_ALIGENIE_LIGHT) +// url_iot += BLINKER_F("&aliType=light"); +// #elif defined(BLINKER_ALIGENIE_OUTLET) +// url_iot += BLINKER_F("&aliType=outlet"); +// #elif defined(BLINKER_ALIGENIE_SWITCH) +// #elif defined(BLINKER_ALIGENIE_SENSOR) +// url_iot += BLINKER_F("&aliType=sensor"); +// #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + +// #if defined(ESP8266) +// http.begin(url_iot, fingerprint); //HTTP +// #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); +// #endif + int httpCode = http.GET(); + + String payload; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); +#endif + + // payload = ""; + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(BLINKER_F("Maybe you have put in the wrong AuthKey!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your request is too frequently!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your network is disconnected!")); + // ::delay(60000); + + return false; + // } + } + + // String _userID = STRING_find_string(payload, "deviceName", "\"", 4); + // String _userName = STRING_find_string(payload, "iotId", "\"", 4); + // String _key = STRING_find_string(payload, "iotToken", "\"", 4); + // String _productInfo = STRING_find_string(payload, "productKey", "\"", 4); + // String _broker = STRING_find_string(payload, "broker", "\"", 4); + // String _uuid = STRING_find_string(payload, "uuid", "\"", 4); + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + String _host = root[BLINKER_CMD_DETAIL]["host"]; + uint32_t _port = root[BLINKER_CMD_DETAIL]["port"]; + uint8_t _num = _host.indexOf("://"); + + if (isInit) + { + free(MQTT_ID_HTTP); + free(MQTT_NAME_HTTP); + free(MQTT_KEY_HTTP); + free(UUID_HTTP); + free(DEVICE_NAME_HTTP); + + isInit = false; + } + + // if (_broker == BLINKER_HTTP_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME_HTTP, _userID.c_str(), 12); + DEVICE_NAME_HTTP = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(DEVICE_NAME_HTTP, _userID.c_str()); + MQTT_ID_HTTP = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_HTTP, _userID.c_str()); + MQTT_NAME_HTTP = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_HTTP, _userName.c_str()); + MQTT_KEY_HTTP = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_HTTP, _key.c_str()); + // } + // else if (_broker == BLINKER_HTTP_BORKER_QCLOUD) { + // // String id2name = _userID.subString(10, _userID.length()); + // // memcpy(DEVICE_NAME_HTTP, _userID.c_str(), 12); + // DEVICE_NAME_HTTP = (char*)malloc((_userID.length()+1)*sizeof(char)); + // strcpy(DEVICE_NAME_HTTP, _userID.c_str()); + // String IDtest = _productInfo + _userID; + // MQTT_ID_HTTP = (char*)malloc((IDtest.length()+1)*sizeof(char)); + // strcpy(MQTT_ID_HTTP, IDtest.c_str()); + // String NAMEtest = IDtest + ";" + _userName; + // MQTT_NAME_HTTP = (char*)malloc((NAMEtest.length()+1)*sizeof(char)); + // strcpy(MQTT_NAME_HTTP, NAMEtest.c_str()); + // MQTT_KEY_HTTP = (char*)malloc((_key.length()+1)*sizeof(char)); + // strcpy(MQTT_KEY_HTTP, _key.c_str()); + // } + // else if (_broker == BLINKER_HTTP_BORKER_BLINKER) { + // // memcpy(DEVICE_NAME_HTTP, _userID.c_str(), 12); + // DEVICE_NAME_HTTP = (char*)malloc((_userID.length()+1)*sizeof(char)); + // strcpy(DEVICE_NAME_HTTP, _userID.c_str()); + // MQTT_ID_HTTP = (char*)malloc((_userID.length()+1)*sizeof(char)); + // strcpy(MQTT_ID_HTTP, _userID.c_str()); + // MQTT_NAME_HTTP = (char*)malloc((_userName.length()+1)*sizeof(char)); + // strcpy(MQTT_NAME_HTTP, _userName.c_str()); + // MQTT_KEY_HTTP = (char*)malloc((_key.length()+1)*sizeof(char)); + // strcpy(MQTT_KEY_HTTP, _key.c_str()); + // } + UUID_HTTP = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_HTTP, _uuid.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME_HTTP: "), DEVICE_NAME_HTTP); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_HTTP: "), MQTT_ID_HTTP); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_HTTP: "), MQTT_NAME_HTTP); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_HTTP: "), MQTT_KEY_HTTP); + BLINKER_LOG_ALL(BLINKER_F("UUID_HTTP: "), UUID_HTTP); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + BLINKER_LOG_FreeHeap_ALL(); + + isInit = true; + + isConnect_HTTP = true; + + return true; +} + + + +bool BlinkerHTTP::checkInit() +{ + if (!_isWiFiInit) + { + switch (_configType) + { + case COMM : + _connectTime = millis(); + // BLINKER_LOG(BLINKER_F("checkInit...")); + if (WiFi.status() != WL_CONNECTED) { + ::delay(500); + + if (millis() - _connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { + // _connectTime = millis(); + BLINKER_LOG(BLINKER_F("WiFi connect timeout, please check ssid and pswd!")); + BLINKER_LOG(BLINKER_F("Retring WiFi connect again!")); + return false; + } + + // BLINKER_LOG(BLINKER_F("checkInit...")); + + return false; + } + BLINKER_LOG(BLINKER_F("WiFi Connected.")); + BLINKER_LOG(BLINKER_F("IP Address: ")); + BLINKER_LOG(WiFi.localIP()); + _isWiFiInit = true; + _connectTime = 0; + + // begin(); + + return false; + case BLINKER_SMART_CONFIG : + switch (_configStatus) + { + case SMART_BEGIN : + if (WiFi.smartConfigDone()) + { + BLINKER_LOG(BLINKER_F("SmartConfig received.")); + _connectTime = millis(); + + #if defined(ESP8266) + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + #endif + + _configStatus = SMART_DONE; + } + else return false; + case SMART_DONE : + if (WiFi.status() != WL_CONNECTED) + { + if (millis() - _connectTime > 15000) + { + BLINKER_LOG(BLINKER_F("SmartConfig timeout.")); + WiFi.stopSmartConfig(); + _configStatus = SMART_TIMEOUT; + } + return false; + } + else if (WiFi.status() == WL_CONNECTED) + { + // WiFi.stopSmartConfig(); + + BLINKER_LOG(BLINKER_F("WiFi Connected.")); + BLINKER_LOG(BLINKER_F("IP Address: ")); + BLINKER_LOG(WiFi.localIP()); + _isWiFiInit = true; + _connectTime = 0; + + // begin(); + + return false; + } + // return false; + case SMART_TIMEOUT : + WiFi.beginSmartConfig(); + _configStatus = SMART_BEGIN; + BLINKER_LOG(BLINKER_F("Waiting for SmartConfig.")); + return false; + default : + return false; + } + case BLINKER_AP_CONFIG : + #if defined(BLINKER_APCONFIG) + switch (_configStatus) + { + case APCFG_BEGIN : + checkAPCFG(); + return false; + case APCFG_DONE : + if (WiFi.status() != WL_CONNECTED) + { + if (millis() - _connectTime > 15000) + { + BLINKER_LOG(BLINKER_F("APConfig timeout.")); + _configStatus = APCFG_TIMEOUT; + } + return false; + } + else if (WiFi.status() == WL_CONNECTED) + { + BLINKER_LOG(BLINKER_F("WiFi Connected.")); + BLINKER_LOG(BLINKER_F("IP Address: ")); + BLINKER_LOG(WiFi.localIP()); + _isWiFiInit = true; + _connectTime = 0; + + // begin(); + + return false; + } + // return false; + case APCFG_TIMEOUT : + softAPinit(); + return false; + default : + return false; + } + #endif + default : + return false; + } + } + + // if (!_isBegin) + // { + // _isBegin = begin(); + // return _isBegin; + // } + return true; +} + +void BlinkerHTTP::commonBegin(const char* _ssid, const char* _pswd) +{ + _configType = COMM; + + connectWiFi(_ssid, _pswd); + + #if defined(ESP8266) + BLINKER_LOG(BLINKER_F("ESP8266_HTTP initialized...")); + #elif defined(ESP32) + BLINKER_LOG(BLINKER_F("ESP32_HTTP initialized...")); + #endif +} + +void BlinkerHTTP::smartconfigBegin() +{ + _configType = BLINKER_SMART_CONFIG; + + if (!autoInit()) smartconfig(); + else _configStatus = SMART_DONE; + + #if defined(ESP8266) + BLINKER_LOG(BLINKER_F("ESP8266_HTTP initialized...")); + #elif defined(ESP32) + BLINKER_LOG(BLINKER_F("ESP32_HTTP initialized...")); + #endif +} + +void BlinkerHTTP::apconfigBegin() +{ + #if defined(BLINKER_APCONFIG) + _configType = BLINKER_AP_CONFIG; + + if (!autoInit()) softAPinit(); + else _configStatus = APCFG_DONE; + + #if defined(ESP8266) + BLINKER_LOG(BLINKER_F("ESP8266_HTTP initialized...")); + #elif defined(ESP32) + BLINKER_LOG(BLINKER_F("ESP32_HTTP initialized...")); + #endif + #endif +} + +bool BlinkerHTTP::autoInit() +{ + WiFi.mode(WIFI_STA); + String _hostname = BLINKER_F("DiyArduino_"); + _hostname += macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(_hostname.c_str()); + #elif defined(ESP32) + WiFi.setHostname(_hostname.c_str()); + #endif + + WiFi.begin(); + ::delay(500); + + BLINKER_LOG(BLINKER_F("Waiting for WiFi "), + BLINKER_WIFI_AUTO_INIT_TIMEOUT / 1000, + BLINKER_F("s, will enter SMARTCONFIG or "), + BLINKER_F("APCONFIG while WiFi not connect!")); + + uint8_t _times = 0; + while (WiFi.status() != WL_CONNECTED) { + ::delay(500); + if (_times > BLINKER_WIFI_AUTO_INIT_TIMEOUT / 500) break; + _times++; + } + + if (WiFi.status() != WL_CONNECTED) return false; + else { + // BLINKER_LOG(BLINKER_F("WiFi Connected.")); + // BLINKER_LOG(BLINKER_F("IP Address: ")); + // BLINKER_LOG(WiFi.localIP()); + // _isWiFiInit = true; + + // begin(); + + return true; + } +} + +void BlinkerHTTP::smartconfig() +{ + WiFi.mode(WIFI_STA); + + String _hostname = BLINKER_F("DiyArduino_"); + _hostname += macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(_hostname.c_str()); + #elif defined(ESP32) + WiFi.setHostname(_hostname.c_str()); + #endif + + WiFi.beginSmartConfig(); + + _configStatus = SMART_BEGIN; + + BLINKER_LOG(BLINKER_F("Waiting for SmartConfig.")); + // while (!WiFi.smartConfigDone()) { + // ::delay(500); + // } + + // BLINKER_LOG(BLINKER_F("SmartConfig received.")); + + // BLINKER_LOG(BLINKER_F("Waiting for WiFi")); + // while (WiFi.status() != WL_CONNECTED) { + // ::delay(500); + // } + + // BLINKER_LOG(BLINKER_F("WiFi Connected.")); + + // BLINKER_LOG(BLINKER_F("IP Address: ")); + // BLINKER_LOG(WiFi.localIP()); +} +#if defined(BLINKER_APCONFIG) +void BlinkerHTTP::softAPinit() +{ + // WiFiServer _apServer(80); + // WiFiClient _apClient; + IPAddress apIP(192, 168, 4, 1); + #if defined(ESP8266) + IPAddress netMsk(255, 255, 255, 0); + #endif + + // _apServer = new WiFiServer(80); + + WiFi.mode(WIFI_AP); + + delay(1000); + + String softAP_ssid = BLINKER_F("DiyArduino_"); + softAP_ssid += macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(softAP_ssid.c_str()); + WiFi.softAPConfig(apIP, apIP, netMsk); + #elif defined(ESP32) + WiFi.setHostname(softAP_ssid.c_str()); + WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); + #endif + + WiFi.softAP(softAP_ssid.c_str(), NULL); + delay(100); + + // _apServer->begin(); + // BLINKER_LOG(BLINKER_F("AP IP address: "), WiFi.softAPIP()); + // BLINKER_LOG(BLINKER_F("HTTP _apServer started")); + // BLINKER_LOG(BLINKER_F("URL: http://"), WiFi.softAPIP()); + + #if defined(ESP8266) + if (!MDNS.begin(softAP_ssid.c_str(), WiFi.localIP())) { + #elif defined(ESP32) + if (!MDNS.begin(softAP_ssid.c_str())) { + #endif + while(1) { + ::delay(100); + } + } + + BLINKER_LOG(BLINKER_F("mDNS responder started")); + + MDNS.addService(BLINKER_MDNS_SERVICE_BLINKER, "tcp", WS_SERVERPORT); + MDNS.addServiceTxt(BLINKER_MDNS_SERVICE_BLINKER, "tcp", "deviceName", macDeviceName()); + + webSocket_HTTP.begin(); + webSocket_HTTP.onEvent(webSocketEvent_HTTP); + + _configStatus = APCFG_BEGIN; + isApCfg = true; + + BLINKER_LOG(BLINKER_F("Wait for APConfig")); + + // while(WiFi.status() != WL_CONNECTED) + // { + // // serverClient(); + // _apClient = _apServer->available(); + // // if (_apClient.status() == CLOSED) + // if (!_apClient.connected()) + // { + // _apClient.stop(); + // BLINKER_LOG(BLINKER_F("Connection closed on _apClient")); + // } + // else + // { + // if (_apClient.available()) + // { + // String data = _apClient.readStringUntil('\r'); + + // // data = data.substring(4, data.length() - 9); + // _apClient.flush(); + + // BLINKER_LOG(BLINKER_F("clientData: "), data); + + // if (STRING_contains_string(data, "ssid") && + // STRING_contains_string(data, "pswd")) + // { + // String msg = BLINKER_F("{\"hello\":\"world\"}"); + + // String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); + // s += BLINKER_F("Content-Type: application/json;"); + // s += BLINKER_F("charset=utf-8\r\n"); + // s += BLINKER_F("Content-Length: "); + // s += String(msg.length()); + // s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); + // s += msg; + // s += BLINKER_F("\r\n"); + + // _apClient.print(s); + + // _apClient.stop(); + + // parseUrl(data); + // } + // } + // } + // ::delay(10); + // } +} + +void BlinkerHTTP::checkAPCFG() +{ + // if(WiFi.status() != WL_CONNECTED) + // { + webSocket_HTTP.loop(); + + #if defined(ESP8266) + MDNS.update(); + #endif + + if (isAvail_HTTP) + { + BLINKER_LOG(BLINKER_F("checkAPCFG: "), msgBuf_HTTP); + + if (STRING_contains_string(msgBuf_HTTP, "ssid") && \ + STRING_contains_string(msgBuf_HTTP, "pswd")) + { + parseUrl(msgBuf_HTTP); + } + isAvail_HTTP = false; + } + + // serverClient(); + // _apClient = _apServer->available(); + // // if (_apClient.status() == CLOSED) + // if (!_apClient.connected()) + // { + // _apClient.stop(); + // BLINKER_LOG(BLINKER_F("Connection closed on _apClient")); + // } + // else + // { + // if (_apClient.available()) + // { + // String data = _apClient.readStringUntil('\r'); + + // // data = data.substring(4, data.length() - 9); + // _apClient.flush(); + + // BLINKER_LOG(BLINKER_F("clientData: "), data); + + // if (STRING_contains_string(data, "ssid") && + // STRING_contains_string(data, "pswd")) + // { + // String msg = BLINKER_F("{\"hello\":\"world\"}"); + + // String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); + // s += BLINKER_F("Content-Type: application/json;"); + // s += BLINKER_F("charset=utf-8\r\n"); + // s += BLINKER_F("Content-Length: "); + // s += String(msg.length()); + // s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); + // s += msg; + // s += BLINKER_F("\r\n"); + + // _apClient.print(s); + + // _apClient.stop(); + + // parseUrl(data); + // } + // } + // } + // ::delay(10); + // } +} + +// void BlinkerHTTP::serverClient() +// { +// if (!_apClient) +// { +// _apClient = _apServer->available(); +// } +// else +// { +// // if (_apClient.status() == CLOSED) +// if (!_apClient.connected()) +// { +// _apClient.stop(); +// BLINKER_LOG(BLINKER_F("Connection closed on _apClient")); +// } +// else +// { +// if (_apClient.available()) +// { +// String data = _apClient.readStringUntil('\r'); + +// // data = data.substring(4, data.length() - 9); +// _apClient.flush(); + +// BLINKER_LOG(BLINKER_F("clientData: "), data); + +// if (STRING_contains_string(data, "ssid") && +// STRING_contains_string(data, "pswd")) +// { +// String msg = BLINKER_F("{\"hello\":\"world\"}"); + +// String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); +// s += BLINKER_F("Content-Type: application/json;"); +// s += BLINKER_F("charset=utf-8\r\n"); +// s += BLINKER_F("Content-Length: "); +// s += String(msg.length()); +// s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); +// s += msg; +// s += BLINKER_F("\r\n"); + +// _apClient.print(s); + +// _apClient.stop(); + +// parseUrl(data); +// } +// } +// } +// } +// } + +bool BlinkerHTTP::parseUrl(String data) +{ + BLINKER_LOG(BLINKER_F("APCONFIG data: "), data); + // DynamicJsonBuffer jsonBuffer; + // JsonObject& wifi_data = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject wifi_data = jsonBuffer.as(); + + // if (!wifi_data.success()) + if (error) + { + return false; + } + + String _ssid = wifi_data["ssid"]; + String _pswd = wifi_data["pswd"]; + + BLINKER_LOG(BLINKER_F("ssid: "), _ssid); + BLINKER_LOG(BLINKER_F("pswd: "), _pswd); + + // free(_apServer); + MDNS.end(); + webSocket_HTTP.close(); + + connectWiFi(_ssid, _pswd); + + _configStatus = APCFG_DONE; + _connectTime = millis(); + return true; +} +#endif +void BlinkerHTTP::connectWiFi(String _ssid, String _pswd) +{ + connectWiFi(_ssid.c_str(), _pswd.c_str()); +} + +void BlinkerHTTP::connectWiFi(const char* _ssid, const char* _pswd) +{ + uint32_t _connectTime = millis(); + + BLINKER_LOG(BLINKER_F("Connecting to "), _ssid); + + WiFi.mode(WIFI_STA); + String _hostname = BLINKER_F("DiyArduinoMQTT_"); + _hostname += macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(_hostname.c_str()); + #elif defined(ESP32) + WiFi.setHostname(_hostname.c_str()); + #endif + + if (_pswd && strlen(_pswd)) { + WiFi.begin(_ssid, _pswd); + } + else { + WiFi.begin(_ssid); + } + + // while (WiFi.status() != WL_CONNECTED) { + // ::delay(50); + + // if (millis() - _connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { + // _connectTime = millis(); + // BLINKER_LOG(BLINKER_F("WiFi connect timeout, please check ssid and pswd!")); + // BLINKER_LOG(BLINKER_F("Retring WiFi connect again!")); + // } + // } + // BLINKER_LOG(BLINKER_F("Connected")); + + // IPAddress myip = WiFi.localIP(); + // BLINKER_LOG(BLINKER_F("Your IP is: "), myip); + + // _isWiFiInit = true; +} + +#endif + +#endif diff --git a/blinker-library/src/Adapters/BlinkerMQTT.h b/blinker-library/src/Adapters/BlinkerMQTT.h new file mode 100644 index 0000000..0d1e514 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerMQTT.h @@ -0,0 +1,3397 @@ +#ifndef BLINKER_MQTT_H +#define BLINKER_MQTT_H + +#if (defined(ESP8266) || defined(ESP32)) + +#define BLINKER_MQTT + +#if defined(ESP8266) + #include + #include + #include + #include + + #include + + ESP8266WiFiMulti wifiMulti; +#elif defined(ESP32) + #include + + #if defined(ESP32) + extern "C" { + #include + #include + #include + } + #endif + + #include + #include + #include + + #include + + WiFiMulti wifiMulti; +#endif + +#include + +#include "../modules/WebSockets/WebSocketsServer.h" +#include "../modules/mqtt/Adafruit_MQTT.h" +#include "../modules/mqtt/Adafruit_MQTT_Client.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +// #include "Adapters/BlinkerMQTT.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +enum b_config_t { + COMM, + BLINKER_SMART_CONFIG, + BLINKER_AP_CONFIG, + BLINKER_MULTI +}; + +enum b_configStatus_t { + AUTO_INIT, + AUTO_DONE, + SMART_BEGIN, + SMART_DONE, + SMART_TIMEOUT, + APCFG_BEGIN, + APCFG_DONE, + APCFG_TIMEOUT +}; + +enum b_broker_t { + aliyun_b, + blinker_b +}; + + +// static WiFiServer *_apServer; +// static WiFiClient _apClient; + +// class BlinkerSharer +// { +// public : +// BlinkerSharer(const String & _uuid) +// { +// name = (char*)malloc((_uuid.length()+1)*sizeof(char)); +// strcpy(name, _uuid.c_str()); +// } + +// char * uuid() { return name; } + +// private : +// char * name; +// }; + +char* MQTT_HOST_MQTT; +char* MQTT_ID_MQTT; +char* MQTT_NAME_MQTT; +char* MQTT_KEY_MQTT; +char* MQTT_PRODUCTINFO_MQTT; +char* UUID_MQTT; +char* DEVICE_NAME_MQTT; +char* BLINKER_PUB_TOPIC_MQTT; +char* BLINKER_SUB_TOPIC_MQTT; +// char* BLINKER_RRPC_PUB_TOPIC_MQTT; +char* BLINKER_RRPC_SUB_TOPIC_MQTT; +uint16_t MQTT_PORT_MQTT; + +class BlinkerMQTT : public BlinkerStream +{ + public : + BlinkerMQTT(); + + int connect(); + int connected(); + int mConnected(); + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + int miAvail(); + // bool extraAvailable(); + void subscribe(); + char * lastRead(); + void flush(); + int print(char * data, bool needCheck = true); + int toServer(char * data); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + int miPrint(const String & data); + void aliType(const String & type); + void duerType(const String & type); + void miType(const String & type); + void begin(const char* auth); + bool begin(); + int autoPrint(unsigned long id); + // bool autoPrint(char *name, char *type, char *data); + // bool autoPrint(char *name1, char *type1, char *data1, + // char *name2, char *type2, char *data2); + char * deviceName(); + char * authKey() { return _authKey; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_MQTT; } + int init() { if (!isMQTTinit) checkInit(); return isMQTTinit; } + int reRegister() { return connectServer(); } + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + bool checkInit(); + void commonBegin(const char* _ssid, const char* _pswd); + void smartconfigBegin(); + void multiBegin(const char* _ssid, const char* _pswd); + void apconfigBegin(); + bool autoInit(); + void smartconfig(); + #if defined(BLINKER_APCONFIG) + void softAPinit(); + void checkAPCFG(); + bool parseUrl(String data); + #endif + void connectWiFi(String _ssid, String _pswd); + void connectWiFi(const char* _ssid, const char* _pswd); + + private : + bool isMQTTinit = false; + bool isMQTTset = false; + + int connectServer(); + void mDNSInit(); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkMIOTKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + int checkMIOTPrintSpan(); + int checkPrintLimit(); + void parseData(const char* data); + + bool checkConfig(); + + protected : + b_broker_t _use_broker = aliyun_b; + char _messageId[20]; + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + bool _isWiFiInit = false; + bool _isBegin = false; + b_config_t _configType = COMM; + b_configStatus_t _configStatus = AUTO_INIT; + uint32_t _connectTime = 0; + uint8_t _connectTimes = 0; + // const char* _authKey; + char* _authKey; + char* _aliType; + char* _duerType; + char* _miType; + // char _authKey[BLINKER_AUTHKEY_SIZE]; + bool* isHandle;// = &isConnect; + bool isAlive = false; + // bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + uint8_t respMIOTTimes = 0; + uint32_t respMIOTTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + uint32_t miKaTime = 0; + bool isMIOTAlive = false; + bool isMIOTAvail = false; + char* mqtt_broker; + + int isJson(const String & data); + + #if defined(BLINKER_APCONFIG) + // WiFiServer *_apServer; + // WiFiClient _apClient; + #endif + + uint8_t reconnect_time = 0; + uint32_t _reRegister_time = 0; + uint8_t _reRegister_times = 0; + + uint32_t _print_time = 0; + uint8_t _print_times = 0; + + char message_id[24]; + bool is_rrpc = false; +}; + +#if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + BearSSL::WiFiClientSecure client_mqtt; + #else + WiFiClient client_mqtt; + #endif + // WiFiClientSecure client_mqtt; +#elif defined(ESP32) + WiFiClientSecure client_s; +#endif + +#define BLINKER_PROTOCOL_MQTT mqtt_MQTT + +WiFiClient client; +Adafruit_MQTT_Client* mqtt_MQTT = NULL; +// Adafruit_MQTT_Publish *iotPub; +Adafruit_MQTT_Subscribe* iotSub_MQTT; +// Adafruit_MQTT_Subscribe* iotSub_RRPC_MQTT; + +#define WS_SERVERPORT 81 +WebSocketsServer webSocket_MQTT = WebSocketsServer(WS_SERVERPORT); + +char* msgBuf_MQTT; +bool isFresh_MQTT = false; +bool isConnect_MQTT = false; +bool isAvail_MQTT = false; +bool isApCfg = false; +uint8_t ws_num_MQTT = 0; +uint8_t dataFrom_MQTT = BLINKER_MSG_FROM_MQTT; + +void webSocketEvent_MQTT(uint8_t num, WStype_t type, \ + uint8_t * payload, size_t length) +{ + + switch(type) + { + case WStype_DISCONNECTED: + BLINKER_LOG_ALL(BLINKER_F("Disconnected! "), num); + + if (!isApCfg) isConnect_MQTT = false; + break; + case WStype_CONNECTED: + { + IPAddress ip = webSocket_MQTT.remoteIP(num); + + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", Connected from: "), ip, + BLINKER_F(", url: "), (char *)payload); + + // send message to client + webSocket_MQTT.sendTXT(num, "{\"state\":\"connected\"}\n"); + + ws_num_MQTT = num; + + if (!isApCfg) isConnect_MQTT = true; + } + break; + case WStype_TEXT: + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", get Text: "), (char *)payload, \ + BLINKER_F(", length: "), length); + + if (length < BLINKER_MAX_READ_SIZE) { + if (isFresh_MQTT) free(msgBuf_MQTT); + msgBuf_MQTT = (char*)malloc((length+1)*sizeof(char)); + strcpy(msgBuf_MQTT, (char*)payload); + isAvail_MQTT = true; + isFresh_MQTT = true; + + BLINKER_LOG_ALL(BLINKER_F("isAvail_MQTT: "), isAvail_MQTT); + } + + if (!isApCfg) dataFrom_MQTT = BLINKER_MSG_FROM_WS; + + ws_num_MQTT = num; + + // send message to client + // webSocket_MQTT.sendTXT(num, "message here"); + + // send data to all connected clients + // webSocket_MQTT.broadcastTXT("message here"); + break; + case WStype_BIN: + // BLINKER_LOG("num: ", num, " get binary length: ", length); + // hexdump(payload, length); + + // send message to client + // webSocket_MQTT.sendBIN(num, payload, length); + break; + default : + break; + } +} + +BlinkerMQTT::BlinkerMQTT() { isHandle = &isConnect_MQTT; } + +uint32_t con_log = 0; + +int BlinkerMQTT::connect() +{ + if (!checkInit()) return false; + + int8_t ret; + + // if ((millis() - con_log) >= 5000) + // { + // con_log += 5000; + // BLINKER_LOG(BLINKER_F("Connecting to MQTT...heap ")); + // BLINKER_LOG_FreeHeap_ALL(); + // } + + webSocket_MQTT.loop(); + + if (mqtt_MQTT->connected()) + { + return true; + } + + disconnect(); + + if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + { + yield(); + return false; + } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + BLINKER_LOG(BLINKER_F("reconnect_time: "), reconnect_time); + + // if (reconnect_time >= 12) + // { + // // if ((millis() - _reRegister_time) >= 60000) + // // { + // // // reRegister(); + // ESP.restart(); + // // } + // // else + // // { + // // return false; + // // } + // // reconnect_time = 0; + // } + + // BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_MQTT: "), MQTT_ID_MQTT); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_MQTT: "), MQTT_NAME_MQTT); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_MQTT: "), MQTT_KEY_MQTT); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + client_mqtt.setInsecure(); + ::delay(10); + #endif + #endif + + if ((ret = mqtt_MQTT->connect()) != 0) + { + BLINKER_LOG(mqtt_MQTT->connectErrorString(ret)); + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + if (ret == 4) + { + if (_reRegister_times < BLINKER_SERVER_CONNECT_LIMIT) + { + if (reRegister()) + { + _reRegister_times = 0; + } + else + { + _reRegister_times++; + _reRegister_time = millis(); + } + } + else + { + if (millis() - _reRegister_time >= 60000 * 1) _reRegister_times = 0; + } + + BLINKER_LOG_ALL(BLINKER_F("_reRegister_times1: "), _reRegister_times); + return false; + } + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 6) + { + if (_reRegister_times < BLINKER_SERVER_CONNECT_LIMIT) + { + if (reRegister()) + { + _reRegister_times = 0; + } + else + { + _reRegister_times++; + _reRegister_time = millis(); + } + } + else + { + if (millis() - _reRegister_time >= 60000 * 1) _reRegister_times = 0; + } + + reconnect_time = 0; + + BLINKER_LOG_ALL(BLINKER_F("_reRegister_times2: "), _reRegister_times); + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + if (!isMQTTinit) + { + isMQTTinit = true; + + mqtt_MQTT->subscribeTopic(BLINKER_SUB_TOPIC_MQTT); + BLINKER_LOG_ALL(BLINKER_F("MQTT subscribe: "), BLINKER_SUB_TOPIC_MQTT); + } + + this->latestTime = millis(); + + return true; +} + +int BlinkerMQTT::connected() +{ + if (!checkInit()) return false; + + // BLINKER_LOG_ALL(BLINKER_F("MQTT Connected check: "), connect()); + // BLINKER_LOG_ALL(BLINKER_F("isMQTTinit"), isMQTTinit); + + if (!isMQTTinit) + { + connect(); + return *isHandle; + } + + return mqtt_MQTT->connected() || *isHandle; +} + +int BlinkerMQTT::mConnected() +{ + if (!checkInit()) return false; + + if (!isMQTTinit) return false; + else return mqtt_MQTT->connected(); +} + +void BlinkerMQTT::disconnect() +{ + if (!checkInit()) return; + + if (isMQTTset) { + // mqtt_MQTT->disconnect(); + mqtt_MQTT->disconnectServer(); + + // BLINKER_LOG_ALL(BLINKER_F("disconnectServer")); + } + + if (*isHandle) webSocket_MQTT.disconnect(); +} + +void BlinkerMQTT::ping() +{ + if (!checkInit()) return; + + BLINKER_LOG(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!mqtt_MQTT->ping()) + { + disconnect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } +} + +int BlinkerMQTT::available() +{ + if (!checkInit()) return false; + + webSocket_MQTT.loop(); + + checkKA(); +#if defined(ESP8266) + MDNS.update(); +#endif + // if (!mqtt_MQTT->connected() || + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + { + ping(); + } + else + { + subscribe(); + } + + if (isAvail_MQTT) + { + BLINKER_LOG_ALL(BLINKER_F("available: "), isAvail_MQTT); + + isAvail_MQTT = false; + return true; + } + else { + return false; + } +} + +int BlinkerMQTT::aligenieAvail() +{ + if (!checkInit()) return false; + + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerMQTT::duerAvail() +{ + if (!checkInit()) return false; + + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerMQTT::miAvail() +{ + if (!checkInit()) return false; + + if (isMIOTAvail) + { + isMIOTAvail = false; + return true; + } + else { + return false; + } +} + +// bool BlinkerMQTT::extraAvailable() +// { +// if (isBavail) +// { +// isBavail = false; +// return true; +// } +// else +// { +// return false; +// } +// } + +void BlinkerMQTT::subscribe() +{ + if (!checkInit()) return; + + if (!isMQTTinit) return; + + Adafruit_MQTT_Subscribe *subscription; + while ((subscription = mqtt_MQTT->readSubscription(10))) + { + if (subscription == iotSub_MQTT) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), (char *)iotSub_MQTT->lastread); + + parseData((char *)iotSub_MQTT->lastread); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(String((char *)iotSub_MQTT->lastread)); + // DynamicJsonDocument jsonBuffer(1024); + // deserializeJson(jsonBuffer, String((char *)iotSub_MQTT->lastread)); + // JsonObject root = jsonBuffer.as(); + + // String _uuid = root["fromDevice"].as(); + // String dataGet = root["data"].as(); + + // BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + // BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + // if (strcmp(_uuid.c_str(), UUID_MQTT) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + // kaTime = millis(); + // isAvail_MQTT = true; + // isAlive = true; + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // } + // else if (_uuid == BLINKER_CMD_ALIGENIE) + // { + // BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + // aliKaTime = millis(); + // isAliAlive = true; + // isAliAvail = true; + // } + // else if (_uuid == BLINKER_CMD_DUEROS) + // { + // BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + // duerKaTime = millis(); + // isDuerAlive = true; + // isDuerAvail = true; + // } + // else if (_uuid == BLINKER_CMD_MIOT) + // { + // BLINKER_LOG_ALL(BLINKER_F("form MIOT")); + + // miKaTime = millis(); + // isMIOTAlive = true; + // isMIOTAvail = true; + // } + // else if (_uuid == BLINKER_CMD_SERVERCLIENT) + // { + // BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + // isAvail_MQTT = true; + // isAlive = true; + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // } + // else + // { + // if (_sharerCount) + // { + // for (uint8_t num = 0; num < _sharerCount; num++) + // { + // if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + // { + // _sharerFrom = num; + + // kaTime = millis(); + + // BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + // BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + // _needCheckShare = false; + + // break; + // } + // else + // { + // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, check is from bridge/share device, data: "), dataGet); + + // _needCheckShare = true; + // } + // } + // } + // // else + // // { + // // dataGet = String((char *)iotSub_MQTT->lastread); + // // root.printTo(dataGet); + // serializeJson(root, dataGet); + + // // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, + // // check is from bridge/share device, \ + // // data: "), dataGet); + + // // // return; + + // // // isBavail = true; + + // // _needCheckShare = true; + // // } + + // isAvail_MQTT = true; + // isAlive = true; + // } + + // // memset(msgBuf_MQTT, 0, BLINKER_MAX_READ_SIZE); + // // memcpy(msgBuf_MQTT, dataGet.c_str(), dataGet.length()); + + // if (isFresh_MQTT) free(msgBuf_MQTT); + // msgBuf_MQTT = (char*)malloc((dataGet.length()+1)*sizeof(char)); + // strcpy(msgBuf_MQTT, dataGet.c_str()); + // isFresh_MQTT = true; + + // this->latestTime = millis(); + + // dataFrom_MQTT = BLINKER_MSG_FROM_MQTT; + } + // else if (subscription == iotSub_RRPC_MQTT) + // { + // BLINKER_LOG_ALL(BLINKER_F("Got: "), (char *)iotSub_RRPC_MQTT->lastread); + // } + } + + if (mqtt_MQTT->check_extra()) + { + BLINKER_LOG_ALL(BLINKER_F("Got extra topic: "), (char *)mqtt_MQTT->get_extra_topic()); + BLINKER_LOG_ALL(BLINKER_F("Got extra data: "), (char *)mqtt_MQTT->get_extra_data()); + + if (strncmp(BLINKER_RRPC_SUB_TOPIC_MQTT, + (char *)mqtt_MQTT->get_extra_topic(), + strlen(BLINKER_RRPC_SUB_TOPIC_MQTT)) + == 0) + { + // char message_id[24]; + memset(message_id, '\0', 24); + + memmove(message_id, + mqtt_MQTT->get_extra_topic()+strlen(BLINKER_RRPC_SUB_TOPIC_MQTT), + strlen(mqtt_MQTT->get_extra_topic()) - strlen(BLINKER_RRPC_SUB_TOPIC_MQTT)); + + BLINKER_LOG_ALL(BLINKER_F("from server RRPC, message_id: "), message_id); + + parseData((char *)mqtt_MQTT->get_extra_data()); + + // char BLINKER_RRPC_PUB_TOPIC_MQTT[128]; + + // strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, "/sys/"); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_PRODUCTINFO_MQTT); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/"); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_ID_MQTT); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/rrpc/response/"); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, message_id); + + is_rrpc = true; + + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_RRPC_PUB_TOPIC_MQTT: "), BLINKER_RRPC_PUB_TOPIC_MQTT); + + // mqtt_MQTT->publish(BLINKER_RRPC_PUB_TOPIC_MQTT, base64::encode("hello blinker").c_str()); + } + } +} + +void BlinkerMQTT::parseData(const char* data) +{ + DynamicJsonDocument jsonBuffer(1024); + deserializeJson(jsonBuffer, String(data)); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"].as(); + String dataGet = root["data"].as(); + + if (_use_broker == blinker_b) + { + if (_uuid == "ServerSender") + { + _uuid = root["data"]["from"].as(); + String _mId = root["data"]["messageId"].as(); + strcpy(_messageId, _mId.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_messageId: "), _mId); + } + } + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_MQTT) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_MQTT = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_MIOT) + { + BLINKER_LOG_ALL(BLINKER_F("form MIOT")); + + miKaTime = millis(); + isMIOTAlive = true; + isMIOTAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT || _uuid == "senderClient1") + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_MQTT = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + BLINKER_LOG_ALL(BLINKER_F("_sharerCount: "), _sharerCount); + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + dataGet = root["data"].as(); + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, check is from bridge/share device, data: "), dataGet); + + _needCheckShare = true; + + dataGet = data; + } + } + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority&share uuid found, check is from bridge/share device, data: "), dataGet); + + _needCheckShare = true; + + dataGet = data; + } + // dataGet = String((char *)iotSub_MQTT->lastread); + // root.printTo(dataGet); + // serializeJson(root, dataGet); + + // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, + // check is from bridge/share device, \ + // data: "), dataGet); + + // // return; + + // // isBavail = true; + + // _needCheckShare = true; + // } + + isAvail_MQTT = true; + isAlive = true; + } + + // memset(msgBuf_MQTT, 0, BLINKER_MAX_READ_SIZE); + // memcpy(msgBuf_MQTT, dataGet.c_str(), dataGet.length()); + + if (isFresh_MQTT) free(msgBuf_MQTT); + msgBuf_MQTT = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_MQTT, dataGet.c_str()); + isFresh_MQTT = true; + + this->latestTime = millis(); + + dataFrom_MQTT = BLINKER_MSG_FROM_MQTT; +} + +char * BlinkerMQTT::lastRead() +{ + if (isFresh_MQTT) return msgBuf_MQTT; + else return ""; +} + +void BlinkerMQTT::flush() +{ + if (isFresh_MQTT) + { + BLINKER_LOG_ALL(BLINKER_F("flush")); + + // _needCheckShare = false; + + free(msgBuf_MQTT); isFresh_MQTT = false; isAvail_MQTT = false; + isAliAvail = false; isDuerAvail = false; isMIOTAvail = false;//isBavail = false; + } +} + +int BlinkerMQTT::print(char * data, bool needCheck) +{ + if (!checkInit()) return false; + + // BLINKER_LOG_FreeHeap(); + if (*isHandle && dataFrom_MQTT == BLINKER_MSG_FROM_WS) + { + if (needCheck) + { + if (!checkPrintSpan()) + { + respTime = millis(); + return false; + } + } + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("WS response: ")); + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + strcat(data, BLINKER_CMD_NEWLINE); + + webSocket_MQTT.sendTXT(ws_num_MQTT, data); + + return true; + } + else + { + // // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // uint8_t num = strlen(data) - 1; + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data.substring(0, data.length() - 1); + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_ID_MQTT; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_MQTT; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + // else + // { + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data; + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_ID_MQTT; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_MQTT; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + + uint16_t num = strlen(data); + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+7] = data[c_num-1]; + } + + data[num+8] = '\0'; + + char data_add[20] = "{\"data\":"; + for(uint8_t c_num = 0; c_num < 8; c_num++) + { + data[c_num] = data_add[c_num]; + } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, ",\"fromDevice\":\""); + strcat(data, DEVICE_NAME_MQTT); + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, "\",\"toDevice\":\""); + + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + strcat(data, _sharers[_sharerFrom]->uuid()); + } + else + { + strcat(data, UUID_MQTT); + } + // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // strcat(data, data_add.c_str()); + + strcat(data, "\",\"deviceType\":\"OwnApp\"}"); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + if (!isJson(STRING_format(data))) return false; + + // String data_add = BLINKER_F("{\"data\":"); + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\""); + // if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + // { + // data_add += _sharers[_sharerFrom]->uuid(); + // } + // else + // { + // data_add += UUID_MQTT; + // } + + // data_add += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + // if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (mqtt_MQTT->connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + + if (!checkPrintLimit()) + { + return false; + } + + _print_times++; + + BLINKER_LOG_ALL(BLINKER_F("_print_times: "), _print_times); + } + + // if (! mqtt_MQTT->publish(BLINKER_PUB_TOPIC_MQTT, data_add.c_str())) + if (! mqtt_MQTT->publish(BLINKER_PUB_TOPIC_MQTT, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } + } +} + +int BlinkerMQTT::toServer(char * data) +{ + if (!checkInit()) return false; + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish to server...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (mqtt_MQTT->connected()) + { + if (! mqtt_MQTT->publish(BLINKER_PUB_TOPIC_MQTT, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerMQTT::bPrint(char * name, const String & data) +{ + if (!checkInit()) return false; + + // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data.substring(0, data.length() - 1); + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_ID_MQTT; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + // else + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data; + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_ID_MQTT; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + + String data_add = BLINKER_F("{\"data\":"); + // for(uint8_t c_num = 0; c_num < 8; c_num++) + // { + // data[c_num] = data_add[c_num]; + // } + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += DEVICE_NAME_MQTT; + data_add += BLINKER_F("\",\"toDevice\":\""); + data_add += name; + data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, MQTT_ID_MQTT); + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, name); + // data_add = BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // strcat(data, data_add.c_str()); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_MQTT->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + + // if (! iotPub.publish(payload.c_str())) { + + // String bPubTopic = BLINKER_F(""); + + // if (strcmp(mqtt_broker, BLINKER_MQTT_BORKER_ONENET) == 0) + // { + // bPubTopic = MQTT_PRODUCTINFO_MQTT; + // bPubTopic += BLINKER_F("/"); + // bPubTopic += name; + // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // bPubTopic = BLINKER_PUB_TOPIC_MQTT; + // } + + if (! mqtt_MQTT->publish(BLINKER_PUB_TOPIC_MQTT, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerMQTT::aliPrint(const String & data) +{ + if (!checkInit()) return false; + + String data_add = BLINKER_F("{\"data\":"); + + if (_use_broker == aliyun_b) + { + data_add += data; + } + else if (_use_broker == blinker_b) + { + data_add += data.substring(0, data.length() - 1); + data_add += BLINKER_F(",\"messageId\":\""); + data_add += STRING_format(_messageId); + data_add += BLINKER_F("\"}"); + } + + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += DEVICE_NAME_MQTT; + + if (_use_broker == aliyun_b) + { + data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + } + else if (_use_broker == blinker_b) + { + data_add += BLINKER_F("\",\"toDevice\":\"ServerReceiver\""); + } + + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_MQTT->connected()) + { + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + + char BLINKER_RRPC_PUB_TOPIC_MQTT[128]; + + if (is_rrpc) + { + + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, "/sys/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_PRODUCTINFO_MQTT); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, DEVICE_NAME_MQTT); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/rrpc/response/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, message_id); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_RRPC_PUB_TOPIC_MQTT: "), BLINKER_RRPC_PUB_TOPIC_MQTT); + } + else + { + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, BLINKER_PUB_TOPIC_MQTT); + } + + is_rrpc = false; + + char send_data[1024]; + + if (_use_broker == aliyun_b) + { + strcpy(send_data, base64::encode(data_add).c_str()); + } + else if (_use_broker == blinker_b) + { + strcpy(send_data, data_add.c_str()); + } + + if (! mqtt_MQTT->publish(BLINKER_RRPC_PUB_TOPIC_MQTT, send_data)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerMQTT::duerPrint(const String & data, bool report) +{ + if (!checkInit()) return false; + + String data_add = BLINKER_F("{\"data\":"); + + if (report) + { + data_add += BLINKER_F("{\"report\":"); + + if (_use_broker == aliyun_b) + { + data_add += data; + } + else if (_use_broker == blinker_b) + { + data_add += data.substring(0, data.length() - 1); + data_add += BLINKER_F(",\"messageId\":\""); + data_add += STRING_format(_messageId); + data_add += BLINKER_F("\"}"); + } + + data_add += BLINKER_F("}"); + } + else + { + if (_use_broker == aliyun_b) + { + data_add += data; + } + else if (_use_broker == blinker_b) + { + data_add += data.substring(0, data.length() - 1); + data_add += BLINKER_F(",\"messageId\":\""); + data_add += STRING_format(_messageId); + data_add += BLINKER_F("\"}"); + } + } + + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += DEVICE_NAME_MQTT; + if (_use_broker == aliyun_b) + { + data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + } + else if (_use_broker == blinker_b) + { + data_add += BLINKER_F("\",\"toDevice\":\"ServerReceiver\""); + } + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + BLINKER_LOG_ALL(BLINKER_F("is_rrpc: "), is_rrpc); + + if (mqtt_MQTT->connected()) + { + // if (!checkDuerKA()) + // { + // return false; + // } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + + char BLINKER_RRPC_PUB_TOPIC_MQTT[128]; + + if (is_rrpc) + { + + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, "/sys/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_PRODUCTINFO_MQTT); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, DEVICE_NAME_MQTT); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/rrpc/response/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, message_id); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_RRPC_PUB_TOPIC_MQTT: "), BLINKER_RRPC_PUB_TOPIC_MQTT); + } + else + { + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, BLINKER_PUB_TOPIC_MQTT); + } + + char send_data[1024]; + + if (_use_broker == aliyun_b) + { + strcpy(send_data, base64::encode(data_add).c_str()); + } + else if (_use_broker == blinker_b) + { + strcpy(send_data, data_add.c_str()); + } + + if (! mqtt_MQTT->publish(BLINKER_RRPC_PUB_TOPIC_MQTT, send_data)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + is_rrpc = false; + + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + is_rrpc = false; + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerMQTT::miPrint(const String & data) +{ + if (!checkInit()) return false; + + String data_add = BLINKER_F("{\"data\":"); + + if (_use_broker == aliyun_b) + { + data_add += data; + } + else if (_use_broker == blinker_b) + { + data_add += data.substring(0, data.length() - 1); + data_add += BLINKER_F(",\"messageId\":\""); + data_add += STRING_format(_messageId); + data_add += BLINKER_F("\"}"); + } + + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += DEVICE_NAME_MQTT; + if (_use_broker == aliyun_b) + { + data_add += BLINKER_F("\",\"toDevice\":\"MIOT_r\""); + } + else if (_use_broker == blinker_b) + { + data_add += BLINKER_F("\",\"toDevice\":\"ServerReceiver\""); + } + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT MIOT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_MQTT->connected()) + { + if (!checkMIOTKA()) + { + return false; + } + + if (!checkMIOTPrintSpan()) + { + respMIOTTime = millis(); + return false; + } + respMIOTTime = millis(); + + + char BLINKER_RRPC_PUB_TOPIC_MQTT[128]; + + if (is_rrpc) + { + + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, "/sys/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_PRODUCTINFO_MQTT); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, DEVICE_NAME_MQTT); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/rrpc/response/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, message_id); + } + else + { + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, BLINKER_PUB_TOPIC_MQTT); + } + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_RRPC_PUB_TOPIC_MQTT: "), BLINKER_RRPC_PUB_TOPIC_MQTT); + + is_rrpc = false; + + char send_data[1024]; + + if (_use_broker == aliyun_b) + { + strcpy(send_data, base64::encode(data_add).c_str()); + } + else if (_use_broker == blinker_b) + { + strcpy(send_data, data_add.c_str()); + } + + if (! mqtt_MQTT->publish(BLINKER_RRPC_PUB_TOPIC_MQTT, send_data)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isMIOTAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isMIOTAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +void BlinkerMQTT::aliType(const String & type) +{ + _aliType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_aliType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +} + +void BlinkerMQTT::duerType(const String & type) +{ + _duerType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_duerType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_duerType: "), _duerType); +} + +void BlinkerMQTT::miType(const String & type) +{ + _miType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_miType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_miType: "), _miType); +} + +void BlinkerMQTT::begin(const char* auth) { + // if (!checkInit()) return; + // _authKey = auth; + _authKey = (char*)malloc((strlen(auth)+1)*sizeof(char)); + strcpy(_authKey, auth); + + BLINKER_LOG_ALL(BLINKER_F("_authKey: "), auth); +} + +bool BlinkerMQTT::begin() { + // if (connectServer()) { + // mDNSInit(); + // isMQTTinit = true; + // } + // else { + // uint32_t re_time = millis(); + + if (isMQTTinit) return true; + // bool isConnect_MQTT = true; + // while(1) + // { + // re_time = millis(); + // ::delay(10000); + // BLINKER_ERR_LOG("Maybe you have put in the wrong AuthKey!"); + // BLINKER_ERR_LOG("Or maybe your request is too frequently!"); + // BLINKER_ERR_LOG("Or maybe your network is disconnected!"); + if (_connectTimes < BLINKER_SERVER_CONNECT_LIMIT) + { + if (_connectTime == 0 || (millis() - _connectTime) >= 10000) + { + _connectTime = millis(); + if (connectServer()) { + _connectTimes = 0; + mDNSInit(); + isMQTTinit = true; + return true; + } + else { + _connectTimes++; + isMQTTinit = false; + // ::delay(10000); + // BLINKER_ERR_LOG("init error, ", _connectTime); + // BLINKER_ERR_LOG("Maybe you have put in the wrong AuthKey!"); + // BLINKER_ERR_LOG("Or maybe your request is too frequently!"); + // BLINKER_ERR_LOG("Or maybe your network is disconnected!"); + return false; + } + } + } + else + { + if (millis() - _connectTime > 60000 * 1) _connectTimes = 0; + } + + + // BLINKER_ERR_LOG("init error1, ", _connectTime); + // ::delay(1000); + return false; + // delay(10000); + // while ((millis() - re_time) < 10000) + // { + // if (WiFi.status() != WL_CONNECTED && isConnect_MQTT) + // { + // isConnect_MQTT = false; + // WiFi.begin(); + // WiFi.reconnect(); + // } + // else if (WiFi.status() == WL_CONNECTED && !isConnect_MQTT) + // { + // isConnect_MQTT = true; + // } + // // ::delay(10); + // yield(); + // // WiFi.status(); + // } + // } + // } +} + +int BlinkerMQTT::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"auto\":{\"trig\":true,"); + payload += BLINKER_F("\"id\":"); + payload += String(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(DEVICE_NAME_MQTT); + payload += BLINKER_F("\",\"deviceType\":\"Auto\""); + payload += BLINKER_F(",\"toDevice\":\"serverClient\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_MQTT->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_MQTT->publish(BLINKER_PUB_TOPIC_MQTT, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// bool BlinkerMQTT::autoPrint(char *name, char *type, char *data) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_MQTT); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_MQTT->connected()) { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +// bool BlinkerMQTT::autoPrint(char *name1, char *type1, char *data1 +// , char *name2, char *type2, char *data2) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data1); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_MQTT); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name1; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type1; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_MQTT->connected()) +// { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data2); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_MQTT); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name2; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type2; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else +// { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +char * BlinkerMQTT::deviceName() { return DEVICE_NAME_MQTT;/*MQTT_ID_MQTT;*/ } + +void BlinkerMQTT::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (uint8_t num = _sharerCount; num > 0; num--) + { + delete _sharers[num - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerMQTT::connectServer() { + const int httpsPort = 443; +#if defined(ESP8266) + String host = BLINKER_F(BLINKER_SERVER_HOST); + String fingerprint = BLINKER_F("84 5f a4 8a 70 5e 79 7e f5 b3 b4 20 45 c8 35 55 72 f6 85 5a"); + + #ifndef BLINKER_WITHOUT_SSL + client_mqtt.stop(); + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + #else + WiFiClient client_s; + #endif + + String url_iot = BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + url_iot += _authKey; + url_iot += _aliType; + url_iot += _duerType; + url_iot += _miType; + url_iot += BLINKER_F("&version="); + url_iot += BLINKER_OTA_VERSION_CODE; + #ifndef BLINKER_WITHOUT_SSL + url_iot += BLINKER_F("&protocol=mqtts"); + #else + url_iot += BLINKER_F("&protocol=mqtt"); + #endif + // url_iot += BLINKER_OTA_VERSION_CODE; + + #ifndef BLINKER_WITHOUT_SSL + url_iot = "https://" + host + url_iot; + #else + url_iot = "http://" + host + url_iot; + #endif + HTTPClient http; + + String payload; + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] begin: "), url_iot); + + #ifndef BLINKER_WITHOUT_SSL + if (http.begin(*client_s, url_iot)) { // HTTPS + #else + if (http.begin(client_s, url_iot)) { + #endif + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + +#elif defined(ESP32) + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + // const char* ca = + // "-----BEGIN CERTIFICATE-----\n" + // "MIIEgDCCA2igAwIBAgIQDKTfhr9lmWbWUT0hjX36oDANBgkqhkiG9w0BAQsFADBy\n" + // "MQswCQYDVQQGEwJDTjElMCMGA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywg\n" + // "SW5jLjEdMBsGA1UECxMURG9tYWluIFZhbGlkYXRlZCBTU0wxHTAbBgNVBAMTFFRy\n" + // "dXN0QXNpYSBUTFMgUlNBIENBMB4XDTE4MDEwNDAwMDAwMFoXDTE5MDEwNDEyMDAw\n" + // "MFowGDEWMBQGA1UEAxMNaW90ZGV2LmNsei5tZTCCASIwDQYJKoZIhvcNAQEBBQAD\n" + // "ggEPADCCAQoCggEBALbOFn7cJ2I/FKMJqIaEr38n4kCuJCCeNf1bWdWvOizmU2A8\n" + // "QeTAr5e6Q3GKeJRdPnc8xXhqkTm4LOhgdZB8KzuVZARtu23D4vj4sVzxgC/zwJlZ\n" + // "MRMxN+cqI37kXE8gGKW46l2H9vcukylJX+cx/tjWDfS2YuyXdFuS/RjhCxLgXzbS\n" + // "cve1W0oBZnBPRSMV0kgxTWj7hEGZNWKIzK95BSCiMN59b+XEu3NWGRb/VzSAiJEy\n" + // "Hy9DcDPBC9TEg+p5itHtdMhy2gq1OwsPgl9HUT0xmDATSNEV2RB3vwviNfu9/Eif\n" + // "ObhsV078zf30TqdiESqISEB68gJ0Otru67ePoTkCAwEAAaOCAWowggFmMB8GA1Ud\n" + // "IwQYMBaAFH/TmfOgRw4xAFZWIo63zJ7dygGKMB0GA1UdDgQWBBR/KLqnke61779P\n" + // "xc9htonQwLOxPDAYBgNVHREEETAPgg1pb3RkZXYuY2x6Lm1lMA4GA1UdDwEB/wQE\n" + // "AwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTAYDVR0gBEUwQzA3\n" + // "BglghkgBhv1sAQIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQu\n" + // "Y29tL0NQUzAIBgZngQwBAgEwgYEGCCsGAQUFBwEBBHUwczAlBggrBgEFBQcwAYYZ\n" + // "aHR0cDovL29jc3AyLmRpZ2ljZXJ0LmNvbTBKBggrBgEFBQcwAoY+aHR0cDovL2Nh\n" + // "Y2VydHMuZGlnaXRhbGNlcnR2YWxpZGF0aW9uLmNvbS9UcnVzdEFzaWFUTFNSU0FD\n" + // "QS5jcnQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtM4eyrWB14ajJpQ\n" + // "ibZ5FbzVuvv2Le0FOSoss7UFCDJUYiz2LiV8yOhL4KTY+oVVkqHaYtcFS1CYZNzj\n" + // "6xWcqYZJ+pgsto3WBEgNEEe0uLSiTW6M10hm0LFW9Det3k8fqwSlljqMha3gkpZ6\n" + // "8WB0f2clXOuC+f1SxAOymnGUsSqbU0eFSgevcOIBKR7Hr3YXBXH3jjED76Q52OMS\n" + // "ucfOM9/HB3jN8o/ioQbkI7xyd/DUQtzK6hSArEoYRl3p5H2P4fr9XqmpoZV3i3gQ\n" + // "oOdVycVtpLunyUoVAB2DcOElfDxxXCvDH3XsgoIU216VY03MCaUZf7kZ2GiNL+UX\n" + // "9UBd0Q==\n" + // "-----END CERTIFICATE-----\n"; +// #endif + + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + url_iot += _authKey; + url_iot += _aliType; + url_iot += _duerType; + url_iot += _miType; + url_iot += BLINKER_F("&version="); + url_iot += BLINKER_OTA_VERSION_CODE; + url_iot += BLINKER_F("&protocol=mqtts"); + +// #if defined(BLINKER_ALIGENIE_LIGHT) +// url_iot += BLINKER_F("&aliType=light"); +// #elif defined(BLINKER_ALIGENIE_OUTLET) +// url_iot += BLINKER_F("&aliType=outlet"); +// #elif defined(BLINKER_ALIGENIE_SWITCH) +// #elif defined(BLINKER_ALIGENIE_SENSOR) +// url_iot += BLINKER_F("&aliType=sensor"); +// #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + +// #if defined(ESP8266) +// http.begin(url_iot, fingerprint); //HTTP +// #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); +// #endif + int httpCode = http.GET(); + + String payload; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); +#endif + + // payload = ""; + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(BLINKER_F("Maybe you have put in the wrong AuthKey!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your request is too frequently!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your network is disconnected!")); + // ::delay(60000); + + return false; + // } + } + + // String _userID = STRING_find_string(payload, "deviceName", "\"", 4); + // String _userName = STRING_find_string(payload, "iotId", "\"", 4); + // String _key = STRING_find_string(payload, "iotToken", "\"", 4); + // String _productInfo = STRING_find_string(payload, "productKey", "\"", 4); + // String _broker = STRING_find_string(payload, "broker", "\"", 4); + // String _uuid = STRING_find_string(payload, "uuid", "\"", 4); + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + String _host = root[BLINKER_CMD_DETAIL]["host"]; + uint32_t _port = root[BLINKER_CMD_DETAIL]["port"]; + uint8_t _num = _host.indexOf("://"); + BLINKER_LOG_ALL("_num: ", _num); + if (_num > 0) _num += 3; + _host = _host.substring(_num, _host.length()); + + + // if (isMQTTinit) + // { + // free(MQTT_HOST_MQTT); + // free(MQTT_ID_MQTT); + // free(MQTT_NAME_MQTT); + // free(MQTT_KEY_MQTT); + // free(MQTT_PRODUCTINFO_MQTT); + // free(UUID_MQTT); + // free(DEVICE_NAME_MQTT); + // free(BLINKER_PUB_TOPIC_MQTT); + // free(BLINKER_SUB_TOPIC_MQTT); + // // free(BLINKER_RRPC_PUB_TOPIC_MQTT); + // free(BLINKER_RRPC_SUB_TOPIC_MQTT); + free(mqtt_MQTT); + free(iotSub_MQTT); + // // free(iotSub_RRPC_MQTT); + + // isMQTTinit = false; + // } + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); + #if defined(BLINKER_WITHOUT_SSL) + if(!isMQTTinit) DEVICE_NAME_MQTT = (char*)malloc((24+1)*sizeof(char)); + strcpy(DEVICE_NAME_MQTT, _userName.substring(0, 24).c_str()); + #else + if(!isMQTTinit) DEVICE_NAME_MQTT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(DEVICE_NAME_MQTT, _userID.c_str()); + #endif + if(!isMQTTinit) MQTT_ID_MQTT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_MQTT, _userID.c_str()); + if(!isMQTTinit) MQTT_NAME_MQTT = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_MQTT, _userName.c_str()); + if(!isMQTTinit) MQTT_KEY_MQTT = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_MQTT, _key.c_str()); + if(!isMQTTinit) MQTT_PRODUCTINFO_MQTT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_MQTT, _productInfo.c_str()); + if(!isMQTTinit) MQTT_HOST_MQTT = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_MQTT, BLINKER_MQTT_ALIYUN_HOST); + MQTT_PORT_MQTT = BLINKER_MQTT_ALIYUN_PORT; + + _use_broker = aliyun_b; + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + // String id2name = _userID.subString(10, _userID.length()); + // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); + if(!isMQTTinit) DEVICE_NAME_MQTT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(DEVICE_NAME_MQTT, _userID.c_str()); + String IDtest = _productInfo + _userID; + if(!isMQTTinit) MQTT_ID_MQTT = (char*)malloc((IDtest.length()+1)*sizeof(char)); + strcpy(MQTT_ID_MQTT, IDtest.c_str()); + String NAMEtest = IDtest + ";" + _userName; + if(!isMQTTinit) MQTT_NAME_MQTT = (char*)malloc((NAMEtest.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_MQTT, NAMEtest.c_str()); + if(!isMQTTinit) MQTT_KEY_MQTT = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_MQTT, _key.c_str()); + if(!isMQTTinit) MQTT_PRODUCTINFO_MQTT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_MQTT, _productInfo.c_str()); + if(!isMQTTinit) MQTT_HOST_MQTT = (char*)malloc((strlen(BLINKER_MQTT_QCLOUD_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_MQTT, BLINKER_MQTT_QCLOUD_HOST); + MQTT_PORT_MQTT = BLINKER_MQTT_QCLOUD_PORT; + } + else if (_broker == BLINKER_MQTT_BORKER_BLINKER) { + // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); + if(!isMQTTinit) DEVICE_NAME_MQTT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(DEVICE_NAME_MQTT, _userID.c_str()); + if(!isMQTTinit) MQTT_ID_MQTT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_MQTT, _userID.c_str()); + if(!isMQTTinit) MQTT_NAME_MQTT = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_MQTT, _userName.c_str()); + if(!isMQTTinit) MQTT_KEY_MQTT = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_MQTT, _key.c_str()); + if(!isMQTTinit) MQTT_PRODUCTINFO_MQTT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_MQTT, _productInfo.c_str()); + if(!isMQTTinit) MQTT_HOST_MQTT = (char*)malloc((_host.length()+1)*sizeof(char)); + strcpy(MQTT_HOST_MQTT, _host.c_str()); + MQTT_PORT_MQTT = _port; + + _use_broker = blinker_b; + } + if(!isMQTTinit) UUID_MQTT = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_MQTT, _uuid.c_str()); + + // char uuid_eeprom[BLINKER_AUUID_SIZE]; + + // // BLINKER_LOG_ALL(("====================")); + + // char _authCheck; + // EEPROM.begin(BLINKER_EEP_SIZE); + // EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + // if (strcmp(uuid_eeprom, _uuid.c_str()) != 0) { + // // strcpy(UUID_MQTT, _uuid.c_str()); + + // strcpy(uuid_eeprom, _uuid.c_str()); + // EEPROM.put(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + // EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + + // BLINKER_LOG_ALL(BLINKER_F("====================")); + // BLINKER_LOG_ALL(BLINKER_F("uuid_eeprom: "), uuid_eeprom); + // BLINKER_LOG_ALL(BLINKER_F("_uuid: "), _uuid); + // // isNew = true; + // } + // EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + // // if (_authCheck != BLINKER_AUTH_CHECK_DATA) { + // // EEPROM.put(BLINKER_EEP_ADDR_AUTH_CHECK, BLINKER_AUTH_CHECK_DATA); + // // isAuth = true; + // // } + // EEPROM.commit(); + // EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME_MQTT: "), DEVICE_NAME_MQTT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_MQTT: "), MQTT_PRODUCTINFO_MQTT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_MQTT: "), MQTT_ID_MQTT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_MQTT: "), MQTT_NAME_MQTT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_MQTT: "), MQTT_KEY_MQTT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_MQTT); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_MQTT); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), _host); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), _port); + BLINKER_LOG_ALL(BLINKER_F("UUID_MQTT: "), UUID_MQTT); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_MQTT; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += DEVICE_NAME_MQTT; + PUB_TOPIC_STR += BLINKER_F("/s"); + + if(!isMQTTinit) BLINKER_PUB_TOPIC_MQTT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_MQTT: "), BLINKER_PUB_TOPIC_MQTT); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_MQTT; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += DEVICE_NAME_MQTT; + SUB_TOPIC_STR += BLINKER_F("/r"); + + if(!isMQTTinit) BLINKER_SUB_TOPIC_MQTT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_MQTT: "), BLINKER_SUB_TOPIC_MQTT); + + + SUB_TOPIC_STR = BLINKER_F("/sys/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_MQTT; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += DEVICE_NAME_MQTT; + SUB_TOPIC_STR += BLINKER_F("/rrpc/request/"); + + if(!isMQTTinit) BLINKER_RRPC_SUB_TOPIC_MQTT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_RRPC_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str()); + + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + String PUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += _userID; + PUB_TOPIC_STR += BLINKER_F("/s"); + + if(!isMQTTinit) BLINKER_PUB_TOPIC_MQTT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_MQTT: "), BLINKER_PUB_TOPIC_MQTT); + + String SUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += _userID; + SUB_TOPIC_STR += BLINKER_F("/r"); + + if(!isMQTTinit) BLINKER_SUB_TOPIC_MQTT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_MQTT: "), BLINKER_SUB_TOPIC_MQTT); + } + else if (_broker == BLINKER_MQTT_BORKER_BLINKER) { + String PUB_TOPIC_STR = BLINKER_F("/device"); + // PUB_TOPIC_STR += MQTT_PRODUCTINFO_MQTT; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_ID_MQTT; + PUB_TOPIC_STR += BLINKER_F("/s"); + + if(!isMQTTinit) BLINKER_PUB_TOPIC_MQTT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_MQTT: "), BLINKER_PUB_TOPIC_MQTT); + + String SUB_TOPIC_STR = BLINKER_F("/device"); + // SUB_TOPIC_STR += MQTT_PRODUCTINFO_MQTT; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_ID_MQTT; + SUB_TOPIC_STR += BLINKER_F("/r"); + + if(!isMQTTinit) BLINKER_SUB_TOPIC_MQTT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_MQTT: "), BLINKER_SUB_TOPIC_MQTT); + + + // SUB_TOPIC_STR = BLINKER_F("/sys/"); + // SUB_TOPIC_STR += MQTT_PRODUCTINFO_MQTT; + // SUB_TOPIC_STR += BLINKER_F("/"); + // SUB_TOPIC_STR += MQTT_ID_MQTT; + // SUB_TOPIC_STR += BLINKER_F("/rrpc/request/"); + + // BLINKER_RRPC_SUB_TOPIC_MQTT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // // memcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str(), str_len); + // strcpy(BLINKER_RRPC_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str()); + + } + + // BLINKER_LOG_FreeHeap(); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // if (isMQTTset) + // { + // mqtt_MQTT->setConnect(MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); + // } + // else + // { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_MQTT, MQTT_PORT_MQTT, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_MQTT = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); + #elif defined(ESP32) + mqtt_MQTT = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); + #endif + + // isMQTTset = true; + // } + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_MQTT, MQTT_PORT_MQTT, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_MQTT = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); + #elif defined(ESP32) + mqtt_MQTT = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); + #endif + } + else if (_broker == BLINKER_MQTT_BORKER_BLINKER) { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_MQTT, MQTT_PORT_MQTT, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_MQTT = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); + #elif defined(ESP32) + mqtt_MQTT = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); + #endif + } + + // iotPub = new Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + // if (!isMQTTinit) + iotSub_MQTT = new Adafruit_MQTT_Subscribe(mqtt_MQTT, BLINKER_SUB_TOPIC_MQTT); + + // iotSub_RRPC_MQTT = new Adafruit_MQTT_Subscribe(mqtt_MQTT, BLINKER_RRPC_SUB_TOPIC_MQTT); + + // mqtt_broker = (char*)malloc((_broker.length()+1)*sizeof(char)); + // strcpy(mqtt_broker, _broker.c_str()); + // mqtt_broker = _broker; + + // mDNSInit(MQTT_ID_MQTT); + this->latestTime = millis() - BLINKER_MQTT_CONNECT_TIMESLOT; + // if (!isMQTTinit) + mqtt_MQTT->subscribe(iotSub_MQTT); + // mqtt_MQTT->subscribe(iotSub_RRPC_MQTT); + + #if defined(ESP8266) + // client_s->stop(); + // if (!isMQTTinit) + #ifndef BLINKER_WITHOUT_SSL + client_mqtt.setInsecure(); + #endif + #elif defined(ESP32) + client_s.setInsecure(); + #endif + // connect(); + + BLINKER_LOG_FreeHeap(); + + return true; +} + +void BlinkerMQTT::mDNSInit() +{ +#if defined(ESP8266) + if (!MDNS.begin(DEVICE_NAME_MQTT, WiFi.localIP())) { +#elif defined(ESP32) + if (!MDNS.begin(DEVICE_NAME_MQTT)) { +#endif + while(1) { + ::delay(100); + } + } + + BLINKER_LOG(BLINKER_F("mDNS responder started")); + + MDNS.addService(BLINKER_MDNS_SERVICE_BLINKER, "tcp", WS_SERVERPORT); + MDNS.addServiceTxt(BLINKER_MDNS_SERVICE_BLINKER, "tcp", "deviceName", String(DEVICE_NAME_MQTT)); + MDNS.addServiceTxt(BLINKER_MDNS_SERVICE_BLINKER, "tcp", "mac", macDeviceName()); + + webSocket_MQTT.begin(); + webSocket_MQTT.onEvent(webSocketEvent_MQTT); + BLINKER_LOG(BLINKER_F("webSocket_MQTT server started")); + BLINKER_LOG(BLINKER_F("ws://"), DEVICE_NAME_MQTT, BLINKER_F(".local:"), WS_SERVERPORT); + + isApCfg = false; +} + +void BlinkerMQTT::checkKA() { + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerMQTT::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerMQTT::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerMQTT::checkMIOTKA() { + if (millis() - miKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerMQTT::checkCanPrint() { + if ((millis() - printTime >= BLINKER_MQTT_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerMQTT::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerMQTT::checkPrintSpan() { + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) { + BLINKER_ERR_LOG(BLINKER_F("WEBSOCKETS CLIENT NOT ALIVE OR MSG LIMIT")); + + return false; + } + else { + respTimes++; + return true; + } + } + else { + respTimes = 0; + return true; + } +} + +int BlinkerMQTT::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerMQTT::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerMQTT::checkMIOTPrintSpan() +{ + if (millis() - respMIOTTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respMIOTTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respMIOTTimes++; + return true; + } + } + else + { + respMIOTTimes = 0; + return true; + } +} + +int BlinkerMQTT::checkPrintLimit() +{ + if ((millis() - _print_time) < 60000) + { + if (_print_times < 30) return true; + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT MSG LIMIT")); + return false; + } + } + else + { + _print_time = millis(); + _print_times = 0; + return true; + } +} + +int BlinkerMQTT::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(STRING_format(data)); + DynamicJsonDocument jsonBuffer(2048); + DeserializationError error = deserializeJson(jsonBuffer, STRING_format(data)); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG("Print data is not Json! ", data); + return false; + } + + return true; +} + +bool BlinkerMQTT::checkInit() +{ + char ok[2 + 1] = "OK"; + + if (!_isWiFiInit) + { + switch (_configType) + { + case COMM : + _connectTime = millis(); + // BLINKER_LOG(BLINKER_F("checkInit...")); + if (WiFi.status() != WL_CONNECTED) { + ::delay(500); + + if (millis() - _connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { + // _connectTime = millis(); + BLINKER_LOG(BLINKER_F("WiFi connect timeout, please check ssid and pswd!")); + BLINKER_LOG(BLINKER_F("Retring WiFi connect again!")); + return false; + } + + // BLINKER_LOG(BLINKER_F("checkInit...")); + + return false; + } + BLINKER_LOG(BLINKER_F("WiFi Connected.")); + BLINKER_LOG(BLINKER_F("IP Address: ")); + BLINKER_LOG(WiFi.localIP()); + _isWiFiInit = true; + _connectTime = 0; + + // begin(); + + return false; + case BLINKER_SMART_CONFIG : + switch (_configStatus) + { + case AUTO_INIT : + if (WiFi.status() != WL_CONNECTED) { + ::delay(500); + return false; + } + else { + BLINKER_LOG(BLINKER_F("WiFi Connected.")); + BLINKER_LOG(BLINKER_F("IP Address: ")); + BLINKER_LOG(WiFi.localIP()); + + _isWiFiInit = true; + _connectTime = 0; + // _isWiFiInit = true; + + // begin(); + _configStatus = AUTO_DONE; + + return false; + } + case SMART_BEGIN : + if (WiFi.smartConfigDone()) + { + BLINKER_LOG(BLINKER_F("SmartConfig received.")); + _connectTime = millis(); + + #if defined(ESP8266) + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + #endif + + _configStatus = SMART_DONE; + } + else return false; + case SMART_DONE : + if (WiFi.status() != WL_CONNECTED) + { + if (millis() - _connectTime > 15000) + { + BLINKER_LOG(BLINKER_F("SmartConfig timeout.")); + WiFi.stopSmartConfig(); + _configStatus = SMART_TIMEOUT; + } + return false; + } + else if (WiFi.status() == WL_CONNECTED) + { + // WiFi.stopSmartConfig(); + + BLINKER_LOG(BLINKER_F("WiFi Connected.")); + BLINKER_LOG(BLINKER_F("IP Address: ")); + BLINKER_LOG(WiFi.localIP()); + _isWiFiInit = true; + _connectTime = 0; + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_WLAN_CHECK, ok); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG(BLINKER_F("Save wlan config")); + + // begin(); + + return false; + } + // return false; + case SMART_TIMEOUT : + WiFi.beginSmartConfig(); + _configStatus = SMART_BEGIN; + BLINKER_LOG(BLINKER_F("Waiting for SmartConfig.")); + return false; + default : + yield(); + return false; + } + case BLINKER_AP_CONFIG : + #if defined(BLINKER_APCONFIG) + switch (_configStatus) + { + case AUTO_INIT : + if (WiFi.status() != WL_CONNECTED) { + ::delay(500); + return false; + } + else { + BLINKER_LOG(BLINKER_F("WiFi Connected.")); + BLINKER_LOG(BLINKER_F("IP Address: ")); + BLINKER_LOG(WiFi.localIP()); + + _isWiFiInit = true; + _connectTime = 0; + // _isWiFiInit = true; + + // begin(); + _configStatus = AUTO_DONE; + + return false; + } + case APCFG_BEGIN : + checkAPCFG(); + return false; + case APCFG_DONE : + if (WiFi.status() != WL_CONNECTED) + { + if (millis() - _connectTime > 15000) + { + BLINKER_LOG(BLINKER_F("APConfig timeout.")); + WiFi.disconnect(); + _configStatus = APCFG_TIMEOUT; + } + return false; + } + else if (WiFi.status() == WL_CONNECTED) + { + BLINKER_LOG(BLINKER_F("WiFi Connected.")); + BLINKER_LOG(BLINKER_F("IP Address: ")); + BLINKER_LOG(WiFi.localIP()); + _isWiFiInit = true; + _connectTime = 0; + + // begin(); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_WLAN_CHECK, ok); + EEPROM.commit(); + EEPROM.end(); + + return false; + } + // return false; + case APCFG_TIMEOUT : + softAPinit(); + return false; + default : + yield(); + return false; + } + #endif + case BLINKER_MULTI: + _connectTime = millis(); + // BLINKER_LOG(BLINKER_F("checkInit...")); + if (wifiMulti.run() != WL_CONNECTED) { + ::delay(500); + + if (millis() - _connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { + // _connectTime = millis(); + BLINKER_LOG(BLINKER_F("WiFi connect timeout, please check ssid and pswd!")); + BLINKER_LOG(BLINKER_F("Retring WiFi connect again!")); + return false; + } + + // BLINKER_LOG(BLINKER_F("checkInit...")); + + return false; + } + BLINKER_LOG(BLINKER_F("WiFi Connected.")); + BLINKER_LOG(BLINKER_F("IP Address: ")); + BLINKER_LOG(WiFi.localIP()); + _isWiFiInit = true; + _connectTime = 0; + + // begin(); + + return false; + default : + return false; + } + } + + if (!_isBegin) + { + _isBegin = begin(); + return _isBegin; + } + return true; +} + +void BlinkerMQTT::commonBegin(const char* _ssid, const char* _pswd) +{ + _configType = COMM; + + connectWiFi(_ssid, _pswd); + + #if defined(ESP8266) + BLINKER_LOG(BLINKER_F("ESP8266_MQTT initialized...")); + #elif defined(ESP32) + BLINKER_LOG(BLINKER_F("ESP32_MQTT initialized...")); + #endif +} + +void BlinkerMQTT::smartconfigBegin() +{ + _configType = BLINKER_SMART_CONFIG; + + if (!autoInit()) smartconfig(); + // else _configStatus = SMART_DONE; + + #if defined(ESP8266) + BLINKER_LOG(BLINKER_F("ESP8266_MQTT initialized...")); + #elif defined(ESP32) + BLINKER_LOG(BLINKER_F("ESP32_MQTT initialized...")); + #endif +} + +void BlinkerMQTT::multiBegin(const char* _ssid, const char* _pswd) +{ + _configType = BLINKER_MULTI; + + WiFi.mode(WIFI_STA); + String _hostname = BLINKER_F("DiyArduinoMQTT_"); + _hostname += macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(_hostname.c_str()); + #elif defined(ESP32) + WiFi.setHostname(_hostname.c_str()); + #endif + + wifiMulti.addAP(_ssid, _pswd); + + BLINKER_LOG(BLINKER_F("wifiMulti add "), _ssid); + + #if defined(ESP8266) + BLINKER_LOG(BLINKER_F("ESP8266_MQTT initialized...")); + #elif defined(ESP32) + BLINKER_LOG(BLINKER_F("ESP32_MQTT initialized...")); + #endif +} + +void BlinkerMQTT::apconfigBegin() +{ + #if defined(BLINKER_APCONFIG) + _configType = BLINKER_AP_CONFIG; + + if (!autoInit()) softAPinit(); + // else _configStatus = APCFG_DONE; + + #if defined(ESP8266) + BLINKER_LOG(BLINKER_F("ESP8266_MQTT initialized...")); + #elif defined(ESP32) + BLINKER_LOG(BLINKER_F("ESP32_MQTT initialized...")); + #endif + #endif +} + +bool BlinkerMQTT::checkConfig() { + BLINKER_LOG_ALL(BLINKER_F("check wlan config")); + + char ok[2 + 1]; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_WLAN_CHECK, ok); + EEPROM.commit(); + EEPROM.end(); + + if (String(ok) != String("OK")) { + + BLINKER_LOG(BLINKER_F("wlan config check,fail")); + + // _status = BWL_CONFIG_FAIL; + return false; + } + else { + + BLINKER_LOG(BLINKER_F("wlan config check,success")); + + // _status = BWL_CONFIG_SUCCESS; + return true; + } +} + +bool BlinkerMQTT::autoInit() +{ + WiFi.mode(WIFI_STA); + String _hostname = BLINKER_F("DiyArduino_"); + _hostname += macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(_hostname.c_str()); + #elif defined(ESP32) + WiFi.setHostname(_hostname.c_str()); + #endif + + if (checkConfig()) + { + #ifdef ESP8266 + struct station_config conf; + wifi_station_get_config_default(&conf); + WiFi.begin(reinterpret_cast(conf.ssid), reinterpret_cast(conf.password)); + #elif defined(ESP32) + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + WiFi.begin(reinterpret_cast(conf.sta.ssid), reinterpret_cast(conf.sta.password)); + #endif + // WiFi.begin(WiFi.SSID(), WiFi.psk()); + ::delay(500); + + // BLINKER_LOG(BLINKER_F("Waiting for WiFi "), + // BLINKER_WIFI_AUTO_INIT_TIMEOUT / 1000, + // BLINKER_F("s, will enter SMARTCONFIG or "), + // BLINKER_F("APCONFIG while WiFi not connect!")); + + BLINKER_LOG(BLINKER_F("Connecting to WiFi: "), WiFi.SSID()); + + // uint8_t _times = 0; + // while (WiFi.status() != WL_CONNECTED) { + // ::delay(500); + // // if (_times > BLINKER_WIFI_AUTO_INIT_TIMEOUT / 500) break; + // // _times++; + // } + + // if (WiFi.status() != WL_CONNECTED) return false; + // else { + // // BLINKER_LOG(BLINKER_F("WiFi Connected.")); + // // BLINKER_LOG(BLINKER_F("IP Address: ")); + // // BLINKER_LOG(WiFi.localIP()); + // // _isWiFiInit = true; + + // // begin(); + + // return true; + // } + return true; + } + + return false; +} + +void BlinkerMQTT::smartconfig() +{ + WiFi.mode(WIFI_STA); + + String _hostname = BLINKER_F("DiyArduino_"); + _hostname += macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(_hostname.c_str()); + #elif defined(ESP32) + WiFi.setHostname(_hostname.c_str()); + #endif + + WiFi.beginSmartConfig(); + + _configStatus = SMART_BEGIN; + + BLINKER_LOG(BLINKER_F("Waiting for SmartConfig.")); + // while (!WiFi.smartConfigDone()) { + // ::delay(500); + // } + + // BLINKER_LOG(BLINKER_F("SmartConfig received.")); + + // BLINKER_LOG(BLINKER_F("Waiting for WiFi")); + // while (WiFi.status() != WL_CONNECTED) { + // ::delay(500); + // } + + // BLINKER_LOG(BLINKER_F("WiFi Connected.")); + + // BLINKER_LOG(BLINKER_F("IP Address: ")); + // BLINKER_LOG(WiFi.localIP()); +} +#if defined(BLINKER_APCONFIG) +void BlinkerMQTT::softAPinit() +{ + // WiFiServer _apServer(80); + // WiFiClient _apClient; + IPAddress apIP(192, 168, 4, 1); + #if defined(ESP8266) + IPAddress netMsk(255, 255, 255, 0); + #endif + + // _apServer = new WiFiServer(80); + + WiFi.mode(WIFI_AP); + + delay(1000); + + String softAP_ssid = BLINKER_F("DiyArduino_"); + softAP_ssid += macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(softAP_ssid.c_str()); + WiFi.softAPConfig(apIP, apIP, netMsk); + #elif defined(ESP32) + WiFi.setHostname(softAP_ssid.c_str()); + WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); + #endif + + WiFi.softAP(softAP_ssid.c_str(), NULL); + delay(100); + + // _apServer->begin(); + // BLINKER_LOG(BLINKER_F("AP IP address: "), WiFi.softAPIP()); + // BLINKER_LOG(BLINKER_F("HTTP _apServer started")); + // BLINKER_LOG(BLINKER_F("URL: http://"), WiFi.softAPIP()); + + // #if defined(ESP8266) + // if (!MDNS.begin(softAP_ssid.c_str(), WiFi.localIP())) { + // #elif defined(ESP32) + // if (!MDNS.begin(softAP_ssid.c_str())) { + // #endif + // while(1) { + // ::delay(100); + // } + // } + + // BLINKER_LOG(BLINKER_F("mDNS responder started")); + + // MDNS.addService(BLINKER_MDNS_SERVICE_BLINKER, "tcp", WS_SERVERPORT); + // MDNS.addServiceTxt(BLINKER_MDNS_SERVICE_BLINKER, "tcp", "deviceName", macDeviceName()); + + webSocket_MQTT.begin(); + webSocket_MQTT.onEvent(webSocketEvent_MQTT); + + _configStatus = APCFG_BEGIN; + isApCfg = true; + + BLINKER_LOG(BLINKER_F("Wait for APConfig")); + + // while(WiFi.status() != WL_CONNECTED) + // { + // // serverClient(); + // _apClient = _apServer->available(); + // // if (_apClient.status() == CLOSED) + // if (!_apClient.connected()) + // { + // _apClient.stop(); + // BLINKER_LOG(BLINKER_F("Connection closed on _apClient")); + // } + // else + // { + // if (_apClient.available()) + // { + // String data = _apClient.readStringUntil('\r'); + + // // data = data.substring(4, data.length() - 9); + // _apClient.flush(); + + // BLINKER_LOG(BLINKER_F("clientData: "), data); + + // if (STRING_contains_string(data, "ssid") && + // STRING_contains_string(data, "pswd")) + // { + // String msg = BLINKER_F("{\"hello\":\"world\"}"); + + // String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); + // s += BLINKER_F("Content-Type: application/json;"); + // s += BLINKER_F("charset=utf-8\r\n"); + // s += BLINKER_F("Content-Length: "); + // s += String(msg.length()); + // s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); + // s += msg; + // s += BLINKER_F("\r\n"); + + // _apClient.print(s); + + // _apClient.stop(); + + // parseUrl(data); + // } + // } + // } + // ::delay(10); + // } +} + +void BlinkerMQTT::checkAPCFG() +{ + // if(WiFi.status() != WL_CONNECTED) + // { + webSocket_MQTT.loop(); + + #if defined(ESP8266) + MDNS.update(); + #endif + + if (isAvail_MQTT) + { + BLINKER_LOG(BLINKER_F("checkAPCFG: "), msgBuf_MQTT); + + if (STRING_contains_string(msgBuf_MQTT, "ssid") && \ + STRING_contains_string(msgBuf_MQTT, "pswd")) + { + parseUrl(msgBuf_MQTT); + } + isAvail_MQTT = false; + } + + // serverClient(); + // _apClient = _apServer->available(); + // // if (_apClient.status() == CLOSED) + // if (!_apClient.connected()) + // { + // _apClient.stop(); + // BLINKER_LOG(BLINKER_F("Connection closed on _apClient")); + // } + // else + // { + // if (_apClient.available()) + // { + // String data = _apClient.readStringUntil('\r'); + + // // data = data.substring(4, data.length() - 9); + // _apClient.flush(); + + // BLINKER_LOG(BLINKER_F("clientData: "), data); + + // if (STRING_contains_string(data, "ssid") && + // STRING_contains_string(data, "pswd")) + // { + // String msg = BLINKER_F("{\"hello\":\"world\"}"); + + // String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); + // s += BLINKER_F("Content-Type: application/json;"); + // s += BLINKER_F("charset=utf-8\r\n"); + // s += BLINKER_F("Content-Length: "); + // s += String(msg.length()); + // s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); + // s += msg; + // s += BLINKER_F("\r\n"); + + // _apClient.print(s); + + // _apClient.stop(); + + // parseUrl(data); + // } + // } + // } + // ::delay(10); + // } +} + +// void BlinkerMQTT::serverClient() +// { +// if (!_apClient) +// { +// _apClient = _apServer->available(); +// } +// else +// { +// // if (_apClient.status() == CLOSED) +// if (!_apClient.connected()) +// { +// _apClient.stop(); +// BLINKER_LOG(BLINKER_F("Connection closed on _apClient")); +// } +// else +// { +// if (_apClient.available()) +// { +// String data = _apClient.readStringUntil('\r'); + +// // data = data.substring(4, data.length() - 9); +// _apClient.flush(); + +// BLINKER_LOG(BLINKER_F("clientData: "), data); + +// if (STRING_contains_string(data, "ssid") && +// STRING_contains_string(data, "pswd")) +// { +// String msg = BLINKER_F("{\"hello\":\"world\"}"); + +// String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); +// s += BLINKER_F("Content-Type: application/json;"); +// s += BLINKER_F("charset=utf-8\r\n"); +// s += BLINKER_F("Content-Length: "); +// s += String(msg.length()); +// s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); +// s += msg; +// s += BLINKER_F("\r\n"); + +// _apClient.print(s); + +// _apClient.stop(); + +// parseUrl(data); +// } +// } +// } +// } +// } + +bool BlinkerMQTT::parseUrl(String data) +{ + BLINKER_LOG(BLINKER_F("APCONFIG data: "), data); + // DynamicJsonBuffer jsonBuffer; + // JsonObject& wifi_data = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject wifi_data = jsonBuffer.as(); + + // if (!wifi_data.success()) + if (error) + { + return false; + } + + String _ssid = wifi_data["ssid"]; + String _pswd = wifi_data["pswd"]; + + BLINKER_LOG(BLINKER_F("ssid: "), _ssid); + BLINKER_LOG(BLINKER_F("pswd: "), _pswd); + + // free(_apServer); + // MDNS.end(); + webSocket_MQTT.close(); + + connectWiFi(_ssid, _pswd); + + _configStatus = APCFG_DONE; + _connectTime = millis(); + return true; +} +#endif +void BlinkerMQTT::connectWiFi(String _ssid, String _pswd) +{ + connectWiFi(_ssid.c_str(), _pswd.c_str()); +} + +void BlinkerMQTT::connectWiFi(const char* _ssid, const char* _pswd) +{ + uint32_t _connectTime = millis(); + + BLINKER_LOG(BLINKER_F("Connecting to "), _ssid); + + WiFi.mode(WIFI_STA); + String _hostname = BLINKER_F("DiyArduinoMQTT_"); + _hostname += macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(_hostname.c_str()); + #elif defined(ESP32) + WiFi.setHostname(_hostname.c_str()); + #endif + + if (_pswd && strlen(_pswd)) { + WiFi.begin(_ssid, _pswd); + } + else { + WiFi.begin(_ssid); + } + + // while (WiFi.status() != WL_CONNECTED) { + // ::delay(50); + + // if (millis() - _connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { + // _connectTime = millis(); + // BLINKER_LOG(BLINKER_F("WiFi connect timeout, please check ssid and pswd!")); + // BLINKER_LOG(BLINKER_F("Retring WiFi connect again!")); + // } + // } + // BLINKER_LOG(BLINKER_F("Connected")); + + // IPAddress myip = WiFi.localIP(); + // BLINKER_LOG(BLINKER_F("Your IP is: "), myip); + + // _isWiFiInit = true; +} + +#endif + +#endif diff --git a/blinker-library/src/Adapters/BlinkerMQTTAT.h b/blinker-library/src/Adapters/BlinkerMQTTAT.h new file mode 100644 index 0000000..363cc86 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerMQTTAT.h @@ -0,0 +1,2650 @@ +#ifndef BLINKER_MQTT_AT_H +#define BLINKER_MQTT_AT_H + +#if (defined(ESP8266) || defined(ESP32)) + +#define BLINKER_AT_MQTT +#define BLINKER_ESP_AT + +#if defined(ESP8266) + #include + #include + #include +#elif defined(ESP32) + #include + #include + #include +#endif + +#include + +#include "../modules/WebSockets/WebSocketsServer.h" +#include "../modules/mqtt/Adafruit_MQTT.h" +#include "../modules/mqtt/Adafruit_MQTT_Client.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +// #include "Adapters/BlinkerMQTTAT.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" +#include "../Blinker/BlinkerMQTTATBase.h" + +char* MQTT_HOST_MQTT_AT; +char* MQTT_ID_MQTT_AT; +char* MQTT_NAME_MQTT_AT; +char* MQTT_KEY_MQTT_AT; +char* MQTT_PRODUCTINFO_MQTT_AT; +char* UUID_MQTT_AT; +char* DEVICE_NAME_MQTT_AT; +char* BLINKER_PUB_TOPIC_MQTT_AT; +char* BLINKER_SUB_TOPIC_MQTT_AT; +uint16_t MQTT_PORT_MQTT_AT; + +class BlinkerMQTTAT : public BlinkerStream +{ + public : + BlinkerMQTTAT(); + + int serialAvailable(); + void serialBegin(Stream& s, bool state); + int serialTimedRead(); + char * serialLastRead(); + // void serialFlush(); + int serialPrint(const String & s1, const String & s2, bool needCheck = true); + int serialPrint(const String & s, bool needCheck = true); + int serialConnect(); + int serialConnected(); + void serialDisconnect(); + + int connect(); + int connected(); + int mConnected(); + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + int miAvail(); + // bool extraAvailable(); + void subscribe(); + char * lastRead(); + void flush(); + int print(char * data, bool needCheck = true); + int mqttPrint(const String & data); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + int miPrint(const String & data); + // void aliType(const String & type); + void begin(const char* auth); + bool begin(); + int autoPrint(unsigned long id); + // bool autoPrint(char *name, char *type, char *data); + // bool autoPrint(char *name1, char *type1, char *data1, + // char *name2, char *type2, char *data2); + int toServer(char * data) { return true; } + char * deviceName(); + char * authKey() { return _authKey; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_MQTT_AT; } + char * deviceId();// { return MQTT_ID; } + char * uuid();// { return UUID; } + void softAPinit(); + int parseUrl(String data); + int autoInit(); + void smartconfig(); + void connectWiFi(String _ssid, String _pswd); + void connectWiFi(const char* _ssid, const char* _pswd); + int init() { return isMQTTinit; } + int reRegister() { return connectServer(); } + void aligenieType(int _type) { _aliType = _type; } + void duerType(int _type) { _duerType = _type; } + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + private : + bool isMQTTinit = false; + + int connectServer(); + void mDNSInit(); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkMIOTKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + int checkMIOTPrintSpan(); + int checkPrintLimit(); + + protected : + bool _isBegin = false; + + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + int _aliType = ALI_NONE; + int _duerType = DUER_NONE; + // uint8_t pinDataNum = 0; + + // io + // - - - - - - - - | - - - - - - - - + // | | |pull_up + // | |mode + // |pin + // pin 40 0-39 + // mode 2 input/output + // pull_up 3 none/pull_up/pull_down + + // const char* _authKey; + char* _authKey; + // char* _aliType; + // char _authKey[BLINKER_AUTHKEY_SIZE]; + bool* isHandle;// = &isConnect; + bool isAlive = false; + // bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + uint8_t respMIOTTimes = 0; + uint32_t respMIOTTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + uint32_t miKaTime = 0; + bool isMIOTAlive = false; + bool isMIOTAvail = false; + char* mqtt_broker; + + Stream* stream; + char* streamData;//[BLINKER_MAX_READ_SIZE]; + bool isSeriaFresh; + bool isSerialConnect; + bool isHWS = false; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; + + uint32_t _print_time = 0; + uint8_t _print_times = 0; +}; + +// #if defined(ESP8266) +// extern BearSSL::WiFiClientSecure client_mqtt; +// // WiFiClientSecure client_mqtt; +// #elif defined(ESP32) +// extern WiFiClientSecure client_s; +// #endif + +// extern WiFiClient client; + +// #endif + +#if defined(ESP8266) + #include + + BearSSL::WiFiClientSecure client_mqtt; + // WiFiClientSecure client_mqtt; +#elif defined(ESP32) + #include "HardwareSerial.h" + + WiFiClientSecure client_s; +#endif + +WiFiClient client; +Adafruit_MQTT_Client* mqtt_MQTT_AT; +// Adafruit_MQTT_Publish *iotPub; +Adafruit_MQTT_Subscribe* iotSub_MQTT_AT; + +#define WS_SERVERPORT 81 +WebSocketsServer webSocket_MQTT_AT = WebSocketsServer(WS_SERVERPORT); + +char* msgBuf_MQTT_AT; +bool isFresh_MQTT_AT = false; +bool isConnect_MQTT_AT = false; +bool isAvail_MQTT_AT = false; +uint8_t ws_num_MQTT_AT = 0; +uint8_t dataFrom_MQTT_AT = BLINKER_MSG_FROM_MQTT; +// bool isATAvaill = false; + +void webSocketEvent_MQTT_AT(uint8_t num, WStype_t type, \ + uint8_t * payload, size_t length) +{ + + switch(type) + { + case WStype_DISCONNECTED: + BLINKER_LOG_ALL(BLINKER_F("Disconnected! "), num); + + isConnect_MQTT_AT = false; + break; + case WStype_CONNECTED: + { + IPAddress ip = webSocket_MQTT_AT.remoteIP(num); + + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", Connected from: "), ip, + BLINKER_F(", url: "), (char *)payload); + + // send message to client + webSocket_MQTT_AT.sendTXT(num, "{\"state\":\"connected\"}\n"); + + ws_num_MQTT_AT = num; + + isConnect_MQTT_AT = true; + } + break; + case WStype_TEXT: + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", get Text: "), (char *)payload, \ + BLINKER_F(", length: "), length); + + if (length < BLINKER_MAX_READ_SIZE) { + if (isFresh_MQTT_AT) free(msgBuf_MQTT_AT); + msgBuf_MQTT_AT = (char*)malloc((length+1)*sizeof(char)); + strcpy(msgBuf_MQTT_AT, (char*)payload); + isAvail_MQTT_AT = true; + isFresh_MQTT_AT = true; + } + + dataFrom_MQTT_AT = BLINKER_MSG_FROM_WS; + + ws_num_MQTT_AT = num; + + // send message to client + // webSocket_MQTT_AT.sendTXT(num, "message here"); + + // send data to all connected clients + // webSocket_MQTT_AT.broadcastTXT("message here"); + break; + case WStype_BIN: + // BLINKER_LOG("num: ", num, " get binary length: ", length); + // hexdump(payload, length); + + // send message to client + // webSocket_MQTT_AT.sendBIN(num, payload, length); + break; + default : + break; + } +} + +BlinkerMQTTAT::BlinkerMQTTAT() +{ + stream = NULL; + isSerialConnect = false; + isHandle = &isConnect_MQTT_AT; +} + +int BlinkerMQTTAT::serialAvailable() +{ + if (stream->available()) + { + // strcpy(streamData, (stream->readStringUntil('\n')).c_str()); + + // BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData); + + // return true; + + if (isSeriaFresh) free(streamData); + streamData = (char*)malloc(1*sizeof(char)); + + int16_t dNum = 0; + int c_d = serialTimedRead(); + while (dNum < BLINKER_MAX_READ_SIZE && + c_d >=0 && c_d != '\n') + { + if (c_d != '\r') + { + streamData[dNum] = (char)c_d; + dNum++; + streamData = (char*)realloc(streamData, (dNum+1)*sizeof(char)); + } + + c_d = serialTimedRead(); + } + dNum++; + streamData = (char*)realloc(streamData, dNum*sizeof(char)); + + streamData[dNum-1] = '\0'; + stream->flush(); + + BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData); + BLINKER_LOG_FreeHeap_ALL(); + + if (strlen(streamData) < BLINKER_MAX_READ_SIZE) + { + if (streamData[strlen(streamData) - 1] == '\r') + streamData[strlen(streamData) - 1] = '\0'; + + isSeriaFresh = true; + return true; + } + else + { + free(streamData); + return false; + } + } + else + { + return false; + } +} + +void BlinkerMQTTAT::serialBegin(Stream& s, bool state) +{ + stream = &s; + stream->setTimeout(BLINKER_STREAM_TIMEOUT); + isHWS = state; + + serialConnect(); + + serialPrint(""); + serialPrint(BLINKER_CMD_BLINKER_MQTT); +} + +int BlinkerMQTTAT::serialTimedRead() +{ + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; +} + +char * BlinkerMQTTAT::serialLastRead() +{ + return streamData; +} + +// void BlinkerMQTTAT::serialFlush() +// { +// if (isSeriaFresh) +// { +// free(streamData); isSeriaFresh = false; +// } +// } + +int BlinkerMQTTAT::serialPrint(const String & s1, const String & s2, bool needCheck) +{ + return serialPrint(s1 + s2, needCheck); +} + +int BlinkerMQTTAT::serialPrint(const String & s, bool needCheck) +{ + BLINKER_LOG_ALL(BLINKER_F("Serial Response: "), s); + + if(serialConnected()) + { + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + stream->println(s); + return true; + } + else + { + BLINKER_LOG_ALL(BLINKER_F("Faile... Disconnected")); + + return false; + } +} + +int BlinkerMQTTAT::serialConnect() +{ + isSerialConnect = true; + return serialConnected(); +} + +int BlinkerMQTTAT::serialConnected() { return isSerialConnect; } + +void BlinkerMQTTAT::serialDisconnect() { isSerialConnect = false; } + +int BlinkerMQTTAT::connect() +{ + if (!_isBegin) + { + _isBegin = begin(); + + if (!_isBegin) return false; + } + + int8_t ret; + + webSocket_MQTT_AT.loop(); + + if (mqtt_MQTT_AT->connected()) + { + return true; + } + + disconnect(); + + if ((millis() - latestTime) < 5000) + { + return false; + } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + #if defined(ESP8266) + client_mqtt.setInsecure(); + #endif + + if ((ret = mqtt_MQTT_AT->connect()) != 0) + { + BLINKER_LOG(mqtt_MQTT_AT->connectErrorString(ret)); + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in 5 seconds...")); + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + reRegister(); + reconnect_time = 0; + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + this->latestTime = millis(); + + return true; +} + +int BlinkerMQTTAT::connected() +{ + if (!_isBegin) + { + _isBegin = begin(); + + if (!_isBegin) return false; + } + + if (!isMQTTinit) + { + return *isHandle; + } + + return mqtt_MQTT_AT->connected() || *isHandle; +} + +int BlinkerMQTTAT::mConnected() +{ + if (!_isBegin) + { + _isBegin = begin(); + + if (!_isBegin) return false; + } + + if (!isMQTTinit) return false; + else return mqtt_MQTT_AT->connected(); +} + +void BlinkerMQTTAT::disconnect() +{ + if (!_isBegin) + { + _isBegin = begin(); + + if (!_isBegin) return; + } + + mqtt_MQTT_AT->disconnect(); + + if (*isHandle) webSocket_MQTT_AT.disconnect(); +} + +void BlinkerMQTTAT::ping() +{ + if (!_isBegin) + { + _isBegin = begin(); + + if (!_isBegin) return; + } + + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (!mqtt_MQTT_AT->ping()) + { + disconnect(); + delay(100); + + connect(); + } + else + { + this->latestTime = millis(); + } +} + +int BlinkerMQTTAT::available() +{ + if (!_isBegin) + { + _isBegin = begin(); + + if (!_isBegin) return false; + } + + webSocket_MQTT_AT.loop(); + + checkKA(); + + // if (!mqtt_MQTT_AT->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + { + ping(); + } + else + { + subscribe(); + } + + if (isAvail_MQTT_AT) + { + isAvail_MQTT_AT = false; + return true; + } + else { + return false; + } +} + +int BlinkerMQTTAT::aligenieAvail() +{ + if (!_isBegin) + { + _isBegin = begin(); + + if (!_isBegin) return false; + } + + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerMQTTAT::duerAvail() +{ + if (!_isBegin) + { + _isBegin = begin(); + + if (!_isBegin) return false; + } + + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerMQTTAT::miAvail() +{ + if (!_isBegin) + { + _isBegin = begin(); + + if (!_isBegin) return false; + } + + if (isMIOTAvail) + { + isMIOTAvail = false; + return true; + } + else { + return false; + } +} + +// int BlinkerMQTTAT::extraAvailable() +// { +// if (isBavail) +// { +// isBavail = false; +// return true; +// } +// else +// { +// return false; +// } +// } + +void BlinkerMQTTAT::subscribe() +{ + if (!_isBegin) + { + _isBegin = begin(); + + if (!_isBegin) return; + } + + if (!isMQTTinit) return; + + Adafruit_MQTT_Subscribe *subscription; + while ((subscription = mqtt_MQTT_AT->readSubscription(10))) + { + if (subscription == iotSub_MQTT_AT) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), (char *)iotSub_MQTT_AT->lastread); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(String((char *)iotSub_MQTT_AT->lastread)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, (char *)iotSub_MQTT_AT->lastread); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"]; + String dataGet = root["data"]; + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_MQTT_AT) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_MQTT_AT = true; + isAlive = true; + + dataGet = dataGet.substring(0, dataGet.length() - 1) + \ + ",\"deviceType\":\"OwnApp\"}"; + + if (!isFresh_MQTT_AT && dataGet.length() < BLINKER_MAX_READ_SIZE) + { + msgBuf_MQTT_AT = (char*)malloc(BLINKER_MAX_READ_SIZE*sizeof(char)); + strcpy(msgBuf_MQTT_AT, dataGet.c_str()); + isFresh_MQTT_AT = true; + } + else if (dataGet.length() < BLINKER_MAX_READ_SIZE) + { + strcpy(msgBuf_MQTT_AT, dataGet.c_str()); + isFresh_MQTT_AT = true; + } + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + + // isAvail_MQTT_AT = true; + // isAlive = true; + + dataGet = dataGet.substring(0, dataGet.length() - 1) + \ + ",\"deviceType\":\"AliGenie\"}"; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + if (!isFresh_MQTT_AT && dataGet.length() < BLINKER_MAX_READ_SIZE) + { + msgBuf_MQTT_AT = (char*)malloc(BLINKER_MAX_READ_SIZE*sizeof(char)); + strcpy(msgBuf_MQTT_AT, dataGet.c_str()); + isFresh_MQTT_AT = true; + } + else if (dataGet.length() < BLINKER_MAX_READ_SIZE) + { + strcpy(msgBuf_MQTT_AT, dataGet.c_str()); + isFresh_MQTT_AT = true; + } + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + + // isAvail_MQTT_AT = true; + // isAlive = true; + + dataGet = dataGet.substring(0, dataGet.length() - 1) + \ + ",\"deviceType\":\"DuerOS\"}"; + + if (!isFresh_MQTT_AT && dataGet.length() < BLINKER_MAX_READ_SIZE) + { + msgBuf_MQTT_AT = (char*)malloc(BLINKER_MAX_READ_SIZE*sizeof(char)); + strcpy(msgBuf_MQTT_AT, dataGet.c_str()); + isFresh_MQTT_AT = true; + } + else if (dataGet.length() < BLINKER_MAX_READ_SIZE) + { + strcpy(msgBuf_MQTT_AT, dataGet.c_str()); + isFresh_MQTT_AT = true; + } + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + isAvail_MQTT_AT = true; + isAlive = true; + + dataGet = dataGet.substring(0, dataGet.length() - 1) + \ + ",\"deviceType\":\"OwnApp\"}"; + + if (!isFresh_MQTT_AT && dataGet.length() < BLINKER_MAX_READ_SIZE) + { + msgBuf_MQTT_AT = (char*)malloc(BLINKER_MAX_READ_SIZE*sizeof(char)); + strcpy(msgBuf_MQTT_AT, dataGet.c_str()); + isFresh_MQTT_AT = true; + } + else if (dataGet.length() < BLINKER_MAX_READ_SIZE) + { + strcpy(msgBuf_MQTT_AT, dataGet.c_str()); + isFresh_MQTT_AT = true; + } + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + check is from bridge/share device, \ + data: "), dataGet); + + _needCheckShare = true; + } + } + } + // else + // { + // dataGet = String((char *)iotSub_MQTT_AT->lastread); + // root.printTo(dataGet); + + // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + // check is from bridge/share device, \ + // data: "), dataGet); + + // _needCheckShare = true; + // } + + // return; + + // isBavail = true; + } + + // memset(msgBuf_MQTT_AT, 0, BLINKER_MAX_READ_SIZE); + // memcpy(msgBuf_MQTT_AT, dataGet.c_str(), dataGet.length()); + + // if (isFresh_MQTT_AT) free(msgBuf_MQTT_AT); + // msgBuf_MQTT_AT = (char*)malloc((dataGet.length()+1)*sizeof(char)); + // strcpy(msgBuf_MQTT_AT, dataGet.c_str()); + // isFresh_MQTT_AT = true; + + this->latestTime = millis(); + + dataFrom_MQTT_AT = BLINKER_MSG_FROM_MQTT; + } + } +} + +char * BlinkerMQTTAT::lastRead() +{ + if (isFresh_MQTT_AT) return msgBuf_MQTT_AT; + return ""; +} + +void BlinkerMQTTAT::flush() +{ + if (isFresh_MQTT_AT) + { + free(msgBuf_MQTT_AT); isFresh_MQTT_AT = false; isAvail_MQTT_AT = false; + isAliAvail = false; isDuerAvail = false; //isBavail = false; + } +} + +int BlinkerMQTTAT::print(char * data, bool needCheck) +{ + // BLINKER_LOG_FreeHeap(); + if (*isHandle && dataFrom_MQTT_AT == BLINKER_MSG_FROM_WS) + { + if (needCheck) + { + if (!checkPrintSpan()) + { + respTime = millis(); + return false; + } + } + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("WS response: ")); + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + strcat(data, BLINKER_CMD_NEWLINE); + + webSocket_MQTT_AT.sendTXT(ws_num_MQTT_AT, data); + + return true; + } + else + { + // // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // uint8_t num = strlen(data) - 1; + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data.substring(0, data.length() - 1); + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_ID_MQTT_AT; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_MQTT_AT; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + // else + // { + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data; + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_ID_MQTT_AT; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_MQTT_AT; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + + // uint16_t num = strlen(data); + // for(uint16_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + + // data[num+8] = '\0'; + + // String data_add = BLINKER_F("{\"data\":"); + // for(uint8_t c_num = 0; c_num < 8; c_num++) + // { + // data[c_num] = data_add[c_num]; + // } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, MQTT_ID_MQTT_AT); + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + // if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + // { + // strcat(data, _sharers[_sharerFrom]->uuid()); + // } + // else + // { + // strcat(data, UUID_MQTT_AT); + // } + // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // strcat(data, data_add.c_str()); + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + // if (!isJson(STRING_format(data))) return false; + + String data_add = BLINKER_F("{\"data\":"); + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_ID_MQTT_AT; + data_add += BLINKER_F("\",\"toDevice\":\""); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + data_add += _sharers[_sharerFrom]->uuid(); + } + else + { + data_add += UUID_MQTT_AT; + } + + data_add += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (mqtt_MQTT_AT->connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + + if (!checkPrintLimit()) + { + return false; + } + + _print_times++; + + BLINKER_LOG_ALL(BLINKER_F("_print_times: "), _print_times); + } + + if (! mqtt_MQTT_AT->publish(BLINKER_PUB_TOPIC_MQTT_AT, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } + } +} + +int BlinkerMQTTAT::mqttPrint(const String & data) { + BLINKER_LOG_ALL(("mqttPrint data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& print_data = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject print_data = jsonBuffer.as(); + + + // if (!print_data.success()) + if (error) + { + BLINKER_ERR_LOG(("Print data not a Json data")); + return false; + } + + if (print_data.containsKey("toDeviceAT")) + { + + String _dType = print_data["toDeviceAT"]; + + BLINKER_LOG_ALL(("mqttPrint _dType: "), _dType); + + print_data.remove("toDeviceAT"); + String _data_; + // print_data.printTo(_data_); + serializeJson(print_data, _data_); + + if (_dType == "AliGenie") + { + return aliPrint(_data_); + } + else if (_dType == "DuerOS") + { + return duerPrint(_data_); + } + else + { + char data_print[512]; + strcpy(data_print, _data_.c_str()); + return print(data_print); + } + } + else + { + char data_print[512]; + strcpy(data_print, data.c_str()); + return print(data_print); + } + + return false; +} + +int BlinkerMQTTAT::bPrint(char * name, const String & data) +{ + // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data.substring(0, data.length() - 1); + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_ID_MQTT_AT; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + // else + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data; + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_ID_MQTT_AT; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + + String data_add = BLINKER_F("{\"data\":"); + // for(uint8_t c_num = 0; c_num < 8; c_num++) + // { + // data[c_num] = data_add[c_num]; + // } + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_ID_MQTT_AT; + data_add += BLINKER_F("\",\"toDevice\":\""); + data_add += name; + data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, MQTT_ID_MQTT_AT); + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, name); + // data_add = BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // strcat(data, data_add.c_str()); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_MQTT_AT->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT_AT, BLINKER_PUB_TOPIC_MQTT_AT); + + // if (! iotPub.publish(payload.c_str())) { + + String bPubTopic = BLINKER_F(""); + + // if (mqtt_broker == BLINKER_MQTT_BORKER_ONENET) + // { + // bPubTopic = MQTT_PRODUCTINFO_MQTT_AT; + // bPubTopic += BLINKER_F("/"); + // bPubTopic += name; + // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // bPubTopic = BLINKER_PUB_TOPIC_MQTT_AT; + // } + + if (! mqtt_MQTT_AT->publish(bPubTopic.c_str(), data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerMQTTAT::aliPrint(const String & data) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_ID_MQTT_AT; + data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_MQTT_AT->connected()) + { + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + if (! mqtt_MQTT_AT->publish(BLINKER_PUB_TOPIC_MQTT_AT, data_add.c_str())) + { + // BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + // BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerMQTTAT::duerPrint(const String & data, bool report) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_ID_MQTT_AT; + data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_MQTT_AT->connected()) + { + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + if (! mqtt_MQTT_AT->publish(BLINKER_PUB_TOPIC_MQTT_AT, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerMQTTAT::miPrint(const String & data) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_ID_MQTT_AT; + data_add += BLINKER_F("\",\"toDevice\":\"MIOT_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT MIOT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_MQTT_AT->connected()) + { + if (!checkMIOTKA()) + { + return false; + } + + if (!checkMIOTPrintSpan()) + { + respMIOTTime = millis(); + return false; + } + respMIOTTime = millis(); + + if (! mqtt_MQTT_AT->publish(BLINKER_PUB_TOPIC_MQTT_AT, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isMIOTAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isMIOTAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// void BlinkerMQTTAT::aliType(const String & type) +// { +// _aliType = (char*)malloc((type.length()+1)*sizeof(char)); +// strcpy(_aliType, type.c_str()); +// BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +// } + +void BlinkerMQTTAT::begin(const char* auth) { + // _authKey = auth; + _authKey = (char*)malloc((strlen(auth)+1)*sizeof(char)); + strcpy(_authKey, auth); + + BLINKER_LOG_ALL(BLINKER_F("_authKey: "), auth); + + // _isBegin = begin(); +} + +bool BlinkerMQTTAT::begin() +{ + // if (connectServer()) { + // mDNSInit(); + // isMQTTinit = true; + // } + // else { + uint32_t re_time = millis(); + bool isConnect_MQTT_AT = true; + + if (isMQTTinit) return true; + + // while(1) + { + re_time = millis(); + // ::delay(10000); + // BLINKER_ERR_LOG("Maybe you have put in the wrong AuthKey!"); + // BLINKER_ERR_LOG("Or maybe your request is too frequently!"); + // BLINKER_ERR_LOG("Or maybe your network is disconnected!"); + BLINKER_LOG_ALL("connectServer"); + if (connectServer()) { + mDNSInit(); + isMQTTinit = true; + return true; + } + else { + isMQTTinit = false; + + return false; + } + // delay(10000); + // while ((millis() - re_time) < 10000) + // { + // if (WiFi.status() != WL_CONNECTED && isConnect_MQTT_AT) + // { + // isConnect_MQTT_AT = false; + // WiFi.begin(); + // WiFi.reconnect(); + // } + // else if (WiFi.status() == WL_CONNECTED && !isConnect_MQTT_AT) + // { + // isConnect_MQTT_AT = true; + // } + // ::delay(10); + // // WiFi.status(); + // } + } + // } +} + +int BlinkerMQTTAT::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"trigged\":true,\"autoData\":{"); + payload += BLINKER_F("\"autoId\":"); + payload += STRING_format(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(MQTT_ID_MQTT_AT); + payload += BLINKER_F("\",\"toDevice\":\"autoManager\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_MQTT_AT->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT_AT, BLINKER_PUB_TOPIC_MQTT_AT); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_MQTT_AT->publish(BLINKER_PUB_TOPIC_MQTT_AT, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// int BlinkerMQTTAT::autoPrint(char *name, char *type, char *data) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_MQTT_AT); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_MQTT_AT->connected()) { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +// int BlinkerMQTTAT::autoPrint(char *name1, char *type1, char *data1 +// , char *name2, char *type2, char *data2) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data1); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_MQTT_AT); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name1; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type1; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_MQTT_AT->connected()) +// { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data2); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_MQTT_AT); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name2; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type2; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else +// { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +char * BlinkerMQTTAT::deviceName() { return DEVICE_NAME_MQTT_AT;/*MQTT_ID_MQTT_AT;*/ } + +char * BlinkerMQTTAT::deviceId() { return MQTT_ID_MQTT_AT; } + +char * BlinkerMQTTAT::uuid() { return UUID_MQTT_AT; } + +void BlinkerMQTTAT::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (_sharerCount; _sharerCount > 0; _sharerCount--) + { + delete _sharers[_sharerCount - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +void BlinkerMQTTAT::softAPinit() +{ + WiFiServer _server(80); + WiFiClient _client; + IPAddress apIP(192, 168, 4, 1); + #if defined(ESP8266) + IPAddress netMsk(255, 255, 255, 0); + #endif + + // _server = new WiFiServer(80); + + WiFi.mode(WIFI_AP); + String softAP_ssid = BLINKER_F("DiyArduino_"); + softAP_ssid += macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(softAP_ssid.c_str()); + WiFi.softAPConfig(apIP, apIP, netMsk); + #elif defined(ESP32) + WiFi.setHostname(softAP_ssid.c_str()); + WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); + #endif + + WiFi.softAP(softAP_ssid.c_str(), ("12345678")); + delay(100); + + _server.begin(); + BLINKER_LOG(BLINKER_F("AP IP address: "), WiFi.softAPIP()); + BLINKER_LOG(BLINKER_F("HTTP _server started")); + BLINKER_LOG(BLINKER_F("URL: http://"), WiFi.softAPIP()); + + while(WiFi.status() != WL_CONNECTED) + { + // serverClient(); + _client = _server.available(); + // if (_client.status() == CLOSED) + if (!_client.connected()) + { + _client.stop(); + BLINKER_LOG(BLINKER_F("Connection closed on _client")); + } + else + { + if (_client.available()) + { + String data = _client.readStringUntil('\r'); + + // data = data.substring(4, data.length() - 9); + _client.flush(); + + BLINKER_LOG(BLINKER_F("clientData: "), data); + + if (STRING_contains_string(data, "ssid") && \ + STRING_contains_string(data, "pswd")) + { + String msg = BLINKER_F("{\"hello\":\"world\"}"); + + String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); + s += BLINKER_F("Content-Type: application/json;"); + s += BLINKER_F("charset=utf-8\r\n"); + s += BLINKER_F("Content-Length: "); + s += String(msg.length()); + s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); + s += msg; + s += BLINKER_F("\r\n"); + + _client.print(s); + + _client.stop(); + + parseUrl(data); + } + } + } + ::delay(10); + } +} + +int BlinkerMQTTAT::parseUrl(String data) +{ + BLINKER_LOG(BLINKER_F("APCONFIG data: "), data); + // DynamicJsonBuffer jsonBuffer; + // JsonObject& wifi_data = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject wifi_data = jsonBuffer.as(); + + // if (!wifi_data.success()) + if (error) + { + return false; + } + + String _ssid = wifi_data["ssid"]; + String _pswd = wifi_data["pswd"]; + + BLINKER_LOG(BLINKER_F("ssid: "), _ssid); + BLINKER_LOG(BLINKER_F("pswd: "), _pswd); + + // free(_server); + connectWiFi(_ssid, _pswd); + return true; +} + +int BlinkerMQTTAT::autoInit() +{ + WiFi.mode(WIFI_STA); + String _hostname = BLINKER_F("DiyArduino_"); + _hostname += macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(_hostname.c_str()); + #elif defined(ESP32) + WiFi.setHostname(_hostname.c_str()); + #endif + + WiFi.begin(); + ::delay(500); + + BLINKER_LOG(BLINKER_F("Waiting for WiFi "), + BLINKER_WIFI_AUTO_INIT_TIMEOUT / 1000, + BLINKER_F("s, will enter SMARTCONFIG or "), + BLINKER_F("APCONFIG while WiFi not connect!")); + + uint8_t _times = 0; + while (WiFi.status() != WL_CONNECTED) { + ::delay(500); + if (_times > BLINKER_WIFI_AUTO_INIT_TIMEOUT / 500) break; + _times++; + } + + if (WiFi.status() != WL_CONNECTED) return false; + else { + BLINKER_LOG(BLINKER_F("WiFi Connected.")); + BLINKER_LOG(BLINKER_F("IP Address: ")); + BLINKER_LOG(WiFi.localIP()); + // mDNSInit(); + return true; + } +} + +void BlinkerMQTTAT::connectWiFi(String _ssid, String _pswd) +{ + connectWiFi(_ssid.c_str(), _pswd.c_str()); +} + +void BlinkerMQTTAT::connectWiFi(const char* _ssid, const char* _pswd) +{ + uint32_t connectTime = millis(); + + BLINKER_LOG(BLINKER_F("Connecting to "), _ssid); + + WiFi.mode(WIFI_STA); + String _hostname = BLINKER_F("DiyArduinoWIFI_"); + _hostname += macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(_hostname.c_str()); + #elif defined(ESP32) + WiFi.setHostname(_hostname.c_str()); + #endif + + if (_pswd && strlen(_pswd)) { + WiFi.begin(_ssid, _pswd); + } + else { + WiFi.begin(_ssid); + } + + while (WiFi.status() != WL_CONNECTED) { + ::delay(50); + + if (millis() - connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { + connectTime = millis(); + BLINKER_LOG(BLINKER_F("WiFi connect timeout, please check ssid and pswd!")); + BLINKER_LOG(BLINKER_F("Retring WiFi connect again!")); + } + } + BLINKER_LOG(BLINKER_F("Connected")); + + IPAddress myip = WiFi.localIP(); + BLINKER_LOG(BLINKER_F("Your IP is: "), myip); + + // mDNSInit(); +} + +void BlinkerMQTTAT::smartconfig() +{ + // Base::begin(); + if (!autoInit()) //smartconfig(); + { + WiFi.mode(WIFI_STA); + String _hostname = BLINKER_F("DiyArduino_"); + _hostname += macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(_hostname.c_str()); + #elif defined(ESP32) + WiFi.setHostname(_hostname.c_str()); + #endif + + WiFi.beginSmartConfig(); + + BLINKER_LOG(BLINKER_F("Waiting for SmartConfig.")); + while (!WiFi.smartConfigDone()) { + ::delay(500); + } + + BLINKER_LOG(BLINKER_F("SmartConfig received.")); + + BLINKER_LOG(BLINKER_F("Waiting for WiFi")); + while (WiFi.status() != WL_CONNECTED) { + ::delay(500); + } + + BLINKER_LOG(BLINKER_F("WiFi Connected.")); + + BLINKER_LOG(BLINKER_F("IP Address: ")); + BLINKER_LOG(WiFi.localIP()); + } + // Base::loadTimer(); + + #if defined(ESP8266) + BLINKER_LOG(BLINKER_F("ESP8266_WIFI initialized...")); + #elif defined(ESP32) + BLINKER_LOG(BLINKER_F("ESP32_WIFI initialized...")); + #endif +} + +int BlinkerMQTTAT::connectServer() { + const int httpsPort = 443; +#if defined(ESP8266) + String host = BLINKER_F(BLINKER_SERVER_HOST); + String fingerprint = BLINKER_F("84 5f a4 8a 70 5e 79 7e f5 b3 b4 20 45 c8 35 55 72 f6 85 5a"); + + // BearSSL::WiFiClientSecure *client_s; + + // client_s = new BearSSL::WiFiClientSecure(); + + // client_mqtt.stop(); + + // BLINKER_LOG_ALL(BLINKER_F("connecting to "), host); + + // // BLINKER_LOG_FreeHeap(); + + // uint8_t connet_times = 0; + // // client_s.stop(); + // ::delay(100); + + // bool mfln = client_s->probeMaxFragmentLength(host, httpsPort, 1024); + // if (mfln) { + // client_s->setBufferSizes(1024, 1024); + // } + // // client_s.setFingerprint(fingerprint.c_str()); + + // client_s->setInsecure(); + + // // while (1) { + // bool cl_connected = false; + // if (!client_s->connect(host, httpsPort)) { + // BLINKER_ERR_LOG(BLINKER_F("server connection failed")); + // // connet_times++; + + // ::delay(1000); + // } + // else { + // BLINKER_LOG_ALL(BLINKER_F("connection succeed")); + // cl_connected = true; + + // // break; + // } + + // // if (connet_times >= 4 && !cl_connected) return BLINKER_CMD_FALSE; + // // } + + // String client_msg; + + // String url_iot = BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + // url_iot += _authKey; + + // if (_aliType == ALI_LIGHT) { + // url_iot += BLINKER_F("&aliType=light"); + // } + // else if (_aliType == ALI_OUTLET) { + // url_iot += BLINKER_F("&aliType=outlet"); + // } + // else if (_aliType == ALI_SENSOR) { + // url_iot += BLINKER_F("&aliType=sensor"); + // } + + // if (_duerType == DUER_LIGHT) { + // url_iot += BLINKER_F("&duerType=LIGHT"); + // } + // else if (_duerType == DUER_OUTLET) { + // url_iot += BLINKER_F("&duerType=SOCKET"); + // } + // else if (_duerType == DUER_SENSOR) { + // url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + // } + + // BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host, url_iot); + + // client_msg = BLINKER_F("GET "); + // client_msg += url_iot; + // client_msg += BLINKER_F(" HTTP/1.1\r\nHost: "); + // client_msg += host; + // client_msg += BLINKER_F(":"); + // client_msg += STRING_format(httpsPort); + // client_msg += BLINKER_F("\r\nConnection: close\r\n\r\n"); + + // client_s->print(client_msg); + + // BLINKER_LOG_ALL(BLINKER_F("client_msg: "), client_msg); + + // unsigned long timeout = millis(); + // while (client_s->available() == 0) { + // if (millis() - timeout > 5000) { + // BLINKER_LOG_ALL(BLINKER_F(">>> Client Timeout !")); + // client_s->stop(); + // return false; + // } + // } + + // String _dataGet; + // String lastGet; + // String lengthOfJson; + // while (client_s->available()) { + // // String line = client_s.readStringUntil('\r'); + // _dataGet = client_s->readStringUntil('\n'); + + // if (_dataGet.startsWith("Content-Length: ")){ + // int addr_start = _dataGet.indexOf(' '); + // int addr_end = _dataGet.indexOf('\0', addr_start + 1); + // lengthOfJson = _dataGet.substring(addr_start + 1, addr_end); + // } + + // if (_dataGet == "\r") { + // BLINKER_LOG_ALL(BLINKER_F("headers received")); + + // break; + // } + // } + + // for(int i=0;iread(); + // } + + // // BLINKER_LOG_FreeHeap(); + + // client_s->stop(); + // client_s->flush(); + + // free(client_s); + + // // BLINKER_LOG_FreeHeap(); + + // _dataGet = lastGet; + + // BLINKER_LOG_ALL(BLINKER_F("_dataGet: "), _dataGet); + + // String payload = _dataGet; + + + + client_mqtt.stop(); + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + + String url_iot = BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + url_iot += _authKey; + // url_iot += _aliType; + + if (_aliType == ALI_LIGHT) { + url_iot += BLINKER_F("&aliType=light"); + } + else if (_aliType == ALI_OUTLET) { + url_iot += BLINKER_F("&aliType=outlet"); + } + else if (_aliType == ALI_SENSOR) { + url_iot += BLINKER_F("&aliType=sensor"); + } + + if (_duerType == DUER_LIGHT) { + url_iot += BLINKER_F("&duerType=LIGHT"); + } + else if (_duerType == DUER_OUTLET) { + url_iot += BLINKER_F("&duerType=SOCKET"); + } + else if (_duerType == DUER_SENSOR) { + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + } + + url_iot = "https://" + host + url_iot; + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... url_iot: "), url_iot); + + BLINKER_LOG_FreeHeap_ALL(); + + HTTPClient http; + + String payload; + + if (http.begin(*client_s, url_iot)) { // HTTPS + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + BLINKER_ERR_LOG_ALL("[HTTPS] Unable to connect\n"); + } + +#elif defined(ESP32) + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + // const char* ca = + // "-----BEGIN CERTIFICATE-----\n" + // "MIIEgDCCA2igAwIBAgIQDKTfhr9lmWbWUT0hjX36oDANBgkqhkiG9w0BAQsFADBy\n" + // "MQswCQYDVQQGEwJDTjElMCMGA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywg\n" + // "SW5jLjEdMBsGA1UECxMURG9tYWluIFZhbGlkYXRlZCBTU0wxHTAbBgNVBAMTFFRy\n" + // "dXN0QXNpYSBUTFMgUlNBIENBMB4XDTE4MDEwNDAwMDAwMFoXDTE5MDEwNDEyMDAw\n" + // "MFowGDEWMBQGA1UEAxMNaW90ZGV2LmNsei5tZTCCASIwDQYJKoZIhvcNAQEBBQAD\n" + // "ggEPADCCAQoCggEBALbOFn7cJ2I/FKMJqIaEr38n4kCuJCCeNf1bWdWvOizmU2A8\n" + // "QeTAr5e6Q3GKeJRdPnc8xXhqkTm4LOhgdZB8KzuVZARtu23D4vj4sVzxgC/zwJlZ\n" + // "MRMxN+cqI37kXE8gGKW46l2H9vcukylJX+cx/tjWDfS2YuyXdFuS/RjhCxLgXzbS\n" + // "cve1W0oBZnBPRSMV0kgxTWj7hEGZNWKIzK95BSCiMN59b+XEu3NWGRb/VzSAiJEy\n" + // "Hy9DcDPBC9TEg+p5itHtdMhy2gq1OwsPgl9HUT0xmDATSNEV2RB3vwviNfu9/Eif\n" + // "ObhsV078zf30TqdiESqISEB68gJ0Otru67ePoTkCAwEAAaOCAWowggFmMB8GA1Ud\n" + // "IwQYMBaAFH/TmfOgRw4xAFZWIo63zJ7dygGKMB0GA1UdDgQWBBR/KLqnke61779P\n" + // "xc9htonQwLOxPDAYBgNVHREEETAPgg1pb3RkZXYuY2x6Lm1lMA4GA1UdDwEB/wQE\n" + // "AwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTAYDVR0gBEUwQzA3\n" + // "BglghkgBhv1sAQIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQu\n" + // "Y29tL0NQUzAIBgZngQwBAgEwgYEGCCsGAQUFBwEBBHUwczAlBggrBgEFBQcwAYYZ\n" + // "aHR0cDovL29jc3AyLmRpZ2ljZXJ0LmNvbTBKBggrBgEFBQcwAoY+aHR0cDovL2Nh\n" + // "Y2VydHMuZGlnaXRhbGNlcnR2YWxpZGF0aW9uLmNvbS9UcnVzdEFzaWFUTFNSU0FD\n" + // "QS5jcnQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtM4eyrWB14ajJpQ\n" + // "ibZ5FbzVuvv2Le0FOSoss7UFCDJUYiz2LiV8yOhL4KTY+oVVkqHaYtcFS1CYZNzj\n" + // "6xWcqYZJ+pgsto3WBEgNEEe0uLSiTW6M10hm0LFW9Det3k8fqwSlljqMha3gkpZ6\n" + // "8WB0f2clXOuC+f1SxAOymnGUsSqbU0eFSgevcOIBKR7Hr3YXBXH3jjED76Q52OMS\n" + // "ucfOM9/HB3jN8o/ioQbkI7xyd/DUQtzK6hSArEoYRl3p5H2P4fr9XqmpoZV3i3gQ\n" + // "oOdVycVtpLunyUoVAB2DcOElfDxxXCvDH3XsgoIU216VY03MCaUZf7kZ2GiNL+UX\n" + // "9UBd0Q==\n" + // "-----END CERTIFICATE-----\n"; +// #endif + + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + url_iot += _authKey; + // url_iot += _aliType; + + if (_aliType == ALI_LIGHT) { + url_iot += BLINKER_F("&aliType=light"); + } + else if (_aliType == ALI_OUTLET) { + url_iot += BLINKER_F("&aliType=outlet"); + } + else if (_aliType == ALI_SENSOR) { + url_iot += BLINKER_F("&aliType=sensor"); + } + + if (_duerType == DUER_LIGHT) { + url_iot += BLINKER_F("&duerType=LIGHT"); + } + else if (_duerType == DUER_OUTLET) { + url_iot += BLINKER_F("&duerType=SOCKET"); + } + else if (_duerType == DUER_SENSOR) { + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + } + +// #if defined(BLINKER_ALIGENIE_LIGHT) +// url_iot += BLINKER_F("&aliType=light"); +// #elif defined(BLINKER_ALIGENIE_OUTLET) +// url_iot += BLINKER_F("&aliType=outlet"); +// #elif defined(BLINKER_ALIGENIE_SWITCH) +// #elif defined(BLINKER_ALIGENIE_SENSOR) +// url_iot += BLINKER_F("&aliType=sensor"); +// #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + +// #if defined(ESP8266) +// http.begin(url_iot, fingerprint); //HTTP +// #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); +// #endif + int httpCode = http.GET(); + + String payload; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); +#endif + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(BLINKER_F("Maybe you have put in the wrong AuthKey!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your request is too frequently!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your network is disconnected!")); + // ::delay(60000); + + return false; + // } + } + + // String _userID = STRING_find_string(payload, "deviceName", "\"", 4); + // String _userName = STRING_find_string(payload, "iotId", "\"", 4); + // String _key = STRING_find_string(payload, "iotToken", "\"", 4); + // String _productInfo = STRING_find_string(payload, "productKey", "\"", 4); + // String _broker = STRING_find_string(payload, "broker", "\"", 4); + // String _uuid = STRING_find_string(payload, "uuid", "\"", 4); + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + + if (isMQTTinit) + { + free(MQTT_HOST_MQTT_AT); + free(MQTT_ID_MQTT_AT); + free(MQTT_NAME_MQTT_AT); + free(MQTT_KEY_MQTT_AT); + free(MQTT_PRODUCTINFO_MQTT_AT); + free(UUID_MQTT_AT); + free(DEVICE_NAME_MQTT_AT); + free(BLINKER_PUB_TOPIC_MQTT_AT); + free(BLINKER_SUB_TOPIC_MQTT_AT); + free(mqtt_MQTT_AT); + free(iotSub_MQTT_AT); + + isMQTTinit = false; + } + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME_MQTT_AT, _userID.c_str(), 12); + DEVICE_NAME_MQTT_AT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(DEVICE_NAME_MQTT_AT, _userID.c_str()); + MQTT_ID_MQTT_AT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_MQTT_AT, _userID.c_str()); + MQTT_NAME_MQTT_AT = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_MQTT_AT, _userName.c_str()); + MQTT_KEY_MQTT_AT = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_MQTT_AT, _key.c_str()); + MQTT_PRODUCTINFO_MQTT_AT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_MQTT_AT, _productInfo.c_str()); + MQTT_HOST_MQTT_AT = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_MQTT_AT, BLINKER_MQTT_ALIYUN_HOST); + MQTT_PORT_MQTT_AT = BLINKER_MQTT_ALIYUN_PORT; + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + // String id2name = _userID.subString(10, _userID.length()); + // memcpy(DEVICE_NAME_MQTT_AT, _userID.c_str(), 12); + DEVICE_NAME_MQTT_AT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(DEVICE_NAME_MQTT_AT, _userID.c_str()); + String IDtest = _productInfo + _userID; + MQTT_ID_MQTT_AT = (char*)malloc((IDtest.length()+1)*sizeof(char)); + strcpy(MQTT_ID_MQTT_AT, IDtest.c_str()); + String NAMEtest = IDtest + ";" + _userName; + MQTT_NAME_MQTT_AT = (char*)malloc((NAMEtest.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_MQTT_AT, NAMEtest.c_str()); + MQTT_KEY_MQTT_AT = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_MQTT_AT, _key.c_str()); + MQTT_PRODUCTINFO_MQTT_AT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_MQTT_AT, _productInfo.c_str()); + MQTT_HOST_MQTT_AT = (char*)malloc((strlen(BLINKER_MQTT_QCLOUD_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_MQTT_AT, BLINKER_MQTT_QCLOUD_HOST); + MQTT_PORT_MQTT_AT = BLINKER_MQTT_QCLOUD_PORT; + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + // memcpy(DEVICE_NAME_MQTT_AT, _userID.c_str(), 12); + DEVICE_NAME_MQTT_AT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(DEVICE_NAME_MQTT_AT, _userID.c_str()); + MQTT_ID_MQTT_AT = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_ID_MQTT_AT, _userName.c_str()); + MQTT_NAME_MQTT_AT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_MQTT_AT, _productInfo.c_str()); + MQTT_KEY_MQTT_AT = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_MQTT_AT, _key.c_str()); + MQTT_PRODUCTINFO_MQTT_AT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_MQTT_AT, _productInfo.c_str()); + MQTT_HOST_MQTT_AT = (char*)malloc((strlen(BLINKER_MQTT_ONENET_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_MQTT_AT, BLINKER_MQTT_ONENET_HOST); + MQTT_PORT_MQTT_AT = BLINKER_MQTT_ONENET_PORT; + } + UUID_MQTT_AT = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_MQTT_AT, _uuid.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME_MQTT_AT: "), DEVICE_NAME_MQTT_AT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_MQTT_AT: "), MQTT_PRODUCTINFO_MQTT_AT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_MQTT_AT: "), MQTT_ID_MQTT_AT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_MQTT_AT: "), MQTT_NAME_MQTT_AT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_MQTT_AT: "), MQTT_KEY_MQTT_AT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_MQTT_AT); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_MQTT_AT); + BLINKER_LOG_ALL(BLINKER_F("UUID_MQTT_AT: "), UUID_MQTT_AT); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_MQTT_AT; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_ID_MQTT_AT; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_MQTT_AT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_MQTT_AT, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_MQTT_AT, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_MQTT_AT: "), BLINKER_PUB_TOPIC_MQTT_AT); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_MQTT_AT; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_ID_MQTT_AT; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_MQTT_AT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_MQTT_AT, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_MQTT_AT, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_MQTT_AT: "), BLINKER_SUB_TOPIC_MQTT_AT); + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + String PUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT_AT; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += _userID; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_MQTT_AT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_MQTT_AT, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_MQTT_AT, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_MQTT_AT: "), BLINKER_PUB_TOPIC_MQTT_AT); + + String SUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT_AT; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += _userID; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_MQTT_AT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_MQTT_AT, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_MQTT_AT, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_MQTT_AT: "), BLINKER_SUB_TOPIC_MQTT_AT); + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + uint8_t str_len; + String PUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT_AT; + PUB_TOPIC_STR += BLINKER_F("/onenet_rule/r"); + // str_len = PUB_TOPIC_STR.length() + 1; + BLINKER_PUB_TOPIC_MQTT_AT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_MQTT_AT, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_MQTT_AT, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_MQTT_AT: "), BLINKER_PUB_TOPIC_MQTT_AT); + + String SUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT_AT; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += _userID; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_MQTT_AT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_MQTT_AT, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_MQTT_AT, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_MQTT_AT: "), BLINKER_SUB_TOPIC_MQTT_AT); + } + + // BLINKER_LOG_FreeHeap(); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_MQTT_AT, MQTT_PORT_MQTT_AT, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_MQTT_AT = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_MQTT_AT, MQTT_PORT_MQTT_AT, MQTT_ID_MQTT_AT, MQTT_NAME_MQTT_AT, MQTT_KEY_MQTT_AT); + #elif defined(ESP32) + mqtt_MQTT_AT = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_MQTT_AT, MQTT_PORT_MQTT_AT, MQTT_ID_MQTT_AT, MQTT_NAME_MQTT_AT, MQTT_KEY_MQTT_AT); + #endif + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_MQTT_AT, MQTT_PORT_MQTT_AT, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_MQTT_AT = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_MQTT_AT, MQTT_PORT_MQTT_AT, MQTT_ID_MQTT_AT, MQTT_NAME_MQTT_AT, MQTT_KEY_MQTT_AT); + #elif defined(ESP32) + mqtt_MQTT_AT = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_MQTT_AT, MQTT_PORT_MQTT_AT, MQTT_ID_MQTT_AT, MQTT_NAME_MQTT_AT, MQTT_KEY_MQTT_AT); + #endif + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + mqtt_MQTT_AT = new Adafruit_MQTT_Client(&client, MQTT_HOST_MQTT_AT, MQTT_PORT_MQTT_AT, MQTT_ID_MQTT_AT, MQTT_NAME_MQTT_AT, MQTT_KEY_MQTT_AT); + } + + // iotPub = new Adafruit_MQTT_Publish(mqtt_MQTT_AT, BLINKER_PUB_TOPIC_MQTT_AT); + // if (!isMQTTinit) + iotSub_MQTT_AT = new Adafruit_MQTT_Subscribe(mqtt_MQTT_AT, BLINKER_SUB_TOPIC_MQTT_AT); + + mqtt_broker = (char*)malloc((_broker.length()+1)*sizeof(char)); + strcpy(mqtt_broker, _broker.c_str()); + // mqtt_broker = _broker; + + // mDNSInit(MQTT_ID_MQTT_AT); + this->latestTime = millis(); + // if (!isMQTTinit) + mqtt_MQTT_AT->subscribe(iotSub_MQTT_AT); + + #if defined(ESP8266) + // client_s->stop(); + client_mqtt.setInsecure(); + #endif + // connect(); + + return true; +} + +void BlinkerMQTTAT::mDNSInit() +{ +#if defined(ESP8266) + if (!MDNS.begin(DEVICE_NAME_MQTT_AT, WiFi.localIP())) { +#elif defined(ESP32) + if (!MDNS.begin(DEVICE_NAME_MQTT_AT)) { +#endif + while(1) { + ::delay(100); + } + } + + BLINKER_LOG(BLINKER_F("mDNS responder started")); + + MDNS.addService(BLINKER_MDNS_SERVICE_BLINKER, "tcp", WS_SERVERPORT); + MDNS.addServiceTxt(BLINKER_MDNS_SERVICE_BLINKER, "tcp", "deviceName", String(DEVICE_NAME_MQTT_AT)); + + webSocket_MQTT_AT.begin(); + webSocket_MQTT_AT.onEvent(webSocketEvent_MQTT_AT); + BLINKER_LOG(BLINKER_F("webSocket_MQTT_AT server started")); + BLINKER_LOG(BLINKER_F("ws://"), DEVICE_NAME_MQTT_AT, BLINKER_F(".local:"), WS_SERVERPORT); +} + +void BlinkerMQTTAT::checkKA() { + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerMQTTAT::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerMQTTAT::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerMQTTAT::checkMIOTKA() { + if (millis() - miKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerMQTTAT::checkCanPrint() { + if ((millis() - printTime >= BLINKER_MQTT_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerMQTTAT::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerMQTTAT::checkPrintSpan() { + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) { + BLINKER_ERR_LOG(BLINKER_F("WEBSOCKETS CLIENT NOT ALIVE OR MSG LIMIT")); + + return false; + } + else { + respTimes++; + return true; + } + } + else { + respTimes = 0; + return true; + } +} + +int BlinkerMQTTAT::checkMIOTPrintSpan() +{ + if (millis() - respMIOTTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respMIOTTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respMIOTTimes++; + return true; + } + } + else + { + respMIOTTimes = 0; + return true; + } +} + +int BlinkerMQTTAT::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerMQTTAT::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerMQTTAT::checkPrintLimit() +{ + if ((millis() - _print_time) < 60000) + { + if (_print_times < 10) return true; + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT MSG LIMIT")); + return false; + } + } + else + { + _print_time = millis(); + _print_times = 0; + return true; + } +} + +int BlinkerMQTTAT::isJson(const String & data) +{ + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(STRING_format(data)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG("Print data is not Json! ", data); + return false; + } + + return true; +} + +#endif + +#endif diff --git a/blinker-library/src/Adapters/BlinkerMQTTAUTO.h b/blinker-library/src/Adapters/BlinkerMQTTAUTO.h new file mode 100644 index 0000000..40e63ab --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerMQTTAUTO.h @@ -0,0 +1,2079 @@ +#ifndef BLINKER_MQTT_AUTO_H +#define BLINKER_MQTT_AUTO_H + +#if (defined(ESP8266) || defined(ESP32)) + +#if defined(ESP8266) + #include + #include + #include +#elif defined(ESP32) + #include + #include + #include +#endif + +#include + +#include "../modules/WebSockets/WebSocketsServer.h" +#include "../modules/mqtt/Adafruit_MQTT.h" +#include "../modules/mqtt/Adafruit_MQTT_Client.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +// #include "Adapters/BlinkerMQTTAUTO.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +char* MQTT_HOST_AUTO; +char* MQTT_ID_AUTO; +char* MQTT_NAME_AUTO; +char* MQTT_KEY_AUTO; +char* MQTT_PRODUCTINFO_AUTO; +char* UUID_AUTO; +char* AUTHKEY_AUTO; +char* MQTT_DEVICEID_AUTO; +// char* DEVICE_NAME; +char* BLINKER_PUB_TOPIC_AUTO; +char* BLINKER_SUB_TOPIC_AUTO; +uint16_t MQTT_PORT_AUTO; + +class BlinkerMQTTAUTO : public BlinkerStream +{ + public : + BlinkerMQTTAUTO(); + + int connect(); + int connected(); + int mConnected(); + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + // bool extraAvailable(); + void subscribe(); + char * lastRead(); + void flush(); + int print(char * data, bool needCheck = true); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + void aliType(const String & type); + void duerType(const String & type); + void begin(const char* auth, const char* type); + // bool begin(); + int autoPrint(unsigned long id); + // bool autoPrint(char *name, char *type, char *data); + // bool autoPrint(char *name1, char *type1, char *data1, + // char *name2, char *type2, char *data2); + char * deviceName(); + char * authKey() { return AUTHKEY_AUTO; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_AUTO; } + int init() { return isMQTTinit; } + int reRegister() { return connectServer(); } + int deviceRegister() { return connectServer(); } + int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + + private : + bool isMQTTinit = false; + + int connectServer(); + void mDNSInit(); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + int pubHello(); + + protected : + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + char* _deviceType; + // const char* _authKey; + // char* _authKey; + char* _vipKey; + char* _aliType; + char* _duerType; + // char _authKey[BLINKER_AUTHKEY_SIZE]; + bool* isHandle;// = &isConnect; + bool isAlive = false; + bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + // char* mqtt_broker; + + bool isNew = false; + bool isAuth = false; + bool isFirst = false; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; + + bool _isAuthKey = false; +}; + +// #if defined(ESP8266) +// extern BearSSL::WiFiClientSecure client_mqtt; +// // WiFiClientSecure client_mqtt; +// #elif defined(ESP32) +// extern WiFiClientSecure client_s; +// #endif + +// extern WiFiClient client; + + +#if defined(ESP8266) + BearSSL::WiFiClientSecure client_mqtt; + // WiFiClientSecure client_mqtt; +#elif defined(ESP32) + WiFiClientSecure client_s; +#endif + +WiFiClient client; +Adafruit_MQTT_Client* mqtt_AUTO; +// Adafruit_MQTT_Publish *iotPub; +Adafruit_MQTT_Subscribe* iotSub_AUTO; + +#define WS_SERVERPORT 81 +WebSocketsServer webSocket_AUTO = WebSocketsServer(WS_SERVERPORT); + +char* msgBuf_AUTO; +bool isFresh_AUTO = false; +bool isConnect_AUTO = false; +bool isAvail_AUTO = false; +uint8_t ws_num_AUTO = 0; +uint8_t dataFrom_AUTO = BLINKER_MSG_FROM_MQTT; + +void webSocketEvent_AUTO(uint8_t num, WStype_t type, \ + uint8_t * payload, size_t length) +{ + + switch(type) + { + case WStype_DISCONNECTED: + BLINKER_LOG_ALL(BLINKER_F("Disconnected! "), num); + + isConnect_AUTO = false; + break; + case WStype_CONNECTED: + { + IPAddress ip = webSocket_AUTO.remoteIP(num); + + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", Connected from: "), ip, + BLINKER_F(", url: "), (char *)payload); + + // send message to client + webSocket_AUTO.sendTXT(num, "{\"state\":\"connected\"}\n"); + + ws_num_AUTO = num; + + isConnect_AUTO = true; + } + break; + case WStype_TEXT: + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", get Text: "), (char *)payload, \ + BLINKER_F(", length: "), length); + + if (length < BLINKER_MAX_READ_SIZE) { + if (isFresh_AUTO) free(msgBuf_AUTO); + msgBuf_AUTO = (char*)malloc((length+1)*sizeof(char)); + strcpy(msgBuf_AUTO, (char*)payload); + isAvail_AUTO = true; + isFresh_AUTO = true; + } + + dataFrom_AUTO = BLINKER_MSG_FROM_WS; + + ws_num_AUTO = num; + + // send message to client + // webSocket_MQTT.sendTXT(num, "message here"); + + // send data to all connected clients + // webSocket_MQTT.broadcastTXT("message here"); + break; + case WStype_BIN: + // BLINKER_LOG("num: ", num, " get binary length: ", length); + // hexdump(payload, length); + + // send message to client + // webSocket_MQTT.sendBIN(num, payload, length); + break; + default : + break; + } +} + +BlinkerMQTTAUTO::BlinkerMQTTAUTO() { isHandle = &isConnect_AUTO; } + +int BlinkerMQTTAUTO::connect() +{ + int8_t ret; + + webSocket_AUTO.loop(); + + if (!isMQTTinit) { + return *isHandle; + } + + if (mqtt_AUTO->connected()) + { + return true; + } + + disconnect(); + + if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + { + yield(); + return false; + } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + #if defined(ESP8266) + client_mqtt.setInsecure(); + ::delay(10); + #endif + + if ((ret = mqtt_AUTO->connect()) != 0) + { + BLINKER_LOG(mqtt_AUTO->connectErrorString(ret)); + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + if (ret == 4) reRegister(); + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + reRegister(); + reconnect_time = 0; + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + if (isNew) + { + if (pubHello()) { + isNew = false; + } + } + + this->latestTime = millis(); + + return true; +} + +int BlinkerMQTTAUTO::connected() +{ + if (!isMQTTinit) + { + return *isHandle; + } + + return mqtt_AUTO->connected() || *isHandle; +} + +int BlinkerMQTTAUTO::mConnected() +{ + if (!isMQTTinit) return false; + else return mqtt_AUTO->connected(); +} + +void BlinkerMQTTAUTO::disconnect() +{ + if (isMQTTinit) mqtt_AUTO->disconnect(); + + if (*isHandle) webSocket_AUTO.disconnect(); +} + +void BlinkerMQTTAUTO::ping() +{ + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!isMQTTinit) return; + + if (!mqtt_AUTO->ping()) + { + disconnect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } +} + +int BlinkerMQTTAUTO::available() +{ + webSocket_AUTO.loop(); + + if (isMQTTinit) { + checkKA(); + + // if (!mqtt_PRO->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + { + ping(); + } + else + { + subscribe(); + } + } + + if (isAvail_AUTO) + { + isAvail_AUTO = false; + return true; + } + else { + return false; + } +} + +int BlinkerMQTTAUTO::aligenieAvail() +{ + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerMQTTAUTO::duerAvail() +{ + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +// bool BlinkerMQTTAUTO::extraAvailable() +// { +// if (isBavail) +// { +// isBavail = false; +// return true; +// } +// else +// { +// return false; +// } +// } + +void BlinkerMQTTAUTO::subscribe() +{ + if (!isMQTTinit) return; + + Adafruit_MQTT_Subscribe *subscription; + while ((subscription = mqtt_AUTO->readSubscription(10))) + { + if (subscription == iotSub_AUTO) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), (char *)iotSub_AUTO->lastread); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(String((char *)iotSub_AUTO->lastread)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, String((char *)iotSub_AUTO->lastread)); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"]; + String dataGet = root["data"]; + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_AUTO) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_AUTO = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT) + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_AUTO = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + check is from bridge/share device, \ + data: "), dataGet); + + _needCheckShare = true; + } + } + } + // else + // { + // dataGet = String((char *)iotSub_MQTT->lastread); + // root.printTo(dataGet); + serializeJson(root, dataGet); + + // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + // check is from bridge/share device, \ + // data: "), dataGet); + + // // return; + + // // isBavail = true; + + // _needCheckShare = true; + // } + + isAvail_AUTO = true; + isAlive = true; + } + + // memset(msgBuf_MQTT, 0, BLINKER_MAX_READ_SIZE); + // memcpy(msgBuf_MQTT, dataGet.c_str(), dataGet.length()); + + if (isFresh_AUTO) free(msgBuf_AUTO); + msgBuf_AUTO = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_AUTO, dataGet.c_str()); + isFresh_AUTO = true; + + this->latestTime = millis(); + + dataFrom_AUTO = BLINKER_MSG_FROM_MQTT; + } + } +} + +char * BlinkerMQTTAUTO::lastRead() +{ + if (isFresh_AUTO) return msgBuf_AUTO; + else return ""; +} + +void BlinkerMQTTAUTO::flush() +{ + if (isFresh_AUTO) + { + free(msgBuf_AUTO); isFresh_AUTO = false; isAvail_AUTO = false; + isAliAvail = false; //isBavail = false; + } +} + +int BlinkerMQTTAUTO::print(char * data, bool needCheck) +{ + // BLINKER_LOG_FreeHeap(); + if (*isHandle && dataFrom_AUTO == BLINKER_MSG_FROM_WS) + { + if (needCheck) + { + if (!checkPrintSpan()) + { + respTime = millis(); + return false; + } + } + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("WS response: ")); + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + strcat(data, BLINKER_CMD_NEWLINE); + + webSocket_AUTO.sendTXT(ws_num_AUTO, data); + + return true; + } + else + { + // // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // uint8_t num = strlen(data) - 1; + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data.substring(0, data.length() - 1); + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_ID_MQTT; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_MQTT; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + // else + // { + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data; + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_ID_MQTT; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_MQTT; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + + uint16_t num = strlen(data); + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+7] = data[c_num-1]; + } + + data[num+8] = '\0'; + + char data_add[20] = "{\"data\":"; + for(uint8_t c_num = 0; c_num < 8; c_num++) + { + data[c_num] = data_add[c_num]; + } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, ",\"fromDevice\":\""); + strcat(data, MQTT_ID_AUTO); + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, "\",\"toDevice\":\""); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + strcat(data, _sharers[_sharerFrom]->uuid()); + } + else + { + strcat(data, UUID_AUTO); + } + // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // strcat(data, data_add.c_str()); + + strcat(data, "\",\"deviceType\":\"OwnApp\"}"); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (mqtt_AUTO->connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + + if (! mqtt_AUTO->publish(BLINKER_PUB_TOPIC_AUTO, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } + } +} + +int BlinkerMQTTAUTO::bPrint(char * name, const String & data) +{ + // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data.substring(0, data.length() - 1); + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_ID_MQTT; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + // else + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data; + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_ID_MQTT; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + + String data_add = BLINKER_F("{\"data\":"); + // for(uint8_t c_num = 0; c_num < 8; c_num++) + // { + // data[c_num] = data_add[c_num]; + // } + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_AUTO; + data_add += BLINKER_F("\",\"toDevice\":\""); + data_add += name; + data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, MQTT_ID_MQTT); + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, name); + // data_add = BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // strcat(data, data_add.c_str()); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_AUTO->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + + // if (! iotPub.publish(payload.c_str())) { + + // String bPubTopic = BLINKER_F(""); + + // if (strcmp(mqtt_broker, BLINKER_MQTT_BORKER_ONENET) == 0) + // { + // bPubTopic = MQTT_PRODUCTINFO_MQTT; + // bPubTopic += BLINKER_F("/"); + // bPubTopic += name; + // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // bPubTopic = BLINKER_PUB_TOPIC_MQTT; + // } + + if (! mqtt_AUTO->publish(BLINKER_PUB_TOPIC_AUTO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerMQTTAUTO::aliPrint(const String & data) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_AUTO; + data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_AUTO->connected()) + { + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + if (! mqtt_AUTO->publish(BLINKER_PUB_TOPIC_AUTO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerMQTTAUTO::duerPrint(const String & data, bool report) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_AUTO; + data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_AUTO->connected()) + { + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + if (! mqtt_AUTO->publish(BLINKER_PUB_TOPIC_AUTO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +void BlinkerMQTTAUTO::aliType(const String & type) +{ + _aliType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_aliType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +} + +void BlinkerMQTTAUTO::duerType(const String & type) +{ + _duerType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_duerType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_duerType: "), _duerType); +} + +void BlinkerMQTTAUTO::begin(const char* auth, const char* type) { + // if (!checkInit()) return; + // _authKey = auth; + _vipKey = (char*)malloc((strlen(auth)+1)*sizeof(char)); + strcpy(_vipKey, auth); + + _deviceType = (char*)malloc((strlen(type)+1)*sizeof(char)); + strcpy(_deviceType, type); + + BLINKER_LOG_ALL(BLINKER_F("_vipKey: "), auth); + BLINKER_LOG_ALL(BLINKER_F("_deviceType: "), type); + + mDNSInit(); +} + +int BlinkerMQTTAUTO::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"trigged\":true,\"autoData\":{"); + payload += BLINKER_F("\"autoId\":"); + payload += STRING_format(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(MQTT_DEVICEID_AUTO); + payload += BLINKER_F("\",\"toDevice\":\"autoManager\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_AUTO->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_AUTO->publish(BLINKER_PUB_TOPIC_AUTO, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// bool BlinkerMQTTAUTO::autoPrint(char *name, char *type, char *data) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_MQTT); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_MQTT->connected()) { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +// bool BlinkerMQTTAUTO::autoPrint(char *name1, char *type1, char *data1 +// , char *name2, char *type2, char *data2) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data1); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_MQTT); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name1; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type1; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_MQTT->connected()) +// { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data2); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_MQTT); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name2; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type2; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else +// { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +char * BlinkerMQTTAUTO::deviceName() { return MQTT_DEVICEID_AUTO;/*MQTT_ID_MQTT;*/ } + +void BlinkerMQTTAUTO::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (uint8_t num = _sharerCount; num > 0; num--) + { + delete _sharers[num - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerMQTTAUTO::authCheck() +{ + uint8_t _authCheck; + + BLINKER_LOG_ALL(BLINKER_F("authCheck start")); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck == BLINKER_AUTH_CHECK_DATA) + { + EEPROM.commit(); + EEPROM.end(); + isAuth = true; + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return true; + } + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return false; +} + +int BlinkerMQTTAUTO::connectServer() +{ + const int httpsPort = 443; + #if defined(ESP8266) + String host = BLINKER_F(BLINKER_SERVER_HOST); + #elif defined(ESP32) + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + #endif + if (!_isAuthKey) + { + #if defined(ESP8266) + // String host = BLINKER_F(BLINKER_SERVER_HOST); + String fingerprint = BLINKER_F("84 5f a4 8a 70 5e 79 7e f5 b3 b4 20 45 c8 35 55 72 f6 85 5a"); + + // WiFiClientSecure client_s; + + // BearSSL::WiFiClientSecure *client_s; + + // client_s = new BearSSL::WiFiClientSecure(); + + // BLINKER_LOG_ALL(BLINKER_F("connecting to "), host); + + // // BLINKER_LOG_FreeHeap(); + + // uint8_t connet_times = 0; + // // client_s.stop(); + // ::delay(100); + + // // bool mfln = client_s.probeMaxFragmentLength(host, httpsPort, 1024); + // // if (mfln) { + // // client_s.setBufferSizes(1024, 1024); + // // } + // client_s->setFingerprint(fingerprint.c_str()); + + // client_s->setInsecure(); + + // // while (1) { + // bool cl_connected = false; + // if (!client_s->connect(host, httpsPort)) { + // BLINKER_ERR_LOG(BLINKER_F("server connection failed")); + // // connet_times++; + + // ::delay(1000); + // } + // else { + // BLINKER_LOG_ALL(BLINKER_F("connection succeed")); + // cl_connected = true; + + // // break; + // } + + // // if (connet_times >= 4 && !cl_connected) return BLINKER_CMD_FALSE; + // // } + + // String client_msg; + + // String url_iot = BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + // url_iot += _authKey; + // url_iot += _aliType; + // url_iot += _duerType; + + // // #if defined(BLINKER_ALIGENIE_LIGHT) + // // url_iot += BLINKER_F("&aliType=light"); + // // #elif defined(BLINKER_ALIGENIE_OUTLET) + // // url_iot += BLINKER_F("&aliType=outlet"); + // // #elif defined(BLINKER_ALIGENIE_SWITCH) + // // #elif defined(BLINKER_ALIGENIE_SENSOR) + // // url_iot += BLINKER_F("&aliType=sensor"); + // // #endif + + // BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host, url_iot); + + // client_msg = BLINKER_F("GET "); + // client_msg += url_iot; + // client_msg += BLINKER_F(" HTTP/1.1\r\nHost: "); + // client_msg += host; + // client_msg += BLINKER_F(":"); + // client_msg += STRING_format(httpsPort); + // client_msg += BLINKER_F("\r\nConnection: close\r\n\r\n"); + + // client_s->print(client_msg); + + // BLINKER_LOG_ALL(BLINKER_F("client_msg: "), client_msg); + + // unsigned long timeout = millis(); + // while (client_s->available() == 0) { + // if (millis() - timeout > 5000) { + // BLINKER_LOG_ALL(BLINKER_F(">>> Client Timeout !")); + // client_s->stop(); + // return false; + // } + // } + + // String _dataGet; + // String lastGet; + // String lengthOfJson; + // while (client_s->available()) { + // // String line = client_s.readStringUntil('\r'); + // _dataGet = client_s->readStringUntil('\n'); + + // if (_dataGet.startsWith("Content-Length: ")){ + // int addr_start = _dataGet.indexOf(' '); + // int addr_end = _dataGet.indexOf('\0', addr_start + 1); + // lengthOfJson = _dataGet.substring(addr_start + 1, addr_end); + // } + + // if (_dataGet == "\r") { + // BLINKER_LOG_ALL(BLINKER_F("headers received")); + + // break; + // } + // } + + // for(int i=0;iread(); + // } + + // // BLINKER_LOG_FreeHeap(); + + // client_s->stop(); + // client_s->flush(); + + // free(client_s); + + // // BLINKER_LOG_FreeHeap(); + + // _dataGet = lastGet; + + // BLINKER_LOG_ALL(BLINKER_F("_dataGet: "), _dataGet); + + // String payload = _dataGet; + + + + client_mqtt.stop(); + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + + String url_iot = BLINKER_F("/api/v1/user/device/auth/get?deviceType="); + url_iot += _deviceType; + url_iot += BLINKER_F("&typeKey="); + url_iot += _vipKey; + url_iot += BLINKER_F("&deviceName="); + url_iot += macDeviceName(); + + url_iot = "https://" + host + url_iot; + + HTTPClient http; + + String payload; + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] begin: "), url_iot); + + if (http.begin(*client_s, url_iot)) { // HTTPS + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + + #elif defined(ESP32) + // String host = BLINKER_F(BLINKER_SERVER_HTTPS); + // const char* ca = + // "-----BEGIN CERTIFICATE-----\n" + // "MIIEgDCCA2igAwIBAgIQDKTfhr9lmWbWUT0hjX36oDANBgkqhkiG9w0BAQsFADBy\n" + // "MQswCQYDVQQGEwJDTjElMCMGA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywg\n" + // "SW5jLjEdMBsGA1UECxMURG9tYWluIFZhbGlkYXRlZCBTU0wxHTAbBgNVBAMTFFRy\n" + // "dXN0QXNpYSBUTFMgUlNBIENBMB4XDTE4MDEwNDAwMDAwMFoXDTE5MDEwNDEyMDAw\n" + // "MFowGDEWMBQGA1UEAxMNaW90ZGV2LmNsei5tZTCCASIwDQYJKoZIhvcNAQEBBQAD\n" + // "ggEPADCCAQoCggEBALbOFn7cJ2I/FKMJqIaEr38n4kCuJCCeNf1bWdWvOizmU2A8\n" + // "QeTAr5e6Q3GKeJRdPnc8xXhqkTm4LOhgdZB8KzuVZARtu23D4vj4sVzxgC/zwJlZ\n" + // "MRMxN+cqI37kXE8gGKW46l2H9vcukylJX+cx/tjWDfS2YuyXdFuS/RjhCxLgXzbS\n" + // "cve1W0oBZnBPRSMV0kgxTWj7hEGZNWKIzK95BSCiMN59b+XEu3NWGRb/VzSAiJEy\n" + // "Hy9DcDPBC9TEg+p5itHtdMhy2gq1OwsPgl9HUT0xmDATSNEV2RB3vwviNfu9/Eif\n" + // "ObhsV078zf30TqdiESqISEB68gJ0Otru67ePoTkCAwEAAaOCAWowggFmMB8GA1Ud\n" + // "IwQYMBaAFH/TmfOgRw4xAFZWIo63zJ7dygGKMB0GA1UdDgQWBBR/KLqnke61779P\n" + // "xc9htonQwLOxPDAYBgNVHREEETAPgg1pb3RkZXYuY2x6Lm1lMA4GA1UdDwEB/wQE\n" + // "AwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTAYDVR0gBEUwQzA3\n" + // "BglghkgBhv1sAQIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQu\n" + // "Y29tL0NQUzAIBgZngQwBAgEwgYEGCCsGAQUFBwEBBHUwczAlBggrBgEFBQcwAYYZ\n" + // "aHR0cDovL29jc3AyLmRpZ2ljZXJ0LmNvbTBKBggrBgEFBQcwAoY+aHR0cDovL2Nh\n" + // "Y2VydHMuZGlnaXRhbGNlcnR2YWxpZGF0aW9uLmNvbS9UcnVzdEFzaWFUTFNSU0FD\n" + // "QS5jcnQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtM4eyrWB14ajJpQ\n" + // "ibZ5FbzVuvv2Le0FOSoss7UFCDJUYiz2LiV8yOhL4KTY+oVVkqHaYtcFS1CYZNzj\n" + // "6xWcqYZJ+pgsto3WBEgNEEe0uLSiTW6M10hm0LFW9Det3k8fqwSlljqMha3gkpZ6\n" + // "8WB0f2clXOuC+f1SxAOymnGUsSqbU0eFSgevcOIBKR7Hr3YXBXH3jjED76Q52OMS\n" + // "ucfOM9/HB3jN8o/ioQbkI7xyd/DUQtzK6hSArEoYRl3p5H2P4fr9XqmpoZV3i3gQ\n" + // "oOdVycVtpLunyUoVAB2DcOElfDxxXCvDH3XsgoIU216VY03MCaUZf7kZ2GiNL+UX\n" + // "9UBd0Q==\n" + // "-----END CERTIFICATE-----\n"; + // #endif + + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/auth/get?deviceType="); + url_iot += _deviceType; + url_iot += BLINKER_F("&typeKey="); + url_iot += _vipKey; + url_iot += BLINKER_F("&deviceName="); + url_iot += macDeviceName(); + + // #if defined(BLINKER_ALIGENIE_LIGHT) + // url_iot += BLINKER_F("&aliType=light"); + // #elif defined(BLINKER_ALIGENIE_OUTLET) + // url_iot += BLINKER_F("&aliType=outlet"); + // #elif defined(BLINKER_ALIGENIE_SWITCH) + // #elif defined(BLINKER_ALIGENIE_SENSOR) + // url_iot += BLINKER_F("&aliType=sensor"); + // #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + // #if defined(ESP8266) + // http.begin(url_iot, fingerprint); //HTTP + // #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); + // #endif + int httpCode = http.GET(); + + String payload; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + #endif + + // payload = ""; + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_AUTHKEY)) { + // while(1) { + BLINKER_ERR_LOG(BLINKER_F("Maybe you have put in the wrong AuthKey!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your request is too frequently!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your network is disconnected!")); + // ::delay(60000); + + return false; + // } + } + + String _getAuthKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_AUTHKEY]; + + AUTHKEY_AUTO = (char*)malloc((_getAuthKey.length()+1)*sizeof(char)); + strcpy(AUTHKEY_AUTO, _getAuthKey.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_AUTO: "), AUTHKEY_AUTO); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + _isAuthKey = true; + } + // TBD + +#if defined(ESP8266) + // client_mqtt.stop(); + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + + String url_iot = BLINKER_F("/api/v1/user/device/auth?authKey="); + url_iot += AUTHKEY_AUTO; + // url_iot += _aliType; + // url_iot += _duerType; + + url_iot = "https://" + host + url_iot; + + HTTPClient http; + + String payload = ""; + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] begin: "), url_iot); + + if (http.begin(*client_s, url_iot)) { // HTTPS + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + +#elif defined(ESP32) + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/auth?authKey="); + url_iot += AUTHKEY_AUTO; + // url_iot += _aliType; + // url_iot += _duerType; + +// #if defined(BLINKER_ALIGENIE_LIGHT) +// url_iot += BLINKER_F("&aliType=light"); +// #elif defined(BLINKER_ALIGENIE_OUTLET) +// url_iot += BLINKER_F("&aliType=outlet"); +// #elif defined(BLINKER_ALIGENIE_SWITCH) +// #elif defined(BLINKER_ALIGENIE_SENSOR) +// url_iot += BLINKER_F("&aliType=sensor"); +// #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + +// #if defined(ESP8266) +// http.begin(url_iot, fingerprint); //HTTP +// #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); +// #endif + int httpCode = http.GET(); + + String payload = ""; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); +#endif + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) + { + // while(1) { + BLINKER_ERR_LOG(BLINKER_F("Maybe you have put in the wrong AuthKey!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your request is too frequently!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your network is disconnected!")); + // ::delay(60000); + + return false; + // } + } + + // String _userID = STRING_find_string(payload, "deviceName", "\"", 4); + // String _userName = STRING_find_string(payload, "iotId", "\"", 4); + // String _key = STRING_find_string(payload, "iotToken", "\"", 4); + // String _productInfo = STRING_find_string(payload, "productKey", "\"", 4); + // String _broker = STRING_find_string(payload, "broker", "\"", 4); + // String _uuid = STRING_find_string(payload, "uuid", "\"", 4); + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + + if (isMQTTinit) + { + free(MQTT_HOST_AUTO); + free(MQTT_ID_AUTO); + free(MQTT_NAME_AUTO); + free(MQTT_KEY_AUTO); + free(MQTT_PRODUCTINFO_AUTO); + free(UUID_AUTO); + // free(AUTHKEY_AUTO); + free(MQTT_DEVICEID_AUTO); + free(BLINKER_PUB_TOPIC_AUTO); + free(BLINKER_SUB_TOPIC_AUTO); + free(mqtt_AUTO); + free(iotSub_AUTO); + + isMQTTinit = false; + } + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME, _userID.c_str(), 12); + // String _deviceName = _userID.substring(12, 36); + // MQTT_DEVICEID_PRO = (char*)malloc((_deviceName.length()+1)*sizeof(char)); + // String _deviceName = _userID.substring(12, 36); + MQTT_DEVICEID_AUTO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_AUTO, _userID.c_str()); + MQTT_ID_AUTO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_AUTO, _userID.c_str()); + MQTT_NAME_AUTO = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_AUTO, _userName.c_str()); + MQTT_KEY_AUTO = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_AUTO, _key.c_str()); + MQTT_PRODUCTINFO_AUTO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_AUTO, _productInfo.c_str()); + MQTT_HOST_AUTO = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_AUTO, BLINKER_MQTT_ALIYUN_HOST); + // AUTHKEY_AUTO = (char*)malloc((_authKey.length()+1)*sizeof(char)); + // strcpy(AUTHKEY_AUTO, _authKey.c_str()); + MQTT_PORT_AUTO = BLINKER_MQTT_ALIYUN_PORT; + + BLINKER_LOG_ALL(("====================")); + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + // String id2name = _userID.subString(10, _userID.length()); + // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); + // DEVICE_NAME_MQTT = (char*)malloc((_userID.length()+1)*sizeof(char)); + // strcpy(DEVICE_NAME_MQTT, _userID.c_str()); + // String IDtest = _productInfo + _userID; + // MQTT_ID_MQTT = (char*)malloc((IDtest.length()+1)*sizeof(char)); + // strcpy(MQTT_ID_MQTT, IDtest.c_str()); + // String NAMEtest = IDtest + ";" + _userName; + // MQTT_NAME_MQTT = (char*)malloc((NAMEtest.length()+1)*sizeof(char)); + // strcpy(MQTT_NAME_MQTT, NAMEtest.c_str()); + // MQTT_KEY_MQTT = (char*)malloc((_key.length()+1)*sizeof(char)); + // strcpy(MQTT_KEY_MQTT, _key.c_str()); + // MQTT_PRODUCTINFO_MQTT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + // strcpy(MQTT_PRODUCTINFO_MQTT, _productInfo.c_str()); + // MQTT_HOST_MQTT = (char*)malloc((strlen(BLINKER_MQTT_QCLOUD_HOST)+1)*sizeof(char)); + // strcpy(MQTT_HOST_MQTT, BLINKER_MQTT_QCLOUD_HOST); + // MQTT_PORT_MQTT = BLINKER_MQTT_QCLOUD_PORT; + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); + // DEVICE_NAME_MQTT = (char*)malloc((_userID.length()+1)*sizeof(char)); + // strcpy(DEVICE_NAME_MQTT, _userID.c_str()); + // MQTT_ID_MQTT = (char*)malloc((_userName.length()+1)*sizeof(char)); + // strcpy(MQTT_ID_MQTT, _userName.c_str()); + // MQTT_NAME_MQTT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + // strcpy(MQTT_NAME_MQTT, _productInfo.c_str()); + // MQTT_KEY_MQTT = (char*)malloc((_key.length()+1)*sizeof(char)); + // strcpy(MQTT_KEY_MQTT, _key.c_str()); + // MQTT_PRODUCTINFO_MQTT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + // strcpy(MQTT_PRODUCTINFO_MQTT, _productInfo.c_str()); + // MQTT_HOST_MQTT = (char*)malloc((strlen(BLINKER_MQTT_ONENET_HOST)+1)*sizeof(char)); + // strcpy(MQTT_HOST_MQTT, BLINKER_MQTT_ONENET_HOST); + // MQTT_PORT_MQTT = BLINKER_MQTT_ONENET_PORT; + } + UUID_AUTO = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_AUTO, _uuid.c_str()); + + char uuid_eeprom[BLINKER_AUUID_SIZE]; + + BLINKER_LOG_ALL(("==========AUTH CHECK==========")); + + if (!isFirst) + { + char _authCheck; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + if (strcmp(uuid_eeprom, _uuid.c_str()) != 0) { + // strcpy(UUID_PRO, _uuid.c_str()); + + strcpy(uuid_eeprom, _uuid.c_str()); + EEPROM.put(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("uuid_eeprom: "), uuid_eeprom); + BLINKER_LOG_ALL(BLINKER_F("_uuid: "), _uuid); + isNew = true; + } + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck != BLINKER_AUTH_CHECK_DATA) { + EEPROM.put(BLINKER_EEP_ADDR_AUTH_CHECK, BLINKER_AUTH_CHECK_DATA); + isAuth = true; + } + EEPROM.commit(); + EEPROM.end(); + + isFirst = true; + } + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME: "), macDeviceName()); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_AUTO: "), MQTT_PRODUCTINFO_AUTO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_DEVICEID_AUTO: "), MQTT_DEVICEID_AUTO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_AUTO: "), MQTT_ID_AUTO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_AUTO: "), MQTT_NAME_AUTO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_AUTO: "), MQTT_KEY_AUTO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_AUTO); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_AUTO); + BLINKER_LOG_ALL(BLINKER_F("UUID_AUTO: "), UUID_AUTO); + BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_AUTO: "), AUTHKEY_AUTO); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_AUTO; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_DEVICEID_AUTO; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_AUTO = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_AUTO, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_AUTO: "), BLINKER_PUB_TOPIC_AUTO); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_AUTO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_DEVICEID_AUTO; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_AUTO = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_AUTO, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_AUTO: "), BLINKER_SUB_TOPIC_AUTO); + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + // String PUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT; + // PUB_TOPIC_STR += BLINKER_F("/"); + // PUB_TOPIC_STR += _userID; + // PUB_TOPIC_STR += BLINKER_F("/s"); + + // BLINKER_PUB_TOPIC_MQTT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // // memcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str(), str_len); + // strcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str()); + + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_MQTT: "), BLINKER_PUB_TOPIC_MQTT); + + // String SUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT; + // SUB_TOPIC_STR += BLINKER_F("/"); + // SUB_TOPIC_STR += _userID; + // SUB_TOPIC_STR += BLINKER_F("/r"); + + // BLINKER_SUB_TOPIC_MQTT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // // memcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str(), str_len); + // strcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str()); + + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_MQTT: "), BLINKER_SUB_TOPIC_MQTT); + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + // // uint8_t str_len; + // String PUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT; + // PUB_TOPIC_STR += BLINKER_F("/onenet_rule/r"); + // // str_len = PUB_TOPIC_STR.length() + 1; + // BLINKER_PUB_TOPIC_MQTT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // // memcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str(), str_len); + // strcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str()); + + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_MQTT: "), BLINKER_PUB_TOPIC_MQTT); + + // String SUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT; + // SUB_TOPIC_STR += BLINKER_F("/"); + // SUB_TOPIC_STR += _userID; + // SUB_TOPIC_STR += BLINKER_F("/r"); + + // BLINKER_SUB_TOPIC_MQTT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // // memcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str(), str_len); + // strcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str()); + + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_MQTT: "), BLINKER_SUB_TOPIC_MQTT); + } + + // BLINKER_LOG_FreeHeap(); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_MQTT, MQTT_PORT_MQTT, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_AUTO = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_AUTO, MQTT_PORT_AUTO, MQTT_ID_AUTO, MQTT_NAME_AUTO, MQTT_KEY_AUTO); + #elif defined(ESP32) + mqtt_AUTO = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_AUTO, MQTT_PORT_AUTO, MQTT_ID_AUTO, MQTT_NAME_AUTO, MQTT_KEY_AUTO); + #endif + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + // #if defined(ESP8266) + // // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_MQTT, MQTT_PORT_MQTT, 4096); + // // if (mfln) { + // // client_mqtt.setBufferSizes(1024, 1024); + // // } + // // client_mqtt.setInsecure(); + // mqtt_MQTT = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); + // #elif defined(ESP32) + // mqtt_MQTT = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); + // #endif + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + // mqtt_MQTT = new Adafruit_MQTT_Client(&client, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); + } + + // iotPub = new Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + // if (!isMQTTinit) + iotSub_AUTO = new Adafruit_MQTT_Subscribe(mqtt_AUTO, BLINKER_SUB_TOPIC_AUTO); + + // mqtt_broker = (char*)malloc((_broker.length()+1)*sizeof(char)); + // strcpy(mqtt_broker, _broker.c_str()); + // mqtt_broker = _broker; + + // mDNSInit(MQTT_ID_MQTT); + this->latestTime = millis() - BLINKER_MQTT_CONNECT_TIMESLOT; + // if (!isMQTTinit) + mqtt_AUTO->subscribe(iotSub_AUTO); + isMQTTinit = true; + + #if defined(ESP8266) + // client_s->stop(); + // if (!isMQTTinit) + client_mqtt.setInsecure(); + #endif + // connect(); + + BLINKER_LOG_FreeHeap(); + + return true; +} + +void BlinkerMQTTAUTO::mDNSInit() +{ +#if defined(ESP8266) + if (!MDNS.begin(macDeviceName().c_str(), WiFi.localIP())) { +#elif defined(ESP32) + if (!MDNS.begin(macDeviceName().c_str())) { +#endif + while(1) { + ::delay(100); + } + } + + BLINKER_LOG(BLINKER_F("mDNS responder started")); + + String _service = STRING_format(BLINKER_MDNS_SERVICE_BLINKER) + _deviceType; + + MDNS.addService(_service.c_str(), "tcp", WS_SERVERPORT); + MDNS.addServiceTxt(_service.c_str(), "tcp", "deviceName", macDeviceName()); + + webSocket_AUTO.begin(); + webSocket_AUTO.onEvent(webSocketEvent_AUTO); + BLINKER_LOG(BLINKER_F("webSocket_MQTT server started")); + BLINKER_LOG(BLINKER_F("ws://"), macDeviceName(), BLINKER_F(".local:"), WS_SERVERPORT); +} + +void BlinkerMQTTAUTO::checkKA() { + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerMQTTAUTO::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerMQTTAUTO::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerMQTTAUTO::checkCanPrint() { + if ((millis() - printTime >= BLINKER_MQTT_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerMQTTAUTO::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerMQTTAUTO::checkPrintSpan() { + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) { + BLINKER_ERR_LOG(BLINKER_F("WEBSOCKETS CLIENT NOT ALIVE OR MSG LIMIT")); + + return false; + } + else { + respTimes++; + return true; + } + } + else { + respTimes = 0; + return true; + } +} + +int BlinkerMQTTAUTO::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerMQTTAUTO::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerMQTTAUTO::pubHello() +{ + char stateJsonStr[256] = ("{\"message\":\"Registration successful\"}"); + + BLINKER_LOG_ALL(BLINKER_F("PUB hello: "), stateJsonStr); + + return print(stateJsonStr, false); +} + +int BlinkerMQTTAUTO::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(STRING_format(data)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG("Print data is not Json! ", data); + return false; + } + + return true; +} + +#endif + +#endif diff --git a/blinker-library/src/Adapters/BlinkerMQTTLP.h b/blinker-library/src/Adapters/BlinkerMQTTLP.h new file mode 100644 index 0000000..447be14 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerMQTTLP.h @@ -0,0 +1,2477 @@ +// #ifndef BLINKER_MQTT_LP_H +// #define BLINKER_MQTT_LP_H + +// #if defined(ESP8266) || defined(ESP32) + +// // #define BLINKER_MQTT + +// #if defined(ESP8266) +// #include +// #include +// #include +// #elif defined(ESP32) +// #include +// #include +// #include +// #endif + +// // #include + +// #include "modules/WebSockets/WebSocketsServer.h" +// #include "modules/mqtt/Adafruit_MQTT.h" +// #include "modules/mqtt/Adafruit_MQTT_Client.h" +// #include "modules/ArduinoJson/ArduinoJson.h" + +// // #include "Adapters/BlinkerMQTTLP.h" +// #include "Blinker/BlinkerConfig.h" +// #include "Blinker/BlinkerDebug.h" +// #include "Blinker/BlinkerStream.h" +// #include "Blinker/BlinkerUtility.h" + +// enum b_config_t { +// COMM, +// BLINKER_SMART_CONFIG, +// BLINKER_AP_CONFIG +// }; + +// enum b_configStatus_t { +// SMART_BEGIN, +// SMART_DONE, +// SMART_TIMEOUT, +// APCFG_BEGIN, +// APCFG_DONE, +// APCFG_TIMEOUT +// }; + + +// // static WiFiServer *_apServer; +// // static WiFiClient _apClient; + +// // class BlinkerSharer +// // { +// // public : +// // BlinkerSharer(const String & _uuid) +// // { +// // name = (char*)malloc((_uuid.length()+1)*sizeof(char)); +// // strcpy(name, _uuid.c_str()); +// // } + +// // char * uuid() { return name; } + +// // private : +// // char * name; +// // }; + +// class BlinkerMQTTLP : public BlinkerStream +// { +// public : +// BlinkerMQTTLP(); + +// int connect(); +// int connected(); +// int mConnected(); +// void disconnect(); +// void ping(); +// int available(); +// int aligenieAvail(); +// int duerAvail(); +// // bool extraAvailable(); +// void subscribe(); +// char * lastRead(); +// void flush(); +// int print(char * data, bool needCheck = true); +// int bPrint(char * name, const String & data); +// int aliPrint(const String & data); +// int duerPrint(const String & data, bool report = false); +// void aliType(const String & type); +// void duerType(const String & type); +// void begin(const char* auth); +// bool begin(); +// int autoPrint(unsigned long id); +// // bool autoPrint(char *name, char *type, char *data); +// // bool autoPrint(char *name1, char *type1, char *data1, +// // char *name2, char *type2, char *data2); +// char * deviceName(); +// char * authKey() { return _authKey; } +// int init() { if (!isMQTTinit) checkInit(); return isMQTTinit; } +// int reRegister() { return connectServer(); } +// void freshAlive() { kaTime = millis(); isAlive = true; } +// void sharers(const String & data); +// int needFreshShare() { +// if (_needCheckShare) +// { +// BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); +// _needCheckShare = false; +// return true; +// } +// else +// { +// return false; +// } +// } + +// bool checkInit(); +// void commonBegin(const char* _ssid, const char* _pswd); +// void smartconfigBegin(); +// void apconfigBegin(); +// bool autoInit(); +// void smartconfig(); +// #if defined(BLINKER_APCONFIG) +// void softAPinit(); +// void checkAPCFG(); +// bool parseUrl(String data); +// #endif +// void connectWiFi(String _ssid, String _pswd); +// void connectWiFi(const char* _ssid, const char* _pswd); + +// private : +// bool isMQTTinit = false; + +// int connectServer(); +// void mDNSInit(); +// void checkKA(); +// int checkAliKA(); +// int checkDuerKA(); +// int checkCanPrint(); +// int checkCanBprint(); +// int checkPrintSpan(); +// int checkAliPrintSpan(); +// int checkDuerPrintSpan(); + +// bool isLowPower = false; + +// protected : +// BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; +// uint8_t _sharerCount = 0; +// uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; +// bool _isWiFiInit = false; +// bool _isBegin = false; +// b_config_t _configType = COMM; +// b_configStatus_t _configStatus = SMART_BEGIN; +// uint32_t _connectTime = 0; +// // const char* _authKey; +// char* _authKey; +// char* _aliType; +// char* _duerType; +// // char _authKey[BLINKER_AUTHKEY_SIZE]; +// bool* isHandle;// = &isConnect; +// bool isAlive = false; +// // bool isBavail = false; +// bool _needCheckShare = false; +// uint32_t latestTime; +// uint32_t printTime = 0; +// uint32_t bPrintTime = 0; +// uint32_t kaTime = 0; +// uint32_t linkTime = 0; +// uint8_t respTimes = 0; +// uint32_t respTime = 0; +// uint8_t respAliTimes = 0; +// uint32_t respAliTime = 0; +// uint8_t respDuerTimes = 0; +// uint32_t respDuerTime = 0; + +// uint32_t aliKaTime = 0; +// bool isAliAlive = false; +// bool isAliAvail = false; +// uint32_t duerKaTime = 0; +// bool isDuerAlive = false; +// bool isDuerAvail = false; +// char* mqtt_broker; + +// int isJson(const String & data); + +// #if defined(BLINKER_APCONFIG) +// WiFiServer *_apServer; +// WiFiClient _apClient; +// #endif + +// uint8_t reconnect_time = 0; +// }; + +// char* MQTT_HOST_MQTT; +// char* MQTT_ID_MQTT; +// char* MQTT_NAME_MQTT; +// char* MQTT_KEY_MQTT; +// char* MQTT_PRODUCTINFO_MQTT; +// char* UUID_MQTT; +// char* DEVICE_NAME_MQTT; +// char* BLINKER_PUB_TOPIC_MQTT; +// char* BLINKER_SUB_TOPIC_MQTT; +// uint16_t MQTT_PORT_MQTT; + +// #if defined(ESP8266) +// BearSSL::WiFiClientSecure client_mqtt; +// // WiFiClientSecure client_mqtt; +// #elif defined(ESP32) +// WiFiClientSecure client_s; +// #endif + +// WiFiClient client; +// Adafruit_MQTT_Client* mqtt_MQTT; +// // Adafruit_MQTT_Publish *iotPub; +// Adafruit_MQTT_Subscribe* iotSub_MQTT; + +// #define WS_SERVERPORT 81 +// WebSocketsServer webSocket_MQTT = WebSocketsServer(WS_SERVERPORT); + +// char* msgBuf_MQTT; +// bool isFresh_MQTT = false; +// bool isConnect_MQTT = false; +// bool isAvail_MQTT = false; +// uint8_t ws_num_MQTT = 0; +// uint8_t dataFrom_MQTT = BLINKER_MSG_FROM_MQTT; + +// void webSocketEvent_MQTT(uint8_t num, WStype_t type, \ +// uint8_t * payload, size_t length) +// { + +// switch(type) +// { +// case WStype_DISCONNECTED: +// BLINKER_LOG_ALL(BLINKER_F("Disconnected! "), num); + +// isConnect_MQTT = false; +// break; +// case WStype_CONNECTED: +// { +// IPAddress ip = webSocket_MQTT.remoteIP(num); + +// BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ +// BLINKER_F(", Connected from: "), ip, +// BLINKER_F(", url: "), (char *)payload); + +// // send message to client +// webSocket_MQTT.sendTXT(num, "{\"state\":\"connected\"}\n"); + +// ws_num_MQTT = num; + +// isConnect_MQTT = true; +// } +// break; +// case WStype_TEXT: +// BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ +// BLINKER_F(", get Text: "), (char *)payload, \ +// BLINKER_F(", length: "), length); + +// if (length < BLINKER_MAX_READ_SIZE) { +// if (isFresh_MQTT) free(msgBuf_MQTT); +// msgBuf_MQTT = (char*)malloc((length+1)*sizeof(char)); +// strcpy(msgBuf_MQTT, (char*)payload); +// isAvail_MQTT = true; +// isFresh_MQTT = true; +// } + +// dataFrom_MQTT = BLINKER_MSG_FROM_WS; + +// ws_num_MQTT = num; + +// // send message to client +// // webSocket_MQTT.sendTXT(num, "message here"); + +// // send data to all connected clients +// // webSocket_MQTT.broadcastTXT("message here"); +// break; +// case WStype_BIN: +// // BLINKER_LOG("num: ", num, " get binary length: ", length); +// // hexdump(payload, length); + +// // send message to client +// // webSocket_MQTT.sendBIN(num, payload, length); +// break; +// default : +// break; +// } +// } + +// BlinkerMQTTLP::BlinkerMQTTLP() { isHandle = &isConnect_MQTT; } + +// int BlinkerMQTTLP::connect() +// { +// if (!checkInit()) return false; + +// int8_t ret; + +// webSocket_MQTT.loop(); + +// if (mqtt_MQTT->connected()) +// { +// return true; +// } + +// disconnect(); + +// if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) +// { +// yield(); +// return false; +// } + +// BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + +// // BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_MQTT: "), MQTT_ID_MQTT); +// // BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_MQTT: "), MQTT_NAME_MQTT); +// // BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_MQTT: "), MQTT_KEY_MQTT); + +// #if defined(ESP8266) +// client_mqtt.setInsecure(); +// ::delay(10); +// #endif + +// if ((ret = mqtt_MQTT->connect()) != 0) +// { +// BLINKER_LOG(mqtt_MQTT->connectErrorString(ret)); +// BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ +// BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ +// BLINKER_F(" seconds...")); + +// if (ret == 4) reRegister(); + +// this->latestTime = millis(); +// reconnect_time += 1; +// if (reconnect_time >= 12) +// { +// reRegister(); +// reconnect_time = 0; +// } +// return false; +// } + +// reconnect_time = 0; + +// BLINKER_LOG(BLINKER_F("MQTT Connected!")); +// BLINKER_LOG_FreeHeap(); + +// if (!isMQTTinit) +// { +// isMQTTinit = true; + +// mqtt_MQTT->subscribeTopic(BLINKER_SUB_TOPIC_MQTT); +// BLINKER_LOG_ALL(BLINKER_F("MQTT subscribe: "), BLINKER_SUB_TOPIC_MQTT); +// } + +// this->latestTime = millis(); + +// return true; +// } + +// int BlinkerMQTTLP::connected() +// { +// if (!checkInit()) return false; + +// if (!isMQTTinit) +// { +// return *isHandle; +// } + +// return mqtt_MQTT->connected() || *isHandle; +// } + +// int BlinkerMQTTLP::mConnected() +// { +// if (!checkInit()) return false; + +// if (!isMQTTinit) return false; +// else return mqtt_MQTT->connected(); +// } + +// void BlinkerMQTTLP::disconnect() +// { +// if (!checkInit()) return; + +// mqtt_MQTT->disconnect(); + +// if (*isHandle) webSocket_MQTT.disconnect(); +// } + +// void BlinkerMQTTLP::ping() +// { +// if (!checkInit()) return; + +// BLINKER_LOG(BLINKER_F("MQTT Ping!")); + +// BLINKER_LOG_FreeHeap_ALL(); + +// if (!mqtt_MQTT->ping()) +// { +// disconnect(); +// // delay(100); + +// // connect(); +// } +// else +// { +// this->latestTime = millis(); +// } +// } + +// int BlinkerMQTTLP::available() +// { +// if (!checkInit()) return false; + +// webSocket_MQTT.loop(); + +// checkKA(); + +// // if (!mqtt_MQTT->connected() || +// // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) +// if ((millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) +// { +// ping(); +// } +// else +// { +// subscribe(); +// } + +// if (isAvail_MQTT) +// { +// isAvail_MQTT = false; +// return true; +// } +// else { +// return false; +// } +// } + +// int BlinkerMQTTLP::aligenieAvail() +// { +// if (!checkInit()) return false; + +// if (isAliAvail) +// { +// isAliAvail = false; +// return true; +// } +// else { +// return false; +// } +// } + +// int BlinkerMQTTLP::duerAvail() +// { +// if (!checkInit()) return false; + +// if (isDuerAvail) +// { +// isDuerAvail = false; +// return true; +// } +// else { +// return false; +// } +// } + +// // bool BlinkerMQTTLP::extraAvailable() +// // { +// // if (isBavail) +// // { +// // isBavail = false; +// // return true; +// // } +// // else +// // { +// // return false; +// // } +// // } + +// void BlinkerMQTTLP::subscribe() +// { +// if (!checkInit()) return; + +// if (!isMQTTinit) return; + +// Adafruit_MQTT_Subscribe *subscription; +// while ((subscription = mqtt_MQTT->readSubscription(10))) +// { +// if (subscription == iotSub_MQTT) +// { +// BLINKER_LOG_ALL(BLINKER_F("Got: "), (char *)iotSub_MQTT->lastread); + +// DynamicJsonBuffer jsonBuffer; +// JsonObject& root = jsonBuffer.parseObject(String((char *)iotSub_MQTT->lastread)); + +// String _uuid = root["fromDevice"]; +// String dataGet = root["data"]; + +// BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); +// BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + +// if (strcmp(_uuid.c_str(), UUID_MQTT) == 0) +// { +// BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + +// kaTime = millis(); +// isAvail_MQTT = true; +// isAlive = true; + +// _sharerFrom = BLINKER_MQTT_FROM_AUTHER; +// } +// else if (_uuid == BLINKER_CMD_ALIGENIE) +// { +// BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + +// aliKaTime = millis(); +// isAliAlive = true; +// isAliAvail = true; +// } +// else if (_uuid == BLINKER_CMD_DUEROS) +// { +// BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + +// duerKaTime = millis(); +// isDuerAlive = true; +// isDuerAvail = true; +// } +// else if (_uuid == BLINKER_CMD_SERVERCLIENT) +// { +// BLINKER_LOG_ALL(BLINKER_F("form Sever")); + +// isAvail_MQTT = true; +// isAlive = true; + +// _sharerFrom = BLINKER_MQTT_FROM_AUTHER; +// } +// else +// { +// if (_sharerCount) +// { +// for (uint8_t num = 0; num < _sharerCount; num++) +// { +// if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) +// { +// _sharerFrom = num; + +// kaTime = millis(); + +// BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); +// BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + +// _needCheckShare = false; + +// break; +// } +// else +// { +// BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ +// check is from bridge/share device, \ +// data: "), dataGet); + +// _needCheckShare = true; +// } +// } +// } +// // else +// // { +// // dataGet = String((char *)iotSub_MQTT->lastread); +// root.printTo(dataGet); + +// // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ +// // check is from bridge/share device, \ +// // data: "), dataGet); + +// // // return; + +// // // isBavail = true; + +// // _needCheckShare = true; +// // } + +// isAvail_MQTT = true; +// isAlive = true; +// } + +// // memset(msgBuf_MQTT, 0, BLINKER_MAX_READ_SIZE); +// // memcpy(msgBuf_MQTT, dataGet.c_str(), dataGet.length()); + +// if (isFresh_MQTT) free(msgBuf_MQTT); +// msgBuf_MQTT = (char*)malloc((dataGet.length()+1)*sizeof(char)); +// strcpy(msgBuf_MQTT, dataGet.c_str()); +// isFresh_MQTT = true; + +// this->latestTime = millis(); + +// dataFrom_MQTT = BLINKER_MSG_FROM_MQTT; +// } +// } +// } + +// char * BlinkerMQTTLP::lastRead() +// { +// if (isFresh_MQTT) return msgBuf_MQTT; +// else return ""; +// } + +// void BlinkerMQTTLP::flush() +// { +// if (isFresh_MQTT) +// { +// free(msgBuf_MQTT); isFresh_MQTT = false; isAvail_MQTT = false; +// isAliAvail = false; //isBavail = false; +// } +// } + +// int BlinkerMQTTLP::print(char * data, bool needCheck) +// { +// if (!checkInit()) return false; + +// // BLINKER_LOG_FreeHeap(); +// if (*isHandle && dataFrom_MQTT == BLINKER_MSG_FROM_WS) +// { +// if (needCheck) +// { +// if (!checkPrintSpan()) +// { +// respTime = millis(); +// return false; +// } +// } + +// respTime = millis(); + +// BLINKER_LOG_ALL(BLINKER_F("WS response: ")); +// BLINKER_LOG_ALL(data); +// BLINKER_LOG_ALL(BLINKER_F("Success...")); + +// strcat(data, BLINKER_CMD_NEWLINE); + +// webSocket_MQTT.sendTXT(ws_num_MQTT, data); + +// return true; +// } +// else +// { +// // // String payload; +// // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) +// // { +// // uint8_t num = strlen(data) - 1; +// // for(uint8_t c_num = num; c_num > 0; c_num--) +// // { +// // data[c_num+7] = data[c_num-1]; +// // } +// // // payload = BLINKER_F("{\"data\":"); +// // // payload += data.substring(0, data.length() - 1); +// // // payload += BLINKER_F(",\"fromDevice\":\""); +// // // payload += MQTT_ID_MQTT; +// // // payload += BLINKER_F("\",\"toDevice\":\""); +// // // payload += UUID_MQTT; +// // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); +// // } +// // else +// // { +// // uint8_t num = strlen(data); +// // for(uint8_t c_num = num; c_num > 0; c_num--) +// // { +// // data[c_num+7] = data[c_num-1]; +// // } +// // // payload = BLINKER_F("{\"data\":"); +// // // payload += data; +// // // payload += BLINKER_F(",\"fromDevice\":\""); +// // // payload += MQTT_ID_MQTT; +// // // payload += BLINKER_F("\",\"toDevice\":\""); +// // // payload += UUID_MQTT; +// // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); +// // } + +// uint16_t num = strlen(data); + +// for(uint16_t c_num = num; c_num > 0; c_num--) +// { +// data[c_num+7] = data[c_num-1]; +// } + +// data[num+8] = '\0'; + +// char data_add[20] = "{\"data\":"; +// for(uint8_t c_num = 0; c_num < 8; c_num++) +// { +// data[c_num] = data_add[c_num]; +// } + +// // data_add = BLINKER_F(",\"fromDevice\":\""); +// // strcat(data, data_add.c_str()); +// strcat(data, ",\"fromDevice\":\""); +// strcat(data, MQTT_ID_MQTT); +// // data_add = BLINKER_F("\",\"toDevice\":\""); +// // strcat(data, data_add.c_str()); +// strcat(data, "\",\"toDevice\":\""); +// if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) +// { +// strcat(data, _sharers[_sharerFrom]->uuid()); +// } +// else +// { +// strcat(data, UUID_MQTT); +// } +// // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); +// // strcat(data, data_add.c_str()); + +// strcat(data, "\",\"deviceType\":\"OwnApp\"}"); + +// _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + +// if (!isJson(STRING_format(data))) return false; + +// BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); +// BLINKER_LOG_FreeHeap_ALL(); + +// bool _alive = isAlive; + + +// if (needCheck) +// { +// if (!checkPrintSpan()) +// { +// return false; +// } +// respTime = millis(); +// } + +// if (mqtt_MQTT->connected()) +// { +// if (needCheck) +// { +// if (!checkCanPrint()) +// { +// if (!_alive) +// { +// isAlive = false; +// } +// return false; +// } +// } + +// if (! mqtt_MQTT->publish(BLINKER_PUB_TOPIC_MQTT, data)) +// { +// BLINKER_LOG_ALL(data); +// BLINKER_LOG_ALL(BLINKER_F("...Failed")); +// BLINKER_LOG_FreeHeap_ALL(); + +// if (!_alive) +// { +// isAlive = false; +// } +// return false; +// } +// else +// { +// BLINKER_LOG_ALL(data); +// BLINKER_LOG_ALL(BLINKER_F("...OK!")); +// BLINKER_LOG_FreeHeap_ALL(); + +// if (needCheck) printTime = millis(); + +// if (!_alive) +// { +// isAlive = false; +// } + +// this->latestTime = millis(); + +// return true; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// isAlive = false; +// return false; +// } +// } +// } + +// int BlinkerMQTTLP::bPrint(char * name, const String & data) +// { +// if (!checkInit()) return false; + +// // String payload; +// // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) +// // { +// // payload = BLINKER_F("{\"data\":"); +// // payload += data.substring(0, data.length() - 1); +// // payload += BLINKER_F(",\"fromDevice\":\""); +// // payload += MQTT_ID_MQTT; +// // payload += BLINKER_F("\",\"toDevice\":\""); +// // payload += name; +// // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); +// // } +// // else +// // { +// // payload = BLINKER_F("{\"data\":"); +// // payload += data; +// // payload += BLINKER_F(",\"fromDevice\":\""); +// // payload += MQTT_ID_MQTT; +// // payload += BLINKER_F("\",\"toDevice\":\""); +// // payload += name; +// // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); +// // } + +// // uint8_t num = strlen(data); +// // for(uint8_t c_num = num; c_num > 0; c_num--) +// // { +// // data[c_num+7] = data[c_num-1]; +// // } + +// String data_add = BLINKER_F("{\"data\":"); +// // for(uint8_t c_num = 0; c_num < 8; c_num++) +// // { +// // data[c_num] = data_add[c_num]; +// // } + +// data_add += data; +// data_add += BLINKER_F(",\"fromDevice\":\""); +// data_add += MQTT_ID_MQTT; +// data_add += BLINKER_F("\",\"toDevice\":\""); +// data_add += name; +// data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + +// // data_add = BLINKER_F(",\"fromDevice\":\""); +// // strcat(data, data_add.c_str()); +// // strcat(data, MQTT_ID_MQTT); +// // data_add = BLINKER_F("\",\"toDevice\":\""); +// // strcat(data, data_add.c_str()); +// // strcat(data, name); +// // data_add = BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); +// // strcat(data, data_add.c_str()); + +// if (!isJson(data_add)) return false; + +// BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + +// // bool _alive = isAlive; +// // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + +// // if (!state) { +// // state = (STRING_contains_string(data, BLINKER_CMD_STATE) +// // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); +// // } + +// if (mqtt_MQTT->connected()) { +// // if (!state) { +// if (!checkCanBprint()) { +// // if (!_alive) { +// // isAlive = false; +// // } +// return false; +// } +// // } + +// // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + +// // if (! iotPub.publish(payload.c_str())) { + +// // String bPubTopic = BLINKER_F(""); + +// // if (strcmp(mqtt_broker, BLINKER_MQTT_BORKER_ONENET) == 0) +// // { +// // bPubTopic = MQTT_PRODUCTINFO_MQTT; +// // bPubTopic += BLINKER_F("/"); +// // bPubTopic += name; +// // bPubTopic += BLINKER_F("/r"); +// // } +// // else +// // { +// // bPubTopic = BLINKER_PUB_TOPIC_MQTT; +// // } + +// if (! mqtt_MQTT->publish(BLINKER_PUB_TOPIC_MQTT, data_add.c_str())) +// { +// BLINKER_LOG_ALL(data_add); +// BLINKER_LOG_ALL(BLINKER_F("...Failed")); + +// // if (!_alive) { +// // isAlive = false; +// // } +// return false; +// } +// else +// { +// BLINKER_LOG_ALL(data_add); +// BLINKER_LOG_ALL(BLINKER_F("...OK!")); + +// bPrintTime = millis(); + +// // if (!_alive) { +// // isAlive = false; +// // } + +// this->latestTime = millis(); + +// return true; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// // isAlive = false; +// return false; +// } +// // } +// } + +// int BlinkerMQTTLP::aliPrint(const String & data) +// { +// if (!checkInit()) return false; + +// String data_add = BLINKER_F("{\"data\":"); + +// data_add += data; +// data_add += BLINKER_F(",\"fromDevice\":\""); +// data_add += MQTT_ID_MQTT; +// data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); +// data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + +// if (!isJson(data_add)) return false; + +// BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); +// BLINKER_LOG_FreeHeap_ALL(); + +// if (mqtt_MQTT->connected()) +// { +// if (!checkAliKA()) +// { +// return false; +// } + +// if (!checkAliPrintSpan()) +// { +// respAliTime = millis(); +// return false; +// } +// respAliTime = millis(); + +// if (! mqtt_MQTT->publish(BLINKER_PUB_TOPIC_MQTT, data_add.c_str())) +// { +// BLINKER_LOG_ALL(data_add); +// BLINKER_LOG_ALL(BLINKER_F("...Failed")); +// BLINKER_LOG_FreeHeap_ALL(); + +// isAliAlive = false; +// return false; +// } +// else +// { +// BLINKER_LOG_ALL(data_add); +// BLINKER_LOG_ALL(BLINKER_F("...OK!")); +// BLINKER_LOG_FreeHeap_ALL(); + +// isAliAlive = false; + +// this->latestTime = millis(); + +// return true; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +// int BlinkerMQTTLP::duerPrint(const String & data, bool report) +// { +// if (!checkInit()) return false; + +// String data_add = BLINKER_F("{\"data\":"); + +// data_add += data; +// data_add += BLINKER_F(",\"fromDevice\":\""); +// data_add += MQTT_ID_MQTT; +// data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); +// data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + +// if (!isJson(data_add)) return false; + +// BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); +// BLINKER_LOG_FreeHeap_ALL(); + +// if (mqtt_MQTT->connected()) +// { +// if (!checkDuerKA()) +// { +// return false; +// } + +// if (!checkDuerPrintSpan()) +// { +// respDuerTime = millis(); +// return false; +// } +// respDuerTime = millis(); + +// if (! mqtt_MQTT->publish(BLINKER_PUB_TOPIC_MQTT, data_add.c_str())) +// { +// BLINKER_LOG_ALL(data_add); +// BLINKER_LOG_ALL(BLINKER_F("...Failed")); +// BLINKER_LOG_FreeHeap_ALL(); + +// isDuerAlive = false; +// return false; +// } +// else +// { +// BLINKER_LOG_ALL(data_add); +// BLINKER_LOG_ALL(BLINKER_F("...OK!")); +// BLINKER_LOG_FreeHeap_ALL(); + +// isDuerAlive = false; + +// this->latestTime = millis(); + +// return true; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +// void BlinkerMQTTLP::aliType(const String & type) +// { +// _aliType = (char*)malloc((type.length()+1)*sizeof(char)); +// strcpy(_aliType, type.c_str()); +// BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +// } + +// void BlinkerMQTTLP::duerType(const String & type) +// { +// _duerType = (char*)malloc((type.length()+1)*sizeof(char)); +// strcpy(_duerType, type.c_str()); +// BLINKER_LOG_ALL(BLINKER_F("_duerType: "), _duerType); +// } + +// void BlinkerMQTTLP::begin(const char* auth) { +// // if (!checkInit()) return; +// // _authKey = auth; +// _authKey = (char*)malloc((strlen(auth)+1)*sizeof(char)); +// strcpy(_authKey, auth); + +// BLINKER_LOG_ALL(BLINKER_F("_authKey: "), auth); +// } + +// bool BlinkerMQTTLP::begin() { +// // if (connectServer()) { +// // mDNSInit(); +// // isMQTTinit = true; +// // } +// // else { +// // uint32_t re_time = millis(); + +// if (isMQTTinit) return true; +// // bool isConnect_MQTT = true; +// // while(1) +// // { +// // re_time = millis(); +// // ::delay(10000); +// // BLINKER_ERR_LOG("Maybe you have put in the wrong AuthKey!"); +// // BLINKER_ERR_LOG("Or maybe your request is too frequently!"); +// // BLINKER_ERR_LOG("Or maybe your network is disconnected!"); +// if (_connectTime == 0 || (millis() - _connectTime) >= 10000) +// { +// _connectTime = millis(); +// if (connectServer()) { +// mDNSInit(); +// isMQTTinit = true; +// return true; +// } +// else { +// isMQTTinit = false; +// // ::delay(10000); +// // BLINKER_ERR_LOG("init error, ", _connectTime); +// // BLINKER_ERR_LOG("Maybe you have put in the wrong AuthKey!"); +// // BLINKER_ERR_LOG("Or maybe your request is too frequently!"); +// // BLINKER_ERR_LOG("Or maybe your network is disconnected!"); +// return false; +// } +// } + +// // BLINKER_ERR_LOG("init error1, ", _connectTime); +// // ::delay(1000); +// return false; +// // delay(10000); +// // while ((millis() - re_time) < 10000) +// // { +// // if (WiFi.status() != WL_CONNECTED && isConnect_MQTT) +// // { +// // isConnect_MQTT = false; +// // WiFi.begin(); +// // WiFi.reconnect(); +// // } +// // else if (WiFi.status() == WL_CONNECTED && !isConnect_MQTT) +// // { +// // isConnect_MQTT = true; +// // } +// // // ::delay(10); +// // yield(); +// // // WiFi.status(); +// // } +// // } +// // } +// } + +// int BlinkerMQTTLP::autoPrint(unsigned long id) +// { +// String payload = BLINKER_F("{\"data\":{\"set\":{"); +// payload += BLINKER_F("\"trigged\":true,\"autoData\":{"); +// payload += BLINKER_F("\"autoId\":"); +// payload += STRING_format(id); +// payload += BLINKER_F("}}}"); +// payload += BLINKER_F(",\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_MQTT); +// payload += BLINKER_F("\",\"toDevice\":\"autoManager\"}"); +// // "\",\"deviceType\":\"" + "type" + "\"}"; + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_MQTT->connected()) +// { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ +// linkTime == 0) +// { +// // linkTime = millis(); + +// // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + +// // if (! iotPub.publish(payload.c_str())) { + +// if (! mqtt_MQTT->publish(BLINKER_PUB_TOPIC_MQTT, payload.c_str())) +// { +// BLINKER_LOG_ALL(payload); +// BLINKER_LOG_ALL(BLINKER_F("...Failed")); + +// return false; +// } +// else +// { +// BLINKER_LOG_ALL(payload); +// BLINKER_LOG_ALL(BLINKER_F("...OK!")); + +// linkTime = millis(); + +// this->latestTime = millis(); + +// return true; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +// // bool BlinkerMQTTLP::autoPrint(char *name, char *type, char *data) +// // { +// // String payload = BLINKER_F("{\"data\":{"); +// // payload += STRING_format(data); +// // payload += BLINKER_F("},\"fromDevice\":\""); +// // payload += STRING_format(MQTT_ID_MQTT); +// // payload += BLINKER_F("\",\"toDevice\":\""); +// // payload += name; +// // payload += BLINKER_F("\",\"deviceType\":\""); +// // payload += type; +// // payload += BLINKER_F("\"}"); + +// // BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// // if (mqtt_MQTT->connected()) { +// // if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || +// // linkTime == 0) +// // { +// // linkTime = millis(); + +// // BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// // return true; +// // } +// // else { +// // BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// // return false; +// // } +// // } +// // else +// // { +// // BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// // return false; +// // } +// // } + +// // bool BlinkerMQTTLP::autoPrint(char *name1, char *type1, char *data1 +// // , char *name2, char *type2, char *data2) +// // { +// // String payload = BLINKER_F("{\"data\":{"); +// // payload += STRING_format(data1); +// // payload += BLINKER_F("},\"fromDevice\":\""); +// // payload += STRING_format(MQTT_ID_MQTT); +// // payload += BLINKER_F("\",\"toDevice\":\""); +// // payload += name1; +// // payload += BLINKER_F("\",\"deviceType\":\""); +// // payload += type1; +// // payload += BLINKER_F("\"}"); + +// // BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// // if (mqtt_MQTT->connected()) +// // { +// // if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || +// // linkTime == 0) +// // { +// // linkTime = millis(); + +// // BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// // payload = BLINKER_F("{\"data\":{"); +// // payload += STRING_format(data2); +// // payload += BLINKER_F("},\"fromDevice\":\""); +// // payload += STRING_format(MQTT_ID_MQTT); +// // payload += BLINKER_F("\",\"toDevice\":\""); +// // payload += name2; +// // payload += BLINKER_F("\",\"deviceType\":\""); +// // payload += type2; +// // payload += BLINKER_F("\"}"); + +// // BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// // return true; +// // } +// // else +// // { +// // BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// // return false; +// // } +// // } +// // else +// // { +// // BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// // return false; +// // } +// // } + +// char * BlinkerMQTTLP::deviceName() { return DEVICE_NAME_MQTT;/*MQTT_ID_MQTT;*/ } + +// void BlinkerMQTTLP::sharers(const String & data) +// { +// BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + +// DynamicJsonBuffer jsonBuffer; +// JsonObject& root = jsonBuffer.parseObject(data); + +// if (!root.success()) return; + +// String user_name = ""; + +// if (_sharerCount) +// { +// for (uint8_t num = _sharerCount; num > 0; num--) +// { +// delete _sharers[num - 1]; +// } +// } + +// _sharerCount = 0; + +// for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) +// { +// user_name = root["users"][num].as(); + +// if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) +// { +// BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + +// _sharerCount++; + +// _sharers[num] = new BlinkerSharer(user_name); +// } +// else +// { +// break; +// } +// } +// } + +// int BlinkerMQTTLP::connectServer() { +// const int httpsPort = 443; +// #if defined(ESP8266) +// String host = BLINKER_F(BLINKER_SERVER_HOST); +// String fingerprint = BLINKER_F("84 5f a4 8a 70 5e 79 7e f5 b3 b4 20 45 c8 35 55 72 f6 85 5a"); + +// // WiFiClientSecure client_s; + +// // BearSSL::WiFiClientSecure *client_s; + +// // client_s = new BearSSL::WiFiClientSecure(); + +// // BLINKER_LOG_ALL(BLINKER_F("connecting to "), host); + +// // // BLINKER_LOG_FreeHeap(); + +// // uint8_t connet_times = 0; +// // // client_s.stop(); +// // ::delay(100); + +// // // bool mfln = client_s.probeMaxFragmentLength(host, httpsPort, 1024); +// // // if (mfln) { +// // // client_s.setBufferSizes(1024, 1024); +// // // } +// // client_s->setFingerprint(fingerprint.c_str()); + +// // client_s->setInsecure(); + +// // // while (1) { +// // bool cl_connected = false; +// // if (!client_s->connect(host, httpsPort)) { +// // BLINKER_ERR_LOG(BLINKER_F("server connection failed")); +// // // connet_times++; + +// // ::delay(1000); +// // } +// // else { +// // BLINKER_LOG_ALL(BLINKER_F("connection succeed")); +// // cl_connected = true; + +// // // break; +// // } + +// // // if (connet_times >= 4 && !cl_connected) return BLINKER_CMD_FALSE; +// // // } + +// // String client_msg; + +// // String url_iot = BLINKER_F("/api/v1/user/device/diy/auth?authKey="); +// // url_iot += _authKey; +// // url_iot += _aliType; +// // url_iot += _duerType; + +// // // #if defined(BLINKER_ALIGENIE_LIGHT) +// // // url_iot += BLINKER_F("&aliType=light"); +// // // #elif defined(BLINKER_ALIGENIE_OUTLET) +// // // url_iot += BLINKER_F("&aliType=outlet"); +// // // #elif defined(BLINKER_ALIGENIE_SWITCH) +// // // #elif defined(BLINKER_ALIGENIE_SENSOR) +// // // url_iot += BLINKER_F("&aliType=sensor"); +// // // #endif + +// // BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host, url_iot); + +// // client_msg = BLINKER_F("GET "); +// // client_msg += url_iot; +// // client_msg += BLINKER_F(" HTTP/1.1\r\nHost: "); +// // client_msg += host; +// // client_msg += BLINKER_F(":"); +// // client_msg += STRING_format(httpsPort); +// // client_msg += BLINKER_F("\r\nConnection: close\r\n\r\n"); + +// // client_s->print(client_msg); + +// // BLINKER_LOG_ALL(BLINKER_F("client_msg: "), client_msg); + +// // unsigned long timeout = millis(); +// // while (client_s->available() == 0) { +// // if (millis() - timeout > 5000) { +// // BLINKER_LOG_ALL(BLINKER_F(">>> Client Timeout !")); +// // client_s->stop(); +// // return false; +// // } +// // } + +// // String _dataGet; +// // String lastGet; +// // String lengthOfJson; +// // while (client_s->available()) { +// // // String line = client_s.readStringUntil('\r'); +// // _dataGet = client_s->readStringUntil('\n'); + +// // if (_dataGet.startsWith("Content-Length: ")){ +// // int addr_start = _dataGet.indexOf(' '); +// // int addr_end = _dataGet.indexOf('\0', addr_start + 1); +// // lengthOfJson = _dataGet.substring(addr_start + 1, addr_end); +// // } + +// // if (_dataGet == "\r") { +// // BLINKER_LOG_ALL(BLINKER_F("headers received")); + +// // break; +// // } +// // } + +// // for(int i=0;iread(); +// // } + +// // // BLINKER_LOG_FreeHeap(); + +// // client_s->stop(); +// // client_s->flush(); + +// // free(client_s); + +// // // BLINKER_LOG_FreeHeap(); + +// // _dataGet = lastGet; + +// // BLINKER_LOG_ALL(BLINKER_F("_dataGet: "), _dataGet); + +// // String payload = _dataGet; + + + +// client_mqtt.stop(); + +// std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + +// // client_s->setFingerprint(fingerprint); +// client_s->setInsecure(); + +// String url_iot = BLINKER_F("/api/v1/user/device/diy/auth?authKey="); +// url_iot += _authKey; +// url_iot += _aliType; +// url_iot += _duerType; + +// url_iot = "https://" + host + url_iot; + +// HTTPClient http; + +// String payload; + +// BLINKER_LOG_ALL(BLINKER_F("[HTTP] begin: "), url_iot); + +// if (http.begin(*client_s, url_iot)) { // HTTPS + +// // Serial.print("[HTTPS] GET...\n"); +// // start connection and send HTTP header +// int httpCode = http.GET(); + +// // httpCode will be negative on error +// if (httpCode > 0) { +// // HTTP header has been send and Server response header has been handled + +// BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + +// // file found at server +// if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { +// payload = http.getString(); +// // Serial.println(payload); +// } +// } else { +// BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); +// payload = http.getString(); +// BLINKER_LOG(payload); +// } + +// http.end(); +// } else { +// // Serial.printf("[HTTPS] Unable to connect\n"); +// } + +// #elif defined(ESP32) +// String host = BLINKER_F(BLINKER_SERVER_HTTPS); +// // const char* ca = +// // "-----BEGIN CERTIFICATE-----\n" +// // "MIIEgDCCA2igAwIBAgIQDKTfhr9lmWbWUT0hjX36oDANBgkqhkiG9w0BAQsFADBy\n" +// // "MQswCQYDVQQGEwJDTjElMCMGA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywg\n" +// // "SW5jLjEdMBsGA1UECxMURG9tYWluIFZhbGlkYXRlZCBTU0wxHTAbBgNVBAMTFFRy\n" +// // "dXN0QXNpYSBUTFMgUlNBIENBMB4XDTE4MDEwNDAwMDAwMFoXDTE5MDEwNDEyMDAw\n" +// // "MFowGDEWMBQGA1UEAxMNaW90ZGV2LmNsei5tZTCCASIwDQYJKoZIhvcNAQEBBQAD\n" +// // "ggEPADCCAQoCggEBALbOFn7cJ2I/FKMJqIaEr38n4kCuJCCeNf1bWdWvOizmU2A8\n" +// // "QeTAr5e6Q3GKeJRdPnc8xXhqkTm4LOhgdZB8KzuVZARtu23D4vj4sVzxgC/zwJlZ\n" +// // "MRMxN+cqI37kXE8gGKW46l2H9vcukylJX+cx/tjWDfS2YuyXdFuS/RjhCxLgXzbS\n" +// // "cve1W0oBZnBPRSMV0kgxTWj7hEGZNWKIzK95BSCiMN59b+XEu3NWGRb/VzSAiJEy\n" +// // "Hy9DcDPBC9TEg+p5itHtdMhy2gq1OwsPgl9HUT0xmDATSNEV2RB3vwviNfu9/Eif\n" +// // "ObhsV078zf30TqdiESqISEB68gJ0Otru67ePoTkCAwEAAaOCAWowggFmMB8GA1Ud\n" +// // "IwQYMBaAFH/TmfOgRw4xAFZWIo63zJ7dygGKMB0GA1UdDgQWBBR/KLqnke61779P\n" +// // "xc9htonQwLOxPDAYBgNVHREEETAPgg1pb3RkZXYuY2x6Lm1lMA4GA1UdDwEB/wQE\n" +// // "AwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTAYDVR0gBEUwQzA3\n" +// // "BglghkgBhv1sAQIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQu\n" +// // "Y29tL0NQUzAIBgZngQwBAgEwgYEGCCsGAQUFBwEBBHUwczAlBggrBgEFBQcwAYYZ\n" +// // "aHR0cDovL29jc3AyLmRpZ2ljZXJ0LmNvbTBKBggrBgEFBQcwAoY+aHR0cDovL2Nh\n" +// // "Y2VydHMuZGlnaXRhbGNlcnR2YWxpZGF0aW9uLmNvbS9UcnVzdEFzaWFUTFNSU0FD\n" +// // "QS5jcnQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtM4eyrWB14ajJpQ\n" +// // "ibZ5FbzVuvv2Le0FOSoss7UFCDJUYiz2LiV8yOhL4KTY+oVVkqHaYtcFS1CYZNzj\n" +// // "6xWcqYZJ+pgsto3WBEgNEEe0uLSiTW6M10hm0LFW9Det3k8fqwSlljqMha3gkpZ6\n" +// // "8WB0f2clXOuC+f1SxAOymnGUsSqbU0eFSgevcOIBKR7Hr3YXBXH3jjED76Q52OMS\n" +// // "ucfOM9/HB3jN8o/ioQbkI7xyd/DUQtzK6hSArEoYRl3p5H2P4fr9XqmpoZV3i3gQ\n" +// // "oOdVycVtpLunyUoVAB2DcOElfDxxXCvDH3XsgoIU216VY03MCaUZf7kZ2GiNL+UX\n" +// // "9UBd0Q==\n" +// // "-----END CERTIFICATE-----\n"; +// // #endif + +// HTTPClient http; + +// String url_iot = host; +// url_iot += BLINKER_F("/api/v1/user/device/diy/auth?authKey="); +// url_iot += _authKey; +// url_iot += _aliType; +// url_iot += _duerType; + +// // #if defined(BLINKER_ALIGENIE_LIGHT) +// // url_iot += BLINKER_F("&aliType=light"); +// // #elif defined(BLINKER_ALIGENIE_OUTLET) +// // url_iot += BLINKER_F("&aliType=outlet"); +// // #elif defined(BLINKER_ALIGENIE_SWITCH) +// // #elif defined(BLINKER_ALIGENIE_SENSOR) +// // url_iot += BLINKER_F("&aliType=sensor"); +// // #endif + +// BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + +// // #if defined(ESP8266) +// // http.begin(url_iot, fingerprint); //HTTP +// // #elif defined(ESP32) +// // http.begin(url_iot, ca); TODO +// http.begin(url_iot); +// // #endif +// int httpCode = http.GET(); + +// String payload; + +// if (httpCode > 0) { +// // HTTP header has been send and Server response header has been handled + +// BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + +// // file found at server +// if (httpCode == HTTP_CODE_OK) { +// payload = http.getString(); +// // BLINKER_LOG(payload); +// } +// } +// else { +// BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); +// payload = http.getString(); +// BLINKER_LOG(payload); +// } + +// http.end(); +// #endif + +// // payload = ""; + +// BLINKER_LOG_ALL(BLINKER_F("reply was:")); +// BLINKER_LOG_ALL(BLINKER_F("==============================")); +// BLINKER_LOG_ALL(payload); +// BLINKER_LOG_ALL(BLINKER_F("==============================")); + +// DynamicJsonBuffer jsonBuffer; +// JsonObject& root = jsonBuffer.parseObject(payload); + +// if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || !root.success() || +// !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { +// // while(1) { +// BLINKER_ERR_LOG(BLINKER_F("Maybe you have put in the wrong AuthKey!")); +// BLINKER_ERR_LOG(BLINKER_F("Or maybe your request is too frequently!")); +// BLINKER_ERR_LOG(BLINKER_F("Or maybe your network is disconnected!")); +// // ::delay(60000); + +// return false; +// // } +// } + +// // String _userID = STRING_find_string(payload, "deviceName", "\"", 4); +// // String _userName = STRING_find_string(payload, "iotId", "\"", 4); +// // String _key = STRING_find_string(payload, "iotToken", "\"", 4); +// // String _productInfo = STRING_find_string(payload, "productKey", "\"", 4); +// // String _broker = STRING_find_string(payload, "broker", "\"", 4); +// // String _uuid = STRING_find_string(payload, "uuid", "\"", 4); +// String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; +// String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; +// String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; +// String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; +// String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; +// String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + +// if (isMQTTinit) +// { +// free(MQTT_HOST_MQTT); +// free(MQTT_ID_MQTT); +// free(MQTT_NAME_MQTT); +// free(MQTT_KEY_MQTT); +// free(MQTT_PRODUCTINFO_MQTT); +// free(UUID_MQTT); +// free(DEVICE_NAME_MQTT); +// free(BLINKER_PUB_TOPIC_MQTT); +// free(BLINKER_SUB_TOPIC_MQTT); +// free(mqtt_MQTT); +// free(iotSub_MQTT); + +// isMQTTinit = false; +// } + +// if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { +// // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); +// DEVICE_NAME_MQTT = (char*)malloc((_userID.length()+1)*sizeof(char)); +// strcpy(DEVICE_NAME_MQTT, _userID.c_str()); +// MQTT_ID_MQTT = (char*)malloc((_userID.length()+1)*sizeof(char)); +// strcpy(MQTT_ID_MQTT, _userID.c_str()); +// MQTT_NAME_MQTT = (char*)malloc((_userName.length()+1)*sizeof(char)); +// strcpy(MQTT_NAME_MQTT, _userName.c_str()); +// MQTT_KEY_MQTT = (char*)malloc((_key.length()+1)*sizeof(char)); +// strcpy(MQTT_KEY_MQTT, _key.c_str()); +// MQTT_PRODUCTINFO_MQTT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); +// strcpy(MQTT_PRODUCTINFO_MQTT, _productInfo.c_str()); +// MQTT_HOST_MQTT = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); +// strcpy(MQTT_HOST_MQTT, BLINKER_MQTT_ALIYUN_HOST); +// MQTT_PORT_MQTT = BLINKER_MQTT_ALIYUN_PORT; +// } +// else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { +// // String id2name = _userID.subString(10, _userID.length()); +// // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); +// DEVICE_NAME_MQTT = (char*)malloc((_userID.length()+1)*sizeof(char)); +// strcpy(DEVICE_NAME_MQTT, _userID.c_str()); +// String IDtest = _productInfo + _userID; +// MQTT_ID_MQTT = (char*)malloc((IDtest.length()+1)*sizeof(char)); +// strcpy(MQTT_ID_MQTT, IDtest.c_str()); +// String NAMEtest = IDtest + ";" + _userName; +// MQTT_NAME_MQTT = (char*)malloc((NAMEtest.length()+1)*sizeof(char)); +// strcpy(MQTT_NAME_MQTT, NAMEtest.c_str()); +// MQTT_KEY_MQTT = (char*)malloc((_key.length()+1)*sizeof(char)); +// strcpy(MQTT_KEY_MQTT, _key.c_str()); +// MQTT_PRODUCTINFO_MQTT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); +// strcpy(MQTT_PRODUCTINFO_MQTT, _productInfo.c_str()); +// MQTT_HOST_MQTT = (char*)malloc((strlen(BLINKER_MQTT_QCLOUD_HOST)+1)*sizeof(char)); +// strcpy(MQTT_HOST_MQTT, BLINKER_MQTT_QCLOUD_HOST); +// MQTT_PORT_MQTT = BLINKER_MQTT_QCLOUD_PORT; +// } +// else if (_broker == BLINKER_MQTT_BORKER_ONENET) { +// // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); +// DEVICE_NAME_MQTT = (char*)malloc((_userID.length()+1)*sizeof(char)); +// strcpy(DEVICE_NAME_MQTT, _userID.c_str()); +// MQTT_ID_MQTT = (char*)malloc((_userName.length()+1)*sizeof(char)); +// strcpy(MQTT_ID_MQTT, _userName.c_str()); +// MQTT_NAME_MQTT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); +// strcpy(MQTT_NAME_MQTT, _productInfo.c_str()); +// MQTT_KEY_MQTT = (char*)malloc((_key.length()+1)*sizeof(char)); +// strcpy(MQTT_KEY_MQTT, _key.c_str()); +// MQTT_PRODUCTINFO_MQTT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); +// strcpy(MQTT_PRODUCTINFO_MQTT, _productInfo.c_str()); +// MQTT_HOST_MQTT = (char*)malloc((strlen(BLINKER_MQTT_ONENET_HOST)+1)*sizeof(char)); +// strcpy(MQTT_HOST_MQTT, BLINKER_MQTT_ONENET_HOST); +// MQTT_PORT_MQTT = BLINKER_MQTT_ONENET_PORT; +// } +// UUID_MQTT = (char*)malloc((_uuid.length()+1)*sizeof(char)); +// strcpy(UUID_MQTT, _uuid.c_str()); + +// // char uuid_eeprom[BLINKER_AUUID_SIZE]; + +// // // BLINKER_LOG_ALL(("====================")); + +// // char _authCheck; +// // EEPROM.begin(BLINKER_EEP_SIZE); +// // EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); +// // if (strcmp(uuid_eeprom, _uuid.c_str()) != 0) { +// // // strcpy(UUID_MQTT, _uuid.c_str()); + +// // strcpy(uuid_eeprom, _uuid.c_str()); +// // EEPROM.put(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); +// // EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + +// // BLINKER_LOG_ALL(BLINKER_F("====================")); +// // BLINKER_LOG_ALL(BLINKER_F("uuid_eeprom: "), uuid_eeprom); +// // BLINKER_LOG_ALL(BLINKER_F("_uuid: "), _uuid); +// // // isNew = true; +// // } +// // EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); +// // // if (_authCheck != BLINKER_AUTH_CHECK_DATA) { +// // // EEPROM.put(BLINKER_EEP_ADDR_AUTH_CHECK, BLINKER_AUTH_CHECK_DATA); +// // // isAuth = true; +// // // } +// // EEPROM.commit(); +// // EEPROM.end(); + +// BLINKER_LOG_ALL(BLINKER_F("====================")); +// BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME_MQTT: "), DEVICE_NAME_MQTT); +// BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_MQTT: "), MQTT_PRODUCTINFO_MQTT); +// BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_MQTT: "), MQTT_ID_MQTT); +// BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_MQTT: "), MQTT_NAME_MQTT); +// BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_MQTT: "), MQTT_KEY_MQTT); +// BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); +// BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_MQTT); +// BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_MQTT); +// BLINKER_LOG_ALL(BLINKER_F("UUID_MQTT: "), UUID_MQTT); +// BLINKER_LOG_ALL(BLINKER_F("====================")); + +// if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { +// String PUB_TOPIC_STR = BLINKER_F("/"); +// PUB_TOPIC_STR += MQTT_PRODUCTINFO_MQTT; +// PUB_TOPIC_STR += BLINKER_F("/"); +// PUB_TOPIC_STR += MQTT_ID_MQTT; +// PUB_TOPIC_STR += BLINKER_F("/s"); + +// BLINKER_PUB_TOPIC_MQTT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); +// // memcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str(), str_len); +// strcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str()); + +// BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_MQTT: "), BLINKER_PUB_TOPIC_MQTT); + +// String SUB_TOPIC_STR = BLINKER_F("/"); +// SUB_TOPIC_STR += MQTT_PRODUCTINFO_MQTT; +// SUB_TOPIC_STR += BLINKER_F("/"); +// SUB_TOPIC_STR += MQTT_ID_MQTT; +// SUB_TOPIC_STR += BLINKER_F("/r"); + +// BLINKER_SUB_TOPIC_MQTT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); +// // memcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str(), str_len); +// strcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str()); + +// BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_MQTT: "), BLINKER_SUB_TOPIC_MQTT); +// } +// else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { +// String PUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT; +// PUB_TOPIC_STR += BLINKER_F("/"); +// PUB_TOPIC_STR += _userID; +// PUB_TOPIC_STR += BLINKER_F("/s"); + +// BLINKER_PUB_TOPIC_MQTT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); +// // memcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str(), str_len); +// strcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str()); + +// BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_MQTT: "), BLINKER_PUB_TOPIC_MQTT); + +// String SUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT; +// SUB_TOPIC_STR += BLINKER_F("/"); +// SUB_TOPIC_STR += _userID; +// SUB_TOPIC_STR += BLINKER_F("/r"); + +// BLINKER_SUB_TOPIC_MQTT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); +// // memcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str(), str_len); +// strcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str()); + +// BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_MQTT: "), BLINKER_SUB_TOPIC_MQTT); +// } +// else if (_broker == BLINKER_MQTT_BORKER_ONENET) { +// // uint8_t str_len; +// String PUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT; +// PUB_TOPIC_STR += BLINKER_F("/onenet_rule/r"); +// // str_len = PUB_TOPIC_STR.length() + 1; +// BLINKER_PUB_TOPIC_MQTT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); +// // memcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str(), str_len); +// strcpy(BLINKER_PUB_TOPIC_MQTT, PUB_TOPIC_STR.c_str()); + +// BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_MQTT: "), BLINKER_PUB_TOPIC_MQTT); + +// String SUB_TOPIC_STR = MQTT_PRODUCTINFO_MQTT; +// SUB_TOPIC_STR += BLINKER_F("/"); +// SUB_TOPIC_STR += _userID; +// SUB_TOPIC_STR += BLINKER_F("/r"); + +// BLINKER_SUB_TOPIC_MQTT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); +// // memcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str(), str_len); +// strcpy(BLINKER_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str()); + +// BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_MQTT: "), BLINKER_SUB_TOPIC_MQTT); +// } + +// // BLINKER_LOG_FreeHeap(); + +// if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { +// #if defined(ESP8266) +// // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_MQTT, MQTT_PORT_MQTT, 4096); +// // if (mfln) { +// // client_mqtt.setBufferSizes(1024, 1024); +// // } +// // client_mqtt.setInsecure(); +// mqtt_MQTT = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); +// #elif defined(ESP32) +// mqtt_MQTT = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); +// #endif +// } +// else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { +// #if defined(ESP8266) +// // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_MQTT, MQTT_PORT_MQTT, 4096); +// // if (mfln) { +// // client_mqtt.setBufferSizes(1024, 1024); +// // } +// // client_mqtt.setInsecure(); +// mqtt_MQTT = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); +// #elif defined(ESP32) +// mqtt_MQTT = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); +// #endif +// } +// else if (_broker == BLINKER_MQTT_BORKER_ONENET) { +// mqtt_MQTT = new Adafruit_MQTT_Client(&client, MQTT_HOST_MQTT, MQTT_PORT_MQTT, MQTT_ID_MQTT, MQTT_NAME_MQTT, MQTT_KEY_MQTT); +// } + +// // iotPub = new Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); +// // if (!isMQTTinit) +// iotSub_MQTT = new Adafruit_MQTT_Subscribe(mqtt_MQTT, BLINKER_SUB_TOPIC_MQTT); + +// // mqtt_broker = (char*)malloc((_broker.length()+1)*sizeof(char)); +// // strcpy(mqtt_broker, _broker.c_str()); +// // mqtt_broker = _broker; + +// // mDNSInit(MQTT_ID_MQTT); +// this->latestTime = millis() - BLINKER_MQTT_CONNECT_TIMESLOT; +// // if (!isMQTTinit) +// mqtt_MQTT->subscribe(iotSub_MQTT); + +// #if defined(ESP8266) +// // client_s->stop(); +// // if (!isMQTTinit) +// client_mqtt.setInsecure(); +// #endif +// // connect(); + +// BLINKER_LOG_FreeHeap(); + +// return true; +// } + +// void BlinkerMQTTLP::mDNSInit() +// { +// #if defined(ESP8266) +// if (!MDNS.begin(DEVICE_NAME_MQTT, WiFi.localIP())) { +// #elif defined(ESP32) +// if (!MDNS.begin(DEVICE_NAME_MQTT)) { +// #endif +// while(1) { +// ::delay(100); +// } +// } + +// BLINKER_LOG(BLINKER_F("mDNS responder started")); + +// MDNS.addService(BLINKER_MDNS_SERVICE_BLINKER, "tcp", WS_SERVERPORT); +// MDNS.addServiceTxt(BLINKER_MDNS_SERVICE_BLINKER, "tcp", "deviceName", String(DEVICE_NAME_MQTT)); + +// webSocket_MQTT.begin(); +// webSocket_MQTT.onEvent(webSocketEvent_MQTT); +// BLINKER_LOG(BLINKER_F("webSocket_MQTT server started")); +// BLINKER_LOG(BLINKER_F("ws://"), DEVICE_NAME_MQTT, BLINKER_F(".local:"), WS_SERVERPORT); +// } + +// void BlinkerMQTTLP::checkKA() { +// if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) +// isAlive = false; +// } + +// int BlinkerMQTTLP::checkAliKA() { +// if (millis() - aliKaTime >= 10000) +// return false; +// else +// return true; +// } + +// int BlinkerMQTTLP::checkDuerKA() { +// if (millis() - duerKaTime >= 10000) +// return false; +// else +// return true; +// } + +// int BlinkerMQTTLP::checkCanPrint() { +// if ((millis() - printTime >= BLINKER_MQTT_MSG_LIMIT && isAlive) || printTime == 0) { +// return true; +// } +// else { +// BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + +// checkKA(); + +// return false; +// } +// } + +// int BlinkerMQTTLP::checkCanBprint() { +// if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { +// return true; +// } +// else { +// BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + +// return false; +// } +// } + +// int BlinkerMQTTLP::checkPrintSpan() { +// if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) { +// if (respTimes > BLINKER_PRINT_MSG_LIMIT) { +// BLINKER_ERR_LOG(BLINKER_F("WEBSOCKETS CLIENT NOT ALIVE OR MSG LIMIT")); + +// return false; +// } +// else { +// respTimes++; +// return true; +// } +// } +// else { +// respTimes = 0; +// return true; +// } +// } + +// int BlinkerMQTTLP::checkAliPrintSpan() +// { +// if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) +// { +// if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) +// { +// BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + +// return false; +// } +// else +// { +// respAliTimes++; +// return true; +// } +// } +// else +// { +// respAliTimes = 0; +// return true; +// } +// } + +// int BlinkerMQTTLP::checkDuerPrintSpan() +// { +// if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) +// { +// if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) +// { +// BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + +// return false; +// } +// else +// { +// respDuerTimes++; +// return true; +// } +// } +// else +// { +// respDuerTimes = 0; +// return true; +// } +// } + +// int BlinkerMQTTLP::isJson(const String & data) +// { +// BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + +// DynamicJsonBuffer jsonBuffer; +// JsonObject& root = jsonBuffer.parseObject(STRING_format(data)); + +// if (!root.success()) +// { +// BLINKER_ERR_LOG("Print data is not Json! ", data); +// return false; +// } + +// return true; +// } + +// bool BlinkerMQTTLP::checkInit() +// { +// if (!_isWiFiInit) +// { +// switch (_configType) +// { +// case COMM : +// _connectTime = millis(); +// // BLINKER_LOG(BLINKER_F("checkInit...")); +// if (WiFi.status() != WL_CONNECTED) { +// ::delay(500); + +// if (millis() - _connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { +// // _connectTime = millis(); +// BLINKER_LOG(BLINKER_F("WiFi connect timeout, please check ssid and pswd!")); +// BLINKER_LOG(BLINKER_F("Retring WiFi connect again!")); +// return false; +// } + +// // BLINKER_LOG(BLINKER_F("checkInit...")); + +// return false; +// } +// BLINKER_LOG(BLINKER_F("WiFi Connected.")); +// BLINKER_LOG(BLINKER_F("IP Address: ")); +// BLINKER_LOG(WiFi.localIP()); +// _isWiFiInit = true; +// _connectTime = 0; + +// // begin(); + +// return false; +// case BLINKER_SMART_CONFIG : +// switch (_configStatus) +// { +// case SMART_BEGIN : +// if (WiFi.smartConfigDone()) +// { +// BLINKER_LOG(BLINKER_F("SmartConfig received.")); +// _connectTime = millis(); + +// #if defined(ESP8266) +// BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); +// #endif + +// _configStatus = SMART_DONE; +// } +// else return false; +// case SMART_DONE : +// if (WiFi.status() != WL_CONNECTED) +// { +// if (millis() - _connectTime > 15000) +// { +// BLINKER_LOG(BLINKER_F("SmartConfig timeout.")); +// WiFi.stopSmartConfig(); +// _configStatus = SMART_TIMEOUT; +// } +// return false; +// } +// else if (WiFi.status() == WL_CONNECTED) +// { +// // WiFi.stopSmartConfig(); + +// BLINKER_LOG(BLINKER_F("WiFi Connected.")); +// BLINKER_LOG(BLINKER_F("IP Address: ")); +// BLINKER_LOG(WiFi.localIP()); +// _isWiFiInit = true; +// _connectTime = 0; + +// // begin(); + +// return false; +// } +// // return false; +// case SMART_TIMEOUT : +// WiFi.beginSmartConfig(); +// _configStatus = SMART_BEGIN; +// BLINKER_LOG(BLINKER_F("Waiting for SmartConfig.")); +// return false; +// default : +// return false; +// } +// case BLINKER_AP_CONFIG : +// #if defined(BLINKER_APCONFIG) +// switch (_configStatus) +// { +// case APCFG_BEGIN : +// checkAPCFG(); +// return false; +// case APCFG_DONE : +// if (WiFi.status() != WL_CONNECTED) +// { +// if (millis() - _connectTime > 15000) +// { +// BLINKER_LOG(BLINKER_F("APConfig timeout.")); +// _configStatus = APCFG_TIMEOUT; +// } +// return false; +// } +// else if (WiFi.status() == WL_CONNECTED) +// { +// BLINKER_LOG(BLINKER_F("WiFi Connected.")); +// BLINKER_LOG(BLINKER_F("IP Address: ")); +// BLINKER_LOG(WiFi.localIP()); +// _isWiFiInit = true; +// _connectTime = 0; + +// // begin(); + +// return false; +// } +// // return false; +// case APCFG_TIMEOUT : +// softAPinit(); +// return false; +// default : +// return false; +// } +// #endif +// default : +// return false; +// } +// } + +// if (!_isBegin) +// { +// _isBegin = begin(); +// return _isBegin; +// } +// return true; +// } + +// void BlinkerMQTTLP::commonBegin(const char* _ssid, const char* _pswd) +// { +// _configType = COMM; + +// connectWiFi(_ssid, _pswd); + +// #if defined(ESP8266) +// BLINKER_LOG(BLINKER_F("ESP8266_MQTT initialized...")); +// #elif defined(ESP32) +// BLINKER_LOG(BLINKER_F("ESP32_MQTT initialized...")); +// #endif +// } + +// void BlinkerMQTTLP::smartconfigBegin() +// { +// _configType = BLINKER_SMART_CONFIG; + +// if (!autoInit()) smartconfig(); +// else _configStatus = SMART_DONE; + +// #if defined(ESP8266) +// BLINKER_LOG(BLINKER_F("ESP8266_MQTT initialized...")); +// #elif defined(ESP32) +// BLINKER_LOG(BLINKER_F("ESP32_MQTT initialized...")); +// #endif +// } + +// void BlinkerMQTTLP::apconfigBegin() +// { +// #if defined(BLINKER_APCONFIG) +// _configType = BLINKER_AP_CONFIG; + +// if (!autoInit()) softAPinit(); +// else _configStatus = APCFG_DONE; + +// #if defined(ESP8266) +// BLINKER_LOG(BLINKER_F("ESP8266_MQTT initialized...")); +// #elif defined(ESP32) +// BLINKER_LOG(BLINKER_F("ESP32_MQTT initialized...")); +// #endif +// #endif +// } + +// bool BlinkerMQTTLP::autoInit() +// { +// WiFi.mode(WIFI_STA); +// String _hostname = BLINKER_F("DiyArduino_"); +// _hostname += macDeviceName(); + +// #if defined(ESP8266) +// WiFi.hostname(_hostname.c_str()); +// #elif defined(ESP32) +// WiFi.setHostname(_hostname.c_str()); +// #endif + +// WiFi.begin(); +// ::delay(500); + +// BLINKER_LOG(BLINKER_F("Waiting for WiFi "), +// BLINKER_WIFI_AUTO_INIT_TIMEOUT / 1000, +// BLINKER_F("s, will enter SMARTCONFIG or "), +// BLINKER_F("APCONFIG while WiFi not connect!")); + +// uint8_t _times = 0; +// while (WiFi.status() != WL_CONNECTED) { +// ::delay(500); +// if (_times > BLINKER_WIFI_AUTO_INIT_TIMEOUT / 500) break; +// _times++; +// } + +// if (WiFi.status() != WL_CONNECTED) return false; +// else { +// // BLINKER_LOG(BLINKER_F("WiFi Connected.")); +// // BLINKER_LOG(BLINKER_F("IP Address: ")); +// // BLINKER_LOG(WiFi.localIP()); +// // _isWiFiInit = true; + +// // begin(); + +// return true; +// } +// } + +// void BlinkerMQTTLP::smartconfig() +// { +// WiFi.mode(WIFI_STA); +// String _hostname = BLINKER_F("DiyArduino_"); +// _hostname += macDeviceName(); + +// #if defined(ESP8266) +// WiFi.hostname(_hostname.c_str()); +// #elif defined(ESP32) +// WiFi.setHostname(_hostname.c_str()); +// #endif + +// WiFi.beginSmartConfig(); + +// _configStatus = SMART_BEGIN; + +// BLINKER_LOG(BLINKER_F("Waiting for SmartConfig.")); +// // while (!WiFi.smartConfigDone()) { +// // ::delay(500); +// // } + +// // BLINKER_LOG(BLINKER_F("SmartConfig received.")); + +// // BLINKER_LOG(BLINKER_F("Waiting for WiFi")); +// // while (WiFi.status() != WL_CONNECTED) { +// // ::delay(500); +// // } + +// // BLINKER_LOG(BLINKER_F("WiFi Connected.")); + +// // BLINKER_LOG(BLINKER_F("IP Address: ")); +// // BLINKER_LOG(WiFi.localIP()); +// } +// #if defined(BLINKER_APCONFIG) +// void BlinkerMQTTLP::softAPinit() +// { +// // WiFiServer _apServer(80); +// // WiFiClient _apClient; +// IPAddress apIP(192, 168, 4, 1); +// #if defined(ESP8266) +// IPAddress netMsk(255, 255, 255, 0); +// #endif + +// _apServer = new WiFiServer(80); + +// WiFi.mode(WIFI_AP); +// String softAP_ssid = BLINKER_F("DiyArduino_"); +// softAP_ssid += macDeviceName(); + +// #if defined(ESP8266) +// WiFi.hostname(softAP_ssid.c_str()); +// WiFi.softAPConfig(apIP, apIP, netMsk); +// #elif defined(ESP32) +// WiFi.setHostname(softAP_ssid.c_str()); +// WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); +// #endif + +// WiFi.softAP(softAP_ssid.c_str(), ("12345678")); +// delay(100); + +// _apServer->begin(); +// BLINKER_LOG(BLINKER_F("AP IP address: "), WiFi.softAPIP()); +// BLINKER_LOG(BLINKER_F("HTTP _apServer started")); +// BLINKER_LOG(BLINKER_F("URL: http://"), WiFi.softAPIP()); + +// _configStatus = APCFG_BEGIN; + +// BLINKER_LOG(BLINKER_F("Wait for APConfig")); + +// // while(WiFi.status() != WL_CONNECTED) +// // { +// // // serverClient(); +// // _apClient = _apServer->available(); +// // // if (_apClient.status() == CLOSED) +// // if (!_apClient.connected()) +// // { +// // _apClient.stop(); +// // BLINKER_LOG(BLINKER_F("Connection closed on _apClient")); +// // } +// // else +// // { +// // if (_apClient.available()) +// // { +// // String data = _apClient.readStringUntil('\r'); + +// // // data = data.substring(4, data.length() - 9); +// // _apClient.flush(); + +// // BLINKER_LOG(BLINKER_F("clientData: "), data); + +// // if (STRING_contains_string(data, "ssid") && +// // STRING_contains_string(data, "pswd")) +// // { +// // String msg = BLINKER_F("{\"hello\":\"world\"}"); + +// // String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); +// // s += BLINKER_F("Content-Type: application/json;"); +// // s += BLINKER_F("charset=utf-8\r\n"); +// // s += BLINKER_F("Content-Length: "); +// // s += String(msg.length()); +// // s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); +// // s += msg; +// // s += BLINKER_F("\r\n"); + +// // _apClient.print(s); + +// // _apClient.stop(); + +// // parseUrl(data); +// // } +// // } +// // } +// // ::delay(10); +// // } +// } + +// void BlinkerMQTTLP::checkAPCFG() +// { +// if(WiFi.status() != WL_CONNECTED) +// { +// // serverClient(); +// _apClient = _apServer->available(); +// // if (_apClient.status() == CLOSED) +// if (!_apClient.connected()) +// { +// _apClient.stop(); +// BLINKER_LOG(BLINKER_F("Connection closed on _apClient")); +// } +// else +// { +// if (_apClient.available()) +// { +// String data = _apClient.readStringUntil('\r'); + +// // data = data.substring(4, data.length() - 9); +// _apClient.flush(); + +// BLINKER_LOG(BLINKER_F("clientData: "), data); + +// if (STRING_contains_string(data, "ssid") && \ +// STRING_contains_string(data, "pswd")) +// { +// String msg = BLINKER_F("{\"hello\":\"world\"}"); + +// String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); +// s += BLINKER_F("Content-Type: application/json;"); +// s += BLINKER_F("charset=utf-8\r\n"); +// s += BLINKER_F("Content-Length: "); +// s += String(msg.length()); +// s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); +// s += msg; +// s += BLINKER_F("\r\n"); + +// _apClient.print(s); + +// _apClient.stop(); + +// parseUrl(data); +// } +// } +// } +// ::delay(10); +// } +// } + +// // void BlinkerMQTTLP::serverClient() +// // { +// // if (!_apClient) +// // { +// // _apClient = _apServer->available(); +// // } +// // else +// // { +// // // if (_apClient.status() == CLOSED) +// // if (!_apClient.connected()) +// // { +// // _apClient.stop(); +// // BLINKER_LOG(BLINKER_F("Connection closed on _apClient")); +// // } +// // else +// // { +// // if (_apClient.available()) +// // { +// // String data = _apClient.readStringUntil('\r'); + +// // // data = data.substring(4, data.length() - 9); +// // _apClient.flush(); + +// // BLINKER_LOG(BLINKER_F("clientData: "), data); + +// // if (STRING_contains_string(data, "ssid") && +// // STRING_contains_string(data, "pswd")) +// // { +// // String msg = BLINKER_F("{\"hello\":\"world\"}"); + +// // String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); +// // s += BLINKER_F("Content-Type: application/json;"); +// // s += BLINKER_F("charset=utf-8\r\n"); +// // s += BLINKER_F("Content-Length: "); +// // s += String(msg.length()); +// // s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); +// // s += msg; +// // s += BLINKER_F("\r\n"); + +// // _apClient.print(s); + +// // _apClient.stop(); + +// // parseUrl(data); +// // } +// // } +// // } +// // } +// // } + +// bool BlinkerMQTTLP::parseUrl(String data) +// { +// BLINKER_LOG(BLINKER_F("APCONFIG data: "), data); +// DynamicJsonBuffer jsonBuffer; +// JsonObject& wifi_data = jsonBuffer.parseObject(data); + +// if (!wifi_data.success()) { +// return false; +// } + +// String _ssid = wifi_data["ssid"]; +// String _pswd = wifi_data["pswd"]; + +// BLINKER_LOG(BLINKER_F("ssid: "), _ssid); +// BLINKER_LOG(BLINKER_F("pswd: "), _pswd); + +// free(_apServer); + +// connectWiFi(_ssid, _pswd); + +// _configStatus = APCFG_DONE; +// _connectTime = millis(); +// return true; +// } +// #endif +// void BlinkerMQTTLP::connectWiFi(String _ssid, String _pswd) +// { +// connectWiFi(_ssid.c_str(), _pswd.c_str()); +// } + +// void BlinkerMQTTLP::connectWiFi(const char* _ssid, const char* _pswd) +// { +// uint32_t _connectTime = millis(); + +// BLINKER_LOG(BLINKER_F("Connecting to "), _ssid); + +// WiFi.mode(WIFI_STA); +// String _hostname = BLINKER_F("DiyArduinoMQTT_"); +// _hostname += macDeviceName(); + +// #if defined(ESP8266) +// WiFi.hostname(_hostname.c_str()); +// #elif defined(ESP32) +// WiFi.setHostname(_hostname.c_str()); +// #endif + +// if (_pswd && strlen(_pswd)) { +// WiFi.begin(_ssid, _pswd); +// } +// else { +// WiFi.begin(_ssid); +// } + +// // while (WiFi.status() != WL_CONNECTED) { +// // ::delay(50); + +// // if (millis() - _connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { +// // _connectTime = millis(); +// // BLINKER_LOG(BLINKER_F("WiFi connect timeout, please check ssid and pswd!")); +// // BLINKER_LOG(BLINKER_F("Retring WiFi connect again!")); +// // } +// // } +// // BLINKER_LOG(BLINKER_F("Connected")); + +// // IPAddress myip = WiFi.localIP(); +// // BLINKER_LOG(BLINKER_F("Your IP is: "), myip); + +// // _isWiFiInit = true; +// } + +// #endif + +// #endif diff --git a/blinker-library/src/Adapters/BlinkerPRO.h b/blinker-library/src/Adapters/BlinkerPRO.h new file mode 100644 index 0000000..c07d82e --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerPRO.h @@ -0,0 +1,2019 @@ +#ifndef BLINKER_PRO_H +#define BLINKER_PRO_H + +#if (defined(ESP8266) || defined(ESP32)) + +#if defined(ESP8266) + #include + #include + #include +#elif defined(ESP32) + #include + #include + #include +#endif + +#include + +#include "../modules/WebSockets/WebSocketsServer.h" +#include "../modules/mqtt/Adafruit_MQTT.h" +#include "../modules/mqtt/Adafruit_MQTT_Client.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif + +// #include "../Adapters/BlinkerPRO.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +char* MQTT_HOST_PRO; +char* MQTT_ID_PRO; +char* MQTT_NAME_PRO; +char* MQTT_KEY_PRO; +char* MQTT_PRODUCTINFO_PRO; +char* UUID_PRO; +char* AUTHKEY_PRO; +char* MQTT_DEVICEID_PRO; +// char* DEVICE_NAME; +char* BLINKER_PUB_TOPIC_PRO; +char* BLINKER_SUB_TOPIC_PRO; +uint16_t MQTT_PORT_PRO; + +class BlinkerPRO : public BlinkerStream +{ + public : + BlinkerPRO(); + + int connect(); + int connected(); + int mConnected();// { if (!isMQTTinit) return false; else return mqtt->connected(); } + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + // bool extraAvailable(); + void subscribe(); + char * lastRead(); + void flush(); + int print(char * data, bool needCheck = true); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + // void aliType(const String & type); + void begin(const char* _deviceType); + int autoPrint(unsigned long id); + // bool autoPrint(char *name, char *type, char *data); + // bool autoPrint(char *name1, char *type1, char *data1, \ + // char *name2, char *type2, char *data2); + char * deviceName(); + char * authKey() { return AUTHKEY_PRO; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_PRO; } + int init() { return isMQTTinit; } + int reRegister() { return connectServer(); } + int deviceRegister() { return connectServer(); } + int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + + private : + bool isMQTTinit = false; + + int connectServer(); + void mDNSInit(); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + int pubHello(); + + protected : + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + const char* _deviceType; + // char* _authKey; + // char* _aliType; + bool* isHandle;// = &isConnect; + // bool* isHandle = &isConnect_PRO; + bool isAlive = false; + bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + + bool isNew = false; + bool isAuth = false; + bool isFirst = false; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; +}; + +// #if defined(ESP8266) +// extern BearSSL::WiFiClientSecure client_mqtt; +// // WiFiClientSecure client_mqtt; +// #elif defined(ESP32) +// extern WiFiClientSecure client_s; +// #endif + +// extern WiFiClient client; + + +#if defined(ESP8266) + BearSSL::WiFiClientSecure client_mqtt; + // WiFiClientSecure client_mqtt; +#elif defined(ESP32) + WiFiClientSecure client_s; +#endif + +WiFiClient client; +Adafruit_MQTT_Client* mqtt_PRO; +// Adafruit_MQTT_Publish *iotPub; +Adafruit_MQTT_Subscribe* iotSub_PRO; + +#define WS_SERVERPORT 81 +WebSocketsServer webSocket_PRO = WebSocketsServer(WS_SERVERPORT); + +char* msgBuf_PRO; +bool isFresh_PRO = false; +bool isConnect_PRO = false; +bool isAvail_PRO = false; +uint8_t ws_num_PRO = 0; +uint8_t dataFrom_PRO = BLINKER_MSG_FROM_MQTT; + +void webSocketEvent_PRO(uint8_t num, WStype_t type, \ + uint8_t * payload, size_t length) +{ + + switch(type) + { + case WStype_DISCONNECTED: + BLINKER_LOG_ALL(BLINKER_F("Disconnected! "), num); + + isConnect_PRO = false; + break; + case WStype_CONNECTED: + { + IPAddress ip = webSocket_PRO.remoteIP(num); + + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", Connected from: "), ip, + BLINKER_F(", url: "), (char *)payload); + + // send message to client + webSocket_PRO.sendTXT(num, "{\"state\":\"connected\"}\n"); + + ws_num_PRO = num; + + isConnect_PRO = true; + } + break; + case WStype_TEXT: + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", get Text: "), (char *)payload, \ + BLINKER_F(", length: "), length); + + if (length < BLINKER_MAX_READ_SIZE) { + if (isFresh_PRO) free(msgBuf_PRO); + msgBuf_PRO = (char*)malloc((length+1)*sizeof(char)); + strcpy(msgBuf_PRO, (char*)payload); + isAvail_PRO = true; + isFresh_PRO = true; + } + + dataFrom_PRO = BLINKER_MSG_FROM_WS; + + ws_num_PRO = num; + + // send message to client + // webSocket_PRO.sendTXT(num, "message here"); + + // send data to all connected clients + // webSocket_PRO.broadcastTXT("message here"); + break; + case WStype_BIN: + // BLINKER_LOG("num: ", num, " get binary length: ", length); + // hexdump(payload, length); + + // send message to client + // webSocket_PRO.sendBIN(num, payload, length); + break; + } +} + +BlinkerPRO::BlinkerPRO() { isHandle = &isConnect_PRO; } + +int BlinkerPRO::connect() +{ + int8_t ret; + + webSocket_PRO.loop(); + + if (!isMQTTinit) { + return *isHandle; + } + + if (mqtt_PRO->connected()) + { + return true; + } + + disconnect(); + + if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + { + yield(); + return false; + } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + #if defined(ESP8266) + client_mqtt.setInsecure(); + ::delay(10); + #endif + + BLINKER_LOG_FreeHeap_ALL(); + + if ((ret = mqtt_PRO->connect()) != 0) + { + BLINKER_LOG(mqtt_PRO->connectErrorString(ret)); + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + if (ret == 4) reRegister(); + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + reRegister(); + reconnect_time = 0; + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + if (isNew) + { + if (pubHello()) { + isNew = false; + } + } + + this->latestTime = millis(); + + return true; +} + +int BlinkerPRO::connected() +{ + if (!isMQTTinit) + { + return *isHandle; + } + + return mqtt_PRO->connected() || *isHandle; +} + +int BlinkerPRO::mConnected() +{ + if (!isMQTTinit) return false; + else return mqtt_PRO->connected(); +} + +void BlinkerPRO::disconnect() +{ + if (isMQTTinit) mqtt_PRO->disconnect(); + + if (*isHandle) webSocket_PRO.disconnect(); +} + +void BlinkerPRO::ping() +{ + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!isMQTTinit) return; + + if (!mqtt_PRO->ping()) + { + disconnect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } +} + +int BlinkerPRO::available() +{ + webSocket_PRO.loop(); + + if (isMQTTinit) { + checkKA(); + + // if (!mqtt_PRO->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + { + ping(); + } + else + { + subscribe(); + } + } + + if (isAvail_PRO) + { + isAvail_PRO = false; + return true; + } + else { + return false; + } +} + +int BlinkerPRO::aligenieAvail() +{ + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerPRO::duerAvail() +{ + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +// bool BlinkerPRO::extraAvailable() +// { +// if (isBavail) +// { +// isBavail = false; +// return true; +// } +// else +// { +// return false; +// } +// } + +void BlinkerPRO::subscribe() +{ + if (!isMQTTinit) return; + + Adafruit_MQTT_Subscribe *subscription; + while ((subscription = mqtt_PRO->readSubscription(10))) + { + if (subscription == iotSub_PRO) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), (char *)iotSub_PRO->lastread); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(String((char *)iotSub_PRO->lastread)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, String((char *)iotSub_PRO->lastread)); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"]; + String dataGet = root["data"]; + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_PRO) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_PRO = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT) + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_PRO = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found," + "check is from bridge/share device," + "data: "), dataGet); + + _needCheckShare = true; + } + } + } + + // { + // dataGet = String((char *)iotSub_PRO->lastread); + // root.printTo(dataGet); + serializeJson(root, dataGet); + + // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + // check is from bridge/share device, \ + // data: "), dataGet); + + // // return; + + // // isBavail = true; + + // _needCheckShare = true; + // } + + isAvail_PRO = true; + isAlive = true; + } + + // memset(msgBuf_PRO, 0, BLINKER_MAX_READ_SIZE); + // memcpy(msgBuf_PRO, dataGet.c_str(), dataGet.length()); + + if (isFresh_PRO) free(msgBuf_PRO); + msgBuf_PRO = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_PRO, dataGet.c_str()); + isFresh_PRO = true; + + this->latestTime = millis(); + + dataFrom_PRO = BLINKER_MSG_FROM_MQTT; + } + } +} + +char * BlinkerPRO::lastRead() +{ + if (isFresh_PRO) return msgBuf_PRO; + return ""; +} + +void BlinkerPRO::flush() +{ + if (isFresh_PRO) + { + free(msgBuf_PRO); isFresh_PRO = false; isAvail_PRO = false; + isAliAvail = false; //isBavail = false; + } +} + +int BlinkerPRO::print(char * data, bool needCheck) +{ + // BLINKER_LOG_FreeHeap(); + if (*isHandle && dataFrom_PRO == BLINKER_MSG_FROM_WS) + { + if (needCheck) + { + if (!checkPrintSpan()) + { + respTime = millis(); + return false; + } + } + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("WS response: ")); + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + strcat(data, BLINKER_CMD_NEWLINE); + + webSocket_PRO.sendTXT(ws_num_PRO, data); + + return true; + } + else + { + // // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // uint8_t num = strlen(data) - 1; + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data.substring(0, data.length() - 1); + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_DEVICEID_PRO; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_PRO; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + // else + // { + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data; + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_DEVICEID_PRO; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_PRO; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + + // uint16_t num = strlen(data); + + // for(uint16_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + + // data[num+8] = '\0'; + + // String data_add = BLINKER_F("{\"data\":"); + + // for(uint16_t c_num = 0; c_num < 8; c_num++) + // { + // data[c_num] = data_add[c_num]; + // } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, MQTT_DEVICEID_PRO); + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + // if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + // { + // strcat(data, _sharers[_sharerFrom]->uuid()); + // } + // else + // { + // strcat(data, UUID_PRO); + // } + // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // strcat(data, data_add.c_str()); + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + // if (!isJson(STRING_format(data))) return false; + + String data_add = BLINKER_F("{\"data\":"); + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\""); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + data_add += _sharers[_sharerFrom]->uuid(); + } + else + { + data_add += UUID_PRO; + } + + data_add += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (mqtt_PRO->connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } + } +} + +int BlinkerPRO::bPrint(char * name, const String & data) +{ + // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data.substring(0, data.length() - 1); + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_DEVICEID_PRO; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + // else + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data; + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_DEVICEID_PRO; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + + String data_add = BLINKER_F("{\"data\":"); + // for(uint8_t c_num = 0; c_num < 8; c_num++) + // { + // data[c_num] = data_add[c_num]; + // } + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\""); + data_add += name; + data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, MQTT_DEVICEID_PRO); + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, name); + // data_add = BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // strcat(data, data_add.c_str()); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_PRO->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + + // if (! iotPub.publish(payload.c_str())) { + + // String bPubTopic = BLINKER_F(""); + + // if (mqtt_broker == BLINKER_MQTT_BORKER_ONENET) + // { + // bPubTopic = MQTT_PRODUCTINFO_PRO; + // bPubTopic += BLINKER_F("/"); + // bPubTopic += name; + // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // bPubTopic = BLINKER_PUB_TOPIC_PRO; + // } + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerPRO::aliPrint(const String & data) +{ + // String payload; + + // payload = BLINKER_F("{\"data\":"); + // payload += data; + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_DEVICEID_PRO; + // payload += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + // payload += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + + String data_add = BLINKER_F("{\"data\":"); + // for(uint8_t c_num = 0; c_num < 8; c_num++) + // { + // data[c_num] = data_add[c_num]; + // } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, MQTT_DEVICEID_PRO); + // data_add = BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + // strcat(data, data_add.c_str()); + // data_add = BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + // strcat(data, data_add.c_str()); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerPRO::duerPrint(const String & data, bool report) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// void BlinkerPRO::aliType(const String & type) +// { +// _aliType = (char*)malloc((type.length()+1)*sizeof(char)); +// strcpy(_aliType, type.c_str()); +// BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +// } + +void BlinkerPRO::begin(const char* _type) +{ + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + mDNSInit(); +} + +int BlinkerPRO::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"trigged\":true,\"autoData\":{"); + payload += BLINKER_F("\"autoId\":"); + payload += STRING_format(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(MQTT_DEVICEID_PRO); + payload += BLINKER_F("\",\"toDevice\":\"autoManager\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_PRO->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// bool BlinkerPRO::autoPrint(char *name, char *type, char *data) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_PRO); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_PRO->connected()) { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +// bool BlinkerPRO::autoPrint(char *name1, char *type1, char *data1 +// , char *name2, char *type2, char *data2) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data1); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_PRO); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name1; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type1; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_PRO->connected()) +// { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data2); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_PRO); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name2; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type2; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else +// { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +char * BlinkerPRO::deviceName() { return MQTT_DEVICEID_PRO;/*MQTT_ID_PRO;*/ } + +void BlinkerPRO::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (_sharerCount; _sharerCount > 0; _sharerCount--) + { + delete _sharers[_sharerCount - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerPRO::authCheck() +{ + uint8_t _authCheck; + + BLINKER_LOG_ALL(BLINKER_F("authCheck start")); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck == BLINKER_AUTH_CHECK_DATA) + { + EEPROM.commit(); + EEPROM.end(); + isAuth = true; + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return true; + } + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return false; +} + +int BlinkerPRO::connectServer() { + const int httpsPort = 443; +#if defined(ESP8266) + String host = BLINKER_F(BLINKER_SERVER_HOST); + String fingerprint = BLINKER_F("84 5f a4 8a 70 5e 79 7e f5 b3 b4 20 45 c8 35 55 72 f6 85 5a"); + + // WiFiClientSecure client_s; + +// BearSSL::WiFiClientSecure *client_s; + +// client_s = new BearSSL::WiFiClientSecure(); + +// client_mqtt.stop(); + +// BLINKER_LOG_ALL(BLINKER_F("connecting to "), host); + +// // BLINKER_LOG_FreeHeap(); + +// uint8_t connet_times = 0; +// // client_s.stop(); +// ::delay(100); + +// bool mfln = client_s->probeMaxFragmentLength(host, httpsPort, 1024); +// if (mfln) { +// client_s->setBufferSizes(1024, 1024); +// } +// // client_s.setFingerprint(fingerprint.c_str()); + +// client_s->setInsecure(); + +// // while (1) { +// bool cl_connected = false; +// if (!client_s->connect(host, httpsPort)) { +// BLINKER_ERR_LOG(BLINKER_F("server connection failed")); +// // connet_times++; + +// ::delay(1000); +// } +// else { +// BLINKER_LOG_ALL(BLINKER_F("connection succeed")); +// cl_connected = true; + +// // break; +// } + +// // if (connet_times >= 4 && !cl_connected) return BLINKER_CMD_FALSE; +// // } + +// String client_msg; + +// String url_iot = BLINKER_F("/api/v1/user/device/register?deviceType="); +// url_iot += _deviceType; +// url_iot += BLINKER_F("&deviceName="); +// url_iot += macDeviceName(); + +// if (_deviceType == BLINKER_SMART_LAMP) { +// url_iot += BLINKER_F("&aliType=light"); +// url_iot += BLINKER_F("&duerType=LIGHT"); +// } +// else if (_deviceType == BLINKER_SMART_PLUGIN) { +// url_iot += BLINKER_F("&aliType=outlet"); +// url_iot += BLINKER_F("&duerType=SOCKET"); +// } +// else if (_deviceType == BLINKER_AIR_DETECTOR) { +// url_iot += BLINKER_F("&aliType=sensor"); +// url_iot += BLINKER_F("&duerType=AIR_MONITOR"); +// } + +// // #if defined(BLINKER_ALIGENIE_LIGHT) +// // url_iot += BLINKER_F("&aliType=light"); +// // #elif defined(BLINKER_ALIGENIE_OUTLET) +// // url_iot += BLINKER_F("&aliType=outlet"); +// // #elif defined(BLINKER_ALIGENIE_SWITCH) +// // #elif defined(BLINKER_ALIGENIE_SENSOR) +// // url_iot += BLINKER_F("&aliType=sensor"); +// // #endif + +// BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host, url_iot); + +// client_msg = BLINKER_F("GET "); +// client_msg += url_iot; +// client_msg += BLINKER_F(" HTTP/1.1\r\nHost: "); +// client_msg += host; +// client_msg += BLINKER_F(":"); +// client_msg += STRING_format(httpsPort); +// client_msg += BLINKER_F("\r\nConnection: close\r\n\r\n"); + +// client_s->print(client_msg); + +// BLINKER_LOG_ALL(BLINKER_F("client_msg: "), client_msg); + +// unsigned long timeout = millis(); +// while (client_s->available() == 0) { +// if (millis() - timeout > 5000) { +// BLINKER_LOG_ALL(BLINKER_F(">>> Client Timeout !")); +// client_s->stop(); +// return false; +// } +// } + +// String _dataGet; +// String lastGet; +// String lengthOfJson; +// while (client_s->available()) { +// // String line = client_s.readStringUntil('\r'); +// _dataGet = client_s->readStringUntil('\n'); + +// if (_dataGet.startsWith("Content-Length: ")){ +// int addr_start = _dataGet.indexOf(' '); +// int addr_end = _dataGet.indexOf('\0', addr_start + 1); +// lengthOfJson = _dataGet.substring(addr_start + 1, addr_end); +// } + +// if (_dataGet == "\r") { +// BLINKER_LOG_ALL(BLINKER_F("headers received")); + +// break; +// } +// } + +// for(int i=0;iread(); +// } + +// // BLINKER_LOG_FreeHeap(); + +// client_s->stop(); +// client_s->flush(); + +// free(client_s); + +// // BLINKER_LOG_FreeHeap(); + +// _dataGet = lastGet; + +// BLINKER_LOG_ALL(BLINKER_F("_dataGet: "), _dataGet); + +// String payload = _dataGet; + + + + client_mqtt.stop(); + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + + String url_iot = BLINKER_F("/api/v1/user/device/register?deviceType="); + url_iot += _deviceType; + url_iot += BLINKER_F("&deviceName="); + if (_deviceType != BLINKER_AIR_STATION) + { + url_iot += macDeviceName(); + } + else + { + // url_iot += "TESTA69BA016"; // 1 + // url_iot += "TEST656A2782"; // 2 + // url_iot += "TESTD1C4B294"; // 3 + url_iot += "TEST687991DC"; // 4 + // url_iot += "TEST872B3982"; // 5 + } + + + if (_deviceType == BLINKER_SMART_LAMP) { + url_iot += BLINKER_F("&aliType=light"); + url_iot += BLINKER_F("&duerType=LIGHT"); + } + else if (_deviceType == BLINKER_SMART_PLUGIN) { + url_iot += BLINKER_F("&aliType=outlet"); + url_iot += BLINKER_F("&duerType=SOCKET"); + } + else if (_deviceType == BLINKER_AIR_DETECTOR) { + url_iot += BLINKER_F("&aliType=sensor"); + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + } + + url_iot = "https://" + host + url_iot; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + HTTPClient http; + + String payload; + + if (http.begin(*client_s, url_iot)) { // HTTPS + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + +#elif defined(ESP32) + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + // const char* ca = \ + // "-----BEGIN CERTIFICATE-----\n" \ + // "MIIEgDCCA2igAwIBAgIQDKTfhr9lmWbWUT0hjX36oDANBgkqhkiG9w0BAQsFADBy\n" \ + // "MQswCQYDVQQGEwJDTjElMCMGA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywg\n" \ + // "SW5jLjEdMBsGA1UECxMURG9tYWluIFZhbGlkYXRlZCBTU0wxHTAbBgNVBAMTFFRy\n" \ + // "dXN0QXNpYSBUTFMgUlNBIENBMB4XDTE4MDEwNDAwMDAwMFoXDTE5MDEwNDEyMDAw\n" \ + // "MFowGDEWMBQGA1UEAxMNaW90ZGV2LmNsei5tZTCCASIwDQYJKoZIhvcNAQEBBQAD\n" \ + // "ggEPADCCAQoCggEBALbOFn7cJ2I/FKMJqIaEr38n4kCuJCCeNf1bWdWvOizmU2A8\n" \ + // "QeTAr5e6Q3GKeJRdPnc8xXhqkTm4LOhgdZB8KzuVZARtu23D4vj4sVzxgC/zwJlZ\n" \ + // "MRMxN+cqI37kXE8gGKW46l2H9vcukylJX+cx/tjWDfS2YuyXdFuS/RjhCxLgXzbS\n" \ + // "cve1W0oBZnBPRSMV0kgxTWj7hEGZNWKIzK95BSCiMN59b+XEu3NWGRb/VzSAiJEy\n" \ + // "Hy9DcDPBC9TEg+p5itHtdMhy2gq1OwsPgl9HUT0xmDATSNEV2RB3vwviNfu9/Eif\n" \ + // "ObhsV078zf30TqdiESqISEB68gJ0Otru67ePoTkCAwEAAaOCAWowggFmMB8GA1Ud\n" \ + // "IwQYMBaAFH/TmfOgRw4xAFZWIo63zJ7dygGKMB0GA1UdDgQWBBR/KLqnke61779P\n" \ + // "xc9htonQwLOxPDAYBgNVHREEETAPgg1pb3RkZXYuY2x6Lm1lMA4GA1UdDwEB/wQE\n" \ + // "AwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTAYDVR0gBEUwQzA3\n" \ + // "BglghkgBhv1sAQIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQu\n" \ + // "Y29tL0NQUzAIBgZngQwBAgEwgYEGCCsGAQUFBwEBBHUwczAlBggrBgEFBQcwAYYZ\n" \ + // "aHR0cDovL29jc3AyLmRpZ2ljZXJ0LmNvbTBKBggrBgEFBQcwAoY+aHR0cDovL2Nh\n" \ + // "Y2VydHMuZGlnaXRhbGNlcnR2YWxpZGF0aW9uLmNvbS9UcnVzdEFzaWFUTFNSU0FD\n" \ + // "QS5jcnQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtM4eyrWB14ajJpQ\n" \ + // "ibZ5FbzVuvv2Le0FOSoss7UFCDJUYiz2LiV8yOhL4KTY+oVVkqHaYtcFS1CYZNzj\n" \ + // "6xWcqYZJ+pgsto3WBEgNEEe0uLSiTW6M10hm0LFW9Det3k8fqwSlljqMha3gkpZ6\n" \ + // "8WB0f2clXOuC+f1SxAOymnGUsSqbU0eFSgevcOIBKR7Hr3YXBXH3jjED76Q52OMS\n" \ + // "ucfOM9/HB3jN8o/ioQbkI7xyd/DUQtzK6hSArEoYRl3p5H2P4fr9XqmpoZV3i3gQ\n" \ + // "oOdVycVtpLunyUoVAB2DcOElfDxxXCvDH3XsgoIU216VY03MCaUZf7kZ2GiNL+UX\n" \ + // "9UBd0Q==\n" \ + // "-----END CERTIFICATE-----\n"; +// #endif + + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/register?deviceType="); + url_iot += _deviceType; + url_iot += BLINKER_F("&deviceName="); + if (_deviceType != BLINKER_AIR_STATION) + { + url_iot += macDeviceName(); + } + else + { + // url_iot += "TESTA69BA016"; // 1 + // url_iot += "TEST656A2782"; // 2 + url_iot += "TESTD1C4B294"; // 3 + // url_iot += "TEST687991DC"; // 4 + // url_iot += "TEST872B3982"; // 5 + } + + if (_deviceType == BLINKER_SMART_LAMP) { + url_iot += BLINKER_F("&aliType=light"); + url_iot += BLINKER_F("&duerType=LIGHT"); + } + else if (_deviceType == BLINKER_SMART_PLUGIN) { + url_iot += BLINKER_F("&aliType=outlet"); + url_iot += BLINKER_F("&duerType=SOCKET"); + } + else if (_deviceType == BLINKER_AIR_DETECTOR) { + url_iot += BLINKER_F("&aliType=sensor"); + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + } + +// #if defined(BLINKER_ALIGENIE_LIGHT) +// url_iot += BLINKER_F("&aliType=light"); +// #elif defined(BLINKER_ALIGENIE_OUTLET) +// url_iot += BLINKER_F("&aliType=outlet"); +// #elif defined(BLINKER_ALIGENIE_SWITCH) +// #elif defined(BLINKER_ALIGENIE_SENSOR) +// url_iot += BLINKER_F("&aliType=sensor"); +// #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + +// #if defined(ESP8266) +// http.begin(url_iot, fingerprint); //HTTP +// #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); +// #endif + int httpCode = http.GET(); + + String payload; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); +#endif + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + // String _userID = STRING_find_string(payload, "deviceName", "\"", 4); + // String _userName = STRING_find_string(payload, "iotId", "\"", 4); + // String _key = STRING_find_string(payload, "iotToken", "\"", 4); + // String _productInfo = STRING_find_string(payload, "productKey", "\"", 4); + // String _broker = STRING_find_string(payload, "broker", "\"", 4); + // String _uuid = STRING_find_string(payload, "uuid", "\"", 4); + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + String _authKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_KEY]; + + if (isMQTTinit) + { + free(MQTT_HOST_PRO); + free(MQTT_ID_PRO); + free(MQTT_NAME_PRO); + free(MQTT_KEY_PRO); + free(MQTT_PRODUCTINFO_PRO); + free(UUID_PRO); + free(AUTHKEY_PRO); + free(MQTT_DEVICEID_PRO); + free(BLINKER_PUB_TOPIC_PRO); + free(BLINKER_SUB_TOPIC_PRO); + free(mqtt_PRO); + free(iotSub_PRO); + + isMQTTinit = false; + } + + BLINKER_LOG_ALL(("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME, _userID.c_str(), 12); + // String _deviceName = _userID.substring(12, 36); + // MQTT_DEVICEID_PRO = (char*)malloc((_deviceName.length()+1)*sizeof(char)); + // String _deviceName = _userID.substring(12, 36); + MQTT_DEVICEID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _userID.c_str()); + MQTT_ID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_PRO, _userID.c_str()); + MQTT_NAME_PRO = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_PRO, _userName.c_str()); + MQTT_KEY_PRO = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_PRO, _key.c_str()); + MQTT_PRODUCTINFO_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_PRO, _productInfo.c_str()); + MQTT_HOST_PRO = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_PRO, BLINKER_MQTT_ALIYUN_HOST); + AUTHKEY_PRO = (char*)malloc((_authKey.length()+1)*sizeof(char)); + strcpy(AUTHKEY_PRO, _authKey.c_str()); + MQTT_PORT_PRO = BLINKER_MQTT_ALIYUN_PORT; + + BLINKER_LOG_ALL(("====================")); + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + // String id2name = _userID.subString(10, _userID.length()); + // memcpy(DEVICE_NAME, _userID.c_str(), 12); + MQTT_DEVICEID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _userID.c_str()); + String IDtest = _productInfo + _userID; + MQTT_ID_PRO = (char*)malloc((IDtest.length()+1)*sizeof(char)); + strcpy(MQTT_ID_PRO, IDtest.c_str()); + String NAMEtest = IDtest + ";" + _userName; + MQTT_NAME_PRO = (char*)malloc((NAMEtest.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_PRO, NAMEtest.c_str()); + MQTT_KEY_PRO = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_PRO, _key.c_str()); + MQTT_PRODUCTINFO_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_PRO, _productInfo.c_str()); + MQTT_HOST_PRO = (char*)malloc((strlen(BLINKER_MQTT_QCLOUD_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_PRO, BLINKER_MQTT_QCLOUD_HOST); + MQTT_PORT_PRO = BLINKER_MQTT_QCLOUD_PORT; + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + // memcpy(DEVICE_NAME, _userID.c_str(), 12); + MQTT_DEVICEID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _userID.c_str()); + MQTT_ID_PRO = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_ID_PRO, _userName.c_str()); + MQTT_NAME_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_PRO, _productInfo.c_str()); + MQTT_KEY_PRO = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_PRO, _key.c_str()); + MQTT_PRODUCTINFO_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_PRO, _productInfo.c_str()); + MQTT_HOST_PRO = (char*)malloc((strlen(BLINKER_MQTT_ONENET_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_PRO, BLINKER_MQTT_ONENET_HOST); + MQTT_PORT_PRO = BLINKER_MQTT_ONENET_PORT; + } + UUID_PRO = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_PRO, _uuid.c_str()); + + char uuid_eeprom[BLINKER_AUUID_SIZE]; + + BLINKER_LOG_ALL(("==========AUTH CHECK==========")); + + if (!isFirst) + { + char _authCheck; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + if (strcmp(uuid_eeprom, _uuid.c_str()) != 0) { + // strcpy(UUID_PRO, _uuid.c_str()); + + strcpy(uuid_eeprom, _uuid.c_str()); + EEPROM.put(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("uuid_eeprom: "), uuid_eeprom); + BLINKER_LOG_ALL(BLINKER_F("_uuid: "), _uuid); + isNew = true; + } + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck != BLINKER_AUTH_CHECK_DATA) { + EEPROM.put(BLINKER_EEP_ADDR_AUTH_CHECK, BLINKER_AUTH_CHECK_DATA); + isAuth = true; + } + EEPROM.commit(); + EEPROM.end(); + + isFirst = true; + } + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME: "), macDeviceName()); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_PRO: "), MQTT_PRODUCTINFO_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_DEVICEID_PRO: "), MQTT_DEVICEID_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_PRO: "), MQTT_ID_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_PRO: "), MQTT_NAME_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_PRO: "), MQTT_KEY_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_PRO); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_PRO); + BLINKER_LOG_ALL(BLINKER_F("UUID_PRO: "), UUID_PRO); + BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_PRO: "), AUTHKEY_PRO); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_PRO; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_DEVICEID_PRO; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_PRO = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_PRO: "), BLINKER_PUB_TOPIC_PRO); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_DEVICEID_PRO; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_PRO = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_PRO: "), BLINKER_SUB_TOPIC_PRO); + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + String PUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += _userID; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_PRO = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_PRO: "), BLINKER_PUB_TOPIC_PRO); + + String SUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += _userID; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_PRO = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_PRO: "), BLINKER_SUB_TOPIC_PRO); + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + uint8_t str_len; + String PUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + PUB_TOPIC_STR += BLINKER_F("/onenet_rule/r"); + // str_len = PUB_TOPIC_STR.length() + 1; + BLINKER_PUB_TOPIC_PRO = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_PRO: "), BLINKER_PUB_TOPIC_PRO); + + String SUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += _userID; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_PRO = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_PRO: "), BLINKER_SUB_TOPIC_PRO); + } + + // BLINKER_LOG_FreeHeap(); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_PRO, MQTT_PORT_PRO, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_PRO = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #elif defined(ESP32) + mqtt_PRO = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #endif + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_PRO, MQTT_PORT_PRO, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_PRO = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #elif defined(ESP32) + mqtt_PRO = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #endif + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + mqtt_PRO = new Adafruit_MQTT_Client(&client, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + } + + // iotPub = new Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + // if (!isMQTTinit) + iotSub_PRO = new Adafruit_MQTT_Subscribe(mqtt_PRO, BLINKER_SUB_TOPIC_PRO); + + // mqtt_broker = (char*)malloc((_broker.length()+1)*sizeof(char)); + // strcpy(mqtt_broker, _broker.c_str()); + // mqtt_broker = _broker; + + // mDNSInit(MQTT_ID_PRO); + this->latestTime = millis(); + // if (!isMQTTinit) + mqtt_PRO->subscribe(iotSub_PRO); + isMQTTinit = true; + + #if defined(ESP8266) + // client_s->stop(); + client_mqtt.setInsecure(); + #endif + // connect(); + + return true; +} + +void BlinkerPRO::mDNSInit() +{ +#if defined(ESP8266) + if (!MDNS.begin(macDeviceName().c_str(), WiFi.localIP())) { +#elif defined(ESP32) + if (!MDNS.begin(macDeviceName().c_str())) { +#endif + while(1) { + ::delay(100); + } + } + + BLINKER_LOG(BLINKER_F("mDNS responder started")); + + String _service = STRING_format(BLINKER_MDNS_SERVICE_BLINKER) + _deviceType; + + MDNS.addService(_service.c_str(), "tcp", WS_SERVERPORT); + MDNS.addServiceTxt(_service.c_str(), "tcp", "deviceName", macDeviceName()); + + webSocket_PRO.begin(); + webSocket_PRO.onEvent(webSocketEvent_PRO); + BLINKER_LOG(BLINKER_F("webSocket_PRO server started")); + BLINKER_LOG(BLINKER_F("ws://"), macDeviceName(), BLINKER_F(".local:"), WS_SERVERPORT); +} + +void BlinkerPRO::checkKA() { + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerPRO::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerPRO::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerPRO::checkCanPrint() { + if ((millis() - printTime >= BLINKER_PRO_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerPRO::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerPRO::checkPrintSpan() { + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) { + BLINKER_ERR_LOG(BLINKER_F("WEBSOCKETS CLIENT NOT ALIVE OR MSG LIMIT")); + + return false; + } + else { + respTimes++; + return true; + } + } + else { + respTimes = 0; + return true; + } +} + +int BlinkerPRO::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerPRO::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerPRO::pubHello() +{ + char stateJsonStr[256] = ("{\"message\":\"Registration successful\"}"); + + BLINKER_LOG_ALL(BLINKER_F("PUB hello: "), stateJsonStr); + + return print(stateJsonStr, false); +} + +int BlinkerPRO::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(STRING_format(data)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG("Print data is not Json! ", data); + return false; + } + + return true; +} + +#endif + +#endif diff --git a/blinker-library/src/Adapters/BlinkerPROAIR202.h b/blinker-library/src/Adapters/BlinkerPROAIR202.h new file mode 100644 index 0000000..7559b95 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerPROAIR202.h @@ -0,0 +1,1439 @@ +#ifndef BLINKER_PRO_AIR202_H +#define BLINKER_PRO_AIR202_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" +#include "../Functions/BlinkerHTTPAIR202.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +#include "../Functions/BlinkerMQTTAIR202.h" + +#include + +char* MQTT_HOST_GPRS; +char* MQTT_ID_GPRS; +char* MQTT_NAME_GPRS; +char* MQTT_KEY_GPRS; +char* MQTT_PRODUCTINFO_GPRS; +char* UUID_GPRS; +char* AUTHKEY_GPRS; +char* MQTT_DEVICEID_GPRS; +// char* DEVICE_NAME_GPRS; +char* BLINKER_PUB_TOPIC_GPRS; +char* BLINKER_SUB_TOPIC_GPRS; +uint16_t MQTT_PORT_GPRS; + +BlinkerMQTTAIR202* mqtt_GPRS; + +class BlinkerProAIR202 : public BlinkerStream +{ + public : + BlinkerProAIR202() + : stream(NULL), isConnect(false) + {} + + int connect(); + int connected(); + int mConnected(); + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + void subscribe(); + // int timedRead(); + char * lastRead() { if (isFresh_GPRS) return msgBuf_GPRS; return ""; } + void flush(); + // int print(const String & s, bool needCheck = true); + int print(char * data, bool needCheck = true); + int toServer(char * data); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + // void aliType(const String & type); + // void duerType(const String & type); + void begin(const char* _deviceType, String _imei); + void initStream(Stream& s, bool state, blinker_callback_t func); + int autoPrint(unsigned long id); + char * deviceName(); + char * authKey() { return AUTHKEY_GPRS; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_GPRS; } + int init() { return isMQTTinit; } + int reRegister() { return connectServer(); } + int deviceRegister() { return connectServer(); } + int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + private : + bool isMQTTinit = false; + + int connectServer(); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + + protected : + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + Stream* stream; + // char* streamData; + char* msgBuf_GPRS; + // bool isFresh = false; + bool isFresh_GPRS = false; + bool isConnect; + bool isHWS = false; + char* imei; + // uint8_t respTimes = 0; + // uint32_t respTime = 0; + bool isAvail_GPRS = false; + uint8_t dataFrom_GPRS = BLINKER_MSG_FROM_MQTT; + + // uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + const char* _deviceType; + // char* _aliType; + // char* _duerType; + bool isAlive = false; + // bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + char* mqtt_broker; + + bool isNew = false; + bool isAuth = false; + bool isFirst = false; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; + blinker_callback_t listenFunc = NULL; +}; + +int BlinkerProAIR202::connect() +{ + if (!isMQTTinit) return false; + + if (mqtt_GPRS->connected()) return true; + + disconnect(); + + if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + { + yield(); + return false; + } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!mqtt_GPRS->connect()) + { + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + reRegister(); + reconnect_time = 0; + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + this->latestTime = millis(); + + return true; +} + +int BlinkerProAIR202::connected() +{ + if (!isMQTTinit) return false; + + return mqtt_GPRS->connected(); +} + +int BlinkerProAIR202::mConnected() +{ + if (!isMQTTinit) return false; + else return mqtt_GPRS->connected(); +} + +void BlinkerProAIR202::disconnect() +{ + if (isMQTTinit) mqtt_GPRS->disconnect(); +} + +void BlinkerProAIR202::ping() +{ + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!isMQTTinit) return; + + if (!mqtt_GPRS->connected()) + { + disconnect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } +} + +int BlinkerProAIR202::available() +{ + if (isMQTTinit) { + checkKA(); + + // if (!mqtt_PRO->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > 30000) + { + ping(); + } + else + { + subscribe(); + } + } + + if (isAvail_GPRS) + { + isAvail_GPRS = false; + return true; + } + else { + return false; + } +} + +int BlinkerProAIR202::aligenieAvail() +{ + if (!isMQTTinit) return false; + + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerProAIR202::duerAvail() +{ + if (!isMQTTinit) return false; + + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +void BlinkerProAIR202::subscribe() +{ + if (!isMQTTinit) return; + + if (mqtt_GPRS->readSubscription()) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), mqtt_GPRS->lastRead); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(String(mqtt_GPRS->lastRead)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, String(mqtt_GPRS->lastRead)); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"]; + String dataGet = root["data"]; + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_GPRS) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_GPRS = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT) + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_GPRS = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + check is from bridge/share device, \ + data: "), dataGet); + + _needCheckShare = true; + } + } + } + // root.printTo(dataGet); + serializeJson(root, dataGet); + + isAvail_GPRS = true; + isAlive = true; + } + + if (isFresh_GPRS) free(msgBuf_GPRS); + msgBuf_GPRS = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_GPRS, dataGet.c_str()); + isFresh_GPRS = true; + + this->latestTime = millis(); + + dataFrom_GPRS = BLINKER_MSG_FROM_MQTT; + } +} + +void BlinkerProAIR202::flush() +{ + if (isFresh_GPRS) + { + free(msgBuf_GPRS); isFresh_GPRS = false; isAvail_GPRS = false; + isAliAvail = false; //isBavail = false; + } +} + +int BlinkerProAIR202::print(char * data, bool needCheck) +{ + if (!isMQTTinit) return false; + + BLINKER_LOG_ALL(BLINKER_F("data: "), data); + + uint16_t num = strlen(data); + + data[num+8] = '\0'; + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+7] = data[c_num-1]; + } + + // String data_add = BLINKER_F("{\"data\":"); + char data_add[20] = "{\"data\":"; + for(uint16_t c_num = 0; c_num < 8; c_num++) + { + data[c_num] = data_add[c_num]; + } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, ",\"fromDevice\":\""); + strcat(data, MQTT_DEVICEID_GPRS); + // strcat(data, MQTT_DEVICEID_GPRS); //PRO + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, "\",\"toDevice\":\""); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + strcat(data, _sharers[_sharerFrom]->uuid()); + } + else + { + strcat(data, UUID_GPRS); + } + // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // strcat(data, data_add.c_str()); + strcat(data, "\",\"deviceType\":\"OwnApp\"}"); + + // data_add = STRING_format(data); + + if (!isJson(STRING_format(data))) return false; + + // data_add.replace("\"", "\\22"); + // strcpy(data, data_add.c_str()); + uint16_t d_data_len; + + for (uint16_t d_num = 0; d_num < 1024; d_num++) + { + if (data[d_num] == '\"') + { + data[d_num] = '\\'; + d_data_len = strlen(data); + + // BLINKER_LOG_ALL(BLINKER_F("d_num: "), d_num, + // BLINKER_F(", d_data_len: "), d_data_len); + + for(uint16_t c_num = d_data_len; c_num > d_num; c_num--) + { + data[c_num + 2] = data[c_num]; + } + data[d_num + 1] = '2'; + data[d_num + 2] = '2'; + } + } + + // #if defined(ESP8266) + // data_add = ""; + // #endif + + // if (!isJson(STRING_format(data)) return false; + + // strcpy(data, STRING_format(data).replace("\"", "\\22").c_str()); + + // String msg_data = STRING_format(data); + + // msg_data.replace("\"", "\\22"); + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (mqtt_GPRS->connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + // if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, msg_data.c_str())) + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerProAIR202::toServer(char * data) +{ + if (!isMQTTinit) return false; + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish to server...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (mqtt_GPRS->connected()) + { + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerProAIR202::bPrint(char * name, const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_GPRS); + strcat(data_add, ",\"toDevice\":\""); + strcat(data_add, name); + strcat(data_add, "\",\"deviceType\":\"DiyBridge\"}"); + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\""); + // data_add += name; + // data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_GPRS->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_GPRS); + + // if (! iotPub.publish(payload.c_str())) { + + // String bPubTopic = BLINKER_F(""); + // char bPubTopic[60] = { '\0' }; + + // if (strcmp(mqtt_broker, BLINKER_MQTT_BORKER_ONENET) == 0) + // { + // // bPubTopic = MQTT_PRODUCTINFO_MQTT; + // // bPubTopic += BLINKER_F("/"); + // // bPubTopic += name; + // // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // strcpy(bPubTopic, BLINKER_PUB_TOPIC_GPRS); + // bPubTopic = BLINKER_PUB_TOPIC_GPRS; + // } + + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerProAIR202::aliPrint(const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_DEVICEID_GPRS); + strcat(data_add, "\",\"toDevice\":\"AliGenie_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_GPRS->connected()) + { + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerProAIR202::duerPrint(const String & data, bool report) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_DEVICEID_GPRS); + strcat(data_add, "\",\"toDevice\":\"DuerOS_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_GPRS->connected()) + { + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// void BlinkerProAIR202::aliType(const String & type) +// { +// _aliType = (char*)malloc((type.length()+1)*sizeof(char)); +// strcpy(_aliType, type.c_str()); +// BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +// } + +// void BlinkerProAIR202::duerType(const String & type) +// { +// _duerType = (char*)malloc((type.length()+1)*sizeof(char)); +// strcpy(_duerType, type.c_str()); +// BLINKER_LOG_ALL(BLINKER_F("_duerType: "), _duerType); +// } + +void BlinkerProAIR202::begin(const char* _type, String _imei) +{ + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + // stream = &s; + // stream->setTimeout(BLINKER_STREAM_TIMEOUT); + // isHWS = state; + + imei = (char*)malloc((_imei.length() + 1)*sizeof(char)); + strcpy(imei, _imei.c_str()); + + // AUTHKEY_GPRS = (char*)malloc((strlen(_deviceType) + 1)*sizeof(char)); + // strcpy(AUTHKEY_GPRS, _deviceType); +} + +void BlinkerProAIR202::initStream(Stream& s, bool state, blinker_callback_t func) +{ + // _deviceType = _type; + + // BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + stream = &s; + stream->setTimeout(BLINKER_STREAM_TIMEOUT); + isHWS = state; + + listenFunc = func; + + // _imei = (char*)malloc(imei.length()*sizeof(char)); + // strcpy(_imei, imei.c_str()); +} + +int BlinkerProAIR202::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"trigged\":true,\"autoData\":{"); + payload += BLINKER_F("\"autoId\":"); + payload += STRING_format(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(MQTT_DEVICEID_GPRS); + payload += BLINKER_F("\",\"toDevice\":\"autoManager\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_GPRS->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_GPRS); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +char * BlinkerProAIR202::deviceName() { return MQTT_DEVICEID_GPRS;/*MQTT_ID_PRO;*/ } + +void BlinkerProAIR202::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (uint8_t num = _sharerCount; num > 0; num--) + { + delete _sharers[num - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerProAIR202::authCheck() +{ + uint8_t _authCheck; + + BLINKER_LOG_ALL(BLINKER_F("authCheck start")); + + #if defined(ESP8266) || defined(ESP32) + EEPROM.begin(BLINKER_EEP_SIZE); + #endif + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck == BLINKER_AUTH_CHECK_DATA) + { + #if defined(ESP8266) || defined(ESP32) + EEPROM.commit(); + EEPROM.end(); + #endif + isAuth = true; + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return true; + } + #if defined(ESP8266) || defined(ESP32) + EEPROM.commit(); + EEPROM.end(); + #endif + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return false; +} + +int BlinkerProAIR202::connectServer() +{ + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + String uri = ""; + uri += BLINKER_F("/api/v1/user/device/register?deviceType="); + uri += _deviceType; + uri += BLINKER_F("&deviceName="); + // uri += imei; + if (_deviceType != BLINKER_AIR_STATION) + { + // url_iot += macDeviceName(); + uri += imei; + } + else + { + // uri += "TESTA69BA016"; // 1 + // uri += "TEST656A2782"; // 2 + // uri += "TESTD1C4B294"; // 3 + // uri += "TEST687991DC"; // 4 + uri += "TEST872B3982"; // 5 + } + // uri += BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + // uri += _deviceType; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host + uri); + + BlinkerHTTPAIR202 http(*stream, isHWS, listenFunc); + + http.begin(host, uri); + + String payload; + + if (http.GET()) + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... success")); + + payload = http.getString(); + + // return true; + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed")); + + return false; + } + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + String _authKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_KEY]; + + if (isMQTTinit) + { + free(MQTT_HOST_GPRS); + free(MQTT_ID_GPRS); + free(MQTT_NAME_GPRS); + free(MQTT_KEY_GPRS); + free(MQTT_PRODUCTINFO_GPRS); + free(UUID_GPRS); + free(AUTHKEY_GPRS); + // free(DEVICE_NAME_GPRS); + free(BLINKER_PUB_TOPIC_GPRS); + free(BLINKER_SUB_TOPIC_GPRS); + free(mqtt_GPRS); + // free(iotSub_GPRS); + + isMQTTinit = false; + } + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); + MQTT_DEVICEID_GPRS = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_GPRS, _userID.c_str()); + MQTT_ID_GPRS = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_GPRS, _userID.c_str()); + MQTT_NAME_GPRS = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_GPRS, _userName.c_str()); + MQTT_KEY_GPRS = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_GPRS, _key.c_str()); + MQTT_PRODUCTINFO_GPRS = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_GPRS, _productInfo.c_str()); + MQTT_HOST_GPRS = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_GPRS, BLINKER_MQTT_ALIYUN_HOST); + AUTHKEY_GPRS = (char*)malloc((_authKey.length()+1)*sizeof(char)); + strcpy(AUTHKEY_GPRS, _authKey.c_str()); + MQTT_PORT_GPRS = BLINKER_MQTT_ALIYUN_PORT; + } + + UUID_GPRS = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_GPRS, _uuid.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME_GPRS: "), imei); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_GPRS: "), MQTT_PRODUCTINFO_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_DEVICEID_GPRS: "), MQTT_DEVICEID_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_GPRS: "), MQTT_ID_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_GPRS: "), MQTT_NAME_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_GPRS: "), MQTT_KEY_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_GPRS); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_GPRS); + BLINKER_LOG_ALL(BLINKER_F("UUID_GPRS: "), UUID_GPRS); + BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_GPRS: "), AUTHKEY_GPRS); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_GPRS; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_DEVICEID_GPRS; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_GPRS = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_GPRS, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_GPRS, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_GPRS: "), BLINKER_PUB_TOPIC_GPRS); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_GPRS; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_ID_GPRS; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_GPRS = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_GPRS, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_GPRS, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_GPRS: "), BLINKER_SUB_TOPIC_GPRS); + } + + // String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + // String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + // String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + // String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + // String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + // String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + // String _authKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_KEY]; + + // if (isMQTTinit) + // { + // free(MQTT_HOST_GPRS); + // free(MQTT_ID_GPRS); + // free(MQTT_NAME_GPRS); + // free(MQTT_KEY_GPRS); + // free(MQTT_PRODUCTINFO_GPRS); + // free(UUID_GPRS); + // free(AUTHKEY_GPRS); + // free(MQTT_DEVICEID_GPRS); + // free(BLINKER_PUB_TOPIC_GPRS); + // free(BLINKER_SUB_TOPIC_GPRS); + // free(mqtt_GPRS); + + // isMQTTinit = false; + // } + + // BLINKER_LOG_ALL(("====================")); + + // // if (_broker == "BLINKER_MQTT_BORKER_ALIYUN") { + // // memcpy(DEVICE_NAME, _userID.c_str(), 12); + // String _deviceName = _userID.substring(12, 36); + // MQTT_DEVICEID_GPRS = (char*)malloc((_deviceName.length()+1)*sizeof(char)); + // strcpy(MQTT_DEVICEID_GPRS, _deviceName.c_str()); + // MQTT_ID_GPRS = (char*)malloc((_userID.length()+1)*sizeof(char)); + // strcpy(MQTT_ID_GPRS, _userID.c_str()); + // MQTT_NAME_GPRS = (char*)malloc((_userName.length()+1)*sizeof(char)); + // strcpy(MQTT_NAME_GPRS, _userName.c_str()); + // MQTT_KEY_GPRS = (char*)malloc((_key.length()+1)*sizeof(char)); + // strcpy(MQTT_KEY_GPRS, _key.c_str()); + // MQTT_PRODUCTINFO_GPRS = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + // strcpy(MQTT_PRODUCTINFO_GPRS, _productInfo.c_str()); + // MQTT_HOST_GPRS = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + // strcpy(MQTT_HOST_GPRS, BLINKER_MQTT_ALIYUN_HOST); + // AUTHKEY_GPRS = (char*)malloc((_authKey.length()+1)*sizeof(char)); + // strcpy(AUTHKEY_GPRS, _authKey.c_str()); + // MQTT_PORT_GPRS = BLINKER_MQTT_ALIYUN_PORT; + + // BLINKER_LOG_ALL(("====================")); + // // } + + // UUID_GPRS = (char*)malloc((_uuid.length()+1)*sizeof(char)); + // strcpy(UUID_GPRS, _uuid.c_str()); + + char uuid_eeprom[BLINKER_AUUID_SIZE]; + + BLINKER_LOG_ALL(("==========AUTH CHECK==========")); + + if (!isFirst) + { + char _authCheck; + + #if defined(ESP8266) || defined(ESP32) + EEPROM.begin(BLINKER_EEP_SIZE); + #endif + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + if (strcmp(uuid_eeprom, _uuid.c_str()) != 0) { + // strcpy(UUID_PRO, _uuid.c_str()); + + strcpy(uuid_eeprom, _uuid.c_str()); + EEPROM.put(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("uuid_eeprom: "), uuid_eeprom); + BLINKER_LOG_ALL(BLINKER_F("_uuid: "), _uuid); + isNew = true; + } + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck != BLINKER_AUTH_CHECK_DATA) { + EEPROM.put(BLINKER_EEP_ADDR_AUTH_CHECK, BLINKER_AUTH_CHECK_DATA); + isAuth = true; + } + #if defined(ESP8266) || defined(ESP32) + EEPROM.commit(); + EEPROM.end(); + #endif + + isFirst = true; + } + + // BLINKER_LOG_ALL(BLINKER_F("====================")); + // BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME: "), imei); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_GPRS: "), MQTT_PRODUCTINFO_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_DEVICEID_GPRS: "), MQTT_DEVICEID_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_GPRS: "), MQTT_ID_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_GPRS: "), MQTT_NAME_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_GPRS: "), MQTT_KEY_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + // BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("UUID_GPRS: "), UUID_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_GPRS: "), AUTHKEY_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("====================")); + + // // if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // String PUB_TOPIC_STR = BLINKER_F("/"); + // PUB_TOPIC_STR += MQTT_PRODUCTINFO_GPRS; + // PUB_TOPIC_STR += BLINKER_F("/"); + // PUB_TOPIC_STR += MQTT_DEVICEID_GPRS; + // PUB_TOPIC_STR += BLINKER_F("/s"); + + // BLINKER_PUB_TOPIC_GPRS = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // strcpy(BLINKER_PUB_TOPIC_GPRS, PUB_TOPIC_STR.c_str()); + + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_GPRS: "), BLINKER_PUB_TOPIC_GPRS); + + // String SUB_TOPIC_STR = BLINKER_F("/"); + // SUB_TOPIC_STR += MQTT_PRODUCTINFO_GPRS; + // SUB_TOPIC_STR += BLINKER_F("/"); + // SUB_TOPIC_STR += MQTT_DEVICEID_GPRS; + // SUB_TOPIC_STR += BLINKER_F("/r"); + + // BLINKER_SUB_TOPIC_GPRS = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // strcpy(BLINKER_SUB_TOPIC_GPRS, SUB_TOPIC_STR.c_str()); + + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_GPRS: "), BLINKER_SUB_TOPIC_GPRS); + // // } + + // if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + mqtt_GPRS = new BlinkerMQTTAIR202(*stream, isHWS, MQTT_HOST_GPRS, MQTT_PORT_GPRS, + MQTT_ID_GPRS, MQTT_NAME_GPRS, MQTT_KEY_GPRS, listenFunc); + // } + + this->latestTime = millis(); + isMQTTinit = true; + mqtt_GPRS->subscribe(BLINKER_SUB_TOPIC_GPRS); + + return true; +} + +void BlinkerProAIR202::checkKA() +{ + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerProAIR202::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerProAIR202::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerProAIR202::checkCanPrint() { + if ((millis() - printTime >= BLINKER_PRO_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerProAIR202::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerProAIR202::checkPrintSpan() +{ + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) + { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG(BLINKER_F("DEVICE NOT CONNECT OR MSG LIMIT")); + + return false; + } + else + { + respTimes++; + return true; + } + } + else + { + respTimes = 0; + return true; + } +} + +int BlinkerProAIR202::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerProAIR202::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerProAIR202::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG("Print data is not Json! ", data); + return false; + } + return true; +} + +#endif diff --git a/blinker-library/src/Adapters/BlinkerPROESP.h b/blinker-library/src/Adapters/BlinkerPROESP.h new file mode 100644 index 0000000..801fe67 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerPROESP.h @@ -0,0 +1,3608 @@ +#ifndef BLINKER_PRO_ESP_H +#define BLINKER_PRO_ESP_H + +#if (defined(ESP8266) || defined(ESP32)) + +#if defined(ESP8266) + #include + #include + #include + + #include +#elif defined(ESP32) + #include + + #if defined(ESP32) + extern "C" { + #include + #include + #include + } + #endif + + #include + #include + + #include +#endif + +#include + +#include "../modules/WebSockets/WebSocketsServer.h" +#include "../modules/mqtt/Adafruit_MQTT.h" +#include "../modules/mqtt/Adafruit_MQTT_Client.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +// #include "../Adapters/BlinkerPROESP.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +char* MQTT_HOST_PRO; +char* MQTT_ID_PRO; +char* MQTT_NAME_PRO; +char* MQTT_KEY_PRO; +char* MQTT_PRODUCTINFO_PRO; +char* UUID_PRO; +char* AUTHKEY_PRO; +char* MQTT_DEVICEID_PRO; +// char* DEVICE_NAME; +char* BLINKER_PUB_TOPIC_PRO; +char* BLINKER_SUB_TOPIC_PRO; +char* BLINKER_RRPC_SUB_TOPIC_MQTT; +uint16_t MQTT_PORT_PRO; + +enum b_config_t { + BLINKER_SMART_CONFIG, + BLINKER_AP_CONFIG +}; + +enum b_broker_t { + aliyun_b, + blinker_b +}; + +b_config_t _configType = BLINKER_AP_CONFIG; + +class BlinkerPROESP : public BlinkerStream +{ + public : + BlinkerPROESP(); + + void setSmartConfig() { _configType = BLINKER_SMART_CONFIG; BLINKER_LOG_ALL(BLINKER_F("SmartConfig")); } + void setApConfig() { _configType = BLINKER_AP_CONFIG; BLINKER_LOG_ALL(BLINKER_F("ApConfig")); } + bool checkSmartConfig() { return _configType == BLINKER_SMART_CONFIG; } + int connect(); + int connected(); + int mConnected();// { if (!isMQTTinit) return false; else return mqtt->connected(); } + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + int miAvail(); + // bool extraAvailable(); + void subscribe(); + char * lastRead(); + void flush(); + int print(char * data, bool needCheck = true); + int toServer(char * data); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + int miPrint(const String & data); + // void aliType(const String & type); + void begin(const char* _key, const char* _type); + int autoPrint(unsigned long id); + // bool autoPrint(char *name, char *type, char *data); + // bool autoPrint(char *name1, char *type1, char *data1, \ + // char *name2, char *type2, char *data2); + char * deviceName(); + char * authKey() { return AUTHKEY_PRO; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_PRO; } + int init() + { + // webSocket_PRO.loop(); + + // #if defined(ESP8266) + // MDNS.update(); + // #endif + + return isMQTTinit; + } + int reRegister() { return connectServer(); } + int deviceRegister() { return connectServer(); } + int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + + private : + bool isMQTTinit = false; + bool isWSinit = false; + + int connectServer(); + void mDNSInit(String name = macDeviceName()); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkMIOTKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + int checkMIOTPrintSpan(); + int pubHello(); + void parseData(const char* data); + + protected : + b_broker_t _use_broker = aliyun_b; + char _messageId[20]; + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + const char* _vipKey; + const char* _deviceType; + // char* _authKey; + // char* _aliType; + bool* isHandle;// = &isConnect; + // bool* isHandle = &isConnect_PRO; + bool isAlive = false; + bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + uint8_t respMIOTTimes = 0; + uint32_t respMIOTTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + uint32_t miKaTime = 0; + bool isMIOTAlive = false; + bool isMIOTAvail = false; + + bool isNew = false; + bool isAuth = false; + bool isFirst = false; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; + uint32_t _reRegister_time = 0; + uint8_t _reRegister_times = 0; + + bool _isAuthKey = false; + + char message_id[24]; + bool is_rrpc = false; +}; + +// #if defined(ESP8266) +// extern BearSSL::WiFiClientSecure client_mqtt; +// // WiFiClientSecure client_mqtt; +// #elif defined(ESP32) +// extern WiFiClientSecure client_s; +// #endif + +// extern WiFiClient client; + + +#if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + BearSSL::WiFiClientSecure client_mqtt; + #else + WiFiClient client_mqtt; + #endif + // WiFiClientSecure client_mqtt; +#elif defined(ESP32) + WiFiClientSecure client_s; +#endif + +#define BLINKER_PROTOCOL_MQTT mqtt_PRO + +WiFiClient client; +Adafruit_MQTT_Client* mqtt_PRO = NULL; +// Adafruit_MQTT_Publish *iotPub; +Adafruit_MQTT_Subscribe* iotSub_PRO; + +#define WS_SERVERPORT 81 +WebSocketsServer webSocket_PRO = WebSocketsServer(WS_SERVERPORT); + +char* msgBuf_PRO; +bool isFresh_PRO = false; +bool isConnect_PRO = false; +bool isAvail_PRO = false; +bool isApCfg = false; +uint8_t ws_num_PRO = 0; +uint8_t dataFrom_PRO = BLINKER_MSG_FROM_MQTT; + +void webSocketEvent_PRO(uint8_t num, WStype_t type, \ + uint8_t * payload, size_t length) +{ + + switch(type) + { + case WStype_DISCONNECTED: + BLINKER_LOG_ALL(BLINKER_F("Disconnected! "), num); + + isConnect_PRO = false; + break; + case WStype_CONNECTED: + { + IPAddress ip = webSocket_PRO.remoteIP(num); + + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", Connected from: "), ip, + BLINKER_F(", url: "), (char *)payload); + + // send message to client + webSocket_PRO.sendTXT(num, "{\"state\":\"connected\"}\n"); + + ws_num_PRO = num; + + if (!isApCfg) isConnect_PRO = true; + } + break; + case WStype_TEXT: + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", get Text: "), (char *)payload, \ + BLINKER_F(", length: "), length); + + if (length < BLINKER_MAX_READ_SIZE) { + if (isFresh_PRO) free(msgBuf_PRO); + msgBuf_PRO = (char*)malloc((length+1)*sizeof(char)); + strcpy(msgBuf_PRO, (char*)payload); + isAvail_PRO = true; + isFresh_PRO = true; + } + + if (!isApCfg) isConnect_PRO = true; + + if (!isApCfg) dataFrom_PRO = BLINKER_MSG_FROM_WS; + + ws_num_PRO = num; + + // BLINKER_LOG_ALL(BLINKER_F("isConnect_PRO: "), isConnect_PRO); + + // send message to client + // webSocket_PRO.sendTXT(num, "message here"); + + // send data to all connected clients + // webSocket_PRO.broadcastTXT("message here"); + break; + case WStype_BIN: + // BLINKER_LOG("num: ", num, " get binary length: ", length); + // hexdump(payload, length); + + // send message to client + // webSocket_PRO.sendBIN(num, payload, length); + break; + } +} + +BlinkerPROESP::BlinkerPROESP() { isHandle = &isConnect_PRO; } + +int BlinkerPROESP::connect() +{ + int8_t ret; + +#if defined(ESP8266) + MDNS.update(); +#endif + + webSocket_PRO.loop(); + + if (!isMQTTinit) { + return *isHandle; + } + + if (mqtt_PRO->connected()) + { + return true; + } + + disconnect(); + + if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + { + yield(); + return false; + } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + client_mqtt.setInsecure(); + ::delay(10); + #endif + #endif + + BLINKER_LOG_FreeHeap_ALL(); + + if ((ret = mqtt_PRO->connect()) != 0) + { + BLINKER_LOG(mqtt_PRO->connectErrorString(ret)); + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + if (ret == 4) + { + if (_reRegister_times < BLINKER_SERVER_CONNECT_LIMIT) + { + if (reRegister()) + { + _reRegister_times = 0; + } + else + { + _reRegister_times++; + _reRegister_time = millis(); + } + } + else + { + if (millis() - _reRegister_time >= 60000 * 5) _reRegister_times = 0; + } + + BLINKER_LOG_ALL(BLINKER_F("_reRegister_times: "), _reRegister_times); + } + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + if (_reRegister_times < BLINKER_SERVER_CONNECT_LIMIT) + { + if (reRegister()) + { + _reRegister_times = 0; + } + else + { + _reRegister_times++; + _reRegister_time = millis(); + } + } + else + { + if (millis() - _reRegister_time >= 60000 * 5) _reRegister_times = 0; + } + + reconnect_time = 0; + + BLINKER_LOG_ALL(BLINKER_F("_reRegister_times: "), _reRegister_times); + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + if (isNew) + { + if (pubHello()) { + isNew = false; + } + } + + this->latestTime = millis(); + + return true; +} + +int BlinkerPROESP::connected() +{ + if (!isMQTTinit) + { + return *isHandle; + } + + return mqtt_PRO->connected() || *isHandle; +} + +int BlinkerPROESP::mConnected() +{ + if (!isMQTTinit) return false; + else return mqtt_PRO->connected(); +} + +void BlinkerPROESP::disconnect() +{ + if (isMQTTinit) mqtt_PRO->disconnect(); + + if (*isHandle) webSocket_PRO.disconnect(); +} + +void BlinkerPROESP::ping() +{ + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!isMQTTinit) return; + + if (!mqtt_PRO->ping()) + { + disconnect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } +} + +int BlinkerPROESP::available() +{ +#if defined(ESP8266) + MDNS.update(); +#endif + + // BLINKER_LOG("CHECK available"); + + delay(1); + + webSocket_PRO.loop(); + + if (isMQTTinit) { + checkKA(); + + // if (!mqtt_PRO->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + { + ping(); + } + else + { + subscribe(); + } + } + + if (isAvail_PRO) + { + isAvail_PRO = false; + return true; + } + else { + return false; + } +} + +int BlinkerPROESP::aligenieAvail() +{ + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerPROESP::duerAvail() +{ + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerPROESP::miAvail() +{ + if (isMIOTAvail) + { + isMIOTAvail = false; + return true; + } + else { + return false; + } +} + +// bool BlinkerPROESP::extraAvailable() +// { +// if (isBavail) +// { +// isBavail = false; +// return true; +// } +// else +// { +// return false; +// } +// } + +void BlinkerPROESP::subscribe() +{ + if (!isMQTTinit) return; + + Adafruit_MQTT_Subscribe *subscription; + while ((subscription = mqtt_PRO->readSubscription(10))) + { + if (subscription == iotSub_PRO) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), (char *)iotSub_PRO->lastread); + + parseData((char *)iotSub_PRO->lastread); + // // DynamicJsonBuffer jsonBuffer; + // // JsonObject& root = jsonBuffer.parseObject(String((char *)iotSub_PRO->lastread)); + // DynamicJsonDocument jsonBuffer(1024); + // DeserializationError error = deserializeJson(jsonBuffer, String((char *)iotSub_PRO->lastread)); + // JsonObject root = jsonBuffer.as(); + + // String _uuid = root["fromDevice"]; + // String dataGet = root["data"]; + + // BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + // BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + // if (strcmp(_uuid.c_str(), UUID_PRO) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + // kaTime = millis(); + // isAvail_PRO = true; + // isAlive = true; + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // } + // else if (_uuid == BLINKER_CMD_ALIGENIE) + // { + // BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + // aliKaTime = millis(); + // isAliAlive = true; + // isAliAvail = true; + // } + // else if (_uuid == BLINKER_CMD_DUEROS) + // { + // BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + // duerKaTime = millis(); + // isDuerAlive = true; + // isDuerAvail = true; + // } + // else if (_uuid == BLINKER_CMD_MIOT) + // { + // BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + // miKaTime = millis(); + // isMIOTAlive = true; + // isMIOTAvail = true; + // } + // else if (_uuid == BLINKER_CMD_SERVERCLIENT) + // { + // BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + // isAvail_PRO = true; + // isAlive = true; + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // } + // else + // { + // if (_sharerCount) + // { + // for (uint8_t num = 0; num < _sharerCount; num++) + // { + // if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + // { + // _sharerFrom = num; + + // kaTime = millis(); + + // BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + // BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + // _needCheckShare = false; + + // break; + // } + // else + // { + // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found," + // "check is from bridge/share device," + // "data: "), dataGet); + + // _needCheckShare = true; + // } + // } + // } + + // // { + // // dataGet = String((char *)iotSub_PRO->lastread); + // // root.printTo(dataGet); + // serializeJson(root, dataGet); + + // // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + // // check is from bridge/share device, \ + // // data: "), dataGet); + + // // // return; + + // // // isBavail = true; + + // // _needCheckShare = true; + // // } + + // isAvail_PRO = true; + // isAlive = true; + // } + + // memset(msgBuf_PRO, 0, BLINKER_MAX_READ_SIZE); + // memcpy(msgBuf_PRO, dataGet.c_str(), dataGet.length()); + + // if (isFresh_PRO) free(msgBuf_PRO); + // msgBuf_PRO = (char*)malloc((dataGet.length()+1)*sizeof(char)); + // strcpy(msgBuf_PRO, dataGet.c_str()); + // isFresh_PRO = true; + + // this->latestTime = millis(); + + // dataFrom_PRO = BLINKER_MSG_FROM_MQTT; + } + } + + if (mqtt_PRO->check_extra()) + { + BLINKER_LOG_ALL(BLINKER_F("Got extra topic: "), (char *)mqtt_PRO->get_extra_topic()); + BLINKER_LOG_ALL(BLINKER_F("Got extra data: "), (char *)mqtt_PRO->get_extra_data()); + + if (strncmp(BLINKER_RRPC_SUB_TOPIC_MQTT, + (char *)mqtt_PRO->get_extra_topic(), + strlen(BLINKER_RRPC_SUB_TOPIC_MQTT)) + == 0) + { + // char message_id[24]; + memset(message_id, '\0', 24); + + memmove(message_id, + mqtt_PRO->get_extra_topic()+strlen(BLINKER_RRPC_SUB_TOPIC_MQTT), + strlen(mqtt_PRO->get_extra_topic()) - strlen(BLINKER_RRPC_SUB_TOPIC_MQTT)); + + BLINKER_LOG_ALL(BLINKER_F("from server RRPC, message_id: "), message_id); + + parseData((char *)mqtt_PRO->get_extra_data()); + + // char BLINKER_RRPC_PUB_TOPIC_MQTT[128]; + + // strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, "/sys/"); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_PRODUCTINFO_PRO); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/"); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_DEVICEID_PRO); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/rrpc/response/"); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, message_id); + + is_rrpc = true; + + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_RRPC_PUB_TOPIC_MQTT: "), BLINKER_RRPC_PUB_TOPIC_MQTT); + + // mqtt_PRO->publish(BLINKER_RRPC_PUB_TOPIC_MQTT, base64::encode("hello blinker").c_str()); + } + } +} + +void BlinkerPROESP::parseData(const char* data) +{ + DynamicJsonDocument jsonBuffer(1024); + deserializeJson(jsonBuffer, String(data)); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"].as(); + String dataGet = root["data"].as(); + + if (_use_broker == blinker_b) + { + if (_uuid == "ServerSender") + { + _uuid = root["data"]["from"].as(); + String _mId = root["data"]["messageId"].as(); + strcpy(_messageId, _mId.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_messageId: "), _mId); + } + } + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_PRO) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_PRO = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_MIOT) + { + BLINKER_LOG_ALL(BLINKER_F("form MIOT")); + + miKaTime = millis(); + isMIOTAlive = true; + isMIOTAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT) + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_PRO = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, check is from bridge/share device, data: "), dataGet); + + _needCheckShare = true; + dataGet = data; + } + } + } + else + { + dataGet = data; + } + // dataGet = String((char *)iotSub_PRO->lastread); + // root.printTo(dataGet); + // serializeJson(root, dataGet); + + // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, + // check is from bridge/share device, \ + // data: "), dataGet); + + // // return; + + // // isBavail = true; + + // _needCheckShare = true; + // } + + isAvail_PRO = true; + isAlive = true; + } + + // memset(msgBuf_PRO, 0, BLINKER_MAX_READ_SIZE); + // memcpy(msgBuf_PRO, dataGet.c_str(), dataGet.length()); + + if (isFresh_PRO) free(msgBuf_PRO); + msgBuf_PRO = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_PRO, dataGet.c_str()); + isFresh_PRO = true; + + this->latestTime = millis(); + + dataFrom_PRO = BLINKER_MSG_FROM_MQTT; +} + +char * BlinkerPROESP::lastRead() +{ + if (isFresh_PRO) return msgBuf_PRO; + return ""; +} + +void BlinkerPROESP::flush() +{ + if (isFresh_PRO) + { + free(msgBuf_PRO); isFresh_PRO = false; isAvail_PRO = false; + isAliAvail = false; isDuerAvail = false; isMIOTAvail = false;//isBavail = false; + } +} + +int BlinkerPROESP::print(char * data, bool needCheck) +// int BlinkerPROESP::print(const String & data, bool needCheck) +{ + // BLINKER_LOG_FreeHeap(); + if (*isHandle && dataFrom_PRO == BLINKER_MSG_FROM_WS) + { + if (needCheck) + { + if (!checkPrintSpan()) + { + respTime = millis(); + return false; + } + } + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("WS response: ")); + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + strcat(data, BLINKER_CMD_NEWLINE); + + webSocket_PRO.sendTXT(ws_num_PRO, data); + + return true; + } + else + { + // // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // uint8_t num = strlen(data) - 1; + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data.substring(0, data.length() - 1); + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_DEVICEID_PRO; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_PRO; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + // else + // { + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data; + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_DEVICEID_PRO; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_PRO; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + + uint16_t num = strlen(data); + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+7] = data[c_num-1]; + } + + data[num+8] = '\0'; + + String data_add = BLINKER_F("{\"data\":"); + + for(uint16_t c_num = 0; c_num < 8; c_num++) + { + data[c_num] = data_add[c_num]; + } + + data_add = BLINKER_F(",\"fromDevice\":\""); + strcat(data, data_add.c_str()); + strcat(data, MQTT_DEVICEID_PRO); + data_add = BLINKER_F("\",\"toDevice\":\""); + strcat(data, data_add.c_str()); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + strcat(data, _sharers[_sharerFrom]->uuid()); + } + else + { + strcat(data, UUID_PRO); + } + data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + strcat(data, data_add.c_str()); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + if (!isJson(STRING_format(data))) return false; + + // String data_add = BLINKER_F("{\"data\":"); + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_DEVICEID_PRO; + // data_add += BLINKER_F("\",\"toDevice\":\""); + // if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + // { + // data_add += _sharers[_sharerFrom]->uuid(); + // } + // else + // { + // data_add += UUID_PRO; + // } + + // data_add += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + // if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (mqtt_PRO->connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } + } +} + +int BlinkerPROESP::toServer(char * data) +{ + // if (!checkInit()) return false; + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish to server...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (mqtt_PRO->connected()) + { + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerPROESP::bPrint(char * name, const String & data) +{ + // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data.substring(0, data.length() - 1); + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_DEVICEID_PRO; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + // else + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data; + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_DEVICEID_PRO; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + + String data_add = BLINKER_F("{\"data\":"); + // for(uint8_t c_num = 0; c_num < 8; c_num++) + // { + // data[c_num] = data_add[c_num]; + // } + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\""); + data_add += name; + data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, MQTT_DEVICEID_PRO); + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, name); + // data_add = BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // strcat(data, data_add.c_str()); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_PRO->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + + // if (! iotPub.publish(payload.c_str())) { + + // String bPubTopic = BLINKER_F(""); + + // if (mqtt_broker == BLINKER_MQTT_BORKER_ONENET) + // { + // bPubTopic = MQTT_PRODUCTINFO_PRO; + // bPubTopic += BLINKER_F("/"); + // bPubTopic += name; + // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // bPubTopic = BLINKER_PUB_TOPIC_PRO; + // } + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerPROESP::aliPrint(const String & data) +{ + String data_add = BLINKER_F("{\"data\":"); + + if (_use_broker == aliyun_b) + { + data_add += data; + } + else if (_use_broker == blinker_b) + { + data_add += data.substring(0, data.length() - 1); + data_add += BLINKER_F(",\"messageId\":\""); + data_add += STRING_format(_messageId); + data_add += BLINKER_F("\"}"); + } + + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + + if (_use_broker == aliyun_b) + { + data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + } + else if (_use_broker == blinker_b) + { + data_add += BLINKER_F("\",\"toDevice\":\"ServerReceiver\""); + } + + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + + // if (! iotPub.publish(payload.c_str())) { + + + char BLINKER_RRPC_PUB_TOPIC_MQTT[128]; + + if (is_rrpc) + { + + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, "/sys/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_PRODUCTINFO_PRO); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_DEVICEID_PRO); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/rrpc/response/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, message_id); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_RRPC_PUB_TOPIC_MQTT: "), BLINKER_RRPC_PUB_TOPIC_MQTT); + } + else + { + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, BLINKER_PUB_TOPIC_PRO); + } + + is_rrpc = false; + + char send_data[1024]; + + if (_use_broker == aliyun_b) + { + strcpy(send_data, base64::encode(data_add).c_str()); + } + else if (_use_broker == blinker_b) + { + strcpy(send_data, data_add.c_str()); + } + + if (! mqtt_PRO->publish(BLINKER_RRPC_PUB_TOPIC_MQTT, send_data)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerPROESP::duerPrint(const String & data, bool report) +{ + String data_add = BLINKER_F("{\"data\":"); + + if (report) + { + data_add += BLINKER_F("{\"report\":"); + + if (_use_broker == aliyun_b) + { + data_add += data; + } + else if (_use_broker == blinker_b) + { + data_add += data.substring(0, data.length() - 1); + data_add += BLINKER_F(",\"messageId\":\""); + data_add += STRING_format(_messageId); + data_add += BLINKER_F("\"}"); + } + + data_add += BLINKER_F("}"); + } + else + { + if (_use_broker == aliyun_b) + { + data_add += data; + } + else if (_use_broker == blinker_b) + { + data_add += data.substring(0, data.length() - 1); + data_add += BLINKER_F(",\"messageId\":\""); + data_add += STRING_format(_messageId); + data_add += BLINKER_F("\"}"); + } + } + + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + + if (_use_broker == aliyun_b) + { + data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + } + else if (_use_broker == blinker_b) + { + data_add += BLINKER_F("\",\"toDevice\":\"ServerReceiver\""); + } + + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + + char BLINKER_RRPC_PUB_TOPIC_MQTT[128]; + + if (is_rrpc) + { + + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, "/sys/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_PRODUCTINFO_PRO); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_DEVICEID_PRO); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/rrpc/response/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, message_id); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_RRPC_PUB_TOPIC_MQTT: "), BLINKER_RRPC_PUB_TOPIC_MQTT); + } + else + { + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, BLINKER_PUB_TOPIC_PRO); + } + + char send_data[1024]; + + if (_use_broker == aliyun_b) + { + strcpy(send_data, base64::encode(data_add).c_str()); + } + else if (_use_broker == blinker_b) + { + strcpy(send_data, data_add.c_str()); + } + + if (! mqtt_PRO->publish(BLINKER_RRPC_PUB_TOPIC_MQTT, send_data)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + is_rrpc = false; + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + is_rrpc = false; + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerPROESP::miPrint(const String & data) +{ + String data_add = BLINKER_F("{\"data\":"); + + if (_use_broker == aliyun_b) + { + data_add += data; + } + else if (_use_broker == blinker_b) + { + data_add += data.substring(0, data.length() - 1); + data_add += BLINKER_F(",\"messageId\":\""); + data_add += STRING_format(_messageId); + data_add += BLINKER_F("\"}"); + } + + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + + if (_use_broker == aliyun_b) + { + data_add += BLINKER_F("\",\"toDevice\":\"MIOT_r\""); + } + else if (_use_broker == blinker_b) + { + data_add += BLINKER_F("\",\"toDevice\":\"ServerReceiver\""); + } + + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT MIOT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + + if (!checkMIOTKA()) + { + return false; + } + + if (!checkMIOTPrintSpan()) + { + respMIOTTime = millis(); + return false; + } + respMIOTTime = millis(); + + + char BLINKER_RRPC_PUB_TOPIC_MQTT[128]; + + if (is_rrpc) + { + + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, "/sys/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_PRODUCTINFO_PRO); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_DEVICEID_PRO); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/rrpc/response/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, message_id); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_RRPC_PUB_TOPIC_MQTT: "), BLINKER_RRPC_PUB_TOPIC_MQTT); + } + else + { + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, BLINKER_PUB_TOPIC_PRO); + } + + is_rrpc = false; + + char send_data[1024]; + + if (_use_broker == aliyun_b) + { + strcpy(send_data, base64::encode(data_add).c_str()); + } + else if (_use_broker == blinker_b) + { + strcpy(send_data, data_add.c_str()); + } + + if (! mqtt_PRO->publish(BLINKER_RRPC_PUB_TOPIC_MQTT, send_data)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isMIOTAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isMIOTAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// void BlinkerPROESP::aliType(const String & type) +// { +// _aliType = (char*)malloc((type.length()+1)*sizeof(char)); +// strcpy(_aliType, type.c_str()); +// BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +// } + +void BlinkerPROESP::begin(const char* _key, const char* _type) +{ + _vipKey = _key; + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + mDNSInit(); +} + +int BlinkerPROESP::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"auto\":{\"trig\":true,"); + payload += BLINKER_F("\"id\":"); + payload += String(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(MQTT_DEVICEID_PRO); + payload += BLINKER_F("\",\"deviceType\":\"Auto\""); + payload += BLINKER_F(",\"toDevice\":\"serverClient\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_PRO->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// bool BlinkerPROESP::autoPrint(char *name, char *type, char *data) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_PRO); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_PRO->connected()) { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +// bool BlinkerPROESP::autoPrint(char *name1, char *type1, char *data1 +// , char *name2, char *type2, char *data2) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data1); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_PRO); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name1; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type1; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_PRO->connected()) +// { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data2); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_PRO); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name2; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type2; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else +// { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +char * BlinkerPROESP::deviceName() { return MQTT_DEVICEID_PRO;/*MQTT_ID_PRO;*/ } + +void BlinkerPROESP::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (_sharerCount; _sharerCount > 0; _sharerCount--) + { + delete _sharers[_sharerCount - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerPROESP::authCheck() +{ + uint8_t _authCheck; + + BLINKER_LOG_ALL(BLINKER_F("authCheck start")); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck == BLINKER_AUTH_CHECK_DATA) + { + EEPROM.commit(); + EEPROM.end(); + isAuth = true; + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return true; + } + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return false; +} + +int BlinkerPROESP::connectServer() { + const int httpsPort = 443; + #if defined(ESP8266) + String host = BLINKER_F(BLINKER_SERVER_HOST); + client_mqtt.stop(); + #elif defined(ESP32) + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + #endif + if (!_isAuthKey) + { + #if defined(ESP8266) + // String host = BLINKER_F(BLINKER_SERVER_HOST); + String fingerprint = BLINKER_F("84 5f a4 8a 70 5e 79 7e f5 b3 b4 20 45 c8 35 55 72 f6 85 5a"); + + // WiFiClientSecure client_s; + + // BearSSL::WiFiClientSecure *client_s; + + // client_s = new BearSSL::WiFiClientSecure(); + + // client_mqtt.stop(); + + // BLINKER_LOG_ALL(BLINKER_F("connecting to "), host); + + // // BLINKER_LOG_FreeHeap(); + + // uint8_t connet_times = 0; + // // client_s.stop(); + // ::delay(100); + + // bool mfln = client_s->probeMaxFragmentLength(host, httpsPort, 1024); + // if (mfln) { + // client_s->setBufferSizes(1024, 1024); + // } + // // client_s.setFingerprint(fingerprint.c_str()); + + // client_s->setInsecure(); + + // // while (1) { + // bool cl_connected = false; + // if (!client_s->connect(host, httpsPort)) { + // BLINKER_ERR_LOG(BLINKER_F("server connection failed")); + // // connet_times++; + + // ::delay(1000); + // } + // else { + // BLINKER_LOG_ALL(BLINKER_F("connection succeed")); + // cl_connected = true; + + // // break; + // } + + // // if (connet_times >= 4 && !cl_connected) return BLINKER_CMD_FALSE; + // // } + + // String client_msg; + + // String url_iot = BLINKER_F("/api/v1/user/device/register?deviceType="); + // url_iot += _deviceType; + // url_iot += BLINKER_F("&deviceName="); + // url_iot += macDeviceName(); + + // if (_deviceType == BLINKER_SMART_LAMP) { + // url_iot += BLINKER_F("&aliType=light"); + // url_iot += BLINKER_F("&duerType=LIGHT"); + // } + // else if (_deviceType == BLINKER_SMART_PLUGIN) { + // url_iot += BLINKER_F("&aliType=outlet"); + // url_iot += BLINKER_F("&duerType=SOCKET"); + // } + // else if (_deviceType == BLINKER_AIR_DETECTOR) { + // url_iot += BLINKER_F("&aliType=sensor"); + // url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + // } + + // // #if defined(BLINKER_ALIGENIE_LIGHT) + // // url_iot += BLINKER_F("&aliType=light"); + // // #elif defined(BLINKER_ALIGENIE_OUTLET) + // // url_iot += BLINKER_F("&aliType=outlet"); + // // #elif defined(BLINKER_ALIGENIE_SWITCH) + // // #elif defined(BLINKER_ALIGENIE_SENSOR) + // // url_iot += BLINKER_F("&aliType=sensor"); + // // #endif + + // BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host, url_iot); + + // client_msg = BLINKER_F("GET "); + // client_msg += url_iot; + // client_msg += BLINKER_F(" HTTP/1.1\r\nHost: "); + // client_msg += host; + // client_msg += BLINKER_F(":"); + // client_msg += STRING_format(httpsPort); + // client_msg += BLINKER_F("\r\nConnection: close\r\n\r\n"); + + // client_s->print(client_msg); + + // BLINKER_LOG_ALL(BLINKER_F("client_msg: "), client_msg); + + // unsigned long timeout = millis(); + // while (client_s->available() == 0) { + // if (millis() - timeout > 5000) { + // BLINKER_LOG_ALL(BLINKER_F(">>> Client Timeout !")); + // client_s->stop(); + // return false; + // } + // } + + // String _dataGet; + // String lastGet; + // String lengthOfJson; + // while (client_s->available()) { + // // String line = client_s.readStringUntil('\r'); + // _dataGet = client_s->readStringUntil('\n'); + + // if (_dataGet.startsWith("Content-Length: ")){ + // int addr_start = _dataGet.indexOf(' '); + // int addr_end = _dataGet.indexOf('\0', addr_start + 1); + // lengthOfJson = _dataGet.substring(addr_start + 1, addr_end); + // } + + // if (_dataGet == "\r") { + // BLINKER_LOG_ALL(BLINKER_F("headers received")); + + // break; + // } + // } + + // for(int i=0;iread(); + // } + + // // BLINKER_LOG_FreeHeap(); + + // client_s->stop(); + // client_s->flush(); + + // free(client_s); + + // // BLINKER_LOG_FreeHeap(); + + // _dataGet = lastGet; + + // BLINKER_LOG_ALL(BLINKER_F("_dataGet: "), _dataGet); + + // String payload = _dataGet; + + + + // client_mqtt.stop(); + + #ifndef BLINKER_WITHOUT_SSL + client_mqtt.stop(); + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + #else + WiFiClient client_s; + #endif + + String url_iot = BLINKER_F("/api/v1/user/device/auth/get?deviceType="); + url_iot += _deviceType; + url_iot += BLINKER_F("&typeKey="); + url_iot += _vipKey; + url_iot += BLINKER_F("&deviceName="); + url_iot += macDeviceName(); + + + #if defined(BLINKER_ALIGENIE_LIGHT) + url_iot += BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + url_iot += BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + url_iot += BLINKER_F("&aliType=multi_outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + url_iot += BLINKER_F("&aliType=sensor"); + #elif defined(BLINKER_ALIGENIE_TYPE) + url_iot += BLINKER_ALIGENIE_TYPE; + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + url_iot += BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + url_iot += BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_MULTI_OUTLET) + url_iot += BLINKER_F("&duerType=MULTI_SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + #elif defined(BLINKER_DUEROS_TYPE) + url_iot += BLINKER_DUEROS_TYPE; + #endif + + #if defined(BLINKER_MIOT_LIGHT) + url_iot += BLINKER_F("&miType=light"); + #elif defined(BLINKER_MIOT_OUTLET) + url_iot += BLINKER_F("&miType=outlet"); + #elif defined(BLINKER_MIOT_MULTI_OUTLET) + url_iot += BLINKER_F("&miType=multi_outlet"); + #elif defined(BLINKER_MIOT_SENSOR) + url_iot += BLINKER_F("&miType=sensor"); + #elif defined(BLINKER_MIOT_TYPE) + url_iot += BLINKER_MIOT_TYPE; + #endif + + url_iot += BLINKER_F("&version="); + url_iot += BLINKER_OTA_VERSION_CODE; + #ifndef BLINKER_WITHOUT_SSL + url_iot += BLINKER_F("&protocol=mqtts"); + #else + url_iot += BLINKER_F("&protocol=mqtt"); + #endif + + #ifndef BLINKER_WITHOUT_SSL + url_iot = "https://" + host + url_iot; + #else + url_iot = "http://" + host + url_iot; + #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + HTTPClient http; + + String payload; + + #ifndef BLINKER_WITHOUT_SSL + if (http.begin(*client_s, url_iot)) { // HTTPS + #else + if (http.begin(client_s, url_iot)) { + #endif + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + + #elif defined(ESP32) + // String host = BLINKER_F(BLINKER_SERVER_HTTPS); + // const char* ca = \ + // "-----BEGIN CERTIFICATE-----\n" \ + // "MIIEgDCCA2igAwIBAgIQDKTfhr9lmWbWUT0hjX36oDANBgkqhkiG9w0BAQsFADBy\n" \ + // "MQswCQYDVQQGEwJDTjElMCMGA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywg\n" \ + // "SW5jLjEdMBsGA1UECxMURG9tYWluIFZhbGlkYXRlZCBTU0wxHTAbBgNVBAMTFFRy\n" \ + // "dXN0QXNpYSBUTFMgUlNBIENBMB4XDTE4MDEwNDAwMDAwMFoXDTE5MDEwNDEyMDAw\n" \ + // "MFowGDEWMBQGA1UEAxMNaW90ZGV2LmNsei5tZTCCASIwDQYJKoZIhvcNAQEBBQAD\n" \ + // "ggEPADCCAQoCggEBALbOFn7cJ2I/FKMJqIaEr38n4kCuJCCeNf1bWdWvOizmU2A8\n" \ + // "QeTAr5e6Q3GKeJRdPnc8xXhqkTm4LOhgdZB8KzuVZARtu23D4vj4sVzxgC/zwJlZ\n" \ + // "MRMxN+cqI37kXE8gGKW46l2H9vcukylJX+cx/tjWDfS2YuyXdFuS/RjhCxLgXzbS\n" \ + // "cve1W0oBZnBPRSMV0kgxTWj7hEGZNWKIzK95BSCiMN59b+XEu3NWGRb/VzSAiJEy\n" \ + // "Hy9DcDPBC9TEg+p5itHtdMhy2gq1OwsPgl9HUT0xmDATSNEV2RB3vwviNfu9/Eif\n" \ + // "ObhsV078zf30TqdiESqISEB68gJ0Otru67ePoTkCAwEAAaOCAWowggFmMB8GA1Ud\n" \ + // "IwQYMBaAFH/TmfOgRw4xAFZWIo63zJ7dygGKMB0GA1UdDgQWBBR/KLqnke61779P\n" \ + // "xc9htonQwLOxPDAYBgNVHREEETAPgg1pb3RkZXYuY2x6Lm1lMA4GA1UdDwEB/wQE\n" \ + // "AwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTAYDVR0gBEUwQzA3\n" \ + // "BglghkgBhv1sAQIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQu\n" \ + // "Y29tL0NQUzAIBgZngQwBAgEwgYEGCCsGAQUFBwEBBHUwczAlBggrBgEFBQcwAYYZ\n" \ + // "aHR0cDovL29jc3AyLmRpZ2ljZXJ0LmNvbTBKBggrBgEFBQcwAoY+aHR0cDovL2Nh\n" \ + // "Y2VydHMuZGlnaXRhbGNlcnR2YWxpZGF0aW9uLmNvbS9UcnVzdEFzaWFUTFNSU0FD\n" \ + // "QS5jcnQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtM4eyrWB14ajJpQ\n" \ + // "ibZ5FbzVuvv2Le0FOSoss7UFCDJUYiz2LiV8yOhL4KTY+oVVkqHaYtcFS1CYZNzj\n" \ + // "6xWcqYZJ+pgsto3WBEgNEEe0uLSiTW6M10hm0LFW9Det3k8fqwSlljqMha3gkpZ6\n" \ + // "8WB0f2clXOuC+f1SxAOymnGUsSqbU0eFSgevcOIBKR7Hr3YXBXH3jjED76Q52OMS\n" \ + // "ucfOM9/HB3jN8o/ioQbkI7xyd/DUQtzK6hSArEoYRl3p5H2P4fr9XqmpoZV3i3gQ\n" \ + // "oOdVycVtpLunyUoVAB2DcOElfDxxXCvDH3XsgoIU216VY03MCaUZf7kZ2GiNL+UX\n" \ + // "9UBd0Q==\n" \ + // "-----END CERTIFICATE-----\n"; + // #endif + + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/auth/get?deviceType="); + url_iot += _deviceType; + url_iot += BLINKER_F("&typeKey="); + url_iot += _vipKey; + url_iot += BLINKER_F("&deviceName="); + url_iot += macDeviceName(); + + #if defined(BLINKER_ALIGENIE_LIGHT) + url_iot += BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + url_iot += BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + url_iot += BLINKER_F("&aliType=multi_outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + url_iot += BLINKER_F("&aliType=sensor"); + #elif defined(BLINKER_ALIGENIE_TYPE) + url_iot += BLINKER_ALIGENIE_TYPE; + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + url_iot += BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + url_iot += BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_MULTI_OUTLET) + url_iot += BLINKER_F("&duerType=MULTI_SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + #elif defined(BLINKER_DUEROS_TYPE) + url_iot += BLINKER_DUEROS_TYPE; + #endif + + #if defined(BLINKER_MIOT_LIGHT) + url_iot += BLINKER_F("&miType=light"); + #elif defined(BLINKER_MIOT_OUTLET) + url_iot += BLINKER_F("&miType=outlet"); + #elif defined(BLINKER_MIOT_MULTI_OUTLET) + url_iot += BLINKER_F("&miType=multi_outlet"); + #elif defined(BLINKER_MIOT_SENSOR) + url_iot += BLINKER_F("&miType=sensor"); + #elif defined(BLINKER_MIOT_TYPE) + url_iot += BLINKER_MIOT_TYPE; + #endif + + // #if defined(BLINKER_ALIGENIE_LIGHT) + // url_iot += BLINKER_F("&aliType=light"); + // #elif defined(BLINKER_ALIGENIE_OUTLET) + // url_iot += BLINKER_F("&aliType=outlet"); + // #elif defined(BLINKER_ALIGENIE_SWITCH) + // #elif defined(BLINKER_ALIGENIE_SENSOR) + // url_iot += BLINKER_F("&aliType=sensor"); + // #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + // #if defined(ESP8266) + // http.begin(url_iot, fingerprint); //HTTP + // #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); + // #endif + int httpCode = http.GET(); + + String payload; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + #endif + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_AUTHKEY)) { + // while(1) { + BLINKER_ERR_LOG(BLINKER_F("Maybe you have put in the wrong AuthKey!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your request is too frequently!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your network is disconnected!")); + // ::delay(60000); + + return false; + // } + } + + String _getAuthKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_AUTHKEY]; + + AUTHKEY_PRO = (char*)malloc((_getAuthKey.length()+1)*sizeof(char)); + strcpy(AUTHKEY_PRO, _getAuthKey.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_PRO: "), AUTHKEY_PRO); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + _isAuthKey = true; + } + +#if defined(ESP8266) + // client_mqtt.stop(); + + #ifndef BLINKER_WITHOUT_SSL + client_mqtt.stop(); + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + #else + WiFiClient client_s; + #endif + + String url_iot = BLINKER_F("/api/v1/user/device/auth?authKey="); + url_iot += AUTHKEY_PRO; + // url_iot += _aliType; + // url_iot += _duerType; + + #if defined(BLINKER_ALIGENIE_LIGHT) + url_iot += BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + url_iot += BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + url_iot += BLINKER_F("&aliType=multi_outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + url_iot += BLINKER_F("&aliType=sensor"); + #elif defined(BLINKER_ALIGENIE_TYPE) + url_iot += BLINKER_ALIGENIE_TYPE; + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + url_iot += BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + url_iot += BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_MULTI_OUTLET) + url_iot += BLINKER_F("&duerType=MULTI_SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + #elif defined(BLINKER_DUEROS_TYPE) + url_iot += BLINKER_DUEROS_TYPE; + #endif + + #if defined(BLINKER_MIOT_LIGHT) + url_iot += BLINKER_F("&miType=light"); + #elif defined(BLINKER_MIOT_OUTLET) + url_iot += BLINKER_F("&miType=outlet"); + #elif defined(BLINKER_MIOT_MULTI_OUTLET) + url_iot += BLINKER_F("&miType=multi_outlet"); + #elif defined(BLINKER_MIOT_SENSOR) + url_iot += BLINKER_F("&miType=sensor"); + #elif defined(BLINKER_MIOT_TYPE) + url_iot += BLINKER_MIOT_TYPE; + #endif + + url_iot += BLINKER_F("&version="); + url_iot += BLINKER_OTA_VERSION_CODE; + #ifndef BLINKER_WITHOUT_SSL + url_iot += BLINKER_F("&protocol=mqtts"); + #else + url_iot += BLINKER_F("&protocol=mqtt"); + #endif + + #ifndef BLINKER_WITHOUT_SSL + url_iot = "https://" + host + url_iot; + #else + url_iot = "http://" + host + url_iot; + #endif + + HTTPClient http; + + String payload = ""; + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] begin: "), url_iot); + + #ifndef BLINKER_WITHOUT_SSL + if (http.begin(*client_s, url_iot)) { // HTTPS + #else + if (http.begin(client_s, url_iot)) { + #endif + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + +#elif defined(ESP32) + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/auth?authKey="); + url_iot += AUTHKEY_PRO; + // url_iot += _aliType; + // url_iot += _duerType; + + #if defined(BLINKER_ALIGENIE_LIGHT) + url_iot += BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + url_iot += BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + url_iot += BLINKER_F("&aliType=multi_outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + url_iot += BLINKER_F("&aliType=sensor"); + #elif defined(BLINKER_ALIGENIE_FAN) + url_iot += BLINKER_F("&aliType=fan"); + #elif defined(BLINKER_ALIGENIE_AIRCONDITION) + url_iot += BLINKER_F("&aliType=aircondition"); + #elif defined(BLINKER_ALIGENIE_TYPE) + url_iot += BLINKER_ALIGENIE_TYPE; + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + url_iot += BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + url_iot += BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_MULTI_OUTLET) + url_iot += BLINKER_F("&duerType=MULTI_SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + #elif defined(BLINKER_DUEROS_FAN) + url_iot += BLINKER_F("&duerType=FAN"); + #elif defined(BLINKER_DUEROS_AIRCONDITION) + url_iot += BLINKER_F("&duerType=AIR_CONDITION"); + #elif defined(BLINKER_DUEROS_TYPE) + url_iot += BLINKER_DUEROS_TYPE; + #endif + + #if defined(BLINKER_MIOT_LIGHT) + url_iot += BLINKER_F("&miType=light"); + #elif defined(BLINKER_MIOT_OUTLET) + url_iot += BLINKER_F("&miType=outlet"); + #elif defined(BLINKER_MIOT_MULTI_OUTLET) + url_iot += BLINKER_F("&miType=multi_outlet"); + #elif defined(BLINKER_MIOT_SENSOR) + url_iot += BLINKER_F("&miType=sensor"); + #elif defined(BLINKER_MIOT_FAN) + url_iot += BLINKER_F("&miType=fan"); + #elif defined(BLINKER_MIOT_AIRCONDITION) + url_iot += BLINKER_F("&miType=aircondition"); + #elif defined(BLINKER_MIOT_TYPE) + url_iot += BLINKER_MIOT_TYPE; + #endif + + url_iot += BLINKER_F("&version="); + url_iot += BLINKER_OTA_VERSION_CODE; + #ifndef BLINKER_WITHOUT_SSL + url_iot += BLINKER_F("&protocol=mqtts"); + #else + url_iot += BLINKER_F("&protocol=mqtt"); + #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + +// #if defined(ESP8266) +// http.begin(url_iot, fingerprint); //HTTP +// #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); +// #endif + int httpCode = http.GET(); + + String payload = ""; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); +#endif + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(BLINKER_F("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + // String _userID = STRING_find_string(payload, "deviceName", "\"", 4); + // String _userName = STRING_find_string(payload, "iotId", "\"", 4); + // String _key = STRING_find_string(payload, "iotToken", "\"", 4); + // String _productInfo = STRING_find_string(payload, "productKey", "\"", 4); + // String _broker = STRING_find_string(payload, "broker", "\"", 4); + // String _uuid = STRING_find_string(payload, "uuid", "\"", 4); + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + String _authKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_KEY]; + + if (isMQTTinit) + { + free(MQTT_HOST_PRO); + free(MQTT_ID_PRO); + free(MQTT_NAME_PRO); + free(MQTT_KEY_PRO); + free(MQTT_PRODUCTINFO_PRO); + free(UUID_PRO); + // free(AUTHKEY_PRO); + free(MQTT_DEVICEID_PRO); + free(BLINKER_PUB_TOPIC_PRO); + free(BLINKER_SUB_TOPIC_PRO); + free(BLINKER_RRPC_SUB_TOPIC_MQTT); + free(mqtt_PRO); + free(iotSub_PRO); + + isMQTTinit = false; + } + + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME, _userID.c_str(), 12); + // String _deviceName = _userID.substring(12, 36); + // MQTT_DEVICEID_PRO = (char*)malloc((_deviceName.length()+1)*sizeof(char)); + // String _deviceName = _userID.substring(12, 36); + // MQTT_DEVICEID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + // strcpy(MQTT_DEVICEID_PRO, _userID.c_str()); + #if defined(BLINKER_WITHOUT_SSL) + MQTT_DEVICEID_PRO = (char*)malloc((24+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _userName.substring(0, 24).c_str()); + #else + MQTT_DEVICEID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _userID.c_str()); + #endif + MQTT_ID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_PRO, _userID.c_str()); + MQTT_NAME_PRO = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_PRO, _userName.c_str()); + MQTT_KEY_PRO = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_PRO, _key.c_str()); + MQTT_PRODUCTINFO_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_PRO, _productInfo.c_str()); + MQTT_HOST_PRO = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_PRO, BLINKER_MQTT_ALIYUN_HOST); + // AUTHKEY_PRO = (char*)malloc((_authKey.length()+1)*sizeof(char)); + // strcpy(AUTHKEY_PRO, _authKey.c_str()); + MQTT_PORT_PRO = BLINKER_MQTT_ALIYUN_PORT; + + _use_broker = aliyun_b; + + BLINKER_LOG_ALL(BLINKER_F("====================")); + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + // String id2name = _userID.subString(10, _userID.length()); + // memcpy(DEVICE_NAME, _userID.c_str(), 12); + MQTT_DEVICEID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _userID.c_str()); + String IDtest = _productInfo + _userID; + MQTT_ID_PRO = (char*)malloc((IDtest.length()+1)*sizeof(char)); + strcpy(MQTT_ID_PRO, IDtest.c_str()); + String NAMEtest = IDtest + ";" + _userName; + MQTT_NAME_PRO = (char*)malloc((NAMEtest.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_PRO, NAMEtest.c_str()); + MQTT_KEY_PRO = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_PRO, _key.c_str()); + MQTT_PRODUCTINFO_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_PRO, _productInfo.c_str()); + MQTT_HOST_PRO = (char*)malloc((strlen(BLINKER_MQTT_QCLOUD_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_PRO, BLINKER_MQTT_QCLOUD_HOST); + MQTT_PORT_PRO = BLINKER_MQTT_QCLOUD_PORT; + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + // memcpy(DEVICE_NAME, _userID.c_str(), 12); + MQTT_DEVICEID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _userID.c_str()); + MQTT_ID_PRO = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_ID_PRO, _userName.c_str()); + MQTT_NAME_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_PRO, _productInfo.c_str()); + MQTT_KEY_PRO = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_PRO, _key.c_str()); + MQTT_PRODUCTINFO_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_PRO, _productInfo.c_str()); + MQTT_HOST_PRO = (char*)malloc((strlen(BLINKER_MQTT_ONENET_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_PRO, BLINKER_MQTT_ONENET_HOST); + MQTT_PORT_PRO = BLINKER_MQTT_ONENET_PORT; + + // _use_broker = blinker_b; + } + UUID_PRO = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_PRO, _uuid.c_str()); + + char uuid_eeprom[BLINKER_AUUID_SIZE]; + + BLINKER_LOG_ALL(BLINKER_F("==========AUTH CHECK==========")); + + if (!isFirst) + { + char _authCheck; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + if (strcmp(uuid_eeprom, _uuid.c_str()) != 0) { + // strcpy(UUID_PRO, _uuid.c_str()); + + strcpy(uuid_eeprom, _uuid.c_str()); + EEPROM.put(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("uuid_eeprom: "), uuid_eeprom); + BLINKER_LOG_ALL(BLINKER_F("_uuid: "), _uuid); + isNew = true; + } + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck != BLINKER_AUTH_CHECK_DATA) { + EEPROM.put(BLINKER_EEP_ADDR_AUTH_CHECK, BLINKER_AUTH_CHECK_DATA); + isAuth = true; + } + EEPROM.commit(); + EEPROM.end(); + + isFirst = true; + } + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME: "), macDeviceName()); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_PRO: "), MQTT_PRODUCTINFO_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_DEVICEID_PRO: "), MQTT_DEVICEID_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_PRO: "), MQTT_ID_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_PRO: "), MQTT_NAME_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_PRO: "), MQTT_KEY_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_PRO); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_PRO); + BLINKER_LOG_ALL(BLINKER_F("UUID_PRO: "), UUID_PRO); + BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_PRO: "), AUTHKEY_PRO); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_PRO; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_DEVICEID_PRO; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_PRO = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_PRO: "), BLINKER_PUB_TOPIC_PRO); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_DEVICEID_PRO; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_PRO = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_PRO: "), BLINKER_SUB_TOPIC_PRO); + + SUB_TOPIC_STR = BLINKER_F("/sys/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_DEVICEID_PRO; + SUB_TOPIC_STR += BLINKER_F("/rrpc/request/"); + + BLINKER_RRPC_SUB_TOPIC_MQTT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_RRPC_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str()); + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + String PUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += _userID; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_PRO = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_PRO: "), BLINKER_PUB_TOPIC_PRO); + + String SUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += _userID; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_PRO = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_PRO: "), BLINKER_SUB_TOPIC_PRO); + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + uint8_t str_len; + String PUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + PUB_TOPIC_STR += BLINKER_F("/onenet_rule/r"); + // str_len = PUB_TOPIC_STR.length() + 1; + BLINKER_PUB_TOPIC_PRO = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_PRO: "), BLINKER_PUB_TOPIC_PRO); + + String SUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += _userID; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_PRO = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_PRO: "), BLINKER_SUB_TOPIC_PRO); + } + + // BLINKER_LOG_FreeHeap(); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_PRO, MQTT_PORT_PRO, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_PRO = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #elif defined(ESP32) + mqtt_PRO = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #endif + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_PRO, MQTT_PORT_PRO, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_PRO = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #elif defined(ESP32) + mqtt_PRO = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #endif + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + mqtt_PRO = new Adafruit_MQTT_Client(&client, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + } + + // iotPub = new Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + // if (!isMQTTinit) + iotSub_PRO = new Adafruit_MQTT_Subscribe(mqtt_PRO, BLINKER_SUB_TOPIC_PRO); + + // mqtt_broker = (char*)malloc((_broker.length()+1)*sizeof(char)); + // strcpy(mqtt_broker, _broker.c_str()); + // mqtt_broker = _broker; + + MDNS.end(); + webSocket_PRO.close(); + mDNSInit(MQTT_DEVICEID_PRO); + this->latestTime = millis(); + // if (!isMQTTinit) + mqtt_PRO->subscribe(iotSub_PRO); + isMQTTinit = true; + + #if defined(ESP8266) + // client_s->stop(); + // if (!isMQTTinit) + #ifndef BLINKER_WITHOUT_SSL + client_mqtt.setInsecure(); + #endif + #elif defined(ESP32) + client_s.setInsecure(); + #endif + // connect(); + + return true; +} + +void BlinkerPROESP::mDNSInit(String name) +{ + delay(1000); + + BLINKER_LOG(BLINKER_F("WiFi.localIP: "), WiFi.localIP()); + + // MDNS.end(); + +#if defined(ESP8266) + if (!MDNS.begin(name.c_str(), WiFi.localIP())) { +#elif defined(ESP32) + if (!MDNS.begin(name.c_str())) { +#endif + while(1) { + ::delay(100); + } + } + + BLINKER_LOG(BLINKER_F("mDNS responder started")); + + String _service = STRING_format(BLINKER_MDNS_SERVICE_BLINKER) + STRING_format(_deviceType); + + MDNS.addService(BLINKER_MDNS_SERVICE_BLINKER, "tcp", WS_SERVERPORT); + MDNS.addServiceTxt(BLINKER_MDNS_SERVICE_BLINKER, "tcp", "deviceName", name); + MDNS.addServiceTxt(BLINKER_MDNS_SERVICE_BLINKER, "tcp", "mac", macDeviceName()); + + // if (!isWSinit) + // { + webSocket_PRO.begin(); + webSocket_PRO.onEvent(webSocketEvent_PRO); + // } + BLINKER_LOG(BLINKER_F("webSocket_PRO server started")); + BLINKER_LOG(BLINKER_F("ws://"), name, BLINKER_F(".local:"), WS_SERVERPORT); + + // isWSinit = true; + + isApCfg = false; +} + +void BlinkerPROESP::checkKA() { + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerPROESP::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerPROESP::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerPROESP::checkMIOTKA() { + if (millis() - miKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerPROESP::checkCanPrint() { + if ((millis() - printTime >= BLINKER_PRO_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerPROESP::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerPROESP::checkMIOTPrintSpan() +{ + if (millis() - respMIOTTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respMIOTTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respMIOTTimes++; + return true; + } + } + else + { + respMIOTTimes = 0; + return true; + } +} + +int BlinkerPROESP::checkPrintSpan() { + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) { + BLINKER_ERR_LOG(BLINKER_F("WEBSOCKETS CLIENT NOT ALIVE OR MSG LIMIT")); + + return false; + } + else { + respTimes++; + return true; + } + } + else { + respTimes = 0; + return true; + } +} + +int BlinkerPROESP::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerPROESP::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerPROESP::pubHello() +{ + char stateJsonStr[256] = ("{\"message\":\"Registration successful\"}"); + + BLINKER_LOG_ALL(BLINKER_F("PUB hello: "), stateJsonStr); + + return print(stateJsonStr, false); +} + +int BlinkerPROESP::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(STRING_format(data)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG(BLINKER_F("Print data is not Json! "), data); + return false; + } + + return true; +} + + +// static IPAddress apIP(192, 168, 4, 1); +// #if defined(ESP8266) +// static IPAddress netMsk(255, 255, 255, 0); +// #endif + + +enum bwl_status_t +{ + BWL_CONFIG_CKECK, + BWL_CONFIG_FAIL, + BWL_CONFIG_SUCCESS, + BWL_CONNECTING, + BWL_CONNECTED, + BWL_DISCONNECTED, + BWL_SMARTCONFIG_BEGIN, + BWL_SMARTCONFIG_DONE, + BWL_SMARTCONFIG_TIMEOUT, + BWL_STACONFIG_BEGIN, + BWL_APCONFIG_BEGIN, + BWL_APCONFIG_DONE, + BWL_APCONFIG_TIMEOUT, + BWL_CONNECTED_CHECK, + BWL_RESET +}; + +class BlinkerWlan +{ + public : + BlinkerWlan() + : _status(BWL_CONFIG_CKECK) + {} + + bool checkConfig(); + void loadConfig(char *_ssid, char *_pswd); + void saveConfig(char *_ssid, char *_pswd); + void deleteConfig(); + void smartconfigBegin(uint16_t _time = 15000); + bool smartconfigDone(); + void connect(); + bool connected(); + void disconnect(); + void reset(); + bool run(); + bwl_status_t status() { return _status; } + + void setType(const char* _type) { + _deviceType = _type; + +#ifdef BLINKER_DEBUG_ALL + BLINKER_LOG(BLINKER_F("API deviceType: "), _type); +#endif + } + + void softAPinit(); + void serverClient(); + void parseUrl(String data); + void connectWiFi(String _ssid, String _pswd); + void connectWiFi(const char* _ssid, const char* _pswd); + + // uint8_t status() { return _status; } + + private : + + protected : + char *SSID; + char *PSWD; + const char* _deviceType; + uint32_t connectTime; + uint16_t timeout; + bwl_status_t _status; + uint32_t debugStatusTime; +}; + +bool BlinkerWlan::checkConfig() { + BLINKER_LOG_ALL(BLINKER_F("check wlan config")); + + char ok[2 + 1]; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_WLAN_CHECK, ok); + EEPROM.commit(); + EEPROM.end(); + + if (String(ok) != String("OK")) { + + BLINKER_LOG(BLINKER_F("wlan config check,fail")); + + _status = BWL_CONFIG_FAIL; + return false; + } + else { + + BLINKER_LOG(BLINKER_F("wlan config check,success")); + + _status = BWL_CONFIG_SUCCESS; + return true; + } +} + +void BlinkerWlan::loadConfig(char *_ssid, char *_pswd) { + char loadssid[BLINKER_SSID_SIZE]; + char loadpswd[BLINKER_PSWD_SIZE]; + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_SSID, loadssid); + EEPROM.get(BLINKER_EEP_ADDR_PSWD, loadpswd); + // char ok[2 + 1]; + // EEPROM.get(EEP_ADDR_WIFI_CFG + BLINKER_SSID_SIZE + BLINKER_PSWD_SIZE, ok); + EEPROM.commit(); + EEPROM.end(); + + strcpy(_ssid, loadssid); + strcpy(_pswd, loadpswd); + + BLINKER_LOG(BLINKER_F("SSID: "), _ssid, BLINKER_F(" PASWD: "), _pswd); +} + +void BlinkerWlan::saveConfig(char *_ssid, char *_pswd) { + char loadssid[BLINKER_SSID_SIZE]; + char loadpswd[BLINKER_PSWD_SIZE]; + + memcpy(loadssid, _ssid, BLINKER_SSID_SIZE); + memcpy(loadpswd, _pswd, BLINKER_PSWD_SIZE); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_SSID, loadssid); + EEPROM.put(BLINKER_EEP_ADDR_PSWD, loadpswd); + char ok[2 + 1] = "OK"; + EEPROM.put(BLINKER_EEP_ADDR_WLAN_CHECK, ok); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG(BLINKER_F("Save wlan config")); +} + +void BlinkerWlan::deleteConfig() { + char ok[3] = {0}; + EEPROM.begin(BLINKER_EEP_SIZE); + // for (int i = BLINKER_EEP_ADDR_WLAN_CHECK; i < BLINKER_WLAN_CHECK_SIZE; i++) + // EEPROM.write(i, 0); + EEPROM.put(BLINKER_EEP_ADDR_WLAN_CHECK, ok); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG(BLINKER_F("Erase wlan config")); +} + +void BlinkerWlan::smartconfigBegin(uint16_t _time) { + WiFi.mode(WIFI_STA); + delay(100); + String softAP_ssid = STRING_format(_deviceType) + "_" + macDeviceName(); + +#if defined(ESP8266) + WiFi.hostname(softAP_ssid); +#elif defined(ESP32) + WiFi.setHostname(softAP_ssid.c_str()); +#endif + + WiFi.beginSmartConfig(); + connectTime = millis(); + timeout = _time; + _status = BWL_SMARTCONFIG_BEGIN; + + BLINKER_LOG(BLINKER_F("Wait for Smartconfig")); +} + +bool BlinkerWlan::smartconfigDone() { + if (WiFi.smartConfigDone()) + { + // WiFi.setAutoConnect(true); + // WiFi.setAutoReconnect(true); + connectTime = millis(); + + _status = BWL_SMARTCONFIG_DONE; + + BLINKER_LOG(BLINKER_F("SmartConfig Success")); +#if defined(ESP8266) + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + // WiFi.begin(WiFi.SSID().c_str(), WiFi.psk().c_str()); + connectWiFi(WiFi.SSID().c_str(), WiFi.psk().c_str()); + // connectWiFi("有没有wifi", "i8888888"); +#endif + return true; + } + else { + return false; + } +} + +void BlinkerWlan::connect() { + switch (_status) { + case BWL_CONFIG_SUCCESS : + // WiFi.setAutoConnect(false); + // WiFi.setAutoReconnect(true); + + SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + + loadConfig(SSID, PSWD); + // WiFi.begin(SSID, PSWD); + connectWiFi(SSID, PSWD); + + free(SSID); + free(PSWD); + + _status = BWL_CONNECTING; + break; + case BWL_DISCONNECTED : + if (millis() - connectTime > 30000 && WiFi.status() != WL_CONNECTED) { + BLINKER_LOG(BLINKER_F("status: "), WiFi.status()); + + disconnect(); + // SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + // PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + // WiFi.reconnect(); + + char _ssid_[BLINKER_SSID_SIZE]; + char _pswd_[BLINKER_PSWD_SIZE]; + + loadConfig(_ssid_, _pswd_); + connectWiFi(_ssid_, _pswd_); + + // WiFi.setAutoConnect(false); + // WiFi.setAutoReconnect(true); + + // free(SSID); + // free(PSWD); + connectTime = millis(); + BLINKER_LOG(BLINKER_F("connecting BWL_DISCONNECTED")); + + BLINKER_LOG(BLINKER_F("_ssid_: "), _ssid_, BLINKER_F(" _pswd_: "), _pswd_); + } + else if(WiFi.status() == WL_CONNECTED) { + _status = BWL_CONNECTED; + } + break; + } +} + +bool BlinkerWlan::connected() { + switch (_status) { + case BWL_SMARTCONFIG_DONE : + if (WiFi.status() != WL_CONNECTED) { + if (millis() - connectTime > 15000) + { + BLINKER_LOG(BLINKER_F("smartConfig time out")); + + WiFi.stopSmartConfig(); + _status = BWL_SMARTCONFIG_TIMEOUT; + } + return false; + } + else if (WiFi.status() == WL_CONNECTED) { + // WiFi.stopSmartConfig(); + + IPAddress deviceIP = WiFi.localIP(); + BLINKER_LOG(BLINKER_F("WiFi connected")); + BLINKER_LOG(BLINKER_F("IP address: ")); + BLINKER_LOG(deviceIP); + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + + SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + memcpy(SSID,"\0",BLINKER_SSID_SIZE); + memcpy(SSID,WiFi.SSID().c_str(),BLINKER_SSID_SIZE); + memcpy(PSWD,"\0",BLINKER_PSWD_SIZE); + memcpy(PSWD,WiFi.psk().c_str(),BLINKER_PSWD_SIZE); + saveConfig(SSID, PSWD); + free(SSID); + free(PSWD); + + // WiFi.setAutoConnect(true); + // WiFi.setAutoReconnect(true); + + _status = BWL_CONNECTED_CHECK; + + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + // break; + case BWL_APCONFIG_DONE : + if (WiFi.status() != WL_CONNECTED) { + if (millis() - connectTime > 15000) + { + BLINKER_LOG(BLINKER_F("APConfig time out")); + + // WiFi.stopSmartConfig(); + WiFi.disconnect(); + _status = BWL_APCONFIG_TIMEOUT; + } + return false; + } + else if (WiFi.status() == WL_CONNECTED) { + IPAddress deviceIP = WiFi.localIP(); + BLINKER_LOG(BLINKER_F("WiFi connected")); + BLINKER_LOG(BLINKER_F("IP address: ")); + BLINKER_LOG(deviceIP); + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + + // SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + // PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + // memcpy(SSID,"\0",BLINKER_SSID_SIZE); + // memcpy(SSID,WiFi.SSID().c_str(),BLINKER_SSID_SIZE); + // memcpy(PSWD,"\0",BLINKER_PSWD_SIZE); + // memcpy(PSWD,WiFi.psk().c_str(),BLINKER_PSWD_SIZE); + saveConfig(SSID, PSWD); + free(SSID); + free(PSWD); + + // WiFi.setAutoConnect(true); + // WiFi.setAutoReconnect(true); + + _status = BWL_CONNECTED_CHECK; + return true; + } + break; + case BWL_CONNECTING : + if (WiFi.status() == WL_CONNECTED) { + IPAddress deviceIP = WiFi.localIP(); + BLINKER_LOG(BLINKER_F("WiFi connected")); + BLINKER_LOG(BLINKER_F("IP address: ")); + BLINKER_LOG(deviceIP); + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + + _status = BWL_CONNECTED_CHECK; + return true; + } + else if (WiFi.status() != WL_CONNECTED) { + return false; + } + case BWL_CONNECTED_CHECK : + // if (WiFi.status() != WL_CONNECTED) + // _status = BWL_DISCONNECTED; + if (WiFi.status() == WL_CONNECTED) + { + return true; + } + else + { + _status = BWL_DISCONNECTED; + return false; + } + case BWL_RESET : + return false; + default : + if (WiFi.status() == WL_CONNECTED) { + IPAddress deviceIP = WiFi.localIP(); + BLINKER_LOG(BLINKER_F("WiFi connected")); + BLINKER_LOG(BLINKER_F("IP address: ")); + BLINKER_LOG(deviceIP); + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + + _status = BWL_CONNECTED_CHECK; + return true; + } + return false; + } + return false; +} + +void BlinkerWlan::disconnect() { + WiFi.disconnect(); + delay(100); + _status = BWL_DISCONNECTED; + BLINKER_LOG(BLINKER_F("WiFi disconnected")); +} + +void BlinkerWlan::reset() { + disconnect(); + _status = BWL_RESET; +} + +void BlinkerWlan::softAPinit() { + // _server = new WiFiServer(80); + + IPAddress apIP(192, 168, 4, 1); + #if defined(ESP8266) + IPAddress netMsk(255, 255, 255, 0); + #endif + + WiFi.mode(WIFI_AP); + + delay(1000); + + String softAP_ssid = STRING_format(_deviceType) + "_" + macDeviceName(); + +#if defined(ESP8266) + WiFi.hostname(softAP_ssid.c_str()); + WiFi.softAPConfig(apIP, apIP, netMsk); +#elif defined(ESP32) + WiFi.setHostname(softAP_ssid.c_str()); + WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); +#endif + + WiFi.softAP(softAP_ssid.c_str(), NULL); + delay(100); + + // _server->begin(); + // BLINKER_LOG(BLINKER_F("AP IP address: "), WiFi.softAPIP()); + // BLINKER_LOG(BLINKER_F("HTTP _server started")); + // BLINKER_LOG(String("URL: http://" + WiFi.softAPIP())); + + // #if defined(ESP8266) + // if (!MDNS.begin(softAP_ssid.c_str(), WiFi.localIP())) { + // #elif defined(ESP32) + // if (!MDNS.begin(softAP_ssid.c_str())) { + // #endif + // while(1) { + // ::delay(100); + // } + // } + + // BLINKER_LOG(BLINKER_F("mDNS responder started")); + + // MDNS.addService(BLINKER_MDNS_SERVICE_BLINKER, "tcp", WS_SERVERPORT); + // MDNS.addServiceTxt(BLINKER_MDNS_SERVICE_BLINKER, "tcp", "deviceName", macDeviceName()); + + webSocket_PRO.begin(); + webSocket_PRO.onEvent(webSocketEvent_PRO); + + _status = BWL_APCONFIG_BEGIN; + + isApCfg = true; + + BLINKER_LOG(BLINKER_F("Wait for APConfig")); +} + +void BlinkerWlan::serverClient() +{ + webSocket_PRO.loop(); + + #if defined(ESP8266) + MDNS.update(); + #endif + + if (isAvail_PRO) + { + BLINKER_LOG(BLINKER_F("checkAPCFG: "), msgBuf_PRO); + + if (STRING_contains_string(msgBuf_PRO, "ssid") && \ + STRING_contains_string(msgBuf_PRO, "pswd")) + { + parseUrl(msgBuf_PRO); + } + isAvail_PRO = false; + } + // if (!_client) + // { + // _client = _server->available(); + // } + // else + // { + // // if (_client.status() == CLOSED) + // if (!_client.connected()) + // { + // _client.stop(); + // BLINKER_LOG(BLINKER_F("Connection closed on _client")); + // } + // else + // { + // if (_client.available()) + // { + // String data = _client.readStringUntil('\r'); + + // // data = data.substring(4, data.length() - 9); + // _client.flush(); + + // // BLINKER_LOG("clientData: ", data); + + // if (STRING_contains_string(data, "ssid") && STRING_contains_string(data, "pswd")) { + + // String msg = BLINKER_F("{\"hello\":\"world\"}"); + + // String s= BLINKER_F("HTTP/1.1 200 OK\r\nContent-Type: application/json;charset=utf-8\r\n"); + // s += BLINKER_F("Content-Length: "); + // s += String(msg.length()); + // s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); + // s += msg; + // s += BLINKER_F("\r\n"); + + // _client.print(s); + + // _client.stop(); + + // parseUrl(data); + // } + // } + // } + // } +} + +void BlinkerWlan::parseUrl(String data) +{ + BLINKER_LOG(BLINKER_F("APCONFIG data: "), data); + // DynamicJsonBuffer jsonBuffer; + // JsonObject& wifi_data = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject wifi_data = jsonBuffer.as(); + + // if (!wifi_data.success()) + if (error) + { + return; + } + + String _ssid = wifi_data["ssid"]; + String _pswd = wifi_data["pswd"]; + + BLINKER_LOG(BLINKER_F("ssid: "), _ssid); + BLINKER_LOG(BLINKER_F("pswd: "), _pswd); + + // free(_server); + // MDNS.end(); + webSocket_PRO.close(); + + SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + + strcpy(SSID, _ssid.c_str()); + strcpy(PSWD, _pswd.c_str()); + connectWiFi(_ssid, _pswd); + connectTime = millis(); + _status = BWL_APCONFIG_DONE; + + BLINKER_LOG(BLINKER_F("APConfig Success")); +} + +void BlinkerWlan::connectWiFi(String _ssid, String _pswd) +{ + connectWiFi(_ssid.c_str(), _pswd.c_str()); +} + +void BlinkerWlan::connectWiFi(const char* _ssid, const char* _pswd) +{ + uint32_t connectTime = millis(); + + BLINKER_LOG(BLINKER_F("Connecting to "), _ssid); + + WiFi.mode(WIFI_STA); + String _hostname = STRING_format(_deviceType) + "_" + macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(_hostname); + #elif defined(ESP32) + WiFi.setHostname(_hostname.c_str()); + #endif + + if (_pswd && strlen(_pswd)) { + WiFi.begin(_ssid, _pswd); + } + else { + WiFi.begin(_ssid); + } + + // while (WiFi.status() != WL_CONNECTED) { + // ::delay(50); + + // if (millis() - connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { + // connectTime = millis(); + // BLINKER_LOG(("WiFi connect timeout, please check ssid and pswd!")); + // BLINKER_LOG(("Retring WiFi connect again!")); + // } + // } + // BLINKER_LOG(("Connected")); + + // IPAddress myip = WiFi.localIP(); + // BLINKER_LOG(("Your IP is: "), myip); + + // mDNSInit(); +} + +bool BlinkerWlan::run() +{ + // if (millis() - debugStatusTime > 10000) { + // debugStatusTime = millis(); + + // BLINKER_LOG_ALL("WLAN status: ", _status); + // } + + switch (_status) { + case BWL_CONFIG_CKECK : + checkConfig(); + break; + case BWL_CONFIG_FAIL : + // #if defined(BLINKER_ESP_SMARTCONFIG) + // smartconfigBegin(); + // #elif defined(BLINKER_APCONFIG) + // softAPinit(); + // #endif + if (_configType == BLINKER_SMART_CONFIG) + { + smartconfigBegin(); + } + else + { + softAPinit(); + } + break; + case BWL_CONFIG_SUCCESS : + connect(); + break; + case BWL_CONNECTING : + return connected(); + break; + case BWL_CONNECTED : + return connected(); + break; + case BWL_DISCONNECTED : + connect(); + break; + case BWL_SMARTCONFIG_BEGIN : + if (_configType == BLINKER_SMART_CONFIG) + { + smartconfigDone(); + } + else + { + WiFi.stopSmartConfig(); + _status = BWL_CONFIG_FAIL; + } + break; + case BWL_SMARTCONFIG_DONE : + return connected(); + break; + case BWL_SMARTCONFIG_TIMEOUT : + _status = BWL_CONFIG_FAIL; + break; + case BWL_STACONFIG_BEGIN : + connect(); + break; + case BWL_APCONFIG_BEGIN : + serverClient(); + break; + case BWL_APCONFIG_DONE : + return connected(); + break; + case BWL_APCONFIG_TIMEOUT : + _status = BWL_CONFIG_FAIL; + break; + case BWL_CONNECTED_CHECK : + return connected(); + break; + case BWL_RESET: + break; + default : + break; + } + return false; +} + +#endif + +#endif diff --git a/blinker-library/src/Adapters/BlinkerPROESP_QRCODE.h b/blinker-library/src/Adapters/BlinkerPROESP_QRCODE.h new file mode 100644 index 0000000..c0ce5e6 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerPROESP_QRCODE.h @@ -0,0 +1,3408 @@ +#ifndef BLINKER_PRO_ESP_QRCODE_H +#define BLINKER_PRO_ESP_QRCODE_H + +#if (defined(ESP8266) || defined(ESP32)) + +#if defined(ESP8266) + #include + #include + #include + + #include +#elif defined(ESP32) + #include + #include + #include + + #include +#endif + +#include + +#include "../modules/WebSockets/WebSocketsServer.h" +#include "../modules/mqtt/Adafruit_MQTT.h" +#include "../modules/mqtt/Adafruit_MQTT_Client.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +// #include "../Adapters/BlinkerPROESP_QRCODE.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +char* MQTT_HOST_PRO; +char* MQTT_ID_PRO; +char* MQTT_NAME_PRO; +char* MQTT_KEY_PRO; +char* MQTT_PRODUCTINFO_PRO; +char* UUID_PRO; +char* AUTHKEY_PRO; +char* MQTT_DEVICEID_PRO; +// char* DEVICE_NAME; +char* BLINKER_PUB_TOPIC_PRO; +char* BLINKER_SUB_TOPIC_PRO; +char* BLINKER_RRPC_SUB_TOPIC_MQTT; +uint16_t MQTT_PORT_PRO; + +enum b_config_t { + BLINKER_SMART_CONFIG, + BLINKER_AP_CONFIG +}; + +b_config_t _configType = BLINKER_SMART_CONFIG; + +class BlinkerPROESP_QRCODE : public BlinkerStream +{ + public : + BlinkerPROESP_QRCODE(); + + void setSmartConfig() { _configType = BLINKER_SMART_CONFIG; BLINKER_LOG_ALL(BLINKER_F("SmartConfig")); } + void setApConfig() { _configType = BLINKER_AP_CONFIG; BLINKER_LOG_ALL(BLINKER_F("ApConfig")); } + bool checkSmartConfig() { return _configType == BLINKER_SMART_CONFIG; } + int connect(); + int connected(); + int mConnected();// { if (!isMQTTinit) return false; else return mqtt->connected(); } + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + int miAvail(); + // bool extraAvailable(); + void subscribe(); + char * lastRead(); + void flush(); + int print(char * data, bool needCheck = true); + int toServer(char * data); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + int miPrint(const String & data); + // void aliType(const String & type); + void begin(const char* _key, const char* _type); + int autoPrint(unsigned long id); + // bool autoPrint(char *name, char *type, char *data); + // bool autoPrint(char *name1, char *type1, char *data1, \ + // char *name2, char *type2, char *data2); + char * deviceName(); + char * authKey() { return AUTHKEY_PRO; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_PRO; } + int init() + { + // webSocket_PRO.loop(); + + // #if defined(ESP8266) + // MDNS.update(); + // #endif + + return isMQTTinit; + } + int reRegister() { return connectServer(); } + int deviceRegister() { return connectServer(); } + int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + + private : + bool isMQTTinit = false; + bool isWSinit = false; + + int connectServer(); + void mDNSInit(String name = macDeviceName()); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkMIOTKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + int checkMIOTPrintSpan(); + int pubHello(); + void parseData(const char* data); + + protected : + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + const char* _vipKey; + const char* _deviceType; + // char* _authKey; + // char* _aliType; + bool* isHandle;// = &isConnect; + // bool* isHandle = &isConnect_PRO; + bool isAlive = false; + bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + uint8_t respMIOTTimes = 0; + uint32_t respMIOTTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + uint32_t miKaTime = 0; + bool isMIOTAlive = false; + bool isMIOTAvail = false; + + bool isNew = false; + bool isAuth = false; + bool isFirst = false; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; + uint32_t _reRegister_time = 0; + uint8_t _reRegister_times = 0; + + bool _isAuthKey = false; + + char message_id[24]; + bool is_rrpc = false; +}; + +// #if defined(ESP8266) +// extern BearSSL::WiFiClientSecure client_mqtt; +// // WiFiClientSecure client_mqtt; +// #elif defined(ESP32) +// extern WiFiClientSecure client_s; +// #endif + +// extern WiFiClient client; + + +#if defined(ESP8266) + BearSSL::WiFiClientSecure client_mqtt; + // WiFiClientSecure client_mqtt; +#elif defined(ESP32) + WiFiClientSecure client_s; +#endif + +WiFiClient client; +Adafruit_MQTT_Client* mqtt_PRO; +// Adafruit_MQTT_Publish *iotPub; +Adafruit_MQTT_Subscribe* iotSub_PRO; + +#define WS_SERVERPORT 81 +WebSocketsServer webSocket_PRO = WebSocketsServer(WS_SERVERPORT); + +char* msgBuf_PRO; +bool isFresh_PRO = false; +bool isConnect_PRO = false; +bool isAvail_PRO = false; +bool isApCfg = false; +uint8_t ws_num_PRO = 0; +uint8_t dataFrom_PRO = BLINKER_MSG_FROM_MQTT; + +void webSocketEvent_PRO(uint8_t num, WStype_t type, \ + uint8_t * payload, size_t length) +{ + + switch(type) + { + case WStype_DISCONNECTED: + BLINKER_LOG_ALL(BLINKER_F("Disconnected! "), num); + + isConnect_PRO = false; + break; + case WStype_CONNECTED: + { + IPAddress ip = webSocket_PRO.remoteIP(num); + + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", Connected from: "), ip, + BLINKER_F(", url: "), (char *)payload); + + // send message to client + webSocket_PRO.sendTXT(num, "{\"state\":\"connected\"}\n"); + + ws_num_PRO = num; + + if (!isApCfg) isConnect_PRO = true; + } + break; + case WStype_TEXT: + BLINKER_LOG_ALL(BLINKER_F("num: "), num, \ + BLINKER_F(", get Text: "), (char *)payload, \ + BLINKER_F(", length: "), length); + + if (length < BLINKER_MAX_READ_SIZE) { + if (isFresh_PRO) free(msgBuf_PRO); + msgBuf_PRO = (char*)malloc((length+1)*sizeof(char)); + strcpy(msgBuf_PRO, (char*)payload); + isAvail_PRO = true; + isFresh_PRO = true; + } + + if (!isApCfg) isConnect_PRO = true; + + if (!isApCfg) dataFrom_PRO = BLINKER_MSG_FROM_WS; + + ws_num_PRO = num; + + // BLINKER_LOG_ALL(BLINKER_F("isConnect_PRO: "), isConnect_PRO); + + // send message to client + // webSocket_PRO.sendTXT(num, "message here"); + + // send data to all connected clients + // webSocket_PRO.broadcastTXT("message here"); + break; + case WStype_BIN: + // BLINKER_LOG("num: ", num, " get binary length: ", length); + // hexdump(payload, length); + + // send message to client + // webSocket_PRO.sendBIN(num, payload, length); + break; + } +} + +BlinkerPROESP_QRCODE::BlinkerPROESP_QRCODE() { isHandle = &isConnect_PRO; } + +int BlinkerPROESP_QRCODE::connect() +{ + int8_t ret; + +#if defined(ESP8266) + MDNS.update(); +#endif + + webSocket_PRO.loop(); + + if (!isMQTTinit) { + return *isHandle; + } + + if (mqtt_PRO->connected()) + { + return true; + } + + disconnect(); + + if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + { + yield(); + return false; + } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + #if defined(ESP8266) + client_mqtt.setInsecure(); + ::delay(10); + #endif + + BLINKER_LOG_FreeHeap_ALL(); + + if ((ret = mqtt_PRO->connect()) != 0) + { + BLINKER_LOG(mqtt_PRO->connectErrorString(ret)); + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + if (ret == 4) + { + if (_reRegister_times < BLINKER_SERVER_CONNECT_LIMIT) + { + if (reRegister()) + { + _reRegister_times = 0; + } + else + { + _reRegister_times++; + _reRegister_time = millis(); + } + } + else + { + if (millis() - _reRegister_time >= 60000 * 5) _reRegister_times = 0; + } + + BLINKER_LOG_ALL(BLINKER_F("_reRegister_times: "), _reRegister_times); + } + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + if (_reRegister_times < BLINKER_SERVER_CONNECT_LIMIT) + { + if (reRegister()) + { + _reRegister_times = 0; + } + else + { + _reRegister_times++; + _reRegister_time = millis(); + } + } + else + { + if (millis() - _reRegister_time >= 60000 * 5) _reRegister_times = 0; + } + + reconnect_time = 0; + + BLINKER_LOG_ALL(BLINKER_F("_reRegister_times: "), _reRegister_times); + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + if (isNew) + { + if (pubHello()) { + isNew = false; + } + } + + this->latestTime = millis(); + + return true; +} + +int BlinkerPROESP_QRCODE::connected() +{ + if (!isMQTTinit) + { + return *isHandle; + } + + return mqtt_PRO->connected() || *isHandle; +} + +int BlinkerPROESP_QRCODE::mConnected() +{ + if (!isMQTTinit) return false; + else return mqtt_PRO->connected(); +} + +void BlinkerPROESP_QRCODE::disconnect() +{ + if (isMQTTinit) mqtt_PRO->disconnect(); + + if (*isHandle) webSocket_PRO.disconnect(); +} + +void BlinkerPROESP_QRCODE::ping() +{ + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!isMQTTinit) return; + + if (!mqtt_PRO->ping()) + { + disconnect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } +} + +int BlinkerPROESP_QRCODE::available() +{ +#if defined(ESP8266) + MDNS.update(); +#endif + + // BLINKER_LOG("CHECK available"); + + delay(1); + + webSocket_PRO.loop(); + + if (isMQTTinit) { + checkKA(); + + // if (!mqtt_PRO->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + { + ping(); + } + else + { + subscribe(); + } + } + + if (isAvail_PRO) + { + isAvail_PRO = false; + return true; + } + else { + return false; + } +} + +int BlinkerPROESP_QRCODE::aligenieAvail() +{ + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerPROESP_QRCODE::duerAvail() +{ + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerPROESP_QRCODE::miAvail() +{ + if (isMIOTAvail) + { + isMIOTAvail = false; + return true; + } + else { + return false; + } +} + +// bool BlinkerPROESP_QRCODE::extraAvailable() +// { +// if (isBavail) +// { +// isBavail = false; +// return true; +// } +// else +// { +// return false; +// } +// } + +void BlinkerPROESP_QRCODE::subscribe() +{ + if (!isMQTTinit) return; + + Adafruit_MQTT_Subscribe *subscription; + while ((subscription = mqtt_PRO->readSubscription(10))) + { + if (subscription == iotSub_PRO) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), (char *)iotSub_PRO->lastread); + + parseData((char *)iotSub_PRO->lastread); + // // DynamicJsonBuffer jsonBuffer; + // // JsonObject& root = jsonBuffer.parseObject(String((char *)iotSub_PRO->lastread)); + // DynamicJsonDocument jsonBuffer(1024); + // DeserializationError error = deserializeJson(jsonBuffer, String((char *)iotSub_PRO->lastread)); + // JsonObject root = jsonBuffer.as(); + + // String _uuid = root["fromDevice"]; + // String dataGet = root["data"]; + + // BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + // BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + // if (strcmp(_uuid.c_str(), UUID_PRO) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + // kaTime = millis(); + // isAvail_PRO = true; + // isAlive = true; + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // } + // else if (_uuid == BLINKER_CMD_ALIGENIE) + // { + // BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + // aliKaTime = millis(); + // isAliAlive = true; + // isAliAvail = true; + // } + // else if (_uuid == BLINKER_CMD_DUEROS) + // { + // BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + // duerKaTime = millis(); + // isDuerAlive = true; + // isDuerAvail = true; + // } + // else if (_uuid == BLINKER_CMD_MIOT) + // { + // BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + // miKaTime = millis(); + // isMIOTAlive = true; + // isMIOTAvail = true; + // } + // else if (_uuid == BLINKER_CMD_SERVERCLIENT) + // { + // BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + // isAvail_PRO = true; + // isAlive = true; + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // } + // else + // { + // if (_sharerCount) + // { + // for (uint8_t num = 0; num < _sharerCount; num++) + // { + // if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + // { + // _sharerFrom = num; + + // kaTime = millis(); + + // BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + // BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + // _needCheckShare = false; + + // break; + // } + // else + // { + // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found," + // "check is from bridge/share device," + // "data: "), dataGet); + + // _needCheckShare = true; + // } + // } + // } + + // // { + // // dataGet = String((char *)iotSub_PRO->lastread); + // // root.printTo(dataGet); + // serializeJson(root, dataGet); + + // // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + // // check is from bridge/share device, \ + // // data: "), dataGet); + + // // // return; + + // // // isBavail = true; + + // // _needCheckShare = true; + // // } + + // isAvail_PRO = true; + // isAlive = true; + // } + + // memset(msgBuf_PRO, 0, BLINKER_MAX_READ_SIZE); + // memcpy(msgBuf_PRO, dataGet.c_str(), dataGet.length()); + + // if (isFresh_PRO) free(msgBuf_PRO); + // msgBuf_PRO = (char*)malloc((dataGet.length()+1)*sizeof(char)); + // strcpy(msgBuf_PRO, dataGet.c_str()); + // isFresh_PRO = true; + + // this->latestTime = millis(); + + // dataFrom_PRO = BLINKER_MSG_FROM_MQTT; + } + } + + if (mqtt_PRO->check_extra()) + { + BLINKER_LOG_ALL(BLINKER_F("Got extra topic: "), (char *)mqtt_PRO->get_extra_topic()); + BLINKER_LOG_ALL(BLINKER_F("Got extra data: "), (char *)mqtt_PRO->get_extra_data()); + + if (strncmp(BLINKER_RRPC_SUB_TOPIC_MQTT, + (char *)mqtt_PRO->get_extra_topic(), + strlen(BLINKER_RRPC_SUB_TOPIC_MQTT)) + == 0) + { + // char message_id[24]; + memset(message_id, '\0', 24); + + memmove(message_id, + mqtt_PRO->get_extra_topic()+strlen(BLINKER_RRPC_SUB_TOPIC_MQTT), + strlen(mqtt_PRO->get_extra_topic()) - strlen(BLINKER_RRPC_SUB_TOPIC_MQTT)); + + BLINKER_LOG_ALL(BLINKER_F("from server RRPC, message_id: "), message_id); + + parseData((char *)mqtt_PRO->get_extra_data()); + + // char BLINKER_RRPC_PUB_TOPIC_MQTT[128]; + + // strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, "/sys/"); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_PRODUCTINFO_PRO); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/"); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_DEVICEID_PRO); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/rrpc/response/"); + // strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, message_id); + + is_rrpc = true; + + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_RRPC_PUB_TOPIC_MQTT: "), BLINKER_RRPC_PUB_TOPIC_MQTT); + + // mqtt_PRO->publish(BLINKER_RRPC_PUB_TOPIC_MQTT, base64::encode("hello blinker").c_str()); + } + } +} + +void BlinkerPROESP_QRCODE::parseData(const char* data) +{ + DynamicJsonDocument jsonBuffer(1024); + deserializeJson(jsonBuffer, String(data)); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"].as(); + String dataGet = root["data"].as(); + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_PRO) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_PRO = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_MIOT) + { + BLINKER_LOG_ALL(BLINKER_F("form MIOT")); + + miKaTime = millis(); + isMIOTAlive = true; + isMIOTAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT) + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_PRO = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, check is from bridge/share device, data: "), dataGet); + + _needCheckShare = true; + } + } + } + // else + // { + // dataGet = String((char *)iotSub_PRO->lastread); + // root.printTo(dataGet); + serializeJson(root, dataGet); + + // BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, + // check is from bridge/share device, \ + // data: "), dataGet); + + // // return; + + // // isBavail = true; + + // _needCheckShare = true; + // } + + isAvail_PRO = true; + isAlive = true; + } + + // memset(msgBuf_PRO, 0, BLINKER_MAX_READ_SIZE); + // memcpy(msgBuf_PRO, dataGet.c_str(), dataGet.length()); + + if (isFresh_PRO) free(msgBuf_PRO); + msgBuf_PRO = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_PRO, dataGet.c_str()); + isFresh_PRO = true; + + this->latestTime = millis(); + + dataFrom_PRO = BLINKER_MSG_FROM_MQTT; +} + +char * BlinkerPROESP_QRCODE::lastRead() +{ + if (isFresh_PRO) return msgBuf_PRO; + return ""; +} + +void BlinkerPROESP_QRCODE::flush() +{ + if (isFresh_PRO) + { + free(msgBuf_PRO); isFresh_PRO = false; isAvail_PRO = false; + isAliAvail = false; isDuerAvail = false; isMIOTAvail = false;//isBavail = false; + } +} + +int BlinkerPROESP_QRCODE::print(char * data, bool needCheck) +// int BlinkerPROESP_QRCODE::print(const String & data, bool needCheck) +{ + // BLINKER_LOG_FreeHeap(); + if (*isHandle && dataFrom_PRO == BLINKER_MSG_FROM_WS) + { + if (needCheck) + { + if (!checkPrintSpan()) + { + respTime = millis(); + return false; + } + } + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("WS response: ")); + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + strcat(data, BLINKER_CMD_NEWLINE); + + webSocket_PRO.sendTXT(ws_num_PRO, data); + + return true; + } + else + { + // // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // uint8_t num = strlen(data) - 1; + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data.substring(0, data.length() - 1); + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_DEVICEID_PRO; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_PRO; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + // else + // { + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + // // payload = BLINKER_F("{\"data\":"); + // // payload += data; + // // payload += BLINKER_F(",\"fromDevice\":\""); + // // payload += MQTT_DEVICEID_PRO; + // // payload += BLINKER_F("\",\"toDevice\":\""); + // // payload += UUID_PRO; + // // payload += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + // } + + uint16_t num = strlen(data); + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+7] = data[c_num-1]; + } + + data[num+8] = '\0'; + + String data_add = BLINKER_F("{\"data\":"); + + for(uint16_t c_num = 0; c_num < 8; c_num++) + { + data[c_num] = data_add[c_num]; + } + + data_add = BLINKER_F(",\"fromDevice\":\""); + strcat(data, data_add.c_str()); + strcat(data, MQTT_DEVICEID_PRO); + data_add = BLINKER_F("\",\"toDevice\":\""); + strcat(data, data_add.c_str()); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + strcat(data, _sharers[_sharerFrom]->uuid()); + } + else + { + strcat(data, UUID_PRO); + } + data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + strcat(data, data_add.c_str()); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + if (!isJson(STRING_format(data))) return false; + + // String data_add = BLINKER_F("{\"data\":"); + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_DEVICEID_PRO; + // data_add += BLINKER_F("\",\"toDevice\":\""); + // if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + // { + // data_add += _sharers[_sharerFrom]->uuid(); + // } + // else + // { + // data_add += UUID_PRO; + // } + + // data_add += BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + // if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (mqtt_PRO->connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } + } +} + +int BlinkerPROESP_QRCODE::toServer(char * data) +{ + // if (!checkInit()) return false; + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish to server...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (mqtt_PRO->connected()) + { + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerPROESP_QRCODE::bPrint(char * name, const String & data) +{ + // String payload; + // if (STRING_contains_string(data, BLINKER_CMD_NEWLINE)) + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data.substring(0, data.length() - 1); + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_DEVICEID_PRO; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + // else + // { + // payload = BLINKER_F("{\"data\":"); + // payload += data; + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_DEVICEID_PRO; + // payload += BLINKER_F("\",\"toDevice\":\""); + // payload += name; + // payload += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // } + + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + + String data_add = BLINKER_F("{\"data\":"); + // for(uint8_t c_num = 0; c_num < 8; c_num++) + // { + // data[c_num] = data_add[c_num]; + // } + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\""); + data_add += name; + data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, MQTT_DEVICEID_PRO); + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, name); + // data_add = BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + // strcat(data, data_add.c_str()); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_PRO->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + + // if (! iotPub.publish(payload.c_str())) { + + // String bPubTopic = BLINKER_F(""); + + // if (mqtt_broker == BLINKER_MQTT_BORKER_ONENET) + // { + // bPubTopic = MQTT_PRODUCTINFO_PRO; + // bPubTopic += BLINKER_F("/"); + // bPubTopic += name; + // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // bPubTopic = BLINKER_PUB_TOPIC_PRO; + // } + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerPROESP_QRCODE::aliPrint(const String & data) +{ + // String payload; + + // payload = BLINKER_F("{\"data\":"); + // payload += data; + // payload += BLINKER_F(",\"fromDevice\":\""); + // payload += MQTT_DEVICEID_PRO; + // payload += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + // payload += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + // uint8_t num = strlen(data); + // for(uint8_t c_num = num; c_num > 0; c_num--) + // { + // data[c_num+7] = data[c_num-1]; + // } + + String data_add = BLINKER_F("{\"data\":"); + // for(uint8_t c_num = 0; c_num < 8; c_num++) + // { + // data[c_num] = data_add[c_num]; + // } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, MQTT_DEVICEID_PRO); + // data_add = BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + // strcat(data, data_add.c_str()); + // data_add = BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + // strcat(data, data_add.c_str()); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + + // if (! iotPub.publish(payload.c_str())) { + + + char BLINKER_RRPC_PUB_TOPIC_MQTT[128]; + + if (is_rrpc) + { + + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, "/sys/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_PRODUCTINFO_PRO); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_DEVICEID_PRO); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/rrpc/response/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, message_id); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_RRPC_PUB_TOPIC_MQTT: "), BLINKER_RRPC_PUB_TOPIC_MQTT); + } + else + { + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, BLINKER_PUB_TOPIC_PRO); + } + + is_rrpc = false; + + if (! mqtt_PRO->publish(BLINKER_RRPC_PUB_TOPIC_MQTT, base64::encode(data_add).c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerPROESP_QRCODE::duerPrint(const String & data, bool report) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + + char BLINKER_RRPC_PUB_TOPIC_MQTT[128]; + + if (is_rrpc) + { + + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, "/sys/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_PRODUCTINFO_PRO); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_DEVICEID_PRO); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/rrpc/response/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, message_id); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_RRPC_PUB_TOPIC_MQTT: "), BLINKER_RRPC_PUB_TOPIC_MQTT); + } + else + { + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, BLINKER_PUB_TOPIC_PRO); + } + + if (! mqtt_PRO->publish(BLINKER_RRPC_PUB_TOPIC_MQTT, is_rrpc ? base64::encode(data_add).c_str() : data_add.c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + is_rrpc = false; + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + is_rrpc = false; + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerPROESP_QRCODE::miPrint(const String & data) +{ + String data_add = BLINKER_F("{\"data\":"); + + data_add += data; + data_add += BLINKER_F(",\"fromDevice\":\""); + data_add += MQTT_DEVICEID_PRO; + data_add += BLINKER_F("\",\"toDevice\":\"MIOT_r\""); + data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT MIOT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_PRO->connected()) + { + + if (!checkMIOTKA()) + { + return false; + } + + if (!checkMIOTPrintSpan()) + { + respMIOTTime = millis(); + return false; + } + respMIOTTime = millis(); + + + char BLINKER_RRPC_PUB_TOPIC_MQTT[128]; + + if (is_rrpc) + { + + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, "/sys/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_PRODUCTINFO_PRO); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, MQTT_DEVICEID_PRO); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, "/rrpc/response/"); + strcat(BLINKER_RRPC_PUB_TOPIC_MQTT, message_id); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_RRPC_PUB_TOPIC_MQTT: "), BLINKER_RRPC_PUB_TOPIC_MQTT); + } + else + { + strcpy(BLINKER_RRPC_PUB_TOPIC_MQTT, BLINKER_PUB_TOPIC_PRO); + } + + is_rrpc = false; + + if (! mqtt_PRO->publish(BLINKER_RRPC_PUB_TOPIC_MQTT, base64::encode(data_add).c_str())) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isMIOTAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isMIOTAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// void BlinkerPROESP_QRCODE::aliType(const String & type) +// { +// _aliType = (char*)malloc((type.length()+1)*sizeof(char)); +// strcpy(_aliType, type.c_str()); +// BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +// } + +void BlinkerPROESP_QRCODE::begin(const char* _key, const char* _type) +{ + _vipKey = _key; + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + mDNSInit(); +} + +int BlinkerPROESP_QRCODE::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"auto\":{\"trig\":true,"); + payload += BLINKER_F("\"id\":"); + payload += String(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(MQTT_DEVICEID_PRO); + payload += BLINKER_F("\",\"deviceType\":\"Auto\""); + payload += BLINKER_F(",\"toDevice\":\"serverClient\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_PRO->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_PRO->publish(BLINKER_PUB_TOPIC_PRO, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// bool BlinkerPROESP_QRCODE::autoPrint(char *name, char *type, char *data) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_PRO); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_PRO->connected()) { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +// bool BlinkerPROESP_QRCODE::autoPrint(char *name1, char *type1, char *data1 +// , char *name2, char *type2, char *data2) +// { +// String payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data1); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_PRO); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name1; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type1; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + +// if (mqtt_PRO->connected()) +// { +// if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ +// linkTime == 0) +// { +// linkTime = millis(); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// payload = BLINKER_F("{\"data\":{"); +// payload += STRING_format(data2); +// payload += BLINKER_F("},\"fromDevice\":\""); +// payload += STRING_format(MQTT_ID_PRO); +// payload += BLINKER_F("\",\"toDevice\":\""); +// payload += name2; +// payload += BLINKER_F("\",\"deviceType\":\""); +// payload += type2; +// payload += BLINKER_F("\"}"); + +// BLINKER_LOG_ALL(payload, BLINKER_F("...OK!")); + +// return true; +// } +// else +// { +// BLINKER_ERR_LOG_ALL(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + +// return false; +// } +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); +// return false; +// } +// } + +char * BlinkerPROESP_QRCODE::deviceName() { return MQTT_DEVICEID_PRO;/*MQTT_ID_PRO;*/ } + +void BlinkerPROESP_QRCODE::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (_sharerCount; _sharerCount > 0; _sharerCount--) + { + delete _sharers[_sharerCount - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerPROESP_QRCODE::authCheck() +{ + uint8_t _authCheck; + + BLINKER_LOG_ALL(BLINKER_F("authCheck start")); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck == BLINKER_AUTH_CHECK_DATA) + { + EEPROM.commit(); + EEPROM.end(); + isAuth = true; + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return true; + } + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return false; +} + +int BlinkerPROESP_QRCODE::connectServer() { + const int httpsPort = 443; + #if defined(ESP8266) + String host = BLINKER_F(BLINKER_SERVER_HOST); + client_mqtt.stop(); + #elif defined(ESP32) + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + #endif + if (!_isAuthKey) + { + #if defined(ESP8266) + // String host = BLINKER_F(BLINKER_SERVER_HOST); + String fingerprint = BLINKER_F("84 5f a4 8a 70 5e 79 7e f5 b3 b4 20 45 c8 35 55 72 f6 85 5a"); + + // WiFiClientSecure client_s; + + // BearSSL::WiFiClientSecure *client_s; + + // client_s = new BearSSL::WiFiClientSecure(); + + // client_mqtt.stop(); + + // BLINKER_LOG_ALL(BLINKER_F("connecting to "), host); + + // // BLINKER_LOG_FreeHeap(); + + // uint8_t connet_times = 0; + // // client_s.stop(); + // ::delay(100); + + // bool mfln = client_s->probeMaxFragmentLength(host, httpsPort, 1024); + // if (mfln) { + // client_s->setBufferSizes(1024, 1024); + // } + // // client_s.setFingerprint(fingerprint.c_str()); + + // client_s->setInsecure(); + + // // while (1) { + // bool cl_connected = false; + // if (!client_s->connect(host, httpsPort)) { + // BLINKER_ERR_LOG(BLINKER_F("server connection failed")); + // // connet_times++; + + // ::delay(1000); + // } + // else { + // BLINKER_LOG_ALL(BLINKER_F("connection succeed")); + // cl_connected = true; + + // // break; + // } + + // // if (connet_times >= 4 && !cl_connected) return BLINKER_CMD_FALSE; + // // } + + // String client_msg; + + // String url_iot = BLINKER_F("/api/v1/user/device/register?deviceType="); + // url_iot += _deviceType; + // url_iot += BLINKER_F("&deviceName="); + // url_iot += macDeviceName(); + + // if (_deviceType == BLINKER_SMART_LAMP) { + // url_iot += BLINKER_F("&aliType=light"); + // url_iot += BLINKER_F("&duerType=LIGHT"); + // } + // else if (_deviceType == BLINKER_SMART_PLUGIN) { + // url_iot += BLINKER_F("&aliType=outlet"); + // url_iot += BLINKER_F("&duerType=SOCKET"); + // } + // else if (_deviceType == BLINKER_AIR_DETECTOR) { + // url_iot += BLINKER_F("&aliType=sensor"); + // url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + // } + + // // #if defined(BLINKER_ALIGENIE_LIGHT) + // // url_iot += BLINKER_F("&aliType=light"); + // // #elif defined(BLINKER_ALIGENIE_OUTLET) + // // url_iot += BLINKER_F("&aliType=outlet"); + // // #elif defined(BLINKER_ALIGENIE_SWITCH) + // // #elif defined(BLINKER_ALIGENIE_SENSOR) + // // url_iot += BLINKER_F("&aliType=sensor"); + // // #endif + + // BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host, url_iot); + + // client_msg = BLINKER_F("GET "); + // client_msg += url_iot; + // client_msg += BLINKER_F(" HTTP/1.1\r\nHost: "); + // client_msg += host; + // client_msg += BLINKER_F(":"); + // client_msg += STRING_format(httpsPort); + // client_msg += BLINKER_F("\r\nConnection: close\r\n\r\n"); + + // client_s->print(client_msg); + + // BLINKER_LOG_ALL(BLINKER_F("client_msg: "), client_msg); + + // unsigned long timeout = millis(); + // while (client_s->available() == 0) { + // if (millis() - timeout > 5000) { + // BLINKER_LOG_ALL(BLINKER_F(">>> Client Timeout !")); + // client_s->stop(); + // return false; + // } + // } + + // String _dataGet; + // String lastGet; + // String lengthOfJson; + // while (client_s->available()) { + // // String line = client_s.readStringUntil('\r'); + // _dataGet = client_s->readStringUntil('\n'); + + // if (_dataGet.startsWith("Content-Length: ")){ + // int addr_start = _dataGet.indexOf(' '); + // int addr_end = _dataGet.indexOf('\0', addr_start + 1); + // lengthOfJson = _dataGet.substring(addr_start + 1, addr_end); + // } + + // if (_dataGet == "\r") { + // BLINKER_LOG_ALL(BLINKER_F("headers received")); + + // break; + // } + // } + + // for(int i=0;iread(); + // } + + // // BLINKER_LOG_FreeHeap(); + + // client_s->stop(); + // client_s->flush(); + + // free(client_s); + + // // BLINKER_LOG_FreeHeap(); + + // _dataGet = lastGet; + + // BLINKER_LOG_ALL(BLINKER_F("_dataGet: "), _dataGet); + + // String payload = _dataGet; + + + + // client_mqtt.stop(); + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + + String url_iot = BLINKER_F("/api/v1/user/device/auth/get?deviceType="); + url_iot += _deviceType; + url_iot += BLINKER_F("&typeKey="); + url_iot += _vipKey; + url_iot += BLINKER_F("&deviceName="); + url_iot += macDeviceName(); + + + #if defined(BLINKER_ALIGENIE_LIGHT) + url_iot += BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + url_iot += BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + url_iot += BLINKER_F("&aliType=multi_outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + url_iot += BLINKER_F("&aliType=sensor"); + #elif defined(BLINKER_ALIGENIE_TYPE) + url_iot += BLINKER_ALIGENIE_TYPE; + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + url_iot += BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + url_iot += BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_MULTI_OUTLET) + url_iot += BLINKER_F("&duerType=MULTI_SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + #elif defined(BLINKER_DUEROS_TYPE) + url_iot += BLINKER_DUEROS_TYPE; + #endif + + #if defined(BLINKER_MIOT_LIGHT) + url_iot += BLINKER_F("&miType=light"); + #elif defined(BLINKER_MIOT_OUTLET) + url_iot += BLINKER_F("&miType=outlet"); + #elif defined(BLINKER_MIOT_MULTI_OUTLET) + url_iot += BLINKER_F("&miType=multi_outlet"); + #elif defined(BLINKER_MIOT_SENSOR) + url_iot += BLINKER_F("&miType=sensor"); + #elif defined(BLINKER_MIOT_TYPE) + url_iot += BLINKER_MIOT_TYPE; + #endif + + url_iot = "https://" + host + url_iot; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + HTTPClient http; + + String payload; + + if (http.begin(*client_s, url_iot)) { // HTTPS + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + + #elif defined(ESP32) + // String host = BLINKER_F(BLINKER_SERVER_HTTPS); + // const char* ca = \ + // "-----BEGIN CERTIFICATE-----\n" \ + // "MIIEgDCCA2igAwIBAgIQDKTfhr9lmWbWUT0hjX36oDANBgkqhkiG9w0BAQsFADBy\n" \ + // "MQswCQYDVQQGEwJDTjElMCMGA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywg\n" \ + // "SW5jLjEdMBsGA1UECxMURG9tYWluIFZhbGlkYXRlZCBTU0wxHTAbBgNVBAMTFFRy\n" \ + // "dXN0QXNpYSBUTFMgUlNBIENBMB4XDTE4MDEwNDAwMDAwMFoXDTE5MDEwNDEyMDAw\n" \ + // "MFowGDEWMBQGA1UEAxMNaW90ZGV2LmNsei5tZTCCASIwDQYJKoZIhvcNAQEBBQAD\n" \ + // "ggEPADCCAQoCggEBALbOFn7cJ2I/FKMJqIaEr38n4kCuJCCeNf1bWdWvOizmU2A8\n" \ + // "QeTAr5e6Q3GKeJRdPnc8xXhqkTm4LOhgdZB8KzuVZARtu23D4vj4sVzxgC/zwJlZ\n" \ + // "MRMxN+cqI37kXE8gGKW46l2H9vcukylJX+cx/tjWDfS2YuyXdFuS/RjhCxLgXzbS\n" \ + // "cve1W0oBZnBPRSMV0kgxTWj7hEGZNWKIzK95BSCiMN59b+XEu3NWGRb/VzSAiJEy\n" \ + // "Hy9DcDPBC9TEg+p5itHtdMhy2gq1OwsPgl9HUT0xmDATSNEV2RB3vwviNfu9/Eif\n" \ + // "ObhsV078zf30TqdiESqISEB68gJ0Otru67ePoTkCAwEAAaOCAWowggFmMB8GA1Ud\n" \ + // "IwQYMBaAFH/TmfOgRw4xAFZWIo63zJ7dygGKMB0GA1UdDgQWBBR/KLqnke61779P\n" \ + // "xc9htonQwLOxPDAYBgNVHREEETAPgg1pb3RkZXYuY2x6Lm1lMA4GA1UdDwEB/wQE\n" \ + // "AwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTAYDVR0gBEUwQzA3\n" \ + // "BglghkgBhv1sAQIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQu\n" \ + // "Y29tL0NQUzAIBgZngQwBAgEwgYEGCCsGAQUFBwEBBHUwczAlBggrBgEFBQcwAYYZ\n" \ + // "aHR0cDovL29jc3AyLmRpZ2ljZXJ0LmNvbTBKBggrBgEFBQcwAoY+aHR0cDovL2Nh\n" \ + // "Y2VydHMuZGlnaXRhbGNlcnR2YWxpZGF0aW9uLmNvbS9UcnVzdEFzaWFUTFNSU0FD\n" \ + // "QS5jcnQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtM4eyrWB14ajJpQ\n" \ + // "ibZ5FbzVuvv2Le0FOSoss7UFCDJUYiz2LiV8yOhL4KTY+oVVkqHaYtcFS1CYZNzj\n" \ + // "6xWcqYZJ+pgsto3WBEgNEEe0uLSiTW6M10hm0LFW9Det3k8fqwSlljqMha3gkpZ6\n" \ + // "8WB0f2clXOuC+f1SxAOymnGUsSqbU0eFSgevcOIBKR7Hr3YXBXH3jjED76Q52OMS\n" \ + // "ucfOM9/HB3jN8o/ioQbkI7xyd/DUQtzK6hSArEoYRl3p5H2P4fr9XqmpoZV3i3gQ\n" \ + // "oOdVycVtpLunyUoVAB2DcOElfDxxXCvDH3XsgoIU216VY03MCaUZf7kZ2GiNL+UX\n" \ + // "9UBd0Q==\n" \ + // "-----END CERTIFICATE-----\n"; + // #endif + + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/auth/get?deviceType="); + url_iot += _deviceType; + url_iot += BLINKER_F("&typeKey="); + url_iot += _vipKey; + url_iot += BLINKER_F("&deviceName="); + url_iot += macDeviceName(); + + #if defined(BLINKER_ALIGENIE_LIGHT) + url_iot += BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + url_iot += BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + url_iot += BLINKER_F("&aliType=multi_outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + url_iot += BLINKER_F("&aliType=sensor"); + #elif defined(BLINKER_ALIGENIE_TYPE) + url_iot += BLINKER_ALIGENIE_TYPE; + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + url_iot += BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + url_iot += BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_MULTI_OUTLET) + url_iot += BLINKER_F("&duerType=MULTI_SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + #elif defined(BLINKER_DUEROS_TYPE) + url_iot += BLINKER_DUEROS_TYPE; + #endif + + #if defined(BLINKER_MIOT_LIGHT) + url_iot += BLINKER_F("&miType=light"); + #elif defined(BLINKER_MIOT_OUTLET) + url_iot += BLINKER_F("&miType=outlet"); + #elif defined(BLINKER_MIOT_MULTI_OUTLET) + url_iot += BLINKER_F("&miType=multi_outlet"); + #elif defined(BLINKER_MIOT_SENSOR) + url_iot += BLINKER_F("&miType=sensor"); + #elif defined(BLINKER_MIOT_TYPE) + url_iot += BLINKER_MIOT_TYPE; + #endif + + // #if defined(BLINKER_ALIGENIE_LIGHT) + // url_iot += BLINKER_F("&aliType=light"); + // #elif defined(BLINKER_ALIGENIE_OUTLET) + // url_iot += BLINKER_F("&aliType=outlet"); + // #elif defined(BLINKER_ALIGENIE_SWITCH) + // #elif defined(BLINKER_ALIGENIE_SENSOR) + // url_iot += BLINKER_F("&aliType=sensor"); + // #endif + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + // #if defined(ESP8266) + // http.begin(url_iot, fingerprint); //HTTP + // #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); + // #endif + int httpCode = http.GET(); + + String payload; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + #endif + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_AUTHKEY)) { + // while(1) { + BLINKER_ERR_LOG(BLINKER_F("Maybe you have put in the wrong AuthKey!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your request is too frequently!")); + BLINKER_ERR_LOG(BLINKER_F("Or maybe your network is disconnected!")); + // ::delay(60000); + + return false; + // } + } + + String _getAuthKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_AUTHKEY]; + + AUTHKEY_PRO = (char*)malloc((_getAuthKey.length()+1)*sizeof(char)); + strcpy(AUTHKEY_PRO, _getAuthKey.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_PRO: "), AUTHKEY_PRO); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + _isAuthKey = true; + } + +#if defined(ESP8266) + // client_mqtt.stop(); + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + + String url_iot = BLINKER_F("/api/v1/user/device/auth?authKey="); + url_iot += AUTHKEY_PRO; + // url_iot += _aliType; + // url_iot += _duerType; + + #if defined(BLINKER_ALIGENIE_LIGHT) + url_iot += BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + url_iot += BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + url_iot += BLINKER_F("&aliType=multi_outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + url_iot += BLINKER_F("&aliType=sensor"); + #elif defined(BLINKER_ALIGENIE_TYPE) + url_iot += BLINKER_ALIGENIE_TYPE; + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + url_iot += BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + url_iot += BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_MULTI_OUTLET) + url_iot += BLINKER_F("&duerType=MULTI_SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + #elif defined(BLINKER_DUEROS_TYPE) + url_iot += BLINKER_DUEROS_TYPE; + #endif + + #if defined(BLINKER_MIOT_LIGHT) + url_iot += BLINKER_F("&miType=light"); + #elif defined(BLINKER_MIOT_OUTLET) + url_iot += BLINKER_F("&miType=outlet"); + #elif defined(BLINKER_MIOT_MULTI_OUTLET) + url_iot += BLINKER_F("&miType=multi_outlet"); + #elif defined(BLINKER_MIOT_SENSOR) + url_iot += BLINKER_F("&miType=sensor"); + #elif defined(BLINKER_MIOT_TYPE) + url_iot += BLINKER_MIOT_TYPE; + #endif + + url_iot += BLINKER_F("&version="); + url_iot += BLINKER_OTA_VERSION_CODE; + + url_iot = "https://" + host + url_iot; + + HTTPClient http; + + String payload = ""; + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] begin: "), url_iot); + + if (http.begin(*client_s, url_iot)) { // HTTPS + + // Serial.print("[HTTPS] GET...\n"); + // start connection and send HTTP header + int httpCode = http.GET(); + + // httpCode will be negative on error + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + payload = http.getString(); + // Serial.println(payload); + } + } else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); + } else { + // Serial.printf("[HTTPS] Unable to connect\n"); + } + +#elif defined(ESP32) + HTTPClient http; + + String url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/auth?authKey="); + url_iot += AUTHKEY_PRO; + // url_iot += _aliType; + // url_iot += _duerType; + + #if defined(BLINKER_ALIGENIE_LIGHT) + url_iot += BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + url_iot += BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + url_iot += BLINKER_F("&aliType=multi_outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + url_iot += BLINKER_F("&aliType=sensor"); + #elif defined(BLINKER_ALIGENIE_TYPE) + url_iot += BLINKER_ALIGENIE_TYPE; + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + url_iot += BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + url_iot += BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_MULTI_OUTLET) + url_iot += BLINKER_F("&duerType=MULTI_SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + url_iot += BLINKER_F("&duerType=AIR_MONITOR"); + #elif defined(BLINKER_DUEROS_TYPE) + url_iot += BLINKER_DUEROS_TYPE; + #endif + + #if defined(BLINKER_MIOT_LIGHT) + url_iot += BLINKER_F("&miType=light"); + #elif defined(BLINKER_MIOT_OUTLET) + url_iot += BLINKER_F("&miType=outlet"); + #elif defined(BLINKER_MIOT_MULTI_OUTLET) + url_iot += BLINKER_F("&miType=multi_outlet"); + #elif defined(BLINKER_MIOT_SENSOR) + url_iot += BLINKER_F("&miType=sensor"); + #elif defined(BLINKER_MIOT_TYPE) + url_iot += BLINKER_MIOT_TYPE; + #endif + + url_iot += BLINKER_F("&version="); + url_iot += BLINKER_OTA_VERSION_CODE; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + +// #if defined(ESP8266) +// http.begin(url_iot, fingerprint); //HTTP +// #elif defined(ESP32) + // http.begin(url_iot, ca); TODO + http.begin(url_iot); +// #endif + int httpCode = http.GET(); + + String payload = ""; + + if (httpCode > 0) { + // HTTP header has been send and Server response header has been handled + + BLINKER_LOG_ALL(BLINKER_F("[HTTP] GET... code: "), httpCode); + + // file found at server + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + // BLINKER_LOG(payload); + } + } + else { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed, error: "), http.errorToString(httpCode).c_str()); + payload = http.getString(); + BLINKER_LOG(payload); + } + + http.end(); +#endif + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(BLINKER_F("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + // String _userID = STRING_find_string(payload, "deviceName", "\"", 4); + // String _userName = STRING_find_string(payload, "iotId", "\"", 4); + // String _key = STRING_find_string(payload, "iotToken", "\"", 4); + // String _productInfo = STRING_find_string(payload, "productKey", "\"", 4); + // String _broker = STRING_find_string(payload, "broker", "\"", 4); + // String _uuid = STRING_find_string(payload, "uuid", "\"", 4); + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + String _authKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_KEY]; + + if (isMQTTinit) + { + free(MQTT_HOST_PRO); + free(MQTT_ID_PRO); + free(MQTT_NAME_PRO); + free(MQTT_KEY_PRO); + free(MQTT_PRODUCTINFO_PRO); + free(UUID_PRO); + // free(AUTHKEY_PRO); + free(MQTT_DEVICEID_PRO); + free(BLINKER_PUB_TOPIC_PRO); + free(BLINKER_SUB_TOPIC_PRO); + free(BLINKER_RRPC_SUB_TOPIC_MQTT); + free(mqtt_PRO); + free(iotSub_PRO); + + isMQTTinit = false; + } + + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME, _userID.c_str(), 12); + // String _deviceName = _userID.substring(12, 36); + // MQTT_DEVICEID_PRO = (char*)malloc((_deviceName.length()+1)*sizeof(char)); + // String _deviceName = _userID.substring(12, 36); + MQTT_DEVICEID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _userID.c_str()); + MQTT_ID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_PRO, _userID.c_str()); + MQTT_NAME_PRO = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_PRO, _userName.c_str()); + MQTT_KEY_PRO = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_PRO, _key.c_str()); + MQTT_PRODUCTINFO_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_PRO, _productInfo.c_str()); + MQTT_HOST_PRO = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_PRO, BLINKER_MQTT_ALIYUN_HOST); + // AUTHKEY_PRO = (char*)malloc((_authKey.length()+1)*sizeof(char)); + // strcpy(AUTHKEY_PRO, _authKey.c_str()); + MQTT_PORT_PRO = BLINKER_MQTT_ALIYUN_PORT; + + BLINKER_LOG_ALL(BLINKER_F("====================")); + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + // String id2name = _userID.subString(10, _userID.length()); + // memcpy(DEVICE_NAME, _userID.c_str(), 12); + MQTT_DEVICEID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _userID.c_str()); + String IDtest = _productInfo + _userID; + MQTT_ID_PRO = (char*)malloc((IDtest.length()+1)*sizeof(char)); + strcpy(MQTT_ID_PRO, IDtest.c_str()); + String NAMEtest = IDtest + ";" + _userName; + MQTT_NAME_PRO = (char*)malloc((NAMEtest.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_PRO, NAMEtest.c_str()); + MQTT_KEY_PRO = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_PRO, _key.c_str()); + MQTT_PRODUCTINFO_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_PRO, _productInfo.c_str()); + MQTT_HOST_PRO = (char*)malloc((strlen(BLINKER_MQTT_QCLOUD_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_PRO, BLINKER_MQTT_QCLOUD_HOST); + MQTT_PORT_PRO = BLINKER_MQTT_QCLOUD_PORT; + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + // memcpy(DEVICE_NAME, _userID.c_str(), 12); + MQTT_DEVICEID_PRO = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _userID.c_str()); + MQTT_ID_PRO = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_ID_PRO, _userName.c_str()); + MQTT_NAME_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_PRO, _productInfo.c_str()); + MQTT_KEY_PRO = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_PRO, _key.c_str()); + MQTT_PRODUCTINFO_PRO = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_PRO, _productInfo.c_str()); + MQTT_HOST_PRO = (char*)malloc((strlen(BLINKER_MQTT_ONENET_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_PRO, BLINKER_MQTT_ONENET_HOST); + MQTT_PORT_PRO = BLINKER_MQTT_ONENET_PORT; + } + UUID_PRO = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_PRO, _uuid.c_str()); + + char uuid_eeprom[BLINKER_AUUID_SIZE]; + + BLINKER_LOG_ALL(BLINKER_F("==========AUTH CHECK==========")); + + if (!isFirst) + { + char _authCheck; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + if (strcmp(uuid_eeprom, _uuid.c_str()) != 0) { + // strcpy(UUID_PRO, _uuid.c_str()); + + strcpy(uuid_eeprom, _uuid.c_str()); + EEPROM.put(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("uuid_eeprom: "), uuid_eeprom); + BLINKER_LOG_ALL(BLINKER_F("_uuid: "), _uuid); + isNew = true; + } + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck != BLINKER_AUTH_CHECK_DATA) { + EEPROM.put(BLINKER_EEP_ADDR_AUTH_CHECK, BLINKER_AUTH_CHECK_DATA); + isAuth = true; + } + EEPROM.commit(); + EEPROM.end(); + + isFirst = true; + } + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME: "), macDeviceName()); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_PRO: "), MQTT_PRODUCTINFO_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_DEVICEID_PRO: "), MQTT_DEVICEID_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_PRO: "), MQTT_ID_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_PRO: "), MQTT_NAME_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_PRO: "), MQTT_KEY_PRO); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_PRO); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_PRO); + BLINKER_LOG_ALL(BLINKER_F("UUID_PRO: "), UUID_PRO); + BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_PRO: "), AUTHKEY_PRO); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_PRO; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_DEVICEID_PRO; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_PRO = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_PRO: "), BLINKER_PUB_TOPIC_PRO); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_DEVICEID_PRO; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_PRO = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_PRO: "), BLINKER_SUB_TOPIC_PRO); + + SUB_TOPIC_STR = BLINKER_F("/sys/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_DEVICEID_PRO; + SUB_TOPIC_STR += BLINKER_F("/rrpc/request/"); + + BLINKER_RRPC_SUB_TOPIC_MQTT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_RRPC_SUB_TOPIC_MQTT, SUB_TOPIC_STR.c_str()); + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + String PUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += _userID; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_PRO = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_PRO: "), BLINKER_PUB_TOPIC_PRO); + + String SUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += _userID; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_PRO = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_PRO: "), BLINKER_SUB_TOPIC_PRO); + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + uint8_t str_len; + String PUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + PUB_TOPIC_STR += BLINKER_F("/onenet_rule/r"); + // str_len = PUB_TOPIC_STR.length() + 1; + BLINKER_PUB_TOPIC_PRO = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_PRO, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_PRO: "), BLINKER_PUB_TOPIC_PRO); + + String SUB_TOPIC_STR = MQTT_PRODUCTINFO_PRO; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += _userID; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_PRO = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_PRO, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_PRO: "), BLINKER_SUB_TOPIC_PRO); + } + + // BLINKER_LOG_FreeHeap(); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_PRO, MQTT_PORT_PRO, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_PRO = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #elif defined(ESP32) + mqtt_PRO = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #endif + } + else if (_broker == BLINKER_MQTT_BORKER_QCLOUD) { + #if defined(ESP8266) + // bool mfln = client_mqtt.probeMaxFragmentLength(MQTT_HOST_PRO, MQTT_PORT_PRO, 4096); + // if (mfln) { + // client_mqtt.setBufferSizes(1024, 1024); + // } + // client_mqtt.setInsecure(); + mqtt_PRO = new Adafruit_MQTT_Client(&client_mqtt, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #elif defined(ESP32) + mqtt_PRO = new Adafruit_MQTT_Client(&client_s, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + #endif + } + else if (_broker == BLINKER_MQTT_BORKER_ONENET) { + mqtt_PRO = new Adafruit_MQTT_Client(&client, MQTT_HOST_PRO, MQTT_PORT_PRO, MQTT_ID_PRO, MQTT_NAME_PRO, MQTT_KEY_PRO); + } + + // iotPub = new Adafruit_MQTT_Publish(mqtt_PRO, BLINKER_PUB_TOPIC_PRO); + // if (!isMQTTinit) + iotSub_PRO = new Adafruit_MQTT_Subscribe(mqtt_PRO, BLINKER_SUB_TOPIC_PRO); + + // mqtt_broker = (char*)malloc((_broker.length()+1)*sizeof(char)); + // strcpy(mqtt_broker, _broker.c_str()); + // mqtt_broker = _broker; + + MDNS.end(); + webSocket_PRO.close(); + mDNSInit(MQTT_DEVICEID_PRO); + this->latestTime = millis(); + // if (!isMQTTinit) + mqtt_PRO->subscribe(iotSub_PRO); + isMQTTinit = true; + + #if defined(ESP8266) + // client_s->stop(); + client_mqtt.setInsecure(); + #endif + // connect(); + + + + return true; +} + +void BlinkerPROESP_QRCODE::mDNSInit(String name) +{ + delay(1000); + + BLINKER_LOG(BLINKER_F("WiFi.localIP: "), WiFi.localIP()); + +#if defined(ESP8266) + if (!MDNS.begin(name.c_str(), WiFi.localIP())) { +#elif defined(ESP32) + if (!MDNS.begin(name.c_str())) { +#endif + while(1) { + ::delay(100); + } + } + + BLINKER_LOG(BLINKER_F("mDNS responder started")); + + String _service = STRING_format(BLINKER_MDNS_SERVICE_BLINKER) + STRING_format(_deviceType); + + MDNS.addService(BLINKER_MDNS_SERVICE_BLINKER, "tcp", WS_SERVERPORT); + MDNS.addServiceTxt(BLINKER_MDNS_SERVICE_BLINKER, "tcp", "deviceName", name); + + // if (!isWSinit) + // { + webSocket_PRO.begin(); + webSocket_PRO.onEvent(webSocketEvent_PRO); + // } + BLINKER_LOG(BLINKER_F("webSocket_PRO server started")); + BLINKER_LOG(BLINKER_F("ws://"), name, BLINKER_F(".local:"), WS_SERVERPORT); + + // isWSinit = true; + + isApCfg = false; +} + +void BlinkerPROESP_QRCODE::checkKA() { + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerPROESP_QRCODE::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerPROESP_QRCODE::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerPROESP_QRCODE::checkMIOTKA() { + if (millis() - miKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerPROESP_QRCODE::checkCanPrint() { + if ((millis() - printTime >= BLINKER_PRO_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerPROESP_QRCODE::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerPROESP_QRCODE::checkMIOTPrintSpan() +{ + if (millis() - respMIOTTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respMIOTTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respMIOTTimes++; + return true; + } + } + else + { + respMIOTTimes = 0; + return true; + } +} + +int BlinkerPROESP_QRCODE::checkPrintSpan() { + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) { + BLINKER_ERR_LOG(BLINKER_F("WEBSOCKETS CLIENT NOT ALIVE OR MSG LIMIT")); + + return false; + } + else { + respTimes++; + return true; + } + } + else { + respTimes = 0; + return true; + } +} + +int BlinkerPROESP_QRCODE::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerPROESP_QRCODE::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerPROESP_QRCODE::pubHello() +{ + char stateJsonStr[256] = ("{\"message\":\"Registration successful\"}"); + + BLINKER_LOG_ALL(BLINKER_F("PUB hello: "), stateJsonStr); + + return print(stateJsonStr, false); +} + +int BlinkerPROESP_QRCODE::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(STRING_format(data)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG(BLINKER_F("Print data is not Json! "), data); + return false; + } + + return true; +} + + +// static IPAddress apIP(192, 168, 4, 1); +// #if defined(ESP8266) +// static IPAddress netMsk(255, 255, 255, 0); +// #endif + + +enum bwl_status_t +{ + BWL_CONFIG_CKECK, + BWL_CONFIG_FAIL, + BWL_CONFIG_SUCCESS, + BWL_CONNECTING, + BWL_CONNECTED, + BWL_DISCONNECTED, + BWL_SMARTCONFIG_BEGIN, + BWL_SMARTCONFIG_DONE, + BWL_SMARTCONFIG_TIMEOUT, + BWL_STACONFIG_BEGIN, + BWL_APCONFIG_BEGIN, + BWL_APCONFIG_DONE, + BWL_APCONFIG_TIMEOUT, + BWL_CONNECTED_CHECK, + BWL_RESET +}; + +class BlinkerWlan +{ + public : + BlinkerWlan() + : _status(BWL_CONFIG_CKECK) + {} + + bool checkConfig(); + void loadConfig(char *_ssid, char *_pswd); + void saveConfig(char *_ssid, char *_pswd); + void deleteConfig(); + void smartconfigBegin(uint16_t _time = 15000); + bool smartconfigDone(); + void connect(); + bool connected(); + void disconnect(); + void reset(); + bool run(); + bwl_status_t status() { return _status; } + + void setType(const char* _type) { + _deviceType = _type; + +#ifdef BLINKER_DEBUG_ALL + BLINKER_LOG(BLINKER_F("API deviceType: "), _type); +#endif + } + + void softAPinit(); + void serverClient(); + void parseUrl(String data); + void connectWiFi(String _ssid, String _pswd); + void connectWiFi(const char* _ssid, const char* _pswd); + + // uint8_t status() { return _status; } + + private : + + protected : + char *SSID; + char *PSWD; + const char* _deviceType; + uint32_t connectTime; + uint16_t timeout; + bwl_status_t _status; + uint32_t debugStatusTime; +}; + +bool BlinkerWlan::checkConfig() { + BLINKER_LOG_ALL(BLINKER_F("check wlan config")); + + char ok[2 + 1]; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_WLAN_CHECK, ok); + EEPROM.commit(); + EEPROM.end(); + + if (String(ok) != String("OK")) { + + BLINKER_LOG(BLINKER_F("wlan config check,fail")); + + _status = BWL_CONFIG_FAIL; + return false; + } + else { + + BLINKER_LOG(BLINKER_F("wlan config check,success")); + + _status = BWL_CONFIG_SUCCESS; + return true; + } +} + +void BlinkerWlan::loadConfig(char *_ssid, char *_pswd) { + char loadssid[BLINKER_SSID_SIZE]; + char loadpswd[BLINKER_PSWD_SIZE]; + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_SSID, loadssid); + EEPROM.get(BLINKER_EEP_ADDR_PSWD, loadpswd); + // char ok[2 + 1]; + // EEPROM.get(EEP_ADDR_WIFI_CFG + BLINKER_SSID_SIZE + BLINKER_PSWD_SIZE, ok); + EEPROM.commit(); + EEPROM.end(); + + strcpy(_ssid, loadssid); + strcpy(_pswd, loadpswd); + + BLINKER_LOG(BLINKER_F("SSID: "), _ssid, BLINKER_F(" PASWD: "), _pswd); +} + +void BlinkerWlan::saveConfig(char *_ssid, char *_pswd) { + char loadssid[BLINKER_SSID_SIZE]; + char loadpswd[BLINKER_PSWD_SIZE]; + + memcpy(loadssid, _ssid, BLINKER_SSID_SIZE); + memcpy(loadpswd, _pswd, BLINKER_PSWD_SIZE); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_SSID, loadssid); + EEPROM.put(BLINKER_EEP_ADDR_PSWD, loadpswd); + char ok[2 + 1] = "OK"; + EEPROM.put(BLINKER_EEP_ADDR_WLAN_CHECK, ok); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG(BLINKER_F("Save wlan config")); +} + +void BlinkerWlan::deleteConfig() { + char ok[3] = {0}; + EEPROM.begin(BLINKER_EEP_SIZE); + // for (int i = BLINKER_EEP_ADDR_WLAN_CHECK; i < BLINKER_WLAN_CHECK_SIZE; i++) + // EEPROM.write(i, 0); + EEPROM.put(BLINKER_EEP_ADDR_WLAN_CHECK, ok); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG(BLINKER_F("Erase wlan config")); +} + +void BlinkerWlan::smartconfigBegin(uint16_t _time) { + WiFi.mode(WIFI_STA); + delay(100); + String softAP_ssid = STRING_format(_deviceType) + "_" + macDeviceName(); + +#if defined(ESP8266) + WiFi.hostname(softAP_ssid); +#elif defined(ESP32) + WiFi.setHostname(softAP_ssid.c_str()); +#endif + + WiFi.beginSmartConfig(); + connectTime = millis(); + timeout = _time; + _status = BWL_SMARTCONFIG_BEGIN; + + BLINKER_LOG(BLINKER_F("Wait for Smartconfig")); +} + +bool BlinkerWlan::smartconfigDone() { + if (WiFi.smartConfigDone()) + { + // WiFi.setAutoConnect(true); + // WiFi.setAutoReconnect(true); + connectTime = millis(); + + _status = BWL_SMARTCONFIG_DONE; + + BLINKER_LOG(BLINKER_F("SmartConfig Success")); +#if defined(ESP8266) + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + // WiFi.begin(WiFi.SSID().c_str(), WiFi.psk().c_str()); + connectWiFi(WiFi.SSID().c_str(), WiFi.psk().c_str()); + // connectWiFi("有没有wifi", "i8888888"); +#endif + return true; + } + else { + return false; + } +} + +void BlinkerWlan::connect() { + switch (_status) { + case BWL_CONFIG_SUCCESS : + // WiFi.setAutoConnect(false); + // WiFi.setAutoReconnect(true); + + SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + + loadConfig(SSID, PSWD); + // WiFi.begin(SSID, PSWD); + connectWiFi(SSID, PSWD); + + free(SSID); + free(PSWD); + + _status = BWL_CONNECTING; + break; + case BWL_DISCONNECTED : + if (millis() - connectTime > 30000 && WiFi.status() != WL_CONNECTED) { + BLINKER_LOG(BLINKER_F("status: "), WiFi.status()); + + disconnect(); + // SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + // PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + // WiFi.reconnect(); + + char _ssid_[BLINKER_SSID_SIZE]; + char _pswd_[BLINKER_PSWD_SIZE]; + + loadConfig(_ssid_, _pswd_); + connectWiFi(_ssid_, _pswd_); + + // WiFi.setAutoConnect(false); + // WiFi.setAutoReconnect(true); + + // free(SSID); + // free(PSWD); + connectTime = millis(); + BLINKER_LOG(BLINKER_F("connecting BWL_DISCONNECTED")); + + BLINKER_LOG(BLINKER_F("_ssid_: "), _ssid_, BLINKER_F(" _pswd_: "), _pswd_); + } + else if(WiFi.status() == WL_CONNECTED) { + _status = BWL_CONNECTED; + } + break; + } +} + +bool BlinkerWlan::connected() { + switch (_status) { + case BWL_SMARTCONFIG_DONE : + if (WiFi.status() != WL_CONNECTED) { + if (millis() - connectTime > 15000) + { + BLINKER_LOG(BLINKER_F("smartConfig time out")); + + WiFi.stopSmartConfig(); + _status = BWL_SMARTCONFIG_TIMEOUT; + } + return false; + } + else if (WiFi.status() == WL_CONNECTED) { + // WiFi.stopSmartConfig(); + + IPAddress deviceIP = WiFi.localIP(); + BLINKER_LOG(BLINKER_F("WiFi connected")); + BLINKER_LOG(BLINKER_F("IP address: ")); + BLINKER_LOG(deviceIP); + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + + SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + memcpy(SSID,"\0",BLINKER_SSID_SIZE); + memcpy(SSID,WiFi.SSID().c_str(),BLINKER_SSID_SIZE); + memcpy(PSWD,"\0",BLINKER_PSWD_SIZE); + memcpy(PSWD,WiFi.psk().c_str(),BLINKER_PSWD_SIZE); + saveConfig(SSID, PSWD); + free(SSID); + free(PSWD); + + // WiFi.setAutoConnect(true); + // WiFi.setAutoReconnect(true); + + _status = BWL_CONNECTED_CHECK; + + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + // break; + case BWL_APCONFIG_DONE : + if (WiFi.status() != WL_CONNECTED) { + if (millis() - connectTime > 15000) + { + BLINKER_LOG(BLINKER_F("APConfig time out")); + + // WiFi.stopSmartConfig(); + _status = BWL_APCONFIG_TIMEOUT; + } + return false; + } + else if (WiFi.status() == WL_CONNECTED) { + IPAddress deviceIP = WiFi.localIP(); + BLINKER_LOG(BLINKER_F("WiFi connected")); + BLINKER_LOG(BLINKER_F("IP address: ")); + BLINKER_LOG(deviceIP); + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + + // SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + // PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + // memcpy(SSID,"\0",BLINKER_SSID_SIZE); + // memcpy(SSID,WiFi.SSID().c_str(),BLINKER_SSID_SIZE); + // memcpy(PSWD,"\0",BLINKER_PSWD_SIZE); + // memcpy(PSWD,WiFi.psk().c_str(),BLINKER_PSWD_SIZE); + saveConfig(SSID, PSWD); + free(SSID); + free(PSWD); + + // WiFi.setAutoConnect(true); + // WiFi.setAutoReconnect(true); + + _status = BWL_CONNECTED_CHECK; + return true; + } + break; + case BWL_CONNECTING : + if (WiFi.status() == WL_CONNECTED) { + IPAddress deviceIP = WiFi.localIP(); + BLINKER_LOG(BLINKER_F("WiFi connected")); + BLINKER_LOG(BLINKER_F("IP address: ")); + BLINKER_LOG(deviceIP); + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + + _status = BWL_CONNECTED_CHECK; + return true; + } + else if (WiFi.status() != WL_CONNECTED) { + return false; + } + case BWL_CONNECTED_CHECK : + // if (WiFi.status() != WL_CONNECTED) + // _status = BWL_DISCONNECTED; + if (WiFi.status() == WL_CONNECTED) + { + return true; + } + else + { + _status = BWL_DISCONNECTED; + return false; + } + case BWL_RESET : + return false; + default : + if (WiFi.status() == WL_CONNECTED) { + IPAddress deviceIP = WiFi.localIP(); + BLINKER_LOG(BLINKER_F("WiFi connected")); + BLINKER_LOG(BLINKER_F("IP address: ")); + BLINKER_LOG(deviceIP); + BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + + _status = BWL_CONNECTED_CHECK; + return true; + } + return false; + } + return false; +} + +void BlinkerWlan::disconnect() { + WiFi.disconnect(); + delay(100); + _status = BWL_DISCONNECTED; + BLINKER_LOG(BLINKER_F("WiFi disconnected")); +} + +void BlinkerWlan::reset() { + disconnect(); + _status = BWL_RESET; +} + +void BlinkerWlan::softAPinit() { + // _server = new WiFiServer(80); + + IPAddress apIP(192, 168, 4, 1); + #if defined(ESP8266) + IPAddress netMsk(255, 255, 255, 0); + #endif + + WiFi.mode(WIFI_AP); + + delay(1000); + + String softAP_ssid = STRING_format(_deviceType) + "_" + macDeviceName(); + +#if defined(ESP8266) + WiFi.hostname(softAP_ssid.c_str()); + WiFi.softAPConfig(apIP, apIP, netMsk); +#elif defined(ESP32) + WiFi.setHostname(softAP_ssid.c_str()); + WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); +#endif + + WiFi.softAP(softAP_ssid.c_str(), NULL); + delay(100); + + // _server->begin(); + // BLINKER_LOG(BLINKER_F("AP IP address: "), WiFi.softAPIP()); + // BLINKER_LOG(BLINKER_F("HTTP _server started")); + // BLINKER_LOG(String("URL: http://" + WiFi.softAPIP())); + + #if defined(ESP8266) + if (!MDNS.begin(softAP_ssid.c_str(), WiFi.localIP())) { + #elif defined(ESP32) + if (!MDNS.begin(softAP_ssid.c_str())) { + #endif + while(1) { + ::delay(100); + } + } + + BLINKER_LOG(BLINKER_F("mDNS responder started")); + + MDNS.addService(BLINKER_MDNS_SERVICE_BLINKER, "tcp", WS_SERVERPORT); + MDNS.addServiceTxt(BLINKER_MDNS_SERVICE_BLINKER, "tcp", "deviceName", macDeviceName()); + + webSocket_PRO.begin(); + webSocket_PRO.onEvent(webSocketEvent_PRO); + + _status = BWL_APCONFIG_BEGIN; + + isApCfg = true; + + BLINKER_LOG(BLINKER_F("Wait for APConfig")); +} + +void BlinkerWlan::serverClient() +{ + webSocket_PRO.loop(); + + #if defined(ESP8266) + MDNS.update(); + #endif + + if (isAvail_PRO) + { + BLINKER_LOG(BLINKER_F("checkAPCFG: "), msgBuf_PRO); + + if (STRING_contains_string(msgBuf_PRO, "ssid") && \ + STRING_contains_string(msgBuf_PRO, "pswd")) + { + parseUrl(msgBuf_PRO); + } + isAvail_PRO = false; + } + // if (!_client) + // { + // _client = _server->available(); + // } + // else + // { + // // if (_client.status() == CLOSED) + // if (!_client.connected()) + // { + // _client.stop(); + // BLINKER_LOG(BLINKER_F("Connection closed on _client")); + // } + // else + // { + // if (_client.available()) + // { + // String data = _client.readStringUntil('\r'); + + // // data = data.substring(4, data.length() - 9); + // _client.flush(); + + // // BLINKER_LOG("clientData: ", data); + + // if (STRING_contains_string(data, "ssid") && STRING_contains_string(data, "pswd")) { + + // String msg = BLINKER_F("{\"hello\":\"world\"}"); + + // String s= BLINKER_F("HTTP/1.1 200 OK\r\nContent-Type: application/json;charset=utf-8\r\n"); + // s += BLINKER_F("Content-Length: "); + // s += String(msg.length()); + // s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); + // s += msg; + // s += BLINKER_F("\r\n"); + + // _client.print(s); + + // _client.stop(); + + // parseUrl(data); + // } + // } + // } + // } +} + +void BlinkerWlan::parseUrl(String data) +{ + BLINKER_LOG(BLINKER_F("APCONFIG data: "), data); + // DynamicJsonBuffer jsonBuffer; + // JsonObject& wifi_data = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject wifi_data = jsonBuffer.as(); + + // if (!wifi_data.success()) + if (error) + { + return; + } + + String _ssid = wifi_data["ssid"]; + String _pswd = wifi_data["pswd"]; + + BLINKER_LOG(BLINKER_F("ssid: "), _ssid); + BLINKER_LOG(BLINKER_F("pswd: "), _pswd); + + // free(_server); + MDNS.end(); + webSocket_PRO.close(); + + SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); + PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + + strcpy(SSID, _ssid.c_str()); + strcpy(PSWD, _pswd.c_str()); + connectWiFi(_ssid, _pswd); + connectTime = millis(); + _status = BWL_APCONFIG_DONE; + + BLINKER_LOG(BLINKER_F("APConfig Success")); +} + +void BlinkerWlan::connectWiFi(String _ssid, String _pswd) +{ + connectWiFi(_ssid.c_str(), _pswd.c_str()); +} + +void BlinkerWlan::connectWiFi(const char* _ssid, const char* _pswd) +{ + uint32_t connectTime = millis(); + + BLINKER_LOG(BLINKER_F("Connecting to "), _ssid); + + WiFi.mode(WIFI_STA); + String _hostname = STRING_format(_deviceType) + "_" + macDeviceName(); + + #if defined(ESP8266) + WiFi.hostname(_hostname); + #elif defined(ESP32) + WiFi.setHostname(_hostname.c_str()); + #endif + + if (_pswd && strlen(_pswd)) { + WiFi.begin(_ssid, _pswd); + } + else { + WiFi.begin(_ssid); + } + + // while (WiFi.status() != WL_CONNECTED) { + // ::delay(50); + + // if (millis() - connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { + // connectTime = millis(); + // BLINKER_LOG(("WiFi connect timeout, please check ssid and pswd!")); + // BLINKER_LOG(("Retring WiFi connect again!")); + // } + // } + // BLINKER_LOG(("Connected")); + + // IPAddress myip = WiFi.localIP(); + // BLINKER_LOG(("Your IP is: "), myip); + + // mDNSInit(); +} + +bool BlinkerWlan::run() +{ + // if (millis() - debugStatusTime > 10000) { + // debugStatusTime = millis(); + + // BLINKER_LOG_ALL("WLAN status: ", _status); + // } + + switch (_status) { + case BWL_CONFIG_CKECK : + checkConfig(); + break; + case BWL_CONFIG_FAIL : + // #if defined(BLINKER_ESP_SMARTCONFIG) + // smartconfigBegin(); + // #elif defined(BLINKER_APCONFIG) + // softAPinit(); + // #endif + if (_configType == BLINKER_SMART_CONFIG) + { + smartconfigBegin(); + } + else + { + softAPinit(); + } + break; + case BWL_CONFIG_SUCCESS : + connect(); + break; + case BWL_CONNECTING : + return connected(); + break; + case BWL_CONNECTED : + return connected(); + break; + case BWL_DISCONNECTED : + connect(); + break; + case BWL_SMARTCONFIG_BEGIN : + if (_configType == BLINKER_SMART_CONFIG) + { + smartconfigDone(); + } + else + { + WiFi.stopSmartConfig(); + _status = BWL_CONFIG_FAIL; + } + break; + case BWL_SMARTCONFIG_DONE : + return connected(); + break; + case BWL_SMARTCONFIG_TIMEOUT : + _status = BWL_CONFIG_FAIL; + break; + case BWL_STACONFIG_BEGIN : + connect(); + break; + case BWL_APCONFIG_BEGIN : + serverClient(); + break; + case BWL_APCONFIG_DONE : + return connected(); + break; + case BWL_APCONFIG_TIMEOUT : + _status = BWL_CONFIG_FAIL; + break; + case BWL_CONNECTED_CHECK : + return connected(); + break; + case BWL_RESET: + break; + default : + break; + } + return false; +} + +#endif + +#endif diff --git a/blinker-library/src/Adapters/BlinkerPROSIM7020.h b/blinker-library/src/Adapters/BlinkerPROSIM7020.h new file mode 100644 index 0000000..811215c --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerPROSIM7020.h @@ -0,0 +1,1326 @@ +#ifndef BLINKER_PRO_SIM7020_H +#define BLINKER_PRO_SIM7020_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" +#include "../Functions/BlinkerHTTPSIM7020.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +#include "../Functions/BlinkerMQTTSIM7020.h" + +#include + +char* MQTT_HOST_NBIoT; +char* MQTT_ID_NBIoT; +char* MQTT_NAME_NBIoT; +char* MQTT_KEY_NBIoT; +char* MQTT_PRODUCTINFO_NBIoT; +char* UUID_NBIoT; +char* AUTHKEY_NBIoT; +char* MQTT_DEVICEID_NBIoT; +// char* DEVICE_NAME_NBIoT; +char* BLINKER_PUB_TOPIC_NBIoT; +char* BLINKER_SUB_TOPIC_NBIoT; +uint16_t MQTT_PORT_NBIoT; + +BlinkerMQTTSIM7020* mqtt_NBIoT; + +class BlinkerProSIM7020 : public BlinkerStream +{ + public : + BlinkerProSIM7020() + : stream(NULL), isConnect(false) + {} + + int connect(); + int connected(); + int mConnected(); + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + void subscribe(); + int timedRead(); + char * lastRead() { if (isFresh_NBIoT) return msgBuf_NBIoT; return ""; } + void flush(); + // int print(const String & s, bool needCheck = true); + int print(char * data, bool needCheck = true); + int toServer(char * data); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + // void aliType(const String & type); + // void duerType(const String & type); + void begin(const char* _deviceType, String _imei); + void initStream(Stream& s, bool state, blinker_callback_t func); + int autoPrint(unsigned long id); + char * deviceName(); + char * authKey() { return AUTHKEY_NBIoT; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_NBIoT; } + int init() { return isMQTTinit; } + int reRegister() { return connectServer(); } + int deviceRegister() { return connectServer(); } + int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + private : + bool isMQTTinit = false; + + int connectServer(); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + + protected : + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + Stream* stream; + // char* streamData; + char* msgBuf_NBIoT; + // bool isFresh = false; + bool isFresh_NBIoT = false; + bool isConnect; + bool isHWS = false; + char* imei; + // uint8_t respTimes = 0; + // uint32_t respTime = 0; + bool isAvail_NBIoT = false; + uint8_t dataFrom_NBIoT = BLINKER_MSG_FROM_MQTT; + + // uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + const char* _deviceType;//_authKey + // char* _aliType; + // char* _duerType; + bool isAlive = false; + // bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + char* mqtt_broker; + + bool isNew = false; + bool isAuth = false; + bool isFirst = false; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; + blinker_callback_t listenFunc = NULL; +}; + +int BlinkerProSIM7020::connect() +{ + if (!isMQTTinit) return false; + + if (mqtt_NBIoT->connected()) return true; + + disconnect(); + + if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + { + yield(); + return false; + } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!mqtt_NBIoT->connect()) + { + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + reRegister(); + reconnect_time = 0; + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + this->latestTime = millis(); + + return true; +} + +int BlinkerProSIM7020::connected() +{ + if (!isMQTTinit) return false; + + return mqtt_NBIoT->connected(); +} + +int BlinkerProSIM7020::mConnected() +{ + if (!isMQTTinit) return false; + else return mqtt_NBIoT->connected(); +} + +void BlinkerProSIM7020::disconnect() +{ + if (isMQTTinit) mqtt_NBIoT->disconnect(); +} + +void BlinkerProSIM7020::ping() +{ + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!isMQTTinit) return; + + if (!mqtt_NBIoT->connected()) + { + disconnect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } +} + +int BlinkerProSIM7020::available() +{ + if (isMQTTinit) { + checkKA(); + + // if (!mqtt_PRO->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > 30000) + { + ping(); + } + else + { + subscribe(); + } + } + + if (isAvail_NBIoT) + { + isAvail_NBIoT = false; + return true; + } + else { + return false; + } +} + +int BlinkerProSIM7020::aligenieAvail() +{ + if (!isMQTTinit) return false; + + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerProSIM7020::duerAvail() +{ + if (!isMQTTinit) return false; + + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +void BlinkerProSIM7020::subscribe() +{ + if (!isMQTTinit) return; + + if (mqtt_NBIoT->readSubscription()) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), mqtt_NBIoT->lastRead); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(String(mqtt_NBIoT->lastRead)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, String(mqtt_NBIoT->lastRead)); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"]; + String dataGet = root["data"]; + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_NBIoT) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_NBIoT = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT) + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_NBIoT = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + check is from bridge/share device, \ + data: "), dataGet); + + _needCheckShare = true; + } + } + } + // root.printTo(dataGet); + serializeJson(root, dataGet); + + isAvail_NBIoT = true; + isAlive = true; + } + + if (isFresh_NBIoT) free(msgBuf_NBIoT); + msgBuf_NBIoT = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_NBIoT, dataGet.c_str()); + isFresh_NBIoT = true; + + this->latestTime = millis(); + + dataFrom_NBIoT = BLINKER_MSG_FROM_MQTT; + } +} + +void BlinkerProSIM7020::flush() +{ + if (isFresh_NBIoT) + { + free(msgBuf_NBIoT); isFresh_NBIoT = false; isAvail_NBIoT = false; + isAliAvail = false; //isBavail = false; + } +} + +int BlinkerProSIM7020::print(char * data, bool needCheck) +{ + if (!isMQTTinit) return false; + + BLINKER_LOG_ALL(BLINKER_F("data: "), data); + + uint16_t num = strlen(data); + + data[num+8] = '\0'; + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+7] = data[c_num-1]; + } + + // String data_add = BLINKER_F("{\"data\":"); + char data_add[20] = "{\"data\":"; + for(uint16_t c_num = 0; c_num < 8; c_num++) + { + data[c_num] = data_add[c_num]; + } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, ",\"fromDevice\":\""); + strcat(data, MQTT_DEVICEID_NBIoT); + // strcat(data, MQTT_DEVICEID_NBIoT); //PRO + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, "\",\"toDevice\":\""); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + strcat(data, _sharers[_sharerFrom]->uuid()); + } + else + { + strcat(data, UUID_NBIoT); + } + // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // strcat(data, data_add.c_str()); + strcat(data, "\",\"deviceType\":\"OwnApp\"}"); + + // data_add = STRING_format(data); + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (mqtt_NBIoT->connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + // if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, msg_data.c_str())) + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerProSIM7020::toServer(char * data) +{ + if (!isMQTTinit) return false; + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish to server...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (mqtt_NBIoT->connected()) + { + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerProSIM7020::bPrint(char * name, const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_DEVICEID_NBIoT); + strcat(data_add, ",\"toDevice\":\""); + strcat(data_add, name); + strcat(data_add, "\",\"deviceType\":\"DiyBridge\"}"); + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\""); + // data_add += name; + // data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_NBIoT->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_NBIoT); + + // if (! iotPub.publish(payload.c_str())) { + + // String bPubTopic = BLINKER_F(""); + // char bPubTopic[60] = { '\0' }; + + // if (strcmp(mqtt_broker, BLINKER_MQTT_BORKER_ONENET) == 0) + // { + // // bPubTopic = MQTT_PRODUCTINFO_MQTT; + // // bPubTopic += BLINKER_F("/"); + // // bPubTopic += name; + // // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // strcpy(bPubTopic, BLINKER_PUB_TOPIC_NBIoT); + // bPubTopic = BLINKER_PUB_TOPIC_NBIoT; + // } + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerProSIM7020::aliPrint(const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_DEVICEID_NBIoT); + strcat(data_add, "\",\"toDevice\":\"AliGenie_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_NBIoT->connected()) + { + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerProSIM7020::duerPrint(const String & data, bool report) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_DEVICEID_NBIoT); + strcat(data_add, "\",\"toDevice\":\"DuerOS_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_NBIoT->connected()) + { + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +// void BlinkerProSIM7020::aliType(const String & type) +// { +// _aliType = (char*)malloc((type.length()+1)*sizeof(char)); +// strcpy(_aliType, type.c_str()); +// BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +// } + +// void BlinkerProSIM7020::duerType(const String & type) +// { +// _duerType = (char*)malloc((type.length()+1)*sizeof(char)); +// strcpy(_duerType, type.c_str()); +// BLINKER_LOG_ALL(BLINKER_F("_duerType: "), _duerType); +// } + +void BlinkerProSIM7020::begin(const char* _type, String _imei) +{ + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + // stream = &s; + // stream->setTimeout(BLINKER_STREAM_TIMEOUT); + // isHWS = state; + + imei = (char*)malloc((_imei.length() + 1)*sizeof(char)); + strcpy(imei, _imei.c_str()); + + // AUTHKEY_NBIoT = (char*)malloc((strlen(_deviceType) + 1)*sizeof(char)); + // strcpy(AUTHKEY_NBIoT, _deviceType); +} + +void BlinkerProSIM7020::initStream(Stream& s, bool state, blinker_callback_t func) +{ + // _deviceType = _type; + + // BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + stream = &s; + stream->setTimeout(BLINKER_STREAM_TIMEOUT); + isHWS = state; + + listenFunc = func; + + stream->println(BLINKER_CMD_AT); + ::delay(200); + stream->println(BLINKER_CMD_CRESET_RESQ); + + // _imei = (char*)malloc(imei.length()*sizeof(char)); + // strcpy(_imei, imei.c_str()); +} + +int BlinkerProSIM7020::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"trigged\":true,\"autoData\":{"); + payload += BLINKER_F("\"autoId\":"); + payload += STRING_format(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(MQTT_DEVICEID_NBIoT); + payload += BLINKER_F("\",\"toDevice\":\"autoManager\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_NBIoT->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_NBIoT); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +char * BlinkerProSIM7020::deviceName() +{ + BLINKER_LOG_ALL(BLINKER_F("BlinkerProSIM7020::deviceName: "), MQTT_DEVICEID_NBIoT); + return MQTT_DEVICEID_NBIoT;/*MQTT_ID_PRO;*/ +} + +void BlinkerProSIM7020::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (uint8_t num = _sharerCount; num > 0; num--) + { + delete _sharers[num - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerProSIM7020::authCheck() +{ + uint8_t _authCheck; + + BLINKER_LOG_ALL(BLINKER_F("authCheck start")); + + #if defined(ESP8266) || defined(ESP32) + EEPROM.begin(BLINKER_EEP_SIZE); + #endif + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck == BLINKER_AUTH_CHECK_DATA) + { + #if defined(ESP8266) || defined(ESP32) + EEPROM.commit(); + EEPROM.end(); + #endif + isAuth = true; + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return true; + } + #if defined(ESP8266) || defined(ESP32) + EEPROM.commit(); + EEPROM.end(); + #endif + + BLINKER_LOG_ALL(BLINKER_F("authCheck end")); + + return false; +} + +int BlinkerProSIM7020::connectServer() +{ + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + String uri = ""; + uri += BLINKER_F("/api/v1/user/device/register?deviceType="); + uri += _deviceType; + uri += BLINKER_F("&deviceName="); + // uri += imei; + + if (_deviceType != BLINKER_AIR_STATION) + { + // url_iot += macDeviceName(); + uri += imei; + } + else + { + // uri += "TESTA69BA016"; // 1 + // uri += "TEST656A2782"; // 2 + // uri += "TESTD1C4B294"; // 3 + // uri += "TEST687991DC"; // 4 + uri += "TEST872B3982"; // 5 + } + // uri += BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + // uri += _deviceType; + // uri += _aliType; + // uri += _duerType; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host + uri); + + BlinkerHTTPSIM7020 http(*stream, isHWS, listenFunc); + + http.begin(host, uri); + + String payload; + + if (http.GET()) + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... success")); + + payload = http.getString(); + + // return true; + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed")); + + return false; + } + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + String _authKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_KEY]; + + if (isMQTTinit) + { + free(MQTT_HOST_NBIoT); + free(MQTT_ID_NBIoT); + free(MQTT_NAME_NBIoT); + free(MQTT_KEY_NBIoT); + free(MQTT_PRODUCTINFO_NBIoT); + free(UUID_NBIoT); + free(AUTHKEY_NBIoT); + // free(DEVICE_NAME_NBIoT); + free(BLINKER_PUB_TOPIC_NBIoT); + free(BLINKER_SUB_TOPIC_NBIoT); + free(mqtt_NBIoT); + // free(iotSub_NBIoT); + + isMQTTinit = false; + } + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); + // String _deviceName = _userID.substring(12, 36); + MQTT_DEVICEID_NBIoT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_NBIoT, _userID.c_str()); + MQTT_ID_NBIoT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_NBIoT, _userID.c_str()); + MQTT_NAME_NBIoT = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_NBIoT, _userName.c_str()); + MQTT_KEY_NBIoT = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_NBIoT, _key.c_str()); + MQTT_PRODUCTINFO_NBIoT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_NBIoT, _productInfo.c_str()); + MQTT_HOST_NBIoT = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_NBIoT, BLINKER_MQTT_ALIYUN_HOST); + AUTHKEY_NBIoT = (char*)malloc((_authKey.length()+1)*sizeof(char)); + strcpy(AUTHKEY_NBIoT, _authKey.c_str()); + MQTT_PORT_NBIoT = BLINKER_MQTT_ALIYUN_PORT; + } + + UUID_NBIoT = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_NBIoT, _uuid.c_str()); + + char uuid_eeprom[BLINKER_AUUID_SIZE]; + + BLINKER_LOG_ALL(("==========AUTH CHECK==========")); + + if (!isFirst) + { + char _authCheck; + + #if defined(ESP8266) || defined(ESP32) + EEPROM.begin(BLINKER_EEP_SIZE); + #endif + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + if (strcmp(uuid_eeprom, _uuid.c_str()) != 0) { + // strcpy(UUID_PRO, _uuid.c_str()); + + strcpy(uuid_eeprom, _uuid.c_str()); + EEPROM.put(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("uuid_eeprom: "), uuid_eeprom); + BLINKER_LOG_ALL(BLINKER_F("_uuid: "), _uuid); + isNew = true; + } + EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + if (_authCheck != BLINKER_AUTH_CHECK_DATA) { + EEPROM.put(BLINKER_EEP_ADDR_AUTH_CHECK, BLINKER_AUTH_CHECK_DATA); + isAuth = true; + } + #if defined(ESP8266) || defined(ESP32) + EEPROM.commit(); + EEPROM.end(); + #endif + + isFirst = true; + } + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME_NBIoT: "), imei); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_NBIoT: "), MQTT_PRODUCTINFO_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_DEVICEID_NBIoT: "), MQTT_DEVICEID_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_NBIoT: "), MQTT_ID_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_NBIoT: "), MQTT_NAME_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_NBIoT: "), MQTT_KEY_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("UUID_NBIoT: "), UUID_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_NBIoT: "), AUTHKEY_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_NBIoT; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_DEVICEID_NBIoT; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_NBIoT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_NBIoT, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_NBIoT, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_NBIoT: "), BLINKER_PUB_TOPIC_NBIoT); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_NBIoT; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_DEVICEID_NBIoT; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_NBIoT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_NBIoT, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_NBIoT, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_NBIoT: "), BLINKER_SUB_TOPIC_NBIoT); + } + + // if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + mqtt_NBIoT = new BlinkerMQTTSIM7020(*stream, isHWS, MQTT_HOST_NBIoT, MQTT_PORT_NBIoT, + MQTT_ID_NBIoT, MQTT_NAME_NBIoT, MQTT_KEY_NBIoT, listenFunc); + // } + + this->latestTime = millis(); + isMQTTinit = true; + mqtt_NBIoT->subscribe(BLINKER_SUB_TOPIC_NBIoT); + + return true; +} + +void BlinkerProSIM7020::checkKA() +{ + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerProSIM7020::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerProSIM7020::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerProSIM7020::checkCanPrint() { + if ((millis() - printTime >= BLINKER_PRO_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerProSIM7020::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerProSIM7020::checkPrintSpan() +{ + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) + { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG(BLINKER_F("DEVICE NOT CONNECT OR MSG LIMIT")); + + return false; + } + else + { + respTimes++; + return true; + } + } + else + { + respTimes = 0; + return true; + } +} + +int BlinkerProSIM7020::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerProSIM7020::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerProSIM7020::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG("Print data is not Json! ", data); + return false; + } + return true; +} + +#endif diff --git a/blinker-library/src/Adapters/BlinkerQRCodeSIM7000.h b/blinker-library/src/Adapters/BlinkerQRCodeSIM7000.h new file mode 100644 index 0000000..957fe8f --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerQRCodeSIM7000.h @@ -0,0 +1,1274 @@ +#ifndef BLINKER_QRCODE_SIM7000_H +#define BLINKER_QRCODE_SIM7000_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" +#include "../Functions/BlinkerSIM7000.h" +#include "../Functions/BlinkerHTTPSIM7000.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +#include "../Functions/BlinkerMQTTSIM7000.h" + +char* MQTT_HOST_NBIoT; +char* MQTT_ID_NBIoT; +char* MQTT_NAME_NBIoT; +char* MQTT_KEY_NBIoT; +char* MQTT_PRODUCTINFO_NBIoT; +char* UUID_NBIoT; +char* AUTHKEY_NBIoT; +char* MQTT_DEVICEID_NBIoT; +char* DEVICE_NAME_NBIoT; +char* BLINKER_PUB_TOPIC_NBIoT; +char* BLINKER_SUB_TOPIC_NBIoT; +uint16_t MQTT_PORT_NBIoT; + +BlinkerMQTTSIM7000* mqtt_NBIoT; + +class BlinkerQRCodeSIM7000 : public BlinkerStream +{ + public : + BlinkerQRCodeSIM7000() + : stream(NULL), isConnect(false) + {} + + int connect(); + int connected(); + int mConnected(); + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + void subscribe(); + int timedRead(); + char * lastRead() { if (isFresh_NBIoT) return msgBuf_NBIoT; return ""; } + void flush(); + // int print(const String & s, bool needCheck = true); + int print(char * data, bool needCheck = true); + int toServer(char * data); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + void aliType(const String & type); + void duerType(const String & type); + void begin(const char* _auth, const char* _type, String _imei); + void initStream(Stream& s, bool state, blinker_callback_t func); + int autoPrint(unsigned long id); + char * deviceName(); + char * authKey() { return AUTHKEY_NBIoT; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_NBIoT; } + int init() { return isMQTTinit; } + int reRegister() { return connectServer(); } + int deviceRegister() { return connectServer(); } + // int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + private : + bool isMQTTinit = false; + + int connectServer(); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + + protected : + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + Stream* stream; + // char* streamData; + char* msgBuf_NBIoT; + // bool isFresh = false; + bool isFresh_NBIoT = false; + bool isConnect; + bool isHWS = false; + char* imei; + // uint8_t respTimes = 0; + // uint32_t respTime = 0; + bool isAvail_NBIoT = false; + uint8_t dataFrom_NBIoT = BLINKER_MSG_FROM_MQTT; + + // uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + const char* _deviceType;//_authKey + const char* _authKey; + char* _aliType; + char* _duerType; + bool isAlive = false; + // bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + char* mqtt_broker; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; + blinker_callback_t listenFunc = NULL; +}; + +int BlinkerQRCodeSIM7000::connect() +{ + BLINKER_LOG_ALL(BLINKER_F(">>>>>> mqtt connect <<<<<<")); + + if (!isMQTTinit) return false; + + // if (mqtt_NBIoT->connected()) return true; + if (isConnect) return true; + + BLINKER_LOG_ALL(BLINKER_F(">>>>>> mqtt connect failed <<<<<<")); + + disconnect(); + + // if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + // { + // yield(); + // return false; + // } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!mqtt_NBIoT->connect()) + { + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + reRegister(); + reconnect_time = 0; + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + isConnect = true; + + this->latestTime = millis(); + + return true; +} + +int BlinkerQRCodeSIM7000::connected() +{ + if (!isMQTTinit) return false; + + return isConnect;//mqtt_NBIoT->connected(); +} + +int BlinkerQRCodeSIM7000::mConnected() +{ + if (!isMQTTinit) return false; + else return mqtt_NBIoT->connected(); +} + +void BlinkerQRCodeSIM7000::disconnect() +{ + if (isMQTTinit) { + isConnect = false; + mqtt_NBIoT->disconnect(); + } +} + +void BlinkerQRCodeSIM7000::ping() +{ + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!isMQTTinit) return; + + if (!isConnect) + { + // disconnect(); + + delay(100); + + connect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } + + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + + BLINKER_LOG_ALL(BLINKER_F("check isReboot")); + + if (BLINKER_SIM7000.isReboot()) + { + BLINKER_SIM7000.powerCheck(); + + // disconnect(); + } +} + +int BlinkerQRCodeSIM7000::available() +{ + if (isMQTTinit) { + checkKA(); + + // if (!mqtt_PRO->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > 30000) + { + ping(); + } + else + { + subscribe(); + } + } + + if (isAvail_NBIoT) + { + isAvail_NBIoT = false; + return true; + } + else { + return false; + } +} + +int BlinkerQRCodeSIM7000::aligenieAvail() +{ + if (!isMQTTinit) return false; + + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerQRCodeSIM7000::duerAvail() +{ + if (!isMQTTinit) return false; + + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +void BlinkerQRCodeSIM7000::subscribe() +{ + if (!isMQTTinit) return; + + if (mqtt_NBIoT->readSubscription()) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), mqtt_NBIoT->lastRead); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(String(mqtt_NBIoT->lastRead)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, String(mqtt_NBIoT->lastRead)); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"]; + String dataGet = root["data"]; + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_NBIoT) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_NBIoT = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT) + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_NBIoT = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + check is from bridge/share device, \ + data: "), dataGet); + + _needCheckShare = true; + } + } + } + // root.printTo(dataGet); + serializeJson(root, dataGet); + + isAvail_NBIoT = true; + isAlive = true; + } + + if (isFresh_NBIoT) free(msgBuf_NBIoT); + msgBuf_NBIoT = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_NBIoT, dataGet.c_str()); + isFresh_NBIoT = true; + + this->latestTime = millis(); + + dataFrom_NBIoT = BLINKER_MSG_FROM_MQTT; + } +} + +void BlinkerQRCodeSIM7000::flush() +{ + if (isFresh_NBIoT) + { + free(msgBuf_NBIoT); isFresh_NBIoT = false; isAvail_NBIoT = false; + isAliAvail = false; //isBavail = false; + } +} + +int BlinkerQRCodeSIM7000::print(char * data, bool needCheck) +{ + if (!isMQTTinit) return false; + + BLINKER_LOG_ALL(BLINKER_F("data: "), data); + + uint16_t num = strlen(data); + + data[num+8] = '\0'; + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+7] = data[c_num-1]; + } + + // String data_add = BLINKER_F("{\"data\":"); + char data_add[20] = "{\"data\":"; + for(uint16_t c_num = 0; c_num < 8; c_num++) + { + data[c_num] = data_add[c_num]; + } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, ",\"fromDevice\":\""); + strcat(data, MQTT_ID_NBIoT); + // strcat(data, MQTT_DEVICEID_NBIoT); //PRO + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, "\",\"toDevice\":\""); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + strcat(data, _sharers[_sharerFrom]->uuid()); + } + else + { + strcat(data, UUID_NBIoT); + } + // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // strcat(data, data_add.c_str()); + strcat(data, "\",\"deviceType\":\"OwnApp\"}"); + + // data_add = STRING_format(data); + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + // if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, msg_data.c_str())) + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + disconnect(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + + +int BlinkerQRCodeSIM7000::toServer(char * data) +{ + if (!isMQTTinit) return false; + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish to server...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (mqtt_NBIoT->connected()) + { + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerQRCodeSIM7000::bPrint(char * name, const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_NBIoT); + strcat(data_add, ",\"toDevice\":\""); + strcat(data_add, name); + strcat(data_add, "\",\"deviceType\":\"DiyBridge\"}"); + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\""); + // data_add += name; + // data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_NBIoT->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + + // if (! iotPub.publish(payload.c_str())) { + + // String bPubTopic = BLINKER_F(""); + // char bPubTopic[60] = { '\0' }; + + // if (strcmp(mqtt_broker, BLINKER_MQTT_BORKER_ONENET) == 0) + // { + // // bPubTopic = MQTT_PRODUCTINFO_MQTT; + // // bPubTopic += BLINKER_F("/"); + // // bPubTopic += name; + // // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // strcpy(bPubTopic, BLINKER_PUB_TOPIC_MQTT); + // bPubTopic = BLINKER_PUB_TOPIC_MQTT; + // } + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerQRCodeSIM7000::aliPrint(const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_NBIoT); + strcat(data_add, "\",\"toDevice\":\"AliGenie_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_NBIoT->connected()) + { + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerQRCodeSIM7000::duerPrint(const String & data, bool report) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_NBIoT); + strcat(data_add, "\",\"toDevice\":\"DuerOS_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_NBIoT->connected()) + { + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +void BlinkerQRCodeSIM7000::aliType(const String & type) +{ + _aliType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_aliType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +} + +void BlinkerQRCodeSIM7000::duerType(const String & type) +{ + _duerType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_duerType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_duerType: "), _duerType); +} + +void BlinkerQRCodeSIM7000::begin(const char* _auth, const char* _type, String _imei) +{ + _authKey = _auth; + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + // stream = &s; + // stream->setTimeout(BLINKER_STREAM_TIMEOUT); + // isHWS = state; + + imei = (char*)malloc((_imei.length() + 1)*sizeof(char)); + strcpy(imei, _imei.c_str()); + + AUTHKEY_NBIoT = (char*)malloc((strlen(_deviceType) + 1)*sizeof(char)); + strcpy(AUTHKEY_NBIoT, _deviceType); +} + +void BlinkerQRCodeSIM7000::initStream(Stream& s, bool state, blinker_callback_t func) +{ + // _deviceType = _type; + + // BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + stream = &s; + stream->setTimeout(BLINKER_STREAM_TIMEOUT); + isHWS = state; + + listenFunc = func; + + // streamPrint(BLINKER_CMD_AT); + // ::delay(200); + // streamPrint(BLINKER_CMD_CRESET_RESQ); + + // _imei = (char*)malloc(imei.length()*sizeof(char)); + // strcpy(_imei, imei.c_str()); +} + +int BlinkerQRCodeSIM7000::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"trigged\":true,\"autoData\":{"); + payload += BLINKER_F("\"autoId\":"); + payload += STRING_format(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(MQTT_ID_NBIoT); + payload += BLINKER_F("\",\"toDevice\":\"autoManager\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_NBIoT->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +char * BlinkerQRCodeSIM7000::deviceName() +{ + BLINKER_LOG_ALL(BLINKER_F("BlinkerQRCodeSIM7000::deviceName: "), MQTT_ID_NBIoT); + return MQTT_ID_NBIoT;/*MQTT_ID_PRO;*/ +} + +void BlinkerQRCodeSIM7000::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (uint8_t num = _sharerCount; num > 0; num--) + { + delete _sharers[num - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerQRCodeSIM7000::connectServer() +{ + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + String uri = ""; + // uri += BLINKER_F("/api/v1/user/device/register?deviceType="); + // uri += _deviceType; + // uri += BLINKER_F("&deviceName="); + // uri += imei; + uri += BLINKER_F("/api/v1/user/device/scancode/add"); + // uri += BLINKER_F("/post"); + // uri += _deviceType; + // uri += _aliType; + // uri += _duerType; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host + uri); + + BlinkerHTTPSIM7000 http(*stream, isHWS, listenFunc); + + http.begin(host, uri); + + String post_data = "{\"deviceType\":\""; + post_data += STRING_format(_deviceType); + post_data += "\",\"typeKey\":\""; + post_data += STRING_format(_authKey); + post_data += "\",\"registerKey\":\""; + post_data += imei; + post_data += "\",\"expiresIn\": 60}"; + + String payload; + + if (http.POST(post_data, "", "")) + { + BLINKER_LOG(BLINKER_F("[HTTP] POST... success")); + + payload = http.getString(); + + BLINKER_LOG(payload); + + return true; + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] POST... failed")); + + return false; + } + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + + if (isMQTTinit) + { + free(MQTT_HOST_NBIoT); + free(MQTT_ID_NBIoT); + free(MQTT_NAME_NBIoT); + free(MQTT_KEY_NBIoT); + free(MQTT_PRODUCTINFO_NBIoT); + free(UUID_NBIoT); + free(DEVICE_NAME_NBIoT); + free(BLINKER_PUB_TOPIC_NBIoT); + free(BLINKER_SUB_TOPIC_NBIoT); + free(mqtt_NBIoT); + // free(iotSub_NBIoT); + + isMQTTinit = false; + } + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); + DEVICE_NAME_NBIoT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(DEVICE_NAME_NBIoT, _userID.c_str()); + MQTT_ID_NBIoT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_NBIoT, _userID.c_str()); + MQTT_NAME_NBIoT = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_NBIoT, _userName.c_str()); + MQTT_KEY_NBIoT = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_NBIoT, _key.c_str()); + MQTT_PRODUCTINFO_NBIoT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_NBIoT, _productInfo.c_str()); + MQTT_HOST_NBIoT = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_NBIoT, BLINKER_MQTT_ALIYUN_HOST); + MQTT_PORT_NBIoT = BLINKER_MQTT_ALIYUN_PORT; + } + + UUID_NBIoT = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_NBIoT, _uuid.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME_NBIoT: "), DEVICE_NAME_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_NBIoT: "), MQTT_PRODUCTINFO_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_NBIoT: "), MQTT_ID_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_NBIoT: "), MQTT_NAME_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_NBIoT: "), MQTT_KEY_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("UUID_NBIoT: "), UUID_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_NBIoT; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_ID_NBIoT; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_NBIoT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_NBIoT, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_NBIoT, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_NBIoT: "), BLINKER_PUB_TOPIC_NBIoT); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_NBIoT; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_ID_NBIoT; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_NBIoT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_NBIoT, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_NBIoT, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_NBIoT: "), BLINKER_SUB_TOPIC_NBIoT); + } + + // if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + mqtt_NBIoT = new BlinkerMQTTSIM7000(*stream, isHWS, MQTT_HOST_NBIoT, MQTT_PORT_NBIoT, + MQTT_ID_NBIoT, MQTT_NAME_NBIoT, MQTT_KEY_NBIoT, listenFunc); + // } + + this->latestTime = millis(); + isMQTTinit = true; + mqtt_NBIoT->subscribe(BLINKER_SUB_TOPIC_NBIoT); + + return true; +} + +void BlinkerQRCodeSIM7000::checkKA() +{ + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerQRCodeSIM7000::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerQRCodeSIM7000::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerQRCodeSIM7000::checkCanPrint() { + if ((millis() - printTime >= BLINKER_PRO_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerQRCodeSIM7000::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerQRCodeSIM7000::checkPrintSpan() +{ + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) + { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG(BLINKER_F("DEVICE NOT CONNECT OR MSG LIMIT")); + + return false; + } + else + { + respTimes++; + return true; + } + } + else + { + respTimes = 0; + return true; + } +} + +int BlinkerQRCodeSIM7000::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerQRCodeSIM7000::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerQRCodeSIM7000::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG("Print data is not Json! ", data); + return false; + } + return true; +} + + +#endif diff --git a/blinker-library/src/Adapters/BlinkerQRCodeSIM7020.h b/blinker-library/src/Adapters/BlinkerQRCodeSIM7020.h new file mode 100644 index 0000000..354ad2b --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerQRCodeSIM7020.h @@ -0,0 +1,1273 @@ +#ifndef BLINKER_QRCODE_SIM7020_H +#define BLINKER_QRCODE_SIM7020_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" +#include "../Functions/BlinkerSIM7020.h" +#include "../Functions/BlinkerHTTPSIM7020.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +#include "../Functions/BlinkerMQTTSIM7020.h" + +char* MQTT_HOST_NBIoT; +char* MQTT_ID_NBIoT; +char* MQTT_NAME_NBIoT; +char* MQTT_KEY_NBIoT; +char* MQTT_PRODUCTINFO_NBIoT; +char* UUID_NBIoT; +char* AUTHKEY_NBIoT; +char* MQTT_DEVICEID_NBIoT; +char* DEVICE_NAME_NBIoT; +char* BLINKER_PUB_TOPIC_NBIoT; +char* BLINKER_SUB_TOPIC_NBIoT; +uint16_t MQTT_PORT_NBIoT; + +BlinkerMQTTSIM7020* mqtt_NBIoT; + +class BlinkerQRCodeSIM7020 : public BlinkerStream +{ + public : + BlinkerQRCodeSIM7020() + : stream(NULL), isConnect(false) + {} + + int connect(); + int connected(); + int mConnected(); + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + void subscribe(); + int timedRead(); + char * lastRead() { if (isFresh_NBIoT) return msgBuf_NBIoT; return ""; } + void flush(); + // int print(const String & s, bool needCheck = true); + int print(char * data, bool needCheck = true); + int toServer(char * data); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + void aliType(const String & type); + void duerType(const String & type); + void begin(const char* _auth, const char* _type, String _imei); + void initStream(Stream& s, bool state, blinker_callback_t func); + int autoPrint(unsigned long id); + char * deviceName(); + char * authKey() { return AUTHKEY_NBIoT; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_GPRS; } + int init() { return isMQTTinit; } + int reRegister() { return connectServer(); } + int deviceRegister() { return connectServer(); } + // int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + private : + bool isMQTTinit = false; + + int connectServer(); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + + protected : + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + Stream* stream; + // char* streamData; + char* msgBuf_NBIoT; + // bool isFresh = false; + bool isFresh_NBIoT = false; + bool isConnect; + bool isHWS = false; + char* imei; + // uint8_t respTimes = 0; + // uint32_t respTime = 0; + bool isAvail_NBIoT = false; + uint8_t dataFrom_NBIoT = BLINKER_MSG_FROM_MQTT; + + // uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + const char* _deviceType;//_authKey + const char* _authKey; + char* _aliType; + char* _duerType; + bool isAlive = false; + // bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + char* mqtt_broker; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; + blinker_callback_t listenFunc = NULL; +}; + +int BlinkerQRCodeSIM7020::connect() +{ + BLINKER_LOG_ALL(BLINKER_F(">>>>>> mqtt connect <<<<<<")); + + if (!isMQTTinit) return false; + + // if (mqtt_NBIoT->connected()) return true; + if (isConnect) return true; + + BLINKER_LOG_ALL(BLINKER_F(">>>>>> mqtt connect failed <<<<<<")); + + disconnect(); + + // if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + // { + // yield(); + // return false; + // } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!mqtt_NBIoT->connect()) + { + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + reRegister(); + reconnect_time = 0; + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + isConnect = true; + + this->latestTime = millis(); + + return true; +} + +int BlinkerQRCodeSIM7020::connected() +{ + if (!isMQTTinit) return false; + + return isConnect;//mqtt_NBIoT->connected(); +} + +int BlinkerQRCodeSIM7020::mConnected() +{ + if (!isMQTTinit) return false; + else return mqtt_NBIoT->connected(); +} + +void BlinkerQRCodeSIM7020::disconnect() +{ + if (isMQTTinit) { + isConnect = false; + mqtt_NBIoT->disconnect(); + } +} + +void BlinkerQRCodeSIM7020::ping() +{ + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!isMQTTinit) return; + + if (!isConnect) + { + // disconnect(); + + delay(100); + + connect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } + + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + + BLINKER_LOG_ALL(BLINKER_F("check isReboot")); + + if (BLINKER_SIM7020.isReboot()) + { + BLINKER_SIM7020.powerCheck(); + + // disconnect(); + } +} + +int BlinkerQRCodeSIM7020::available() +{ + if (isMQTTinit) { + checkKA(); + + // if (!mqtt_PRO->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > 30000) + { + ping(); + } + else + { + subscribe(); + } + } + + if (isAvail_NBIoT) + { + isAvail_NBIoT = false; + return true; + } + else { + return false; + } +} + +int BlinkerQRCodeSIM7020::aligenieAvail() +{ + if (!isMQTTinit) return false; + + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerQRCodeSIM7020::duerAvail() +{ + if (!isMQTTinit) return false; + + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +void BlinkerQRCodeSIM7020::subscribe() +{ + if (!isMQTTinit) return; + + if (mqtt_NBIoT->readSubscription()) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), mqtt_NBIoT->lastRead); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(String(mqtt_NBIoT->lastRead)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, String(mqtt_NBIoT->lastRead)); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"]; + String dataGet = root["data"]; + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_NBIoT) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_NBIoT = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT) + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_NBIoT = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + check is from bridge/share device, \ + data: "), dataGet); + + _needCheckShare = true; + } + } + } + // root.printTo(dataGet); + serializeJson(root, dataGet); + + isAvail_NBIoT = true; + isAlive = true; + } + + if (isFresh_NBIoT) free(msgBuf_NBIoT); + msgBuf_NBIoT = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_NBIoT, dataGet.c_str()); + isFresh_NBIoT = true; + + this->latestTime = millis(); + + dataFrom_NBIoT = BLINKER_MSG_FROM_MQTT; + } +} + +void BlinkerQRCodeSIM7020::flush() +{ + if (isFresh_NBIoT) + { + free(msgBuf_NBIoT); isFresh_NBIoT = false; isAvail_NBIoT = false; + isAliAvail = false; //isBavail = false; + } +} + +int BlinkerQRCodeSIM7020::print(char * data, bool needCheck) +{ + if (!isMQTTinit) return false; + + BLINKER_LOG_ALL(BLINKER_F("data: "), data); + + uint16_t num = strlen(data); + + data[num+8] = '\0'; + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+7] = data[c_num-1]; + } + + // String data_add = BLINKER_F("{\"data\":"); + char data_add[20] = "{\"data\":"; + for(uint16_t c_num = 0; c_num < 8; c_num++) + { + data[c_num] = data_add[c_num]; + } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, ",\"fromDevice\":\""); + strcat(data, MQTT_ID_NBIoT); + // strcat(data, MQTT_DEVICEID_NBIoT); //PRO + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, "\",\"toDevice\":\""); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + strcat(data, _sharers[_sharerFrom]->uuid()); + } + else + { + strcat(data, UUID_NBIoT); + } + // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // strcat(data, data_add.c_str()); + strcat(data, "\",\"deviceType\":\"OwnApp\"}"); + + // data_add = STRING_format(data); + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + // if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, msg_data.c_str())) + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + disconnect(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + + +int BlinkerQRCodeSIM7020::toServer(char * data) +{ + if (!isMQTTinit) return false; + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish to server...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (mqtt_NBIoT->connected()) + { + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerQRCodeSIM7020::bPrint(char * name, const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_NBIoT); + strcat(data_add, ",\"toDevice\":\""); + strcat(data_add, name); + strcat(data_add, "\",\"deviceType\":\"DiyBridge\"}"); + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\""); + // data_add += name; + // data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_NBIoT->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + + // if (! iotPub.publish(payload.c_str())) { + + // String bPubTopic = BLINKER_F(""); + // char bPubTopic[60] = { '\0' }; + + // if (strcmp(mqtt_broker, BLINKER_MQTT_BORKER_ONENET) == 0) + // { + // // bPubTopic = MQTT_PRODUCTINFO_MQTT; + // // bPubTopic += BLINKER_F("/"); + // // bPubTopic += name; + // // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // strcpy(bPubTopic, BLINKER_PUB_TOPIC_MQTT); + // bPubTopic = BLINKER_PUB_TOPIC_MQTT; + // } + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerQRCodeSIM7020::aliPrint(const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_NBIoT); + strcat(data_add, "\",\"toDevice\":\"AliGenie_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_NBIoT->connected()) + { + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerQRCodeSIM7020::duerPrint(const String & data, bool report) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_NBIoT); + strcat(data_add, "\",\"toDevice\":\"DuerOS_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_NBIoT->connected()) + { + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +void BlinkerQRCodeSIM7020::aliType(const String & type) +{ + _aliType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_aliType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +} + +void BlinkerQRCodeSIM7020::duerType(const String & type) +{ + _duerType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_duerType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_duerType: "), _duerType); +} + +void BlinkerQRCodeSIM7020::begin(const char* _auth, const char* _type, String _imei) +{ + _authKey = _auth; + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + // stream = &s; + // stream->setTimeout(BLINKER_STREAM_TIMEOUT); + // isHWS = state; + + imei = (char*)malloc((_imei.length() + 1)*sizeof(char)); + strcpy(imei, _imei.c_str()); + + AUTHKEY_NBIoT = (char*)malloc((strlen(_deviceType) + 1)*sizeof(char)); + strcpy(AUTHKEY_NBIoT, _deviceType); +} + +void BlinkerQRCodeSIM7020::initStream(Stream& s, bool state, blinker_callback_t func) +{ + // _deviceType = _type; + + // BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + stream = &s; + stream->setTimeout(BLINKER_STREAM_TIMEOUT); + isHWS = state; + + listenFunc = func; + + // streamPrint(BLINKER_CMD_AT); + // ::delay(200); + // streamPrint(BLINKER_CMD_CRESET_RESQ); + + // _imei = (char*)malloc(imei.length()*sizeof(char)); + // strcpy(_imei, imei.c_str()); +} + +int BlinkerQRCodeSIM7020::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"trigged\":true,\"autoData\":{"); + payload += BLINKER_F("\"autoId\":"); + payload += STRING_format(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(MQTT_ID_NBIoT); + payload += BLINKER_F("\",\"toDevice\":\"autoManager\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_NBIoT->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +char * BlinkerQRCodeSIM7020::deviceName() +{ + BLINKER_LOG_ALL(BLINKER_F("BlinkerQRCodeSIM7020::deviceName: "), MQTT_ID_NBIoT); + return MQTT_ID_NBIoT;/*MQTT_ID_PRO;*/ +} + +void BlinkerQRCodeSIM7020::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (uint8_t num = _sharerCount; num > 0; num--) + { + delete _sharers[num - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerQRCodeSIM7020::connectServer() +{ + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + String uri = ""; + // uri += BLINKER_F("/api/v1/user/device/register?deviceType="); + // uri += _deviceType; + // uri += BLINKER_F("&deviceName="); + // uri += imei; + uri += BLINKER_F("/api/v1/user/device/scancode/add"); + // uri += _deviceType; + // uri += _aliType; + // uri += _duerType; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host + uri); + + BlinkerHTTPSIM7020 http(*stream, isHWS, listenFunc); + + http.begin(host, uri); + + String post_data = "{\"deviceType\":\""; + post_data += STRING_format(_deviceType); + post_data += "\",\"typeKey\":\""; + post_data += STRING_format(_authKey); + post_data += "\",\"registerKey\":\""; + post_data += imei; + post_data += "\",\"expiresIn\": 60}"; + + String payload; + + if (http.POST(post_data, "", "")) + { + BLINKER_LOG(BLINKER_F("[HTTP] POST... success")); + + payload = http.getString(); + + BLINKER_LOG(payload); + + return true; + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] POST... failed")); + + return false; + } + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + + if (isMQTTinit) + { + free(MQTT_HOST_NBIoT); + free(MQTT_ID_NBIoT); + free(MQTT_NAME_NBIoT); + free(MQTT_KEY_NBIoT); + free(MQTT_PRODUCTINFO_NBIoT); + free(UUID_NBIoT); + free(DEVICE_NAME_NBIoT); + free(BLINKER_PUB_TOPIC_NBIoT); + free(BLINKER_SUB_TOPIC_NBIoT); + free(mqtt_NBIoT); + // free(iotSub_NBIoT); + + isMQTTinit = false; + } + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); + DEVICE_NAME_NBIoT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(DEVICE_NAME_NBIoT, _userID.c_str()); + MQTT_ID_NBIoT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_NBIoT, _userID.c_str()); + MQTT_NAME_NBIoT = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_NBIoT, _userName.c_str()); + MQTT_KEY_NBIoT = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_NBIoT, _key.c_str()); + MQTT_PRODUCTINFO_NBIoT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_NBIoT, _productInfo.c_str()); + MQTT_HOST_NBIoT = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_NBIoT, BLINKER_MQTT_ALIYUN_HOST); + MQTT_PORT_NBIoT = BLINKER_MQTT_ALIYUN_PORT; + } + + UUID_NBIoT = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_NBIoT, _uuid.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME_NBIoT: "), DEVICE_NAME_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_NBIoT: "), MQTT_PRODUCTINFO_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_NBIoT: "), MQTT_ID_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_NBIoT: "), MQTT_NAME_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_NBIoT: "), MQTT_KEY_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("UUID_NBIoT: "), UUID_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_NBIoT; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_ID_NBIoT; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_NBIoT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_NBIoT, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_NBIoT, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_NBIoT: "), BLINKER_PUB_TOPIC_NBIoT); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_NBIoT; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_ID_NBIoT; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_NBIoT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_NBIoT, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_NBIoT, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_NBIoT: "), BLINKER_SUB_TOPIC_NBIoT); + } + + // if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + mqtt_NBIoT = new BlinkerMQTTSIM7020(*stream, isHWS, MQTT_HOST_NBIoT, MQTT_PORT_NBIoT, + MQTT_ID_NBIoT, MQTT_NAME_NBIoT, MQTT_KEY_NBIoT, listenFunc); + // } + + this->latestTime = millis(); + isMQTTinit = true; + mqtt_NBIoT->subscribe(BLINKER_SUB_TOPIC_NBIoT); + + return true; +} + +void BlinkerQRCodeSIM7020::checkKA() +{ + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerQRCodeSIM7020::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerQRCodeSIM7020::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerQRCodeSIM7020::checkCanPrint() { + if ((millis() - printTime >= BLINKER_PRO_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerQRCodeSIM7020::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerQRCodeSIM7020::checkPrintSpan() +{ + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) + { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG(BLINKER_F("DEVICE NOT CONNECT OR MSG LIMIT")); + + return false; + } + else + { + respTimes++; + return true; + } + } + else + { + respTimes = 0; + return true; + } +} + +int BlinkerQRCodeSIM7020::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerQRCodeSIM7020::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerQRCodeSIM7020::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG("Print data is not Json! ", data); + return false; + } + return true; +} + + +#endif diff --git a/blinker-library/src/Adapters/BlinkerSerial.h b/blinker-library/src/Adapters/BlinkerSerial.h new file mode 100644 index 0000000..1e7d942 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerSerial.h @@ -0,0 +1,196 @@ +#ifndef BLINKER_SERIAL_H +#define BLINKER_SERIAL_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +// #include "../Adapters/BlinkerSerial.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +#if defined(ESP32) + #include + + HardwareSerial *HSerialBLE; +#elif defined (__AVR__) || defined(ESP8266) + #include + + SoftwareSerial *SSerialBLE; +#endif + +class BlinkerSerial : public BlinkerStream +{ + public : + BlinkerSerial() + : stream(NULL), isConnect(false) + {} + + int available(); + void begin(Stream& s, bool state); + int timedRead(); + char * lastRead() { if (isFresh) return streamData; else return ""; } + void flush(); + int print(char * data, bool needCheck = true); + int connect() { isConnect = true; return connected(); } + int connected() { return isConnect; } + void disconnect() { isConnect = false; } + + protected : + Stream* stream; + char* streamData; + bool isFresh; + bool isConnect; + bool isHWS = false; + uint8_t respTimes = 0; + uint32_t respTime = 0; + + int checkPrintSpan(); +}; + +int BlinkerSerial::available() +{ + if (!isHWS) + { + #if defined(__AVR__) || defined(ESP8266) + if (!SSerialBLE->isListening()) + { + SSerialBLE->listen(); + ::delay(100); + } + #endif + } + + if (stream->available()) + { + if (isFresh) free(streamData); + streamData = (char*)malloc(1*sizeof(char)); + + int16_t dNum = 0; + int c_d = timedRead(); + while (dNum < BLINKER_MAX_READ_SIZE && + c_d >=0 && c_d != '\n') + { + if (c_d != '\r') + { + streamData[dNum] = (char)c_d; + dNum++; + streamData = (char*)realloc(streamData, (dNum+1)*sizeof(char)); + } + + c_d = timedRead(); + } + dNum++; + streamData = (char*)realloc(streamData, dNum*sizeof(char)); + + streamData[dNum-1] = '\0'; + stream->flush(); + + BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData); + // BLINKER_LOG_FreeHeap_ALL(); + + if (strlen(streamData) < BLINKER_MAX_READ_SIZE) + { + if (streamData[strlen(streamData) - 1] == '\r') + streamData[strlen(streamData) - 1] = '\0'; + + isFresh = true; + return true; + } + else + { + free(streamData); + return false; + } + } + else + { + return false; + } +} + +void BlinkerSerial::begin(Stream& s, bool state) +{ + stream = &s; + stream->setTimeout(BLINKER_STREAM_TIMEOUT); + isHWS = state; +} + +int BlinkerSerial::timedRead() +{ + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; +} + +void BlinkerSerial::flush() +{ + if (isFresh) + { + free(streamData); isFresh = false; + } +} + +// int BlinkerSerial::print(const String & s, bool needCheck) +int BlinkerSerial::print(char * data, bool needCheck) +{ + if (needCheck) + { + if (!checkPrintSpan()) + { + respTime = millis(); + return false; + } + } + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("Response: "), data); + + if(connected()) + { + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + stream->println(data); + return true; + } + else + { + BLINKER_LOG_ALL(BLINKER_F("Faile... Disconnected")); + + return false; + } +} + +int BlinkerSerial::checkPrintSpan() +{ + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) + { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG(BLINKER_F("DEVICE NOT CONNECT OR MSG LIMIT")); + + return false; + } + else + { + respTimes++; + return true; + } + } + else + { + respTimes = 0; + return true; + } +} + +#endif diff --git a/blinker-library/src/Adapters/BlinkerSerialAIR202.h b/blinker-library/src/Adapters/BlinkerSerialAIR202.h new file mode 100644 index 0000000..f6f7a81 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerSerialAIR202.h @@ -0,0 +1,1386 @@ +#ifndef BLINKER_SERIAL_AIR202_H +#define BLINKER_SERIAL_AIR202_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" +#include "../Functions/BlinkerAIR202.h" +#include "../Functions/BlinkerHTTPAIR202.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +#include "../Functions/BlinkerMQTTAIR202.h" + +char* MQTT_HOST_GPRS; +char* MQTT_ID_GPRS; +char* MQTT_NAME_GPRS; +char* MQTT_KEY_GPRS; +char* MQTT_PRODUCTINFO_GPRS; +char* UUID_GPRS; +char* AUTHKEY_GPRS; +char* MQTT_DEVICEID_GPRS; +char* DEVICE_NAME_GPRS; +char* BLINKER_PUB_TOPIC_GPRS; +char* BLINKER_SUB_TOPIC_GPRS; +uint16_t MQTT_PORT_GPRS; + +BlinkerMQTTAIR202* mqtt_GPRS; + +class BlinkerSerialAIR202 : public BlinkerStream +{ + public : + BlinkerSerialAIR202() + : stream(NULL), isConnect(false) + {} + + int connect(); + int connected(); + int mConnected(); + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + void subscribe(); + // int timedRead(); + char * lastRead() { if (isFresh_GPRS) return msgBuf_GPRS; return ""; } + void flush(); + // int print(const String & s, bool needCheck = true); + int print(char * data, bool needCheck = true); + int toServer(char * data); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + void aliType(const String & type); + void duerType(const String & type); + void begin(const char* _deviceType, String _imei); + void initStream(Stream& s, bool state, blinker_callback_t func); + int autoPrint(unsigned long id); + char * deviceName(); + char * authKey() { return AUTHKEY_GPRS; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_GPRS; } + int init() { return isMQTTinit; } + int reRegister() { return connectServer(); } + int deviceRegister() { return connectServer(); } + // int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + private : + bool isMQTTinit = false; + + int connectServer(); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + + protected : + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + Stream* stream; + // char* streamData; + char* msgBuf_GPRS; + // bool isFresh = false; + bool isFresh_GPRS = false; + bool isConnect; + bool isHWS = false; + char* imei; + // uint8_t respTimes = 0; + // uint32_t respTime = 0; + bool isAvail_GPRS = false; + uint8_t dataFrom_GPRS = BLINKER_MSG_FROM_MQTT; + + // uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + const char* _deviceType; + char* _aliType; + char* _duerType; + bool isAlive = false; + // bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + char* mqtt_broker; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; + blinker_callback_t listenFunc = NULL; +}; + +int BlinkerSerialAIR202::connect() +{ + if (!isMQTTinit) return false; + + if (mqtt_GPRS->connected()) return true; + + disconnect(); + + if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + { + yield(); + return false; + } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!mqtt_GPRS->connect()) + { + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + reRegister(); + reconnect_time = 0; + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + this->latestTime = millis(); + + return true; +} + +int BlinkerSerialAIR202::connected() +{ + if (!isMQTTinit) return false; + + return mqtt_GPRS->connected(); +} + +int BlinkerSerialAIR202::mConnected() +{ + if (!isMQTTinit) return false; + else return mqtt_GPRS->connected(); +} + +void BlinkerSerialAIR202::disconnect() +{ + if (isMQTTinit) mqtt_GPRS->disconnect(); +} + +void BlinkerSerialAIR202::ping() +{ + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!isMQTTinit) return; + + if (!mqtt_GPRS->connected()) + { + disconnect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } + + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + + if (BLINKER_AIR202.isReboot()) + { + BLINKER_AIR202.powerCheck(); + + disconnect(); + } +} + +int BlinkerSerialAIR202::available() +{ + if (isMQTTinit) { + checkKA(); + + // if (!mqtt_PRO->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > 30000) + { + ping(); + } + else + { + subscribe(); + } + } + + if (isAvail_GPRS) + { + isAvail_GPRS = false; + return true; + } + else { + return false; + } +} + +int BlinkerSerialAIR202::aligenieAvail() +{ + if (!isMQTTinit) return false; + + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerSerialAIR202::duerAvail() +{ + if (!isMQTTinit) return false; + + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +void BlinkerSerialAIR202::subscribe() +{ + if (!isMQTTinit) return; + + if (mqtt_GPRS->readSubscription()) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), mqtt_GPRS->lastRead); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(String(mqtt_GPRS->lastRead)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, String(mqtt_GPRS->lastRead)); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"]; + String dataGet = root["data"]; + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_GPRS) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_GPRS = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT) + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_GPRS = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + check is from bridge/share device, \ + data: "), dataGet); + + _needCheckShare = true; + } + } + } + // root.printTo(dataGet); + serializeJson(root, dataGet); + + isAvail_GPRS = true; + isAlive = true; + } + + if (isFresh_GPRS) free(msgBuf_GPRS); + msgBuf_GPRS = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_GPRS, dataGet.c_str()); + isFresh_GPRS = true; + + this->latestTime = millis(); + + dataFrom_GPRS = BLINKER_MSG_FROM_MQTT; + } +} + +void BlinkerSerialAIR202::flush() +{ + if (isFresh_GPRS) + { + free(msgBuf_GPRS); isFresh_GPRS = false; isAvail_GPRS = false; + // isAliAvail = false; //isBavail = false; + } +} + +int BlinkerSerialAIR202::print(char * data, bool needCheck) +{ + BLINKER_LOG_ALL(BLINKER_F("data: "), data); + + uint16_t num = strlen(data); + + data[num+8] = '\0'; + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+7] = data[c_num-1]; + } + + // String data_add = BLINKER_F("{\"data\":"); + char data_add[20] = "{\"data\":"; + for(uint16_t c_num = 0; c_num < 8; c_num++) + { + data[c_num] = data_add[c_num]; + } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, ",\"fromDevice\":\""); + strcat(data, MQTT_ID_GPRS); + // strcat(data, MQTT_DEVICEID_GPRS); //PRO + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, "\",\"toDevice\":\""); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + strcat(data, _sharers[_sharerFrom]->uuid()); + } + else + { + strcat(data, UUID_GPRS); + } + // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // strcat(data, data_add.c_str()); + strcat(data, "\",\"deviceType\":\"OwnApp\"}"); + + // data_add = STRING_format(data); + + if (!isJson(STRING_format(data))) return false; + + // data_add.replace("\"", "\\22"); + // strcpy(data, data_add.c_str()); + uint16_t d_data_len; + + for (uint16_t d_num = 0; d_num < 1024; d_num++) + { + if (data[d_num] == '\"') + { + data[d_num] = '\\'; + d_data_len = strlen(data); + + // BLINKER_LOG_ALL(BLINKER_F("d_num: "), d_num, + // BLINKER_F(", d_data_len: "), d_data_len); + + for(uint16_t c_num = d_data_len; c_num > d_num; c_num--) + { + data[c_num + 2] = data[c_num]; + } + data[d_num + 1] = '2'; + data[d_num + 2] = '2'; + } + } + + // #if defined(ESP8266) + // data_add = ""; + // #endif + + // if (!isJson(STRING_format(data)) return false; + + // strcpy(data, STRING_format(data).replace("\"", "\\22").c_str()); + + // String msg_data = STRING_format(data); + + // msg_data.replace("\"", "\\22"); + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (mqtt_GPRS->connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + // if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, msg_data.c_str())) + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerSerialAIR202::toServer(char * data) +{ + if (!isMQTTinit) return false; + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish to server...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (mqtt_GPRS->connected()) + { + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerSerialAIR202::bPrint(char * name, const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_GPRS); + strcat(data_add, ",\"toDevice\":\""); + strcat(data_add, name); + strcat(data_add, "\",\"deviceType\":\"DiyBridge\"}"); + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\""); + // data_add += name; + // data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_GPRS->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_GPRS); + + // if (! iotPub.publish(payload.c_str())) { + + // String bPubTopic = BLINKER_F(""); + // char bPubTopic[60] = { '\0' }; + + // if (strcmp(mqtt_broker, BLINKER_MQTT_BORKER_ONENET) == 0) + // { + // // bPubTopic = MQTT_PRODUCTINFO_MQTT; + // // bPubTopic += BLINKER_F("/"); + // // bPubTopic += name; + // // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // strcpy(bPubTopic, BLINKER_PUB_TOPIC_GPRS); + // bPubTopic = BLINKER_PUB_TOPIC_GPRS; + // } + + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerSerialAIR202::aliPrint(const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_GPRS); + strcat(data_add, "\",\"toDevice\":\"AliGenie_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_GPRS->connected()) + { + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerSerialAIR202::duerPrint(const String & data, bool report) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_GPRS); + strcat(data_add, "\",\"toDevice\":\"DuerOS_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_GPRS->connected()) + { + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +void BlinkerSerialAIR202::aliType(const String & type) +{ + _aliType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_aliType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +} + +void BlinkerSerialAIR202::duerType(const String & type) +{ + _duerType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_duerType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_duerType: "), _duerType); +} + +void BlinkerSerialAIR202::begin(const char* _type, String _imei) +{ + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + // stream = &s; + // stream->setTimeout(BLINKER_STREAM_TIMEOUT); + // isHWS = state; + + imei = (char*)malloc((_imei.length() + 1)*sizeof(char)); + strcpy(imei, _imei.c_str()); + + AUTHKEY_GPRS = (char*)malloc((strlen(_deviceType) + 1)*sizeof(char)); + strcpy(AUTHKEY_GPRS, _deviceType); +} + +void BlinkerSerialAIR202::initStream(Stream& s, bool state, blinker_callback_t func) +{ + // _deviceType = _type; + + // BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + stream = &s; + stream->setTimeout(BLINKER_STREAM_TIMEOUT); + isHWS = state; + + listenFunc = func; + + // _imei = (char*)malloc(imei.length()*sizeof(char)); + // strcpy(_imei, imei.c_str()); +} + +int BlinkerSerialAIR202::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"trigged\":true,\"autoData\":{"); + payload += BLINKER_F("\"autoId\":"); + payload += STRING_format(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(MQTT_ID_GPRS); + payload += BLINKER_F("\",\"toDevice\":\"autoManager\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_GPRS->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_GPRS); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +char * BlinkerSerialAIR202::deviceName() { return MQTT_ID_GPRS;/*MQTT_ID_PRO;*/ } + +void BlinkerSerialAIR202::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (uint8_t num = _sharerCount; num > 0; num--) + { + delete _sharers[num - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerSerialAIR202::connectServer() +{ + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + String uri = ""; + // uri += BLINKER_F("/api/v1/user/device/register?deviceType="); + // uri += _deviceType; + // uri += BLINKER_F("&deviceName="); + // uri += imei; + uri += BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + uri += _deviceType; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host + uri); + + BlinkerHTTPAIR202 http(*stream, isHWS, listenFunc); + + http.begin(host, uri); + + String payload; + + if (http.GET()) + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... success")); + + payload = http.getString(); + + // return true; + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed")); + + return false; + } + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + + if (isMQTTinit) + { + free(MQTT_HOST_GPRS); + free(MQTT_ID_GPRS); + free(MQTT_NAME_GPRS); + free(MQTT_KEY_GPRS); + free(MQTT_PRODUCTINFO_GPRS); + free(UUID_GPRS); + free(DEVICE_NAME_GPRS); + free(BLINKER_PUB_TOPIC_GPRS); + free(BLINKER_SUB_TOPIC_GPRS); + free(mqtt_GPRS); + // free(iotSub_GPRS); + + isMQTTinit = false; + } + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); + DEVICE_NAME_GPRS = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(DEVICE_NAME_GPRS, _userID.c_str()); + MQTT_ID_GPRS = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_GPRS, _userID.c_str()); + MQTT_NAME_GPRS = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_GPRS, _userName.c_str()); + MQTT_KEY_GPRS = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_GPRS, _key.c_str()); + MQTT_PRODUCTINFO_GPRS = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_GPRS, _productInfo.c_str()); + MQTT_HOST_GPRS = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_GPRS, BLINKER_MQTT_ALIYUN_HOST); + MQTT_PORT_GPRS = BLINKER_MQTT_ALIYUN_PORT; + } + + UUID_GPRS = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_GPRS, _uuid.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME_GPRS: "), DEVICE_NAME_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_GPRS: "), MQTT_PRODUCTINFO_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_GPRS: "), MQTT_ID_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_GPRS: "), MQTT_NAME_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_GPRS: "), MQTT_KEY_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_GPRS); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_GPRS); + BLINKER_LOG_ALL(BLINKER_F("UUID_GPRS: "), UUID_GPRS); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_GPRS; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_ID_GPRS; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_GPRS = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_GPRS, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_GPRS, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_GPRS: "), BLINKER_PUB_TOPIC_GPRS); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_GPRS; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_ID_GPRS; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_GPRS = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_GPRS, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_GPRS, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_GPRS: "), BLINKER_SUB_TOPIC_GPRS); + } + + // String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + // String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + // String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + // String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + // String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + // String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + // String _authKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_KEY]; + + // if (isMQTTinit) + // { + // free(MQTT_HOST_GPRS); + // free(MQTT_ID_GPRS); + // free(MQTT_NAME_GPRS); + // free(MQTT_KEY_GPRS); + // free(MQTT_PRODUCTINFO_GPRS); + // free(UUID_GPRS); + // free(AUTHKEY_GPRS); + // free(MQTT_DEVICEID_GPRS); + // free(BLINKER_PUB_TOPIC_GPRS); + // free(BLINKER_SUB_TOPIC_GPRS); + // free(mqtt_GPRS); + + // isMQTTinit = false; + // } + + // BLINKER_LOG_ALL(("====================")); + + // // if (_broker == "BLINKER_MQTT_BORKER_ALIYUN") { + // // memcpy(DEVICE_NAME, _userID.c_str(), 12); + // String _deviceName = _userID.substring(12, 36); + // MQTT_DEVICEID_GPRS = (char*)malloc((_deviceName.length()+1)*sizeof(char)); + // strcpy(MQTT_DEVICEID_GPRS, _deviceName.c_str()); + // MQTT_ID_GPRS = (char*)malloc((_userID.length()+1)*sizeof(char)); + // strcpy(MQTT_ID_GPRS, _userID.c_str()); + // MQTT_NAME_GPRS = (char*)malloc((_userName.length()+1)*sizeof(char)); + // strcpy(MQTT_NAME_GPRS, _userName.c_str()); + // MQTT_KEY_GPRS = (char*)malloc((_key.length()+1)*sizeof(char)); + // strcpy(MQTT_KEY_GPRS, _key.c_str()); + // MQTT_PRODUCTINFO_GPRS = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + // strcpy(MQTT_PRODUCTINFO_GPRS, _productInfo.c_str()); + // MQTT_HOST_GPRS = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + // strcpy(MQTT_HOST_GPRS, BLINKER_MQTT_ALIYUN_HOST); + // AUTHKEY_GPRS = (char*)malloc((_authKey.length()+1)*sizeof(char)); + // strcpy(AUTHKEY_GPRS, _authKey.c_str()); + // MQTT_PORT_GPRS = BLINKER_MQTT_ALIYUN_PORT; + + // BLINKER_LOG_ALL(("====================")); + // // } + + // UUID_GPRS = (char*)malloc((_uuid.length()+1)*sizeof(char)); + // strcpy(UUID_GPRS, _uuid.c_str()); + + // char uuid_eeprom[BLINKER_AUUID_SIZE]; + + // BLINKER_LOG_ALL(("==========AUTH CHECK==========")); + + // // if (!isFirst) + // // { + // // char _authCheck; + // // EEPROM.begin(BLINKER_EEP_SIZE); + // // EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + // // if (strcmp(uuid_eeprom, _uuid.c_str()) != 0) { + // // // strcpy(UUID_PRO, _uuid.c_str()); + + // // strcpy(uuid_eeprom, _uuid.c_str()); + // // EEPROM.put(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + // // EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + + // // BLINKER_LOG_ALL(BLINKER_F("====================")); + // // BLINKER_LOG_ALL(BLINKER_F("uuid_eeprom: "), uuid_eeprom); + // // BLINKER_LOG_ALL(BLINKER_F("_uuid: "), _uuid); + // // isNew = true; + // // } + // // EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + // // if (_authCheck != BLINKER_AUTH_CHECK_DATA) { + // // EEPROM.put(BLINKER_EEP_ADDR_AUTH_CHECK, BLINKER_AUTH_CHECK_DATA); + // // isAuth = true; + // // } + // // EEPROM.commit(); + // // EEPROM.end(); + + // // isFirst = true; + // // } + + // BLINKER_LOG_ALL(BLINKER_F("====================")); + // BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME: "), imei); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_GPRS: "), MQTT_PRODUCTINFO_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_DEVICEID_GPRS: "), MQTT_DEVICEID_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_GPRS: "), MQTT_ID_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_GPRS: "), MQTT_NAME_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_GPRS: "), MQTT_KEY_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + // BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("UUID_GPRS: "), UUID_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_GPRS: "), AUTHKEY_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("====================")); + + // // if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // String PUB_TOPIC_STR = BLINKER_F("/"); + // PUB_TOPIC_STR += MQTT_PRODUCTINFO_GPRS; + // PUB_TOPIC_STR += BLINKER_F("/"); + // PUB_TOPIC_STR += MQTT_DEVICEID_GPRS; + // PUB_TOPIC_STR += BLINKER_F("/s"); + + // BLINKER_PUB_TOPIC_GPRS = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // strcpy(BLINKER_PUB_TOPIC_GPRS, PUB_TOPIC_STR.c_str()); + + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_GPRS: "), BLINKER_PUB_TOPIC_GPRS); + + // String SUB_TOPIC_STR = BLINKER_F("/"); + // SUB_TOPIC_STR += MQTT_PRODUCTINFO_GPRS; + // SUB_TOPIC_STR += BLINKER_F("/"); + // SUB_TOPIC_STR += MQTT_DEVICEID_GPRS; + // SUB_TOPIC_STR += BLINKER_F("/r"); + + // BLINKER_SUB_TOPIC_GPRS = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // strcpy(BLINKER_SUB_TOPIC_GPRS, SUB_TOPIC_STR.c_str()); + + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_GPRS: "), BLINKER_SUB_TOPIC_GPRS); + // // } + + // if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + mqtt_GPRS = new BlinkerMQTTAIR202(*stream, isHWS, MQTT_HOST_GPRS, MQTT_PORT_GPRS, + MQTT_ID_GPRS, MQTT_NAME_GPRS, MQTT_KEY_GPRS, listenFunc); + // } + + this->latestTime = millis(); + isMQTTinit = true; + mqtt_GPRS->subscribe(BLINKER_SUB_TOPIC_GPRS); + + return true; +} + +void BlinkerSerialAIR202::checkKA() +{ + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerSerialAIR202::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerSerialAIR202::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerSerialAIR202::checkCanPrint() { + if ((millis() - printTime >= BLINKER_PRO_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerSerialAIR202::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerSerialAIR202::checkPrintSpan() +{ + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) + { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG(BLINKER_F("DEVICE NOT CONNECT OR MSG LIMIT")); + + return false; + } + else + { + respTimes++; + return true; + } + } + else + { + respTimes = 0; + return true; + } +} + +int BlinkerSerialAIR202::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerSerialAIR202::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerSerialAIR202::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG("Print data is not Json! ", data); + return false; + } + return true; +} + +#endif diff --git a/blinker-library/src/Adapters/BlinkerSerialGPRS.h b/blinker-library/src/Adapters/BlinkerSerialGPRS.h new file mode 100644 index 0000000..af9626a --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerSerialGPRS.h @@ -0,0 +1,912 @@ +#ifndef BLINKER_SERIAL_GPRS_H +#define BLINKER_SERIAL_GPRS_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" +#include "../Functions/BlinkerHTTPAIR202.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +#include "../Functions/BlinkerMQTTAIR202.h" + +// #if defined(ESP32) +// #include + +// HardwareSerial *HSerial; +// #else +// #include + +// SoftwareSerial *SSerial; +// #endif + +char* MQTT_HOST_GPRS; +char* MQTT_ID_GPRS; +char* MQTT_NAME_GPRS; +char* MQTT_KEY_GPRS; +char* MQTT_PRODUCTINFO_GPRS; +char* UUID_GPRS; +char* AUTHKEY_GPRS; +char* MQTT_DEVICEID_GPRS; +char* DEVICE_NAME_GPRS; +char* BLINKER_PUB_TOPIC_GPRS; +char* BLINKER_SUB_TOPIC_GPRS; +uint16_t MQTT_PORT_GPRS; + +BlinkerMQTTAIR202* mqtt_GPRS; + +class BlinkerSerialGPRS : public BlinkerStream +{ + public : + BlinkerSerialGPRS() + : stream(NULL), isConnect(false) + {} + + int connect(); + int connected(); + int mConnected(); + void disconnect(); + void ping(); + int available(); + void subscribe(); + int timedRead(); + char * lastRead() { if (isFresh_GPRS) return msgBuf_GPRS; return ""; } + void flush(); + // int print(const String & s, bool needCheck = true); + int print(char * data, bool needCheck = true); + int toServer(char * data); + // int bPrint(char * name, const String & data); + // int aliPrint(const String & s); + // int duerPrint(const String & s); + // int aliPrint(const String & data); + // int duerPrint(const String & data, bool report = false); + void begin(const char* _deviceType, String _imei); + void initStream(Stream& s, bool state, blinker_callback_t func); + char * deviceName(); + char * authKey() { return AUTHKEY_GPRS; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_GPRS; } + int init() { return isMQTTinit; } + int reRegister() { return connectServer(); } + int deviceRegister() { return connectServer(); } + // int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + // int needFreshShare(); + + private : + bool isMQTTinit = false; + + int connectServer(); + void checkKA(); + int checkCanPrint(); + int checkPrintSpan(); + protected : + Stream* stream; + // char* streamData; + char* msgBuf_GPRS; + // bool isFresh = false; + bool isFresh_GPRS = false; + bool isConnect; + bool isHWS = false; + char* imei; + uint8_t respTimes = 0; + uint32_t respTime = 0; + bool isAvail_GPRS = false; + uint8_t dataFrom_GPRS = BLINKER_MSG_FROM_MQTT; + + // uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + const char* _deviceType; + bool isAlive = false; + uint32_t kaTime = 0; + uint32_t latestTime; + uint32_t printTime = 0; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; + blinker_callback_t listenFunc = NULL; +}; + +int BlinkerSerialGPRS::connect() +{ + if (!isMQTTinit) return false; + + if (mqtt_GPRS->connected()) return true; + + disconnect(); + + if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + { + yield(); + return false; + } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!mqtt_GPRS->connect()) + { + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + reRegister(); + reconnect_time = 0; + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + this->latestTime = millis(); + + return true; +} + +int BlinkerSerialGPRS::connected() +{ + if (!isMQTTinit) return false; + + return mqtt_GPRS->connected(); +} + +int BlinkerSerialGPRS::mConnected() +{ + if (!isMQTTinit) return false; + else return mqtt_GPRS->connected(); +} + +void BlinkerSerialGPRS::disconnect() +{ + if (isMQTTinit) mqtt_GPRS->disconnect(); +} + +void BlinkerSerialGPRS::ping() +{ + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!isMQTTinit) return; + + if (!mqtt_GPRS->connected()) + { + disconnect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } +} + +int BlinkerSerialGPRS::available() +{ + if (isMQTTinit) { + checkKA(); + + // if (!mqtt_PRO->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > 30000) + { + ping(); + } + else + { + subscribe(); + } + } + + if (isAvail_GPRS) + { + isAvail_GPRS = false; + return true; + } + else { + return false; + } +} + +void BlinkerSerialGPRS::subscribe() +{ + if (!isMQTTinit) return; + + if (mqtt_GPRS->readSubscription()) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), mqtt_GPRS->lastRead); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(String(mqtt_GPRS->lastRead)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, String(mqtt_GPRS->lastRead)); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"]; + String dataGet = root["data"]; + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_GPRS) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_GPRS = true; + isAlive = true; + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + + if (isFresh_GPRS) free(msgBuf_GPRS); + msgBuf_GPRS = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_GPRS, dataGet.c_str()); + isFresh_GPRS = true; + + this->latestTime = millis(); + + dataFrom_GPRS = BLINKER_MSG_FROM_MQTT; + } +} + +void BlinkerSerialGPRS::flush() +{ + if (isFresh_GPRS) + { + free(msgBuf_GPRS); isFresh_GPRS = false; isAvail_GPRS = false; + // isAliAvail = false; //isBavail = false; + } +} + +int BlinkerSerialGPRS::timedRead() +{ + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; +} + +// void BlinkerSerialGPRS::flush() +// { +// if (isFresh) +// { +// free(streamData); isFresh_GPRS = false; +// } +// } + +int BlinkerSerialGPRS::print(char * data, bool needCheck) +{ + BLINKER_LOG_ALL(BLINKER_F("data: "), data); + + uint16_t num = strlen(data); + + data[num+8] = '\0'; + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+7] = data[c_num-1]; + } + + // String data_add = BLINKER_F("{\"data\":"); + char data_add[20] = "{\"data\":"; + for(uint16_t c_num = 0; c_num < 8; c_num++) + { + data[c_num] = data_add[c_num]; + } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, ",\"fromDevice\":\""); + strcat(data, MQTT_ID_GPRS); + // strcat(data, MQTT_DEVICEID_GPRS); //PRO + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, "\",\"toDevice\":\""); + // if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + // { + // strcat(data, _sharers[_sharerFrom]->uuid()); + // } + // else + // { + strcat(data, UUID_GPRS); + // } + // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + // _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // strcat(data, data_add.c_str()); + strcat(data, "\",\"deviceType\":\"OwnApp\"}"); + + // data_add = STRING_format(data); + + if (!isJson(STRING_format(data))) return false; + + // data_add.replace("\"", "\\22"); + // strcpy(data, data_add.c_str()); + uint16_t d_data_len; + + for (uint16_t d_num = 0; d_num < 1024; d_num++) + { + if (data[d_num] == '\"') + { + data[d_num] = '\\'; + d_data_len = strlen(data); + + // BLINKER_LOG_ALL(BLINKER_F("d_num: "), d_num, + // BLINKER_F(", d_data_len: "), d_data_len); + + for(uint16_t c_num = d_data_len; c_num > d_num; c_num--) + { + data[c_num + 2] = data[c_num]; + } + data[d_num + 1] = '2'; + data[d_num + 2] = '2'; + } + } + + // #if defined(ESP8266) + // data_add = ""; + // #endif + + // if (!isJson(STRING_format(data)) return false; + + // strcpy(data, STRING_format(data).replace("\"", "\\22").c_str()); + + // String msg_data = STRING_format(data); + + // msg_data.replace("\"", "\\22"); + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (mqtt_GPRS->connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + // if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, msg_data.c_str())) + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerSerialGPRS::toServer(char * data) +{ + // if (!checkInit()) return false; + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish to server...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (mqtt_GPRS->connected()) + { + if (! mqtt_GPRS->publish(BLINKER_PUB_TOPIC_GPRS, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +// int BlinkerSerialGPRS::aliPrint(const String & s) +// { +// if (!checkPrintSpan()) { +// respTime = millis(); +// return false; +// } + +// String _s = s.substring(0, s.length() - 1); +// _s += BLINKER_F(",\"toDeviceAT\":\"AliGenie\"}"); + +// respTime = millis(); + +// BLINKER_LOG_ALL(BLINKER_F("AliGenie Response: "), _s); + +// if(connected()) { +// BLINKER_LOG_ALL(BLINKER_F("Success...")); + +// stream->println(_s); +// return true; +// } +// else { +// BLINKER_LOG_ALL(BLINKER_F("Faile... Disconnected")); + +// return false; +// } +// } + +// int BlinkerSerialGPRS::duerPrint(const String & s) +// { +// if (!checkPrintSpan()) { +// respTime = millis(); +// return false; +// } + +// String _s = s.substring(0, s.length() - 1); +// _s += BLINKER_F(",\"toDeviceAT\":\"DuerOS\"}"); + +// respTime = millis(); + +// BLINKER_LOG_ALL(BLINKER_F("DuerOS Response: "), _s); + +// if(connected()) { +// BLINKER_LOG_ALL(BLINKER_F("Success...")); + +// stream->println(_s); +// return true; +// } +// else { +// BLINKER_LOG_ALL(BLINKER_F("Faile... Disconnected")); + +// return false; +// } +// } + +// int BlinkerSerialGPRS::print(const String & s, bool needCheck) + +void BlinkerSerialGPRS::begin(const char* _type, String _imei) +{ + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + // stream = &s; + // stream->setTimeout(BLINKER_STREAM_TIMEOUT); + // isHWS = state; + + imei = (char*)malloc((_imei.length() + 1)*sizeof(char)); + strcpy(imei, _imei.c_str()); +} + +void BlinkerSerialGPRS::initStream(Stream& s, bool state, blinker_callback_t func) +{ + // _deviceType = _type; + + // BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + stream = &s; + stream->setTimeout(BLINKER_STREAM_TIMEOUT); + isHWS = state; + + listenFunc = func; + + // streamPrint(BLINKER_CMD_CRESET_RESQ); + + // _imei = (char*)malloc(imei.length()*sizeof(char)); + // strcpy(_imei, imei.c_str()); +} + +char * BlinkerSerialGPRS::deviceName() { return MQTT_DEVICEID_GPRS;/*MQTT_ID_PRO;*/ } + + +void BlinkerSerialGPRS::checkKA() +{ + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerSerialGPRS::checkCanPrint() { + if ((millis() - printTime >= BLINKER_PRO_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerSerialGPRS::checkPrintSpan() +{ + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) + { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG(BLINKER_F("DEVICE NOT CONNECT OR MSG LIMIT")); + + return false; + } + else + { + respTimes++; + return true; + } + } + else + { + respTimes = 0; + return true; + } +} + +int BlinkerSerialGPRS::connectServer() +{ + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + String uri = ""; + // uri += BLINKER_F("/api/v1/user/device/register?deviceType="); + // uri += _deviceType; + // uri += BLINKER_F("&deviceName="); + // uri += imei; + uri += BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + uri += _deviceType; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host + uri); + + BlinkerHTTPAIR202 http(*stream, isHWS, listenFunc); + + http.begin(host, uri); + + String payload; + + if (http.GET()) + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... success")); + + payload = http.getString(); + + // return true; + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed")); + + return false; + } + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + + if (isMQTTinit) + { + free(MQTT_HOST_GPRS); + free(MQTT_ID_GPRS); + free(MQTT_NAME_GPRS); + free(MQTT_KEY_GPRS); + free(MQTT_PRODUCTINFO_GPRS); + free(UUID_GPRS); + free(DEVICE_NAME_GPRS); + free(BLINKER_PUB_TOPIC_GPRS); + free(BLINKER_SUB_TOPIC_GPRS); + free(mqtt_GPRS); + // free(iotSub_GPRS); + + isMQTTinit = false; + } + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); + DEVICE_NAME_GPRS = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(DEVICE_NAME_GPRS, _userID.c_str()); + MQTT_ID_GPRS = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_GPRS, _userID.c_str()); + MQTT_NAME_GPRS = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_GPRS, _userName.c_str()); + MQTT_KEY_GPRS = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_GPRS, _key.c_str()); + MQTT_PRODUCTINFO_GPRS = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_GPRS, _productInfo.c_str()); + MQTT_HOST_GPRS = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_GPRS, BLINKER_MQTT_ALIYUN_HOST); + MQTT_PORT_GPRS = BLINKER_MQTT_ALIYUN_PORT; + } + + UUID_GPRS = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_GPRS, _uuid.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME_GPRS: "), DEVICE_NAME_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_GPRS: "), MQTT_PRODUCTINFO_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_GPRS: "), MQTT_ID_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_GPRS: "), MQTT_NAME_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_GPRS: "), MQTT_KEY_GPRS); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_GPRS); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_GPRS); + BLINKER_LOG_ALL(BLINKER_F("UUID_GPRS: "), UUID_GPRS); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_GPRS; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_ID_GPRS; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_GPRS = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_GPRS, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_GPRS, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_GPRS: "), BLINKER_PUB_TOPIC_GPRS); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_GPRS; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_ID_GPRS; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_GPRS = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_GPRS, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_GPRS, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_GPRS: "), BLINKER_SUB_TOPIC_GPRS); + } + + // String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + // String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + // String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + // String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + // String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + // String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + // String _authKey = root[BLINKER_CMD_DETAIL][BLINKER_CMD_KEY]; + + // if (isMQTTinit) + // { + // free(MQTT_HOST_GPRS); + // free(MQTT_ID_GPRS); + // free(MQTT_NAME_GPRS); + // free(MQTT_KEY_GPRS); + // free(MQTT_PRODUCTINFO_GPRS); + // free(UUID_GPRS); + // free(AUTHKEY_GPRS); + // free(MQTT_DEVICEID_GPRS); + // free(BLINKER_PUB_TOPIC_GPRS); + // free(BLINKER_SUB_TOPIC_GPRS); + // free(mqtt_GPRS); + + // isMQTTinit = false; + // } + + // BLINKER_LOG_ALL(("====================")); + + // // if (_broker == "BLINKER_MQTT_BORKER_ALIYUN") { + // // memcpy(DEVICE_NAME, _userID.c_str(), 12); + // String _deviceName = _userID.substring(12, 36); + // MQTT_DEVICEID_GPRS = (char*)malloc((_deviceName.length()+1)*sizeof(char)); + // strcpy(MQTT_DEVICEID_GPRS, _deviceName.c_str()); + // MQTT_ID_GPRS = (char*)malloc((_userID.length()+1)*sizeof(char)); + // strcpy(MQTT_ID_GPRS, _userID.c_str()); + // MQTT_NAME_GPRS = (char*)malloc((_userName.length()+1)*sizeof(char)); + // strcpy(MQTT_NAME_GPRS, _userName.c_str()); + // MQTT_KEY_GPRS = (char*)malloc((_key.length()+1)*sizeof(char)); + // strcpy(MQTT_KEY_GPRS, _key.c_str()); + // MQTT_PRODUCTINFO_GPRS = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + // strcpy(MQTT_PRODUCTINFO_GPRS, _productInfo.c_str()); + // MQTT_HOST_GPRS = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + // strcpy(MQTT_HOST_GPRS, BLINKER_MQTT_ALIYUN_HOST); + // AUTHKEY_GPRS = (char*)malloc((_authKey.length()+1)*sizeof(char)); + // strcpy(AUTHKEY_GPRS, _authKey.c_str()); + // MQTT_PORT_GPRS = BLINKER_MQTT_ALIYUN_PORT; + + // BLINKER_LOG_ALL(("====================")); + // // } + + // UUID_GPRS = (char*)malloc((_uuid.length()+1)*sizeof(char)); + // strcpy(UUID_GPRS, _uuid.c_str()); + + // char uuid_eeprom[BLINKER_AUUID_SIZE]; + + // BLINKER_LOG_ALL(("==========AUTH CHECK==========")); + + // // if (!isFirst) + // // { + // // char _authCheck; + // // EEPROM.begin(BLINKER_EEP_SIZE); + // // EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + // // if (strcmp(uuid_eeprom, _uuid.c_str()) != 0) { + // // // strcpy(UUID_PRO, _uuid.c_str()); + + // // strcpy(uuid_eeprom, _uuid.c_str()); + // // EEPROM.put(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + // // EEPROM.get(BLINKER_EEP_ADDR_AUUID, uuid_eeprom); + + // // BLINKER_LOG_ALL(BLINKER_F("====================")); + // // BLINKER_LOG_ALL(BLINKER_F("uuid_eeprom: "), uuid_eeprom); + // // BLINKER_LOG_ALL(BLINKER_F("_uuid: "), _uuid); + // // isNew = true; + // // } + // // EEPROM.get(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + // // if (_authCheck != BLINKER_AUTH_CHECK_DATA) { + // // EEPROM.put(BLINKER_EEP_ADDR_AUTH_CHECK, BLINKER_AUTH_CHECK_DATA); + // // isAuth = true; + // // } + // // EEPROM.commit(); + // // EEPROM.end(); + + // // isFirst = true; + // // } + + // BLINKER_LOG_ALL(BLINKER_F("====================")); + // BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME: "), imei); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_GPRS: "), MQTT_PRODUCTINFO_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_DEVICEID_GPRS: "), MQTT_DEVICEID_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_GPRS: "), MQTT_ID_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_GPRS: "), MQTT_NAME_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_GPRS: "), MQTT_KEY_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + // BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("UUID_GPRS: "), UUID_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("AUTHKEY_GPRS: "), AUTHKEY_GPRS); + // BLINKER_LOG_ALL(BLINKER_F("====================")); + + // // if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // String PUB_TOPIC_STR = BLINKER_F("/"); + // PUB_TOPIC_STR += MQTT_PRODUCTINFO_GPRS; + // PUB_TOPIC_STR += BLINKER_F("/"); + // PUB_TOPIC_STR += MQTT_DEVICEID_GPRS; + // PUB_TOPIC_STR += BLINKER_F("/s"); + + // BLINKER_PUB_TOPIC_GPRS = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // strcpy(BLINKER_PUB_TOPIC_GPRS, PUB_TOPIC_STR.c_str()); + + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_GPRS: "), BLINKER_PUB_TOPIC_GPRS); + + // String SUB_TOPIC_STR = BLINKER_F("/"); + // SUB_TOPIC_STR += MQTT_PRODUCTINFO_GPRS; + // SUB_TOPIC_STR += BLINKER_F("/"); + // SUB_TOPIC_STR += MQTT_DEVICEID_GPRS; + // SUB_TOPIC_STR += BLINKER_F("/r"); + + // BLINKER_SUB_TOPIC_GPRS = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // strcpy(BLINKER_SUB_TOPIC_GPRS, SUB_TOPIC_STR.c_str()); + + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_GPRS: "), BLINKER_SUB_TOPIC_GPRS); + // // } + + // if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + mqtt_GPRS = new BlinkerMQTTAIR202(*stream, isHWS, MQTT_HOST_GPRS, MQTT_PORT_GPRS, + MQTT_ID_GPRS, MQTT_NAME_GPRS, MQTT_KEY_GPRS, listenFunc); + // } + + this->latestTime = millis(); + isMQTTinit = true; + mqtt_GPRS->subscribe(BLINKER_SUB_TOPIC_GPRS); + + return true; +} + +// int BlinkerSerialGPRS::connect() +// { +// stream->println(STRING_format(BLINKER_CMD_MCONFIG_RESQ) + +// "=\"" + MQTT_ID_GPRS + +// "\",\"" + MQTT_NAME_GPRS + +// "\",\"" + MQTT_KEY_GPRS + "\""); +// } + +int BlinkerSerialGPRS::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG("Print data is not Json! ", data); + return false; + } + return true; +} + +#endif diff --git a/blinker-library/src/Adapters/BlinkerSerialMQTT.h b/blinker-library/src/Adapters/BlinkerSerialMQTT.h new file mode 100644 index 0000000..92aa263 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerSerialMQTT.h @@ -0,0 +1,283 @@ +#ifndef BLINKER_SERIAL_MQTT_H +#define BLINKER_SERIAL_MQTT_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +// #include "../Adapters/BlinkerSerialMQTT.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +#if defined(ESP32) + #include + + HardwareSerial *HSerialMQTT; +#else + #include + + SoftwareSerial *SSerialMQTT; +#endif + +class BlinkerSerialMQTT : public BlinkerStream +{ + public : + BlinkerSerialMQTT() + : stream(NULL), isConnect(false) + {} + + int available(); + int timedRead(); + void begin(Stream& s, bool state); + char * lastRead() { return isFresh ? streamData : NULL; } + void flush(); + int aliPrint(const String & s); + int duerPrint(const String & s, bool report = false); + int miPrint(const String & s); + // int print(const String & s, bool needCheck = true); + int print(char * data, bool needCheck = true); + int toServer(char * data) { return true; } + int connect() { isConnect = true; return connected(); } + int connected() { return isConnect; } + void disconnect() { isConnect = false; } + + protected : + Stream* stream; + char* streamData; + bool isFresh = false; + bool isConnect; + bool isHWS = false; + uint8_t respTimes = 0; + uint32_t respTime = 0; + + int checkPrintSpan(); +}; + +int BlinkerSerialMQTT::available() +{ + if (!isHWS) + { + #if defined(__AVR__) || defined(ESP8266) + if (!SSerialMQTT->isListening()) + { + SSerialMQTT->listen(); + ::delay(100); + } + #endif + } + + + if (stream->available()) + { + if (isFresh) free(streamData); + streamData = (char*)malloc(1*sizeof(char)); + + int16_t dNum = 0; + int c_d = timedRead(); + while (dNum < BLINKER_MAX_READ_SIZE && + c_d >=0 && c_d != '\n') + { + if (c_d != '\r') + { + streamData[dNum] = (char)c_d; + dNum++; + streamData = (char*)realloc(streamData, (dNum+1)*sizeof(char)); + } + + c_d = timedRead(); + } + dNum++; + streamData = (char*)realloc(streamData, dNum*sizeof(char)); + + streamData[dNum-1] = '\0'; + stream->flush(); + + BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData); + BLINKER_LOG_FreeHeap_ALL(); + + if (strlen(streamData) < BLINKER_MAX_READ_SIZE) + { + if (streamData[strlen(streamData) - 1] == '\r') + streamData[strlen(streamData) - 1] = '\0'; + + isFresh = true; + return true; + } + else + { + free(streamData); + return false; + } + } + else + { + return false; + } +} + +void BlinkerSerialMQTT::begin(Stream& s, bool state) +{ + stream = &s; + stream->setTimeout(BLINKER_STREAM_TIMEOUT); + isHWS = state; +} + +int BlinkerSerialMQTT::timedRead() +{ + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; +} + +void BlinkerSerialMQTT::flush() +{ + if (isFresh) + { + free(streamData); isFresh = false; + } +} + +int BlinkerSerialMQTT::aliPrint(const String & s) +{ + if (!checkPrintSpan()) { + respTime = millis(); + return false; + } + + String _s = s.substring(0, s.length() - 1); + _s += BLINKER_F(",\"toDeviceAT\":\"AliGenie\"}"); + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("AliGenie Response: "), _s); + + if(connected()) { + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + stream->println(_s); + return true; + } + else { + BLINKER_LOG_ALL(BLINKER_F("Faile... Disconnected")); + + return false; + } +} + +int BlinkerSerialMQTT::duerPrint(const String & s, bool report) +{ + if (!checkPrintSpan()) { + respTime = millis(); + return false; + } + + String _s = s.substring(0, s.length() - 1); + _s += BLINKER_F(",\"toDeviceAT\":\"DuerOS\"}"); + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("DuerOS Response: "), _s); + + if(connected()) { + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + stream->println(_s); + return true; + } + else { + BLINKER_LOG_ALL(BLINKER_F("Faile... Disconnected")); + + return false; + } +} + +int BlinkerSerialMQTT::miPrint(const String & s) +{ + if (!checkPrintSpan()) { + respTime = millis(); + return false; + } + + String _s = s.substring(0, s.length() - 1); + _s += BLINKER_F(",\"toDeviceAT\":\"MIOT\"}"); + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("MIOT Response: "), _s); + + if(connected()) { + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + stream->println(_s); + return true; + } + else { + BLINKER_LOG_ALL(BLINKER_F("Faile... Disconnected")); + + return false; + } +} + +// int BlinkerSerialMQTT::print(const String & s, bool needCheck) +int BlinkerSerialMQTT::print(char * data, bool needCheck) +{ + if (needCheck) + { + if (!checkPrintSpan()) + { + respTime = millis(); + return false; + } + } + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("Response: "), data); + + if(connected()) + { + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + stream->println(data); + return true; + } + else + { + BLINKER_LOG_ALL(BLINKER_F("Faile... Disconnected")); + + return false; + } +} + +int BlinkerSerialMQTT::checkPrintSpan() +{ + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) + { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG(BLINKER_F("DEVICE NOT CONNECT OR MSG LIMIT")); + + return false; + } + else + { + respTimes++; + return true; + } + } + else + { + respTimes = 0; + return true; + } +} + +#endif diff --git a/blinker-library/src/Adapters/BlinkerSerialNBIoT.h b/blinker-library/src/Adapters/BlinkerSerialNBIoT.h new file mode 100644 index 0000000..9b061d7 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerSerialNBIoT.h @@ -0,0 +1,256 @@ +#ifndef BLINKER_SERIAL_NBIOT_H +#define BLINKER_SERIAL_NBIOT_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +#if defined(ESP32) + #include + + HardwareSerial *HSerial; +#else + #include + + SoftwareSerial *SSerial; +#endif + +class BlinkerSerialNBIoT : public BlinkerStream +{ + public : + BlinkerSerialNBIoT() + : stream(NULL), isConnect(false) + {} + + int available(); + int timedRead(); + void begin(Stream& s, bool state); + char * lastRead() { return isFresh ? streamData : NULL; } + void flush(); + int aliPrint(const String & s); + int duerPrint(const String & s); + // int print(const String & s, bool needCheck = true); + int print(char * data, bool needCheck = true); + // int toServer(char * data); + int connect() { isConnect = true; return connected(); } + int connected() { return isConnect; } + void disconnect() { isConnect = false; } + + protected : + Stream* stream; + char* streamData; + bool isFresh = false; + bool isConnect; + bool isHWS = false; + uint8_t respTimes = 0; + uint16_t dataLen; + uint32_t respTime = 0; + String httpData; + + int checkPrintSpan(); +}; + +int BlinkerSerialNBIoT::available() +{ + if (!isHWS) + { + #if defined(__AVR__) || defined(ESP8266) + if (!SSerial->isListening()) + { + SSerial->listen(); + ::delay(100); + } + #endif + } + + + if (stream->available()) + { + if (isFresh) free(streamData); + streamData = (char*)malloc(1*sizeof(char)); + + int16_t dNum = 0; + int c_d = timedRead(); + while (dNum < BLINKER_MAX_READ_SIZE && + c_d >=0 && c_d != '\n') + { + if (c_d != '\r') + { + streamData[dNum] = (char)c_d; + dNum++; + streamData = (char*)realloc(streamData, (dNum+1)*sizeof(char)); + } + + c_d = timedRead(); + } + dNum++; + streamData = (char*)realloc(streamData, dNum*sizeof(char)); + + streamData[dNum-1] = '\0'; + stream->flush(); + + BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData); + BLINKER_LOG_FreeHeap_ALL(); + + if (strlen(streamData) < BLINKER_MAX_READ_SIZE) + { + if (streamData[strlen(streamData) - 1] == '\r') + streamData[strlen(streamData) - 1] = '\0'; + + isFresh = true; + return true; + } + else + { + free(streamData); + return false; + } + } + else + { + return false; + } +} + +void BlinkerSerialNBIoT::begin(Stream& s, bool state) +{ + stream = &s; + stream->setTimeout(BLINKER_STREAM_TIMEOUT); + isHWS = state; +} + +int BlinkerSerialNBIoT::timedRead() +{ + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; +} + +void BlinkerSerialNBIoT::flush() +{ + if (isFresh) + { + free(streamData); isFresh = false; + } +} + +int BlinkerSerialNBIoT::aliPrint(const String & s) +{ + if (!checkPrintSpan()) { + respTime = millis(); + return false; + } + + String _s = s.substring(0, s.length() - 1); + _s += BLINKER_F(",\"toDeviceAT\":\"AliGenie\"}"); + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("AliGenie Response: "), _s); + + if(connected()) { + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + stream->println(_s); + return true; + } + else { + BLINKER_LOG_ALL(BLINKER_F("Faile... Disconnected")); + + return false; + } +} + +int BlinkerSerialNBIoT::duerPrint(const String & s) +{ + if (!checkPrintSpan()) { + respTime = millis(); + return false; + } + + String _s = s.substring(0, s.length() - 1); + _s += BLINKER_F(",\"toDeviceAT\":\"DuerOS\"}"); + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("DuerOS Response: "), _s); + + if(connected()) { + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + stream->println(_s); + return true; + } + else { + BLINKER_LOG_ALL(BLINKER_F("Faile... Disconnected")); + + return false; + } +} + +// int BlinkerSerialNBIoT::print(const String & s, bool needCheck) +int BlinkerSerialNBIoT::print(char * data, bool needCheck) +{ + if (needCheck) + { + if (!checkPrintSpan()) + { + respTime = millis(); + return false; + } + } + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("Response: "), data); + + if(connected()) + { + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + stream->println(data); + return true; + } + else + { + BLINKER_LOG_ALL(BLINKER_F("Faile... Disconnected")); + + return false; + } +} + +int BlinkerSerialNBIoT::checkPrintSpan() +{ + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) + { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG(BLINKER_F("DEVICE NOT CONNECT OR MSG LIMIT")); + + return false; + } + else + { + respTimes++; + return true; + } + } + else + { + respTimes = 0; + return true; + } +} + +#endif diff --git a/blinker-library/src/Adapters/BlinkerSerialSIM7000.h b/blinker-library/src/Adapters/BlinkerSerialSIM7000.h new file mode 100644 index 0000000..10bd7c9 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerSerialSIM7000.h @@ -0,0 +1,1269 @@ +#ifndef BLINKER_SERIAL_SIM7000_H +#define BLINKER_SERIAL_SIM7000_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" +#include "../Functions/BlinkerSIM7000.h" +#include "../Functions/BlinkerHTTPSIM7000.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +#include "../Functions/BlinkerMQTTSIM7000.h" + +char* MQTT_HOST_NBIoT; +char* MQTT_ID_NBIoT; +char* MQTT_NAME_NBIoT; +char* MQTT_KEY_NBIoT; +char* MQTT_PRODUCTINFO_NBIoT; +char* UUID_NBIoT; +char* AUTHKEY_NBIoT; +char* MQTT_DEVICEID_NBIoT; +char* DEVICE_NAME_NBIoT; +char* BLINKER_PUB_TOPIC_NBIoT; +char* BLINKER_SUB_TOPIC_NBIoT; +uint16_t MQTT_PORT_NBIoT; + +BlinkerMQTTSIM7000* mqtt_NBIoT; + +class BlinkerSerialSIM7000 : public BlinkerStream +{ + public : + BlinkerSerialSIM7000() + : stream(NULL), isConnect(false) + {} + + int connect(); + int connected(); + int mConnected(); + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + void subscribe(); + int timedRead(); + char * lastRead() { if (isFresh_NBIoT) return msgBuf_NBIoT; return ""; } + void flush(); + // int print(const String & s, bool needCheck = true); + int print(char * data, bool needCheck = true); + int toServer(char * data); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + void aliType(const String & type); + void duerType(const String & type); + void begin(const char* _deviceType, String _imei); + void initStream(Stream& s, bool state, blinker_callback_t func); + int autoPrint(unsigned long id); + char * deviceName(); + char * authKey() { return AUTHKEY_NBIoT; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_NBIoT; } + int init() { return isMQTTinit; } + int reRegister() { return connectServer(); } + int deviceRegister() { return connectServer(); } + // int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + private : + bool isMQTTinit = false; + + int connectServer(); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + + protected : + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + Stream* stream; + // char* streamData; + char* msgBuf_NBIoT; + // bool isFresh = false; + bool isFresh_NBIoT = false; + bool isConnect; + bool isHWS = false; + char* imei; + // uint8_t respTimes = 0; + // uint32_t respTime = 0; + bool isAvail_NBIoT = false; + uint8_t dataFrom_NBIoT = BLINKER_MSG_FROM_MQTT; + + // uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + const char* _deviceType;//_authKey + char* _aliType; + char* _duerType; + bool isAlive = false; + // bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + char* mqtt_broker; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; + blinker_callback_t listenFunc = NULL; +}; + +int BlinkerSerialSIM7000::connect() +{ + // BLINKER_LOG_ALL(BLINKER_F(">>>>>> mqtt connect <<<<<<")); + + if (!isMQTTinit) return false; + + // if (mqtt_NBIoT->connected()) return true; + + if (isConnect) return true; + + BLINKER_LOG_ALL(BLINKER_F(">>>>>> mqtt connect failed <<<<<<")); + + // disconnect(); + // mqtt_NBIoT->disconnect(); + + // if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + // { + // yield(); + // return false; + // } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!mqtt_NBIoT->connect()) + { + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + reRegister(); + reconnect_time = 0; + } + + BLINKER_LOG(BLINKER_F("MQTT disonnected! Retrying")); + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + isConnect = true; + + this->latestTime = millis(); + + char datas[1024] = "{\"state\":\"online\"}"; + print(datas, false); + + return true; +} + +int BlinkerSerialSIM7000::connected() +{ + if (!isMQTTinit) return false; + + return isConnect;//mqtt_NBIoT->connected(); +} + +int BlinkerSerialSIM7000::mConnected() +{ + if (!isMQTTinit) return false; + else return mqtt_NBIoT->connected(); +} + +void BlinkerSerialSIM7000::disconnect() +{ + if (isMQTTinit) { + isConnect = false; + mqtt_NBIoT->disconnect(); + } +} + +void BlinkerSerialSIM7000::ping() +{ + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!isMQTTinit) return; + + if (!mqtt_NBIoT->connected()) + { + // disconnect(); + + delay(100); + + connect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } + + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + + BLINKER_LOG_ALL(BLINKER_F("check isReboot")); + + if (BLINKER_SIM7000.isReboot()) + { + BLINKER_SIM7000.powerCheck(); + + // disconnect(); + } +} + +int BlinkerSerialSIM7000::available() +{ + if (isMQTTinit) { + checkKA(); + + // if (!mqtt_PRO->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > 30000) + { + ping(); + } + else + { + subscribe(); + } + } + + if (isAvail_NBIoT) + { + isAvail_NBIoT = false; + return true; + } + else { + return false; + } +} + +int BlinkerSerialSIM7000::aligenieAvail() +{ + if (!isMQTTinit) return false; + + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerSerialSIM7000::duerAvail() +{ + if (!isMQTTinit) return false; + + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +void BlinkerSerialSIM7000::subscribe() +{ + if (!isMQTTinit) return; + + if (mqtt_NBIoT->readSubscription()) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), mqtt_NBIoT->lastRead); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(String(mqtt_NBIoT->lastRead)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, String(mqtt_NBIoT->lastRead)); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"]; + String dataGet = root["data"]; + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_NBIoT) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_NBIoT = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT) + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_NBIoT = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + check is from bridge/share device, \ + data: "), dataGet); + + _needCheckShare = true; + } + } + } + // root.printTo(dataGet); + serializeJson(root, dataGet); + + isAvail_NBIoT = true; + isAlive = true; + } + + if (isFresh_NBIoT) free(msgBuf_NBIoT); + msgBuf_NBIoT = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_NBIoT, dataGet.c_str()); + isFresh_NBIoT = true; + + this->latestTime = millis(); + + dataFrom_NBIoT = BLINKER_MSG_FROM_MQTT; + } +} + +void BlinkerSerialSIM7000::flush() +{ + if (isFresh_NBIoT) + { + free(msgBuf_NBIoT); isFresh_NBIoT = false; isAvail_NBIoT = false; + isAliAvail = false; //isBavail = false; + } +} + +int BlinkerSerialSIM7000::print(char * data, bool needCheck) +{ + if (!isMQTTinit) return false; + + BLINKER_LOG_ALL(BLINKER_F("data: "), data); + + uint16_t num = strlen(data); + + data[num+8] = '\0'; + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+7] = data[c_num-1]; + } + + // String data_add = BLINKER_F("{\"data\":"); + char data_add[20] = "{\"data\":"; + for(uint16_t c_num = 0; c_num < 8; c_num++) + { + data[c_num] = data_add[c_num]; + } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, ",\"fromDevice\":\""); + strcat(data, MQTT_ID_NBIoT); + // strcat(data, MQTT_DEVICEID_NBIoT); //PRO + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, "\",\"toDevice\":\""); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + strcat(data, _sharers[_sharerFrom]->uuid()); + } + else + { + strcat(data, UUID_NBIoT); + } + // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // strcat(data, data_add.c_str()); + strcat(data, "\",\"deviceType\":\"OwnApp\"}"); + + // data_add = STRING_format(data); + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + // if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, msg_data.c_str())) + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + disconnect(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + + +int BlinkerSerialSIM7000::toServer(char * data) +{ + if (!isMQTTinit) return false; + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish to server...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (mqtt_NBIoT->connected()) + { + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerSerialSIM7000::bPrint(char * name, const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_NBIoT); + strcat(data_add, ",\"toDevice\":\""); + strcat(data_add, name); + strcat(data_add, "\",\"deviceType\":\"DiyBridge\"}"); + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\""); + // data_add += name; + // data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_NBIoT->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + + // if (! iotPub.publish(payload.c_str())) { + + // String bPubTopic = BLINKER_F(""); + // char bPubTopic[60] = { '\0' }; + + // if (strcmp(mqtt_broker, BLINKER_MQTT_BORKER_ONENET) == 0) + // { + // // bPubTopic = MQTT_PRODUCTINFO_MQTT; + // // bPubTopic += BLINKER_F("/"); + // // bPubTopic += name; + // // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // strcpy(bPubTopic, BLINKER_PUB_TOPIC_MQTT); + // bPubTopic = BLINKER_PUB_TOPIC_MQTT; + // } + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerSerialSIM7000::aliPrint(const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_NBIoT); + strcat(data_add, "\",\"toDevice\":\"AliGenie_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_NBIoT->connected()) + { + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerSerialSIM7000::duerPrint(const String & data, bool report) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_NBIoT); + strcat(data_add, "\",\"toDevice\":\"DuerOS_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_NBIoT->connected()) + { + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +void BlinkerSerialSIM7000::aliType(const String & type) +{ + _aliType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_aliType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +} + +void BlinkerSerialSIM7000::duerType(const String & type) +{ + _duerType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_duerType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_duerType: "), _duerType); +} + +void BlinkerSerialSIM7000::begin(const char* _type, String _imei) +{ + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + // stream = &s; + // stream->setTimeout(BLINKER_STREAM_TIMEOUT); + // isHWS = state; + + imei = (char*)malloc((_imei.length() + 1)*sizeof(char)); + strcpy(imei, _imei.c_str()); + + AUTHKEY_NBIoT = (char*)malloc((strlen(_deviceType) + 1)*sizeof(char)); + strcpy(AUTHKEY_NBIoT, _deviceType); +} + +void BlinkerSerialSIM7000::initStream(Stream& s, bool state, blinker_callback_t func) +{ + // _deviceType = _type; + + // BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + stream = &s; + stream->setTimeout(BLINKER_STREAM_TIMEOUT); + isHWS = state; + + listenFunc = func; + + // streamPrint(BLINKER_CMD_AT); + // ::delay(200); + // streamPrint(BLINKER_CMD_CRESET_RESQ); + + // _imei = (char*)malloc(imei.length()*sizeof(char)); + // strcpy(_imei, imei.c_str()); +} + +int BlinkerSerialSIM7000::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"trigged\":true,\"autoData\":{"); + payload += BLINKER_F("\"autoId\":"); + payload += STRING_format(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(MQTT_ID_NBIoT); + payload += BLINKER_F("\",\"toDevice\":\"autoManager\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_NBIoT->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +char * BlinkerSerialSIM7000::deviceName() +{ + BLINKER_LOG_ALL(BLINKER_F("BlinkerSerialSIM7000::deviceName: "), MQTT_ID_NBIoT); + return MQTT_ID_NBIoT;/*MQTT_ID_PRO;*/ +} + +void BlinkerSerialSIM7000::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (uint8_t num = _sharerCount; num > 0; num--) + { + delete _sharers[num - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerSerialSIM7000::connectServer() +{ + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + String uri = ""; + // uri += BLINKER_F("/api/v1/user/device/register?deviceType="); + // uri += _deviceType; + // uri += BLINKER_F("&deviceName="); + // uri += imei; + uri += BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + uri += _deviceType; + uri += _aliType; + uri += _duerType; + uri += BLINKER_F("&protocol=mqtt"); + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host + uri); + + BlinkerHTTPSIM7000 http(*stream, isHWS, listenFunc); + + http.begin(host, uri); + + String payload; + + if (http.GET()) + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... success")); + + payload = http.getString(); + + // return true; + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed")); + + return false; + } + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + + if (isMQTTinit) + { + free(MQTT_HOST_NBIoT); + free(MQTT_ID_NBIoT); + free(MQTT_NAME_NBIoT); + free(MQTT_KEY_NBIoT); + free(MQTT_PRODUCTINFO_NBIoT); + free(UUID_NBIoT); + free(DEVICE_NAME_NBIoT); + free(BLINKER_PUB_TOPIC_NBIoT); + free(BLINKER_SUB_TOPIC_NBIoT); + free(mqtt_NBIoT); + // free(iotSub_NBIoT); + + isMQTTinit = false; + } + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); + DEVICE_NAME_NBIoT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(DEVICE_NAME_NBIoT, _userID.c_str()); + MQTT_ID_NBIoT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_NBIoT, _userID.c_str()); + MQTT_NAME_NBIoT = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_NBIoT, _userName.c_str()); + MQTT_KEY_NBIoT = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_NBIoT, _key.c_str()); + MQTT_PRODUCTINFO_NBIoT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_NBIoT, _productInfo.c_str()); + MQTT_HOST_NBIoT = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_NBIoT, BLINKER_MQTT_ALIYUN_HOST); + MQTT_PORT_NBIoT = BLINKER_MQTT_ALIYUN_PORT; + } + + UUID_NBIoT = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_NBIoT, _uuid.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME_NBIoT: "), DEVICE_NAME_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_NBIoT: "), MQTT_PRODUCTINFO_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_NBIoT: "), MQTT_ID_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_NBIoT: "), MQTT_NAME_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_NBIoT: "), MQTT_KEY_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("UUID_NBIoT: "), UUID_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_NBIoT; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_ID_NBIoT; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_NBIoT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_NBIoT, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_NBIoT, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_NBIoT: "), BLINKER_PUB_TOPIC_NBIoT); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_NBIoT; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_ID_NBIoT; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_NBIoT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_NBIoT, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_NBIoT, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_NBIoT: "), BLINKER_SUB_TOPIC_NBIoT); + } + + // if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + mqtt_NBIoT = new BlinkerMQTTSIM7000(*stream, isHWS, MQTT_HOST_NBIoT, MQTT_PORT_NBIoT, + MQTT_ID_NBIoT, MQTT_NAME_NBIoT, MQTT_KEY_NBIoT, listenFunc); + // } + + this->latestTime = millis(); + isMQTTinit = true; + mqtt_NBIoT->subscribe(BLINKER_SUB_TOPIC_NBIoT); + + return true; +} + +void BlinkerSerialSIM7000::checkKA() +{ + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerSerialSIM7000::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerSerialSIM7000::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerSerialSIM7000::checkCanPrint() { + if ((millis() - printTime >= BLINKER_PRO_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerSerialSIM7000::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerSerialSIM7000::checkPrintSpan() +{ + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) + { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG(BLINKER_F("DEVICE NOT CONNECT OR MSG LIMIT")); + + return false; + } + else + { + respTimes++; + return true; + } + } + else + { + respTimes = 0; + return true; + } +} + +int BlinkerSerialSIM7000::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerSerialSIM7000::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerSerialSIM7000::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG("Print data is not Json! ", data); + return false; + } + return true; +} + + +#endif diff --git a/blinker-library/src/Adapters/BlinkerSerialSIM7020.h b/blinker-library/src/Adapters/BlinkerSerialSIM7020.h new file mode 100644 index 0000000..03b64c1 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerSerialSIM7020.h @@ -0,0 +1,1261 @@ +#ifndef BLINKER_SERIAL_SIM7020_H +#define BLINKER_SERIAL_SIM7020_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" +#include "../Functions/BlinkerSIM7020.h" +#include "../Functions/BlinkerHTTPSIM7020.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +#include "../Functions/BlinkerMQTTSIM7020.h" + +char* MQTT_HOST_NBIoT; +char* MQTT_ID_NBIoT; +char* MQTT_NAME_NBIoT; +char* MQTT_KEY_NBIoT; +char* MQTT_PRODUCTINFO_NBIoT; +char* UUID_NBIoT; +char* AUTHKEY_NBIoT; +char* MQTT_DEVICEID_NBIoT; +char* DEVICE_NAME_NBIoT; +char* BLINKER_PUB_TOPIC_NBIoT; +char* BLINKER_SUB_TOPIC_NBIoT; +uint16_t MQTT_PORT_NBIoT; + +BlinkerMQTTSIM7020* mqtt_NBIoT; + +class BlinkerSerialSIM7020 : public BlinkerStream +{ + public : + BlinkerSerialSIM7020() + : stream(NULL), isConnect(false) + {} + + int connect(); + int connected(); + int mConnected(); + void disconnect(); + void ping(); + int available(); + int aligenieAvail(); + int duerAvail(); + void subscribe(); + int timedRead(); + char * lastRead() { if (isFresh_NBIoT) return msgBuf_NBIoT; return ""; } + void flush(); + // int print(const String & s, bool needCheck = true); + int print(char * data, bool needCheck = true); + int toServer(char * data); + int bPrint(char * name, const String & data); + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + void aliType(const String & type); + void duerType(const String & type); + void begin(const char* _deviceType, String _imei); + void initStream(Stream& s, bool state, blinker_callback_t func); + int autoPrint(unsigned long id); + char * deviceName(); + char * authKey() { return AUTHKEY_NBIoT; } + char * token() { if (!isMQTTinit) return ""; else return MQTT_KEY_NBIoT; } + int init() { return isMQTTinit; } + int reRegister() { return connectServer(); } + int deviceRegister() { return connectServer(); } + // int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + private : + bool isMQTTinit = false; + + int connectServer(); + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkCanPrint(); + int checkCanBprint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + + protected : + BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; + uint8_t _sharerCount = 0; + uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + Stream* stream; + // char* streamData; + char* msgBuf_NBIoT; + // bool isFresh = false; + bool isFresh_NBIoT = false; + bool isConnect; + bool isHWS = false; + char* imei; + // uint8_t respTimes = 0; + // uint32_t respTime = 0; + bool isAvail_NBIoT = false; + uint8_t dataFrom_NBIoT = BLINKER_MSG_FROM_MQTT; + + // uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + const char* _deviceType;//_authKey + char* _aliType; + char* _duerType; + bool isAlive = false; + // bool isBavail = false; + bool _needCheckShare = false; + uint32_t latestTime; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t kaTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + + uint32_t aliKaTime = 0; + bool isAliAlive = false; + bool isAliAvail = false; + uint32_t duerKaTime = 0; + bool isDuerAlive = false; + bool isDuerAvail = false; + char* mqtt_broker; + + int isJson(const String & data); + + uint8_t reconnect_time = 0; + blinker_callback_t listenFunc = NULL; +}; + +int BlinkerSerialSIM7020::connect() +{ + BLINKER_LOG_ALL(BLINKER_F(">>>>>> mqtt connect <<<<<<")); + + if (!isMQTTinit) return false; + + // if (mqtt_NBIoT->connected()) return true; + if (isConnect) return true; + + BLINKER_LOG_ALL(BLINKER_F(">>>>>> mqtt connect failed <<<<<<")); + + disconnect(); + + // if ((millis() - latestTime) < BLINKER_MQTT_CONNECT_TIMESLOT && latestTime > 0) + // { + // yield(); + // return false; + // } + + BLINKER_LOG(BLINKER_F("Connecting to MQTT... ")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!mqtt_NBIoT->connect()) + { + BLINKER_LOG(BLINKER_F("Retrying MQTT connection in "), \ + BLINKER_MQTT_CONNECT_TIMESLOT/1000, \ + BLINKER_F(" seconds...")); + + this->latestTime = millis(); + reconnect_time += 1; + if (reconnect_time >= 12) + { + reRegister(); + reconnect_time = 0; + } + return false; + } + + reconnect_time = 0; + + BLINKER_LOG(BLINKER_F("MQTT Connected!")); + BLINKER_LOG_FreeHeap(); + + isConnect = true; + + this->latestTime = millis(); + + return true; +} + +int BlinkerSerialSIM7020::connected() +{ + if (!isMQTTinit) return false; + + return isConnect;//mqtt_NBIoT->connected(); +} + +int BlinkerSerialSIM7020::mConnected() +{ + if (!isMQTTinit) return false; + else return mqtt_NBIoT->connected(); +} + +void BlinkerSerialSIM7020::disconnect() +{ + if (isMQTTinit) { + isConnect = false; + mqtt_NBIoT->disconnect(); + } +} + +void BlinkerSerialSIM7020::ping() +{ + BLINKER_LOG_ALL(BLINKER_F("MQTT Ping!")); + + BLINKER_LOG_FreeHeap_ALL(); + + if (!isMQTTinit) return; + + if (!isConnect) + { + // disconnect(); + + delay(100); + + connect(); + // delay(100); + + // connect(); + } + else + { + this->latestTime = millis(); + } + + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + + BLINKER_LOG_ALL(BLINKER_F("check isReboot")); + + if (BLINKER_SIM7020.isReboot()) + { + BLINKER_SIM7020.powerCheck(); + + // disconnect(); + } +} + +int BlinkerSerialSIM7020::available() +{ + if (isMQTTinit) { + checkKA(); + + // if (!mqtt_PRO->connected() || \ + // (millis() - this->latestTime) > BLINKER_MQTT_PING_TIMEOUT) + if ((millis() - this->latestTime) > 30000) + { + ping(); + } + else + { + subscribe(); + } + } + + if (isAvail_NBIoT) + { + isAvail_NBIoT = false; + return true; + } + else { + return false; + } +} + +int BlinkerSerialSIM7020::aligenieAvail() +{ + if (!isMQTTinit) return false; + + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerSerialSIM7020::duerAvail() +{ + if (!isMQTTinit) return false; + + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +void BlinkerSerialSIM7020::subscribe() +{ + if (!isMQTTinit) return; + + if (mqtt_NBIoT->readSubscription()) + { + BLINKER_LOG_ALL(BLINKER_F("Got: "), mqtt_NBIoT->lastRead); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(String(mqtt_NBIoT->lastRead)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, String(mqtt_NBIoT->lastRead)); + JsonObject root = jsonBuffer.as(); + + String _uuid = root["fromDevice"]; + String dataGet = root["data"]; + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_NBIoT) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_NBIoT = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT) + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_NBIoT = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found, \ + check is from bridge/share device, \ + data: "), dataGet); + + _needCheckShare = true; + } + } + } + // root.printTo(dataGet); + serializeJson(root, dataGet); + + isAvail_NBIoT = true; + isAlive = true; + } + + if (isFresh_NBIoT) free(msgBuf_NBIoT); + msgBuf_NBIoT = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_NBIoT, dataGet.c_str()); + isFresh_NBIoT = true; + + this->latestTime = millis(); + + dataFrom_NBIoT = BLINKER_MSG_FROM_MQTT; + } +} + +void BlinkerSerialSIM7020::flush() +{ + if (isFresh_NBIoT) + { + free(msgBuf_NBIoT); isFresh_NBIoT = false; isAvail_NBIoT = false; + isAliAvail = false; //isBavail = false; + } +} + +int BlinkerSerialSIM7020::print(char * data, bool needCheck) +{ + if (!isMQTTinit) return false; + + BLINKER_LOG_ALL(BLINKER_F("data: "), data); + + uint16_t num = strlen(data); + + data[num+8] = '\0'; + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+7] = data[c_num-1]; + } + + // String data_add = BLINKER_F("{\"data\":"); + char data_add[20] = "{\"data\":"; + for(uint16_t c_num = 0; c_num < 8; c_num++) + { + data[c_num] = data_add[c_num]; + } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, ",\"fromDevice\":\""); + strcat(data, MQTT_ID_NBIoT); + // strcat(data, MQTT_DEVICEID_NBIoT); //PRO + // data_add = BLINKER_F("\",\"toDevice\":\""); + // strcat(data, data_add.c_str()); + strcat(data, "\",\"toDevice\":\""); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + strcat(data, _sharers[_sharerFrom]->uuid()); + } + else + { + strcat(data, UUID_NBIoT); + } + // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}"); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + // strcat(data, data_add.c_str()); + strcat(data, "\",\"deviceType\":\"OwnApp\"}"); + + // data_add = STRING_format(data); + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (connected()) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + // if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, msg_data.c_str())) + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + disconnect(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + + +int BlinkerSerialSIM7020::toServer(char * data) +{ + if (!isMQTTinit) return false; + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish to server...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (mqtt_NBIoT->connected()) + { + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerSerialSIM7020::bPrint(char * name, const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_NBIoT); + strcat(data_add, ",\"toDevice\":\""); + strcat(data_add, name); + strcat(data_add, "\",\"deviceType\":\"DiyBridge\"}"); + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\""); + // data_add += name; + // data_add += BLINKER_F("\",\"deviceType\":\"DiyBridge\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Bridge Publish...")); + + // bool _alive = isAlive; + // bool state = STRING_contains_string(data, BLINKER_CMD_NOTICE); + + // if (!state) { + // state = (STRING_contains_string(data, BLINKER_CMD_STATE) + // && STRING_contains_string(data, BLINKER_CMD_ONLINE)); + // } + + if (mqtt_NBIoT->connected()) { + // if (!state) { + if (!checkCanBprint()) { + // if (!_alive) { + // isAlive = false; + // } + return false; + } + // } + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + + // if (! iotPub.publish(payload.c_str())) { + + // String bPubTopic = BLINKER_F(""); + // char bPubTopic[60] = { '\0' }; + + // if (strcmp(mqtt_broker, BLINKER_MQTT_BORKER_ONENET) == 0) + // { + // // bPubTopic = MQTT_PRODUCTINFO_MQTT; + // // bPubTopic += BLINKER_F("/"); + // // bPubTopic += name; + // // bPubTopic += BLINKER_F("/r"); + // } + // else + // { + // strcpy(bPubTopic, BLINKER_PUB_TOPIC_MQTT); + // bPubTopic = BLINKER_PUB_TOPIC_MQTT; + // } + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + // if (!_alive) { + // isAlive = false; + // } + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + bPrintTime = millis(); + + // if (!_alive) { + // isAlive = false; + // } + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + // isAlive = false; + return false; + } + // } +} + +int BlinkerSerialSIM7020::aliPrint(const String & data) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_NBIoT); + strcat(data_add, "\",\"toDevice\":\"AliGenie_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"AliGenie_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_NBIoT->connected()) + { + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerSerialSIM7020::duerPrint(const String & data, bool report) +{ + if (!isMQTTinit) return false; + + char data_add[1024] = { '\0' }; + + strcpy(data_add, "{\"data\":"); + strcat(data_add, data.c_str()); + strcat(data_add, ",\"fromDevice\":\""); + strcat(data_add, MQTT_ID_NBIoT); + strcat(data_add, "\",\"toDevice\":\"DuerOS_r\""); + strcat(data_add, "\",\"deviceType\":\"vAssistant\"}"); + + // String data_add = BLINKER_F("{\"data\":"); + + // data_add += data; + // data_add += BLINKER_F(",\"fromDevice\":\""); + // data_add += MQTT_ID_MQTT; + // data_add += BLINKER_F("\",\"toDevice\":\"DuerOS_r\""); + // data_add += BLINKER_F(",\"deviceType\":\"vAssistant\"}"); + + if (!isJson(STRING_format(data_add))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (mqtt_NBIoT->connected()) + { + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, data_add)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +void BlinkerSerialSIM7020::aliType(const String & type) +{ + _aliType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_aliType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_aliType: "), _aliType); +} + +void BlinkerSerialSIM7020::duerType(const String & type) +{ + _duerType = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_duerType, type.c_str()); + BLINKER_LOG_ALL(BLINKER_F("_duerType: "), _duerType); +} + +void BlinkerSerialSIM7020::begin(const char* _type, String _imei) +{ + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + // stream = &s; + // stream->setTimeout(BLINKER_STREAM_TIMEOUT); + // isHWS = state; + + imei = (char*)malloc((_imei.length() + 1)*sizeof(char)); + strcpy(imei, _imei.c_str()); + + AUTHKEY_NBIoT = (char*)malloc((strlen(_deviceType) + 1)*sizeof(char)); + strcpy(AUTHKEY_NBIoT, _deviceType); +} + +void BlinkerSerialSIM7020::initStream(Stream& s, bool state, blinker_callback_t func) +{ + // _deviceType = _type; + + // BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); + + stream = &s; + stream->setTimeout(BLINKER_STREAM_TIMEOUT); + isHWS = state; + + listenFunc = func; + + // streamPrint(BLINKER_CMD_AT); + // ::delay(200); + // streamPrint(BLINKER_CMD_CRESET_RESQ); + + // _imei = (char*)malloc(imei.length()*sizeof(char)); + // strcpy(_imei, imei.c_str()); +} + +int BlinkerSerialSIM7020::autoPrint(unsigned long id) +{ + String payload = BLINKER_F("{\"data\":{\"set\":{"); + payload += BLINKER_F("\"trigged\":true,\"autoData\":{"); + payload += BLINKER_F("\"autoId\":"); + payload += STRING_format(id); + payload += BLINKER_F("}}}"); + payload += BLINKER_F(",\"fromDevice\":\""); + payload += STRING_format(MQTT_ID_NBIoT); + payload += BLINKER_F("\",\"toDevice\":\"autoManager\"}"); + // "\",\"deviceType\":\"" + "type" + "\"}"; + + BLINKER_LOG_ALL(BLINKER_F("autoPrint...")); + + if (mqtt_NBIoT->connected()) + { + if ((millis() - linkTime) > BLINKER_LINK_MSG_LIMIT || \ + linkTime == 0) + { + // linkTime = millis(); + + // Adafruit_MQTT_Publish iotPub = Adafruit_MQTT_Publish(mqtt_MQTT, BLINKER_PUB_TOPIC_MQTT); + + // if (! iotPub.publish(payload.c_str())) { + + if (! mqtt_NBIoT->publish(BLINKER_PUB_TOPIC_NBIoT, payload.c_str())) + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + + return false; + } + else + { + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + + linkTime = millis(); + + this->latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT "), linkTime); + + return false; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +char * BlinkerSerialSIM7020::deviceName() +{ + BLINKER_LOG_ALL(BLINKER_F("BlinkerSerialSIM7020::deviceName: "), MQTT_ID_NBIoT); + return MQTT_ID_NBIoT;/*MQTT_ID_PRO;*/ +} + +void BlinkerSerialSIM7020::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (uint8_t num = _sharerCount; num > 0; num--) + { + delete _sharers[num - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerSerialSIM7020::connectServer() +{ + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + String uri = ""; + // uri += BLINKER_F("/api/v1/user/device/register?deviceType="); + // uri += _deviceType; + // uri += BLINKER_F("&deviceName="); + // uri += imei; + uri += BLINKER_F("/api/v1/user/device/diy/auth?authKey="); + uri += _deviceType; + uri += _aliType; + uri += _duerType; + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), host + uri); + + BlinkerHTTPSIM7020 http(*stream, isHWS, listenFunc); + + http.begin(host, uri); + + String payload; + + if (http.GET()) + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... success")); + + payload = http.getString(); + + // return true; + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] GET... failed")); + + return false; + } + + BLINKER_LOG_ALL(BLINKER_F("reply was:")); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + BLINKER_LOG_ALL(payload); + BLINKER_LOG_ALL(BLINKER_F("==============================")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject root = jsonBuffer.as(); + + if (STRING_contains_string(payload, BLINKER_CMD_NOTFOUND) || error || + !STRING_contains_string(payload, BLINKER_CMD_IOTID)) { + // while(1) { + BLINKER_ERR_LOG(("Please make sure you have register this device!")); + // ::delay(60000); + + return false; + // } + } + + String _userID = root[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME]; + String _userName = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTID]; + String _key = root[BLINKER_CMD_DETAIL][BLINKER_CMD_IOTTOKEN]; + String _productInfo = root[BLINKER_CMD_DETAIL][BLINKER_CMD_PRODUCTKEY]; + String _broker = root[BLINKER_CMD_DETAIL][BLINKER_CMD_BROKER]; + String _uuid = root[BLINKER_CMD_DETAIL][BLINKER_CMD_UUID]; + + if (isMQTTinit) + { + free(MQTT_HOST_NBIoT); + free(MQTT_ID_NBIoT); + free(MQTT_NAME_NBIoT); + free(MQTT_KEY_NBIoT); + free(MQTT_PRODUCTINFO_NBIoT); + free(UUID_NBIoT); + free(DEVICE_NAME_NBIoT); + free(BLINKER_PUB_TOPIC_NBIoT); + free(BLINKER_SUB_TOPIC_NBIoT); + free(mqtt_NBIoT); + // free(iotSub_NBIoT); + + isMQTTinit = false; + } + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + // memcpy(DEVICE_NAME_MQTT, _userID.c_str(), 12); + DEVICE_NAME_NBIoT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(DEVICE_NAME_NBIoT, _userID.c_str()); + MQTT_ID_NBIoT = (char*)malloc((_userID.length()+1)*sizeof(char)); + strcpy(MQTT_ID_NBIoT, _userID.c_str()); + MQTT_NAME_NBIoT = (char*)malloc((_userName.length()+1)*sizeof(char)); + strcpy(MQTT_NAME_NBIoT, _userName.c_str()); + MQTT_KEY_NBIoT = (char*)malloc((_key.length()+1)*sizeof(char)); + strcpy(MQTT_KEY_NBIoT, _key.c_str()); + MQTT_PRODUCTINFO_NBIoT = (char*)malloc((_productInfo.length()+1)*sizeof(char)); + strcpy(MQTT_PRODUCTINFO_NBIoT, _productInfo.c_str()); + MQTT_HOST_NBIoT = (char*)malloc((strlen(BLINKER_MQTT_ALIYUN_HOST)+1)*sizeof(char)); + strcpy(MQTT_HOST_NBIoT, BLINKER_MQTT_ALIYUN_HOST); + MQTT_PORT_NBIoT = BLINKER_MQTT_ALIYUN_PORT; + } + + UUID_NBIoT = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_NBIoT, _uuid.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL(BLINKER_F("DEVICE_NAME_NBIoT: "), DEVICE_NAME_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_PRODUCTINFO_NBIoT: "), MQTT_PRODUCTINFO_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_ID_NBIoT: "), MQTT_ID_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_NAME_NBIoT: "), MQTT_NAME_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_KEY_NBIoT: "), MQTT_KEY_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("MQTT_BROKER: "), _broker); + BLINKER_LOG_ALL(BLINKER_F("HOST: "), MQTT_HOST_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("PORT: "), MQTT_PORT_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("UUID_NBIoT: "), UUID_NBIoT); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + String PUB_TOPIC_STR = BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_PRODUCTINFO_NBIoT; + PUB_TOPIC_STR += BLINKER_F("/"); + PUB_TOPIC_STR += MQTT_ID_NBIoT; + PUB_TOPIC_STR += BLINKER_F("/s"); + + BLINKER_PUB_TOPIC_NBIoT = (char*)malloc((PUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_PUB_TOPIC_NBIoT, PUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_PUB_TOPIC_NBIoT, PUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_PUB_TOPIC_NBIoT: "), BLINKER_PUB_TOPIC_NBIoT); + + String SUB_TOPIC_STR = BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_PRODUCTINFO_NBIoT; + SUB_TOPIC_STR += BLINKER_F("/"); + SUB_TOPIC_STR += MQTT_ID_NBIoT; + SUB_TOPIC_STR += BLINKER_F("/r"); + + BLINKER_SUB_TOPIC_NBIoT = (char*)malloc((SUB_TOPIC_STR.length() + 1)*sizeof(char)); + // memcpy(BLINKER_SUB_TOPIC_NBIoT, SUB_TOPIC_STR.c_str(), str_len); + strcpy(BLINKER_SUB_TOPIC_NBIoT, SUB_TOPIC_STR.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("BLINKER_SUB_TOPIC_NBIoT: "), BLINKER_SUB_TOPIC_NBIoT); + } + + // if (_broker == BLINKER_MQTT_BORKER_ALIYUN) { + mqtt_NBIoT = new BlinkerMQTTSIM7020(*stream, isHWS, MQTT_HOST_NBIoT, MQTT_PORT_NBIoT, + MQTT_ID_NBIoT, MQTT_NAME_NBIoT, MQTT_KEY_NBIoT, listenFunc); + // } + + this->latestTime = millis(); + isMQTTinit = true; + mqtt_NBIoT->subscribe(BLINKER_SUB_TOPIC_NBIoT); + + return true; +} + +void BlinkerSerialSIM7020::checkKA() +{ + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerSerialSIM7020::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerSerialSIM7020::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerSerialSIM7020::checkCanPrint() { + if ((millis() - printTime >= BLINKER_PRO_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerSerialSIM7020::checkCanBprint() { + if ((millis() - bPrintTime >= BLINKER_BRIDGE_MSG_LIMIT) || bPrintTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + return false; + } +} + +int BlinkerSerialSIM7020::checkPrintSpan() +{ + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) + { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG(BLINKER_F("DEVICE NOT CONNECT OR MSG LIMIT")); + + return false; + } + else + { + respTimes++; + return true; + } + } + else + { + respTimes = 0; + return true; + } +} + +int BlinkerSerialSIM7020::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerSerialSIM7020::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerSerialSIM7020::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG("Print data is not Json! ", data); + return false; + } + return true; +} + + +#endif diff --git a/blinker-library/src/Adapters/BlinkerSubDevice.h b/blinker-library/src/Adapters/BlinkerSubDevice.h new file mode 100644 index 0000000..059cc57 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerSubDevice.h @@ -0,0 +1,1109 @@ +#ifndef BLINKER_SUBDEVICE_H +#define BLINKER_SUBDEVICE_H + +#if defined(ESP8266) || defined(ESP32) + +#if defined(ESP8266) + #include + #include + #include +#elif defined(ESP32) + #include + #include + #include +#endif + +#include + +#include "../modules/painlessMesh/painlessMesh.h" + +// #include "../modules/WebSockets/WebSocketsServer.h" +// #include "../modules/mqtt/Adafruit_MQTT.h" +// #include "../modules/mqtt/Adafruit_MQTT_Client.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif +// #include "../Adapters/BlinkerGateway.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +char* msgBuf_mesh; +bool isFresh_mesh = false; +bool isAvail_mesh = false; + +char* msgBuf_PRO; +bool isFresh_PRO = false; +bool isAvail_PRO = false; +char* AUTHKEY_PRO; +char* UUID_PRO; +char* MQTT_DEVICEID_PRO; + +painlessMesh mesh; + +#ifndef BLINKER_MESH_SSID + #define BLINKER_MESH_SSID "blinkerMesh" +#endif + +#ifndef BLINKER_MESH_PSWD + #define BLINKER_MESH_PSWD "blinkerMesh" +#endif + +#ifndef BLINKER_MESH_PORT + #define BLINKER_MESH_PORT 5555 +#endif + +char* meshBuf; +bool isFresh_gate = false; +bool isAvail_gate = false; +uint32_t msgFrom; +bool isTimeSet = false; +float mesh_timezone = 8.0; +bool isNewConnect = false; + +BlinkerSharer * _sharers[BLINKER_MQTT_MAX_SHARERS_NUM]; +uint8_t _sharerCount = 0; +uint8_t _sharerFrom = BLINKER_MQTT_FROM_AUTHER; +bool isAlive = false; +uint32_t kaTime = 0; +bool _needCheckShare = false; +uint32_t latestTime; +uint32_t aliKaTime = 0; +bool isAliAlive = false; +bool isAliAvail = false; +uint32_t duerKaTime = 0; +bool isDuerAlive = false; +bool isDuerAvail = false; +uint32_t miKaTime = 0; +bool isMIOTAlive = false; +bool isMIOTAvail = false; + +void _receivedCallback(uint32_t from, String &msg) +{ + BLINKER_LOG_ALL("bridge: Received from: ", from, ", msg: ",msg); + msgFrom = from; + + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, msg); + JsonObject root = jsonBuffer.as(); + + if (error) + { + BLINKER_ERR_LOG_ALL("msg not Json!"); + return; + } + + if (root.containsKey(BLINKER_CMD_GATE)) + { + BLINKER_LOG_ALL("gate data"); + + if ((!isTimeSet || mesh_timezone != root["tz"]) && root.containsKey("tz")) + { + time_t rtc = root[BLINKER_CMD_TIME]; + mesh_timezone = root["tz"]; + BLINKER_LOG_ALL("rtc: ", rtc, ", tz: ", mesh_timezone); + timeval tv = { rtc, 0 }; + timezone tz = { int16_t(mesh_timezone*60) , 0 }; + settimeofday(&tv, &tz); + + isTimeSet = true; + } + + time_t now = time(nullptr); + BLINKER_LOG_ALL("now: ", now, ", ", ctime(&now)); + + String _data = root[BLINKER_CMD_GATE]; + meshBuf = (char*)malloc((_data.length()+1)*sizeof(char)); + strcpy(meshBuf, _data.c_str()); + + isAvail_gate = true; + } + else if (root.containsKey("meshData")) + { + BLINKER_LOG_ALL("mesh data"); + + String _data = root["meshData"]; + if (isFresh_mesh) free(msgBuf_mesh); + msgBuf_mesh = (char*)malloc((_data.length()+1)*sizeof(char)); + strcpy(msgBuf_mesh, _data.c_str()); + + isAvail_mesh = true; + isFresh_mesh = true; + } + else if (root.containsKey("subDevice")) + { + String _uuid = root["fromDevice"]; + String dataGet = root["data"]; + + BLINKER_LOG_ALL(BLINKER_F("data: "), dataGet); + BLINKER_LOG_ALL(BLINKER_F("fromDevice: "), _uuid); + + if (strcmp(_uuid.c_str(), UUID_PRO) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("Authority uuid")); + + kaTime = millis(); + isAvail_PRO = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else if (_uuid == BLINKER_CMD_ALIGENIE) + { + BLINKER_LOG_ALL(BLINKER_F("form AliGenie")); + + aliKaTime = millis(); + isAliAlive = true; + isAliAvail = true; + } + else if (_uuid == BLINKER_CMD_DUEROS) + { + BLINKER_LOG_ALL(BLINKER_F("form DuerOS")); + + duerKaTime = millis(); + isDuerAlive = true; + isDuerAvail = true; + } + else if (_uuid == BLINKER_CMD_SERVERCLIENT) + { + BLINKER_LOG_ALL(BLINKER_F("form Sever")); + + isAvail_PRO = true; + isAlive = true; + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + } + else + { + if (_sharerCount) + { + for (uint8_t num = 0; num < _sharerCount; num++) + { + if (strcmp(_uuid.c_str(), _sharers[num]->uuid()) == 0) + { + _sharerFrom = num; + + kaTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("From sharer: "), _uuid); + BLINKER_LOG_ALL(BLINKER_F("sharer num: "), num); + + _needCheckShare = false; + + break; + } + else + { + BLINKER_ERR_LOG_ALL(BLINKER_F("No authority uuid found," + "check is from bridge/share device," + "data: "), dataGet); + + _needCheckShare = true; + } + } + } + + serializeJson(root, dataGet); + + isAvail_PRO = true; + isAlive = true; + } + + if (isFresh_PRO) free(msgBuf_PRO); + msgBuf_PRO = (char*)malloc((dataGet.length()+1)*sizeof(char)); + strcpy(msgBuf_PRO, dataGet.c_str()); + isFresh_PRO = true; + + latestTime = millis(); + + // dataFrom_PRO = BLINKER_MSG_FROM_MQTT; + } +} + +void _newConnectionCallback(uint32_t nodeId) +{ + BLINKER_LOG_ALL("--> startHere: New Connection, nodeId = ", nodeId); + BLINKER_LOG_ALL("--> startHere: New Connection, ", mesh.subConnectionJson(true)); + + if (!isNewConnect) isNewConnect = true; +} + +class BlinkerSubDevice : public BlinkerStream +{ + public : + BlinkerSubDevice() + : isDeviceInit(false) + {} + + int connect(); + int connected(); + int mConnected(); + void disconnect(); + int available(); + int meshAvail(); + int aligenieAvail(); + int duerAvail(); + int miAvail(); + char * lastRead(); + char * meshLastRead(); + void flush(); + void meshFlush(); + int subPrint(const String & data); + int print(char * data, bool needCheck = true); + int bPrint(char * name, const String & data) { return false; } + int aliPrint(const String & data); + int duerPrint(const String & data, bool report = false); + int miPrint(const String & data); + void begin(const char* _key, const char* _type); + int autoPrint(unsigned long id); + char * deviceName(); + char * authKey() { return AUTHKEY_PRO; } + char * token() { if (!isAuth) return ""; else return MQTT_KEY_PRO; } + int init() { return isAuth; } + int reRegister(); + int deviceRegister() { return false; } + int authCheck(); + void freshAlive() { kaTime = millis(); isAlive = true; } + void sharers(const String & data); + int needFreshShare() { + if (_needCheckShare) + { + BLINKER_LOG_ALL(BLINKER_F("needFreshShare")); + _needCheckShare = false; + return true; + } + else + { + return false; + } + } + + private : + bool isDeviceInit; + + void checkKA(); + int checkAliKA(); + int checkDuerKA(); + int checkMIOTKA(); + int checkCanPrint(); + int checkPrintSpan(); + int checkAliPrintSpan(); + int checkDuerPrintSpan(); + int checkMIOTPrintSpan(); + int pubHello(); + uint16_t vatFormat(); + bool meshInit(); + void meshCheck(); + void sendBroadcast(String msg); + bool sendSingle(uint32_t toId, String msg); + String gateFormat(const String & msg); + + protected : + const char* _vipKey; + const char* _deviceType; + + bool isBavail = false; + uint32_t printTime = 0; + uint32_t bPrintTime = 0; + uint32_t linkTime = 0; + uint8_t respTimes = 0; + uint32_t respTime = 0; + uint8_t respAliTimes = 0; + uint32_t respAliTime = 0; + uint8_t respDuerTimes = 0; + uint32_t respDuerTime = 0; + uint8_t respMIOTTimes = 0; + uint32_t respMIOTTime = 0; + + bool isNew = false; + bool isAuth = false; + bool isFirst = false; + + int isJson(const String & data); + + bool _isAuthKey = false; + bool _isMeshInit = false; + bool _isHello = false; + uint32_t gateId = 0; + // bool _isTimeSet = false; +}; + +int BlinkerSubDevice::connect() +{ + if (gateId == 0) return false; + return mesh.isConnected(gateId); +} + +int BlinkerSubDevice::connected() +{ + if (gateId == 0) return false; + return mesh.isConnected(gateId); +} + +int BlinkerSubDevice::mConnected() +{ + return true; +} + +void BlinkerSubDevice::disconnect() +{} + +int BlinkerSubDevice::available() +{ + return false; +} + +int BlinkerSubDevice::meshAvail() +{ + if (isAvail_mesh) + { + isAvail_mesh = false; + return true; + } + else { + return false; + } +} + +int BlinkerSubDevice::aligenieAvail() +{ + if (isAliAvail) + { + isAliAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerSubDevice::duerAvail() +{ + if (isDuerAvail) + { + isDuerAvail = false; + return true; + } + else { + return false; + } +} + +int BlinkerSubDevice::miAvail() +{ + if (isMIOTAvail) + { + isMIOTAvail = false; + return true; + } + else { + return false; + } +} + +char * BlinkerSubDevice::lastRead() +{ + if (isFresh_PRO) return msgBuf_PRO; + return ""; +} + +char * BlinkerSubDevice::meshLastRead() +{ + if (isFresh_mesh) return msgBuf_mesh; + return ""; +} + +void BlinkerSubDevice::flush() +{ + if (isFresh_PRO) + { + free(msgBuf_PRO); isFresh_PRO = false; isAvail_PRO = false; + isAliAvail = false; isDuerAvail = false; isMIOTAvail = false;//isBavail = false; + } +} + +void BlinkerSubDevice::meshFlush() +{ + if (isFresh_mesh) + { + free(msgBuf_mesh); isFresh_mesh = false; isAvail_mesh = false; + } +} + +int BlinkerSubDevice::subPrint(const String & data) +{ + String data_add = BLINKER_F("{\"ctrl\":"); + data_add += data; + data_add += BLINKER_F("}"); + + if (!isJson(data_add)) return false; + + if (gateId == 0) return false; + + return sendSingle(gateId, data_add); +} + +int BlinkerSubDevice::print(char * data, bool needCheck) +{ + uint16_t num = strlen(data); + + for(uint16_t c_num = num; c_num > 0; c_num--) + { + data[c_num+15] = data[c_num-1]; + } + + data[num+16] = '\0'; + + String data_add = BLINKER_F("{\"ctrl\":{\"user\":"); + + for(uint16_t c_num = 0; c_num < 16; c_num++) + { + data[c_num] = data_add[c_num]; + } + + // data_add = BLINKER_F(",\"fromDevice\":\""); + // strcat(data, data_add.c_str()); + // strcat(data, MQTT_DEVICEID_PRO); + data_add = BLINKER_F("\",\"toDevice\":\""); + strcat(data, data_add.c_str()); + if (_sharerFrom < BLINKER_MQTT_MAX_SHARERS_NUM) + { + strcat(data, _sharers[_sharerFrom]->uuid()); + } + else + { + strcat(data, UUID_PRO); + } + // data_add = BLINKER_F("\",\"deviceType\":\"OwnApp\"}}"); + data_add = BLINKER_F("}}"); + strcat(data, data_add.c_str()); + + _sharerFrom = BLINKER_MQTT_FROM_AUTHER; + + if (!isJson(STRING_format(data))) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + bool _alive = isAlive; + + if (needCheck) + { + if (!checkPrintSpan()) + { + return false; + } + respTime = millis(); + } + + if (gateId != 0) + { + if (needCheck) + { + if (!checkCanPrint()) + { + if (!_alive) + { + isAlive = false; + } + return false; + } + } + + if (!sendSingle(gateId, data)) + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + if (!_alive) + { + isAlive = false; + } + return false; + } + else + { + BLINKER_LOG_ALL(data); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + if (needCheck) printTime = millis(); + + if (!_alive) + { + isAlive = false; + } + + latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + isAlive = false; + return false; + } +} + +int BlinkerSubDevice::aliPrint(const String & data) +{ + String data_add = BLINKER_F("{\"ctrl\":{\"ali\":"); + + data_add += data; + data_add += BLINKER_F("}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT AliGenie Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (gateId != 0) + { + if (!checkAliKA()) + { + return false; + } + + if (!checkAliPrintSpan()) + { + respAliTime = millis(); + return false; + } + respAliTime = millis(); + + if (!sendSingle(gateId, data)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isAliAlive = false; + + latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerSubDevice::duerPrint(const String & data, bool report) +{ + String data_add = BLINKER_F("{\"ctrl\":{\"duer\":"); + + data_add += data; + data_add += BLINKER_F("}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT DuerOS Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (gateId != 0) + { + if (!checkDuerKA()) + { + return false; + } + + if (!checkDuerPrintSpan()) + { + respDuerTime = millis(); + return false; + } + respDuerTime = millis(); + + if (!sendSingle(gateId, data)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isDuerAlive = false; + + latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +int BlinkerSubDevice::miPrint(const String & data) +{ + String data_add = BLINKER_F("{\"ctrl\":{\"miot\":"); + + data_add += data; + data_add += BLINKER_F("}"); + + if (!isJson(data_add)) return false; + + BLINKER_LOG_ALL(BLINKER_F("MQTT MIOT Publish...")); + BLINKER_LOG_FreeHeap_ALL(); + + if (gateId != 0) + { + if (!checkMIOTKA()) + { + return false; + } + + if (!checkMIOTPrintSpan()) + { + respMIOTTime = millis(); + return false; + } + respMIOTTime = millis(); + + if (!sendSingle(gateId, data)) + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...Failed")); + BLINKER_LOG_FreeHeap_ALL(); + + isMIOTAlive = false; + return false; + } + else + { + BLINKER_LOG_ALL(data_add); + BLINKER_LOG_ALL(BLINKER_F("...OK!")); + BLINKER_LOG_FreeHeap_ALL(); + + isMIOTAlive = false; + + latestTime = millis(); + + return true; + } + } + else + { + BLINKER_ERR_LOG(BLINKER_F("MQTT Disconnected")); + return false; + } +} + +void BlinkerSubDevice::begin(const char* _key, const char* _type) +{ + _vipKey = _key; + _deviceType = _type; + + BLINKER_LOG_ALL(BLINKER_F("PRO deviceType: "), _type); +} + +int BlinkerSubDevice::autoPrint(unsigned long id) +{ + return false; +} + +char * BlinkerSubDevice::deviceName() { return MQTT_DEVICEID_PRO;/*MQTT_ID_PRO;*/ } + +void BlinkerSubDevice::sharers(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("sharers data: "), data); + + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + String user_name = ""; + + if (_sharerCount) + { + for (_sharerCount; _sharerCount > 0; _sharerCount--) + { + delete _sharers[_sharerCount - 1]; + } + } + + _sharerCount = 0; + + for (uint8_t num = 0; num < BLINKER_MQTT_MAX_SHARERS_NUM; num++) + { + user_name = root["users"][num].as(); + + if (user_name.length() >= BLINKER_MQTT_USER_UUID_SIZE) + { + BLINKER_LOG_ALL(BLINKER_F("sharer uuid: "), user_name, BLINKER_F(", length: "), user_name.length()); + + _sharerCount++; + + _sharers[num] = new BlinkerSharer(user_name); + } + else + { + break; + } + } +} + +int BlinkerSubDevice::authCheck() +{ + return false; +} + +void BlinkerSubDevice::checkKA() { + if (millis() - kaTime >= BLINKER_MQTT_KEEPALIVE) + isAlive = false; +} + +int BlinkerSubDevice::checkAliKA() { + if (millis() - aliKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerSubDevice::checkDuerKA() { + if (millis() - duerKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerSubDevice::checkMIOTKA() { + if (millis() - miKaTime >= 10000) + return false; + else + return true; +} + +int BlinkerSubDevice::checkCanPrint() { + if ((millis() - printTime >= BLINKER_PRO_MSG_LIMIT && isAlive) || printTime == 0) { + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("MQTT NOT ALIVE OR MSG LIMIT")); + + checkKA(); + + return false; + } +} + +int BlinkerSubDevice::checkMIOTPrintSpan() +{ + if (millis() - respMIOTTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respMIOTTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respMIOTTimes++; + return true; + } + } + else + { + respMIOTTimes = 0; + return true; + } +} + +int BlinkerSubDevice::checkPrintSpan() { + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) { + BLINKER_ERR_LOG(BLINKER_F("WEBSOCKETS CLIENT NOT ALIVE OR MSG LIMIT")); + + return false; + } + else { + respTimes++; + return true; + } + } + else { + respTimes = 0; + return true; + } +} + +int BlinkerSubDevice::checkAliPrintSpan() +{ + if (millis() - respAliTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respAliTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("ALIGENIE NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respAliTimes++; + return true; + } + } + else + { + respAliTimes = 0; + return true; + } +} + +int BlinkerSubDevice::checkDuerPrintSpan() +{ + if (millis() - respDuerTime < BLINKER_PRINT_MSG_LIMIT/2) + { + if (respDuerTimes > BLINKER_PRINT_MSG_LIMIT/2) + { + BLINKER_ERR_LOG(BLINKER_F("DUEROS NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + respDuerTimes++; + return true; + } + } + else + { + respDuerTimes = 0; + return true; + } +} + +int BlinkerSubDevice::pubHello() +{ + char stateJsonStr[256] = ("{\"message\":\"Registration successful\"}"); + + BLINKER_LOG_ALL(BLINKER_F("PUB hello: "), stateJsonStr); + + return print(stateJsonStr, false); +} + +int BlinkerSubDevice::isJson(const String & data) +{ + BLINKER_LOG_ALL(BLINKER_F("isJson: "), data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(STRING_format(data)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG(BLINKER_F("Print data is not Json! "), data); + return false; + } + + return true; +} + +uint16_t BlinkerSubDevice::vatFormat() +{ + uint16_t vstNum = 0; + #if defined(BLINKER_ALIGENIE_LIGHT) + vstNum |= 0x01 << 0; + #elif defined(BLINKER_ALIGENIE_OUTLET) + vstNum |= 0x01 << 1; + #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + vstNum |= 0x01 << 2; + #elif defined(BLINKER_ALIGENIE_SENSOR) + vstNum |= 0x01 << 3; + #elif defined(BLINKER_ALIGENIE_TYPE) + vstNum |= 0x01 << 0; + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + vstNum |= 0x01 << 4; + #elif defined(BLINKER_DUEROS_OUTLET) + vstNum |= 0x01 << 5; + #elif defined(BLINKER_DUEROS_MULTI_OUTLET) + vstNum |= 0x01 << 6; + #elif defined(BLINKER_DUEROS_SENSOR) + vstNum |= 0x01 << 7; + #elif defined(BLINKER_DUEROS_TYPE) + vstNum |= 0x01 << 4; + #endif + + #if defined(BLINKER_MIOT_LIGHT) + vstNum |= 0x01 << 8; + #elif defined(BLINKER_MIOT_OUTLET) + vstNum |= 0x01 << 9; + #elif defined(BLINKER_MIOT_MULTI_OUTLET) + vstNum |= 0x01 << 10; + #elif defined(BLINKER_MIOT_SENSOR) + vstNum |= 0x01 << 11; + #elif defined(BLINKER_MIOT_TYPE) + vstNum |= 0x01 << 8; + #endif + + BLINKER_LOG_ALL("vstNum: ", vstNum); + + return vstNum; +} + +bool BlinkerSubDevice::meshInit() +{ + // if (WiFi.status() != WL_CONNECTED) return false; + + mesh.setDebugMsgTypes( ERROR | STARTUP | CONNECTION ); // set before init() so that you can see startup messages + // Channel set to 6. Make sure to use the same channel for your mesh and for you other + // network (STATION_SSID) + mesh.init(BLINKER_MESH_SSID, BLINKER_MESH_PSWD, BLINKER_MESH_PORT); + // mesh.stationManual(STATION_SSID, STATION_PASSWORD, STATION_PORT, station_ip); + // BLINKER_LOG_ALL("SSID: ", WiFi.SSID(), ", PWSD: ", WiFi.psk()); + // mesh.stationManual(WiFi.SSID(), WiFi.psk()); + // Bridge node, should (in most cases) be a root node. See [the wiki](https://gitlab.com/painlessMesh/painlessMesh/wikis/Possible-challenges-in-mesh-formation) for some background + // mesh.setRoot(true); + // This and all other mesh should ideally now the mesh contains a root + // mesh.setContainsRoot(true); + + mesh.onReceive(&_receivedCallback); + mesh.onNewConnection(&_newConnectionCallback); + + // WiFi.reconnect(); + + return true; +} + +void BlinkerSubDevice::meshCheck() +{ + if (!_isMeshInit) + { + if (meshInit()) _isMeshInit = true; + } + else + { + // if (WiFi.status() != WL_CONNECTED) return; + mesh.update(); + + if (isAvail_gate) + { + BLINKER_LOG_ALL("new mesh data: ", meshBuf); + + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, meshBuf); + JsonObject root = jsonBuffer.as(); + + if (error) + { + BLINKER_ERR_LOG_ALL("msg not Json!"); + isAvail_gate = false; + free(meshBuf); + return; + } + + if (root.containsKey("hello")) + { + if (gateId != msgFrom) + { + gateId = msgFrom; + isAuth = false; + } + + sendSingle(msgFrom, gateFormat( + "{\"" + STRING_format(BLINKER_CMD_DEVICEINFO) + \ + "\":{" + \ + "\"name\":\"" + macDeviceName() + "\"," + \ + "\"key\":\"" + _vipKey + "\"," + \ + "\"type\":\"" + _deviceType + "\"," + \ + "\"vas\":" + STRING_format(vatFormat()) + "," + \ + "\"auth\":" + STRING_format(isAuth) + \ + "}}")); + } + else if (root.containsKey("auth")) + { + String _deviceName = root["auth"]["deviceName"].as(); + String _uuid = root["auth"]["uuid"].as(); + String _authKey = root["auth"]["authKey"].as(); + + MQTT_DEVICEID_PRO = (char*)malloc((_deviceName.length()+1)*sizeof(char)); + strcpy(MQTT_DEVICEID_PRO, _deviceName.c_str()); + UUID_PRO = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(UUID_PRO, _uuid.c_str()); + AUTHKEY_PRO = (char*)malloc((_authKey.length()+1)*sizeof(char)); + strcpy(AUTHKEY_PRO, _authKey.c_str()); + + + BLINKER_LOG_ALL(BLINKER_F("====================")); + BLINKER_LOG_ALL("MQTT_DEVICEID_PRO: ", MQTT_DEVICEID_PRO); + BLINKER_LOG_ALL("UUID_PRO: ", UUID_PRO); + BLINKER_LOG_ALL("AUTHKEY_PRO: ", AUTHKEY_PRO); + BLINKER_LOG_ALL(BLINKER_F("====================")); + + isAuth = true; + } + + isAvail_gate = false; + free(meshBuf); + } + + if (isNewConnect && !_isHello) + { + sendBroadcast(gateFormat(BLINKER_CMD_NEW)); + _isHello = true; + } + } +} + +void BlinkerSubDevice::sendBroadcast(String msg) +{ + BLINKER_LOG_ALL("broadcast: ", msg); + mesh.sendBroadcast(msg); +} + +bool BlinkerSubDevice::sendSingle(uint32_t toId, String msg) +{ + BLINKER_LOG_ALL("to id: ", toId, ", msg: ", msg); + if (mesh.isConnected(toId)) + { + return mesh.sendSingle(toId, msg); + } + else + { + BLINKER_ERR_LOG("device disconnected"); + return false; + } +} + +String BlinkerSubDevice::gateFormat(const String & msg) +{ + return "{\"" + STRING_format(BLINKER_CMD_GATE) + "\":" + msg + "}"; +} + +#endif + +#endif diff --git a/blinker-library/src/Adapters/BlinkerSubStream.h b/blinker-library/src/Adapters/BlinkerSubStream.h new file mode 100644 index 0000000..37f4b10 --- /dev/null +++ b/blinker-library/src/Adapters/BlinkerSubStream.h @@ -0,0 +1,178 @@ +#ifndef BLINKER_SUBSTREAM_H +#define BLINKER_SUBSTREAM_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +class BlinkerSubStream : public BlinkerStream +{ + public : + BlinkerSubStream() + : isInit(false) + {} + + int available() + { + if (_subAvail && _subRead) + { + if (_subAvail()) + { + String data = _subRead(); + + if (isFresh) free(streamData); + streamData = (char*)malloc((data.length()+1)*sizeof(char)); + strcpy(streamData, data.c_str()); + isFresh = true; + + return true; + } + } + return false; + } + + void begin(const char* auth) + { + _authKey = (char*)malloc((strlen(auth)+1)*sizeof(char)); + strcpy(_authKey, auth); + BLINKER_LOG_ALL(BLINKER_F("_authKey: "), auth); + if (_subBegin) _subBegin(); + } + + char * lastRead() + { + if (isFresh) return streamData; + else return ""; + } + + void flush() + { + if (isFresh) + { + free(streamData); + isFresh = false; + } + } + + int print(char * data, bool needCheck = true) + { + if (needCheck) + { + if (!checkPrintSpan()) + { + respTime = millis(); + return false; + } + } + + respTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("Response: "), data); + + if(connected() && _subPrint) + { + BLINKER_LOG_ALL(BLINKER_F("Success...")); + + _subPrint(data); + return true; + } + else + { + BLINKER_LOG_ALL(BLINKER_F("Faile... Disconnected")); + + return false; + } + } + + int connect() + { + if (_subConnect) return _subConnect(); + else return true; + } + + int connected() + { + if (_subConnected) return _subConnected(); + else return true; + } + + void disconnect() + { + if (_subDisconnect) _subDisconnect(); + } + + int checkPrintSpan() + { + if (millis() - respTime < BLINKER_PRINT_MSG_LIMIT) + { + if (respTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG(BLINKER_F("DEVICE NOT CONNECT OR MSG LIMIT")); + + return false; + } + else + { + respTimes++; + return true; + } + } + else + { + respTimes = 0; + return true; + } + } + + void attachAvailable(blinker_callback_return_int_t func) + { + _subAvail = func; + initStatus |= 0x01 << 0; + if (initStatus == 0x07) isInit = true; + } + + void attachRead(blinker_callback_return_string_t func) + { + _subRead = func; + initStatus |= 0x01 << 1; + if (initStatus == 0x07) isInit = true; + } + + void attachPrint(blinker_callback_with_string_arg_t func) + { + _subPrint = func; + initStatus |= 0x01 << 2; + if (initStatus == 0x07) isInit = true; + } + + void attachBegin(blinker_callback_t func) { _subBegin = func; } + void attachConnect(blinker_callback_return_int_t func) { _subConnect = func; } + void attachConnected(blinker_callback_return_int_t func) { _subConnected = func; } + void attachDisconnect(blinker_callback_t func) { _subDisconnect = func; } + + protected : + char* _authKey; + bool isInit; + int8_t initStatus = 0; + char* streamData; + bool isFresh; + bool isConnect; + uint8_t respTimes = 0; + uint32_t respTime = 0; + blinker_callback_return_int_t _subAvail = NULL; + blinker_callback_return_string_t _subRead = NULL; + blinker_callback_with_string_arg_t _subPrint = NULL; + blinker_callback_t _subBegin = NULL; + blinker_callback_return_int_t _subConnect = NULL; + blinker_callback_return_int_t _subConnected = NULL; + blinker_callback_t _subDisconnect = NULL; +}; + +#endif diff --git a/blinker-library/src/Adapters/test.h b/blinker-library/src/Adapters/test.h new file mode 100644 index 0000000..9b73883 --- /dev/null +++ b/blinker-library/src/Adapters/test.h @@ -0,0 +1,29 @@ +"-----BEGIN CERTIFICATE-----" +"MIIEgDCCA2igAwIBAgIQDKTfhr9lmWbWUT0hjX36oDANBgkqhkiG9w0BAQsFADBy" +"MQswCQYDVQQGEwJDTjElMCMGA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywg" +"SW5jLjEdMBsGA1UECxMURG9tYWluIFZhbGlkYXRlZCBTU0wxHTAbBgNVBAMTFFRy" +"dXN0QXNpYSBUTFMgUlNBIENBMB4XDTE4MDEwNDAwMDAwMFoXDTE5MDEwNDEyMDAw" +"MFowGDEWMBQGA1UEAxMNaW90ZGV2LmNsei5tZTCCASIwDQYJKoZIhvcNAQEBBQAD" +"ggEPADCCAQoCggEBALbOFn7cJ2I/FKMJqIaEr38n4kCuJCCeNf1bWdWvOizmU2A8" +"QeTAr5e6Q3GKeJRdPnc8xXhqkTm4LOhgdZB8KzuVZARtu23D4vj4sVzxgC/zwJlZ" +"MRMxN+cqI37kXE8gGKW46l2H9vcukylJX+cx/tjWDfS2YuyXdFuS/RjhCxLgXzbS" +"cve1W0oBZnBPRSMV0kgxTWj7hEGZNWKIzK95BSCiMN59b+XEu3NWGRb/VzSAiJEy" +"Hy9DcDPBC9TEg+p5itHtdMhy2gq1OwsPgl9HUT0xmDATSNEV2RB3vwviNfu9/Eif" +"ObhsV078zf30TqdiESqISEB68gJ0Otru67ePoTkCAwEAAaOCAWowggFmMB8GA1Ud" +"IwQYMBaAFH/TmfOgRw4xAFZWIo63zJ7dygGKMB0GA1UdDgQWBBR/KLqnke61779P" +"xc9htonQwLOxPDAYBgNVHREEETAPgg1pb3RkZXYuY2x6Lm1lMA4GA1UdDwEB/wQE" +"AwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTAYDVR0gBEUwQzA3" +"BglghkgBhv1sAQIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQu" +"Y29tL0NQUzAIBgZngQwBAgEwgYEGCCsGAQUFBwEBBHUwczAlBggrBgEFBQcwAYYZ" +"aHR0cDovL29jc3AyLmRpZ2ljZXJ0LmNvbTBKBggrBgEFBQcwAoY+aHR0cDovL2Nh" +"Y2VydHMuZGlnaXRhbGNlcnR2YWxpZGF0aW9uLmNvbS9UcnVzdEFzaWFUTFNSU0FD" +"QS5jcnQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtM4eyrWB14ajJpQ" +"ibZ5FbzVuvv2Le0FOSoss7UFCDJUYiz2LiV8yOhL4KTY+oVVkqHaYtcFS1CYZNzj" +"6xWcqYZJ+pgsto3WBEgNEEe0uLSiTW6M10hm0LFW9Det3k8fqwSlljqMha3gkpZ6" +"8WB0f2clXOuC+f1SxAOymnGUsSqbU0eFSgevcOIBKR7Hr3YXBXH3jjED76Q52OMS" +"ucfOM9/HB3jN8o/ioQbkI7xyd/DUQtzK6hSArEoYRl3p5H2P4fr9XqmpoZV3i3gQ" +"oOdVycVtpLunyUoVAB2DcOElfDxxXCvDH3XsgoIU216VY03MCaUZf7kZ2GiNL+UX" +"9UBd0Q==" +"-----END CERTIFICATE-----" + +A123456789B123456789C123456789D123456789E123456789F123456789G123456789H123456789I123456789J123456789K123456789L123456789M123456789N123456789O123456789P123456789Q123456789R123456789S123456789T123456789U123456789V123456789W123456789X123456789Y123456789Z123456789 \ No newline at end of file diff --git a/blinker-library/src/Blinker.h b/blinker-library/src/Blinker.h new file mode 100644 index 0000000..b4852b5 --- /dev/null +++ b/blinker-library/src/Blinker.h @@ -0,0 +1,386 @@ +#ifndef BLINKER_H +#define BLINKER_H + +#if defined(BLINKER_BLE) + + #if defined(BLINKER_ALIGENIE_LIGHT) || defined(BLINKER_ALIGENIE_OUTLET) || \ + defined(BLINKER_ALIGENIE_SWITCH)|| defined(BLINKER_ALIGENIE_SENSOR) + #error This code is intended to run on the BLINKER_MQTT mode! Please check your mode setting. + #endif + + #if defined(BLINKER_DUEROS_LIGHT) || defined(BLINKER_DUEROS_OUTLET) || \ + defined(BLINKER_DUEROS_SWITCH)|| defined(BLINKER_DUEROS_SENSOR) + #error This code is intended to run on the BLINKER_MQTT mode! Please check your mode setting. + #endif + + #if defined(ESP32) + #include "BlinkerESP32BLE.h" + + BlinkerESP32BLE Blinker; + #else + #include "BlinkerSerialBLE.h" + + BlinkerSerialBLE Blinker; + #endif + +#elif defined(BLINKER_WIFI) || defined(BLINKER_MQTT) + + #if defined(BLINKER_APCONFIG_V2) + #define BLINKER_APCONFIG + #define BLINKER_WITHOUT_WS_REG + #endif + + #if defined(BLINKER_WIFI) + #undef BLINKER_WIFI + #define BLINKER_MQTT + #endif + + #define BLINKER_PROTOCOL_HTTP_SERVER + + #include "BlinkerAssistant.h" + + #if (defined(ESP8266) || defined(ESP32)) && !defined(BLINKER_MQTT_AT) + #include "BlinkerESPMQTT.h" + + BlinkerESPMQTT Blinker; + + #else + #define BLINKER_ESP_AT + + #define BLINKER_MQTT_AT + + #undef BLINKER_MQTT + + #include "BlinkerSerialESPMQTT.h" + + BlinkerSerialESPMQTT Blinker; + #endif + +// #elif defined(BLINKER_WIFI_LOWPOWER) + +// #if defined(ESP8266) || defined(ESP32) +// #include "BlinkerESPMQTTLP.h" + +// BlinkerESPMQTTLP Blinker; +// #endif + +#elif defined(BLINKER_PRO) + + #if defined(BLINKER_ALIGENIE_LIGHT) || defined(BLINKER_ALIGENIE_OUTLET) || \ + defined(BLINKER_ALIGENIE_SWITCH)|| defined(BLINKER_ALIGENIE_SENSOR) + #error This code is intended to run on the BLINKER_MQTT mode! Please check your mode setting. + #endif + + #if defined(BLINKER_DUEROS_LIGHT) || defined(BLINKER_DUEROS_OUTLET) || \ + defined(BLINKER_DUEROS_SWITCH)|| defined(BLINKER_DUEROS_SENSOR) + #error This code is intended to run on the BLINKER_MQTT mode! Please check your mode setting. + #endif + + #define BLINKER_ALIGENIE + + #define BLINKER_DUEROS + + #ifndef BLINKER_ESP_SMARTCONFIG + #ifndef BLINKER_APCONFIG + #define BLINKER_ESP_SMARTCONFIG + #endif + #endif + + #define BLINKER_PROTOCOL_HTTP_SERVER + + #if defined(ESP8266) || defined(ESP32) + #include "BlinkerESPPRO.h" + + BlinkerESPPRO Blinker; + #else + #error This code is intended to run on the ESP8266/ESP32 platform! Please check your Tools->Board setting. + #endif + +#elif defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_AUTO) + + #include "BlinkerAssistant.h" + + #if defined(BLINKER_APCONFIG_V2) + #define BLINKER_APCONFIG + #define BLINKER_WITHOUT_WS_REG + #endif + + #define BLINKER_WITHOUT_WS_REG + + #if defined(BLINKER_WIFI_AUTO) + #define BLINKER_PRO_ESP + #endif + + // #ifndef BLINKER_ESP_SMARTCONFIG + // #ifndef BLINKER_APCONFIG + // #define BLINKER_ESP_SMARTCONFIG + // #endif + // #endif + + #if defined(ESP8266) || defined(ESP32) + #include "BlinkerESPPROESP.h" + + BlinkerESPPROESP Blinker; + #else + #error This code is intended to run on the ESP8266/ESP32 platform! Please check your Tools->Board setting. + #endif + +#elif defined(BLINKER_AT_MQTT) + + #define BLINKER_ESP_AT + + #if defined(ESP8266) || defined(ESP32) + #include "BlinkerESPMQTTAT.h" + + BlinkerESPMQTTAT Blinker; + #else + #error This code is intended to run on the ESP8266/ESP32 platform! Please check your Tools->Board setting. + #endif + +#elif defined(BLINKER_WIFI_GATEWAY) + + #include "BlinkerAssistant.h" + + #if defined(ESP8266) || defined(ESP32) + #include "BlinkerESPGateway.h" + + BlinkerESPGateway Blinker; + #else + #error This code is intended to run on the ESP8266/ESP32 platform! Please check your Tools->Board setting. + #endif + +#elif defined(BLINKER_WIFI_SUBDEVICE) + + #include "BlinkerAssistant.h" + + #if defined(ESP8266) || defined(ESP32) + #include "BlinkerESPSubDevice.h" + + BlinkerESPSubDevice Blinker; + #else + #error This code is intended to run on the ESP8266/ESP32 platform! Please check your Tools->Board setting. + #endif + +#elif defined(BLINKER_NBIOT_WH) + + #ifndef BLINKER_NB73_NBIOT + #define BLINKER_NB73_NBIOT + #endif + + #include "BlinkerSerialWHNBIoT.h" + + BlinkerSerialWHNBIoT Blinker; + +#elif defined(BLINKER_NBIOT_SIM7020) + + // #ifndef BLINKER_SIM7020C_NBIOT + // #define BLINKER_SIM7020C_NBIOT + // #endif + + #include "BlinkerSerialSIMNBIoT.h" + + BlinkerSerialSIMNBIoT Blinker; + +#elif defined(BLINKER_NBIOT_SIM7000) + + // #ifndef BLINKER_SIM7020C_NBIOT + // #define BLINKER_SIM7020C_NBIOT + // #endif + + #ifndef BLINKER_WITHOUT_SSL + #define BLINKER_WITHOUT_SSL + #endif + + #include "BlinkerSerialSIM7000NBIoT.h" + + BlinkerSerialSIM7000NBIoT Blinker; + +#elif defined(BLINKER_PRO_SIM7020) + + #include "BlinkerSIMPRO.h" + + BlinkerSIMPRO Blinker; + +#elif defined(BLINKER_GPRS_AIR202) + + // #ifndef BLINKER_AIR202_GPRS + // #define BLINKER_AIR202_GPRS + // #endif + + #include "BlinkerSerialLUATGPRS.h" + + BlinkerSerialLUATGPRS Blinker; + +#elif defined(BLINKER_PRO_AIR202) + + #include "BlinkerLUATPRO.h" + + BlinkerLUATPRO Blinker; + +// #elif defined(BLINKER_WIFI_AUTO) + +// #define BLINKER_MQTT_AUTO + +// #if !defined(BLINKER_ESP_SMARTCONFIG) && !defined(BLINKER_APCONFIG) +// #define BLINKER_ESP_SMARTCONFIG +// #endif + +// #include "BlinkerESPMQTTAUTO.h" + +// BlinkerESPMQTTAUTO Blinker; + +#elif defined(BLINKER_LOWPOWER_AIR202) + + #include "BlinkerLowPowerGPRS.h" + + BlinkerLowPowerGPRS Blinker; + +#elif defined(BLINKER_QRCODE_NBIOT_SIM7020) + + #include "BlinkerQRCodeSIMNBIOT.h" + + BlinkerQRCodeSerialSIMNBIoT Blinker; + +#elif defined(BLINKER_QRCODE_NBIOT_SIM7000) + + #ifndef BLINKER_WITHOUT_SSL + #define BLINKER_WITHOUT_SSL + #endif + + #include "BlinkerQRCodeSIM7000NBIOT.h" + + BlinkerQRCodeSerialSIM7000NBIoT Blinker; + +#elif defined(BLINKER_HTTP) + + #include "BlinkerESPHTTP.h" + + BlinkerESPHTTP Blinker; + +#else + + #error Please set a mode BLINKER_BLE/BLINKER_WIFI/BLINKER_MQTT ! Please check your mode setting. + +#endif + +#include "BlinkerWidgets.h" + +// #if defined(BLINKER_MQTT) +#if defined(BLINKER_ESP_TASK) +#if defined(ESP8266) + #error ESP8266 TASK NOT SUPPORT! + // #include "Schedule.h" + // extern "C" { + // #include "ets_sys.h" + // #include "user_interface.h" + // #include "cont.h" + // } + + // #define blinker_procTaskPrio 1 + // #define blinker_procTaskQueueLen 1 + // os_event_t blinker_procTaskQueue[blinker_procTaskQueueLen]; + // cont_t* blinker_g_pcont __attribute__((section(".noinit"))); + + // // uint32_t oldtime = 0; + // // static uint32_t s_micros_at_task_start; + + // // static uint32_t oldtime = 0; + + // void preloop_update_frequency() __attribute__((weak)); + // void preloop_update_frequency() { + // #if defined(F_CPU) && (F_CPU == 160000000L) + // REG_SET_BIT(0x3ff00014, BIT(0)); + // ets_update_cpu_frequency(160); + // #endif + // } + + // static bool isInit = false; + + // static void blinker_loop_wrapper() { + // preloop_update_frequency(); + // if (!isInit) + // { + // Blinker.beginMQTT(); + // isInit = true; + // } + // else + // { + // Blinker.run(); + // } + // // Blinker.run(); + // run_scheduled_functions(); + // // esp_schedule(); + // } + + // static void blinker_run(os_event_t *events) + // { + // cont_run(blinker_g_pcont, &blinker_loop_wrapper); + // system_os_post(blinker_procTaskPrio, 0, (os_param_t)blinker_g_pcont); + // } + + // void BLINKER_TAST_INIT() + // { + // // ets_task + // // #if defined(BLINKER_MQTT) + // // Blinker.beginMQTT(); + // // #endif + // system_os_task(blinker_run, blinker_procTaskPrio, blinker_procTaskQueue, blinker_procTaskQueueLen); + // system_os_post(blinker_procTaskPrio, 0, (os_param_t)blinker_g_pcont); + // } +// #endif + +// #endif + +// #if defined(ESP32) +#elif defined(ESP32) + #include + #include + #include + + // #if CONFIG_AUTOSTART_ARDUINO + + #if CONFIG_FREERTOS_UNICORE + #define ARDUINO_RUNNING_CORE 0 + #else + #define ARDUINO_RUNNING_CORE 1 + #endif + + void blinkerLoopTask(void *pvParameters) + { + for(;;) { + Blinker.run(); + vTaskDelay(1); + } + } + + extern "C" void BLINKER_TAST_INIT() + { + // initArduino(); + // #if defined(BLINKER_MQTT) + // Blinker.beginMQTT(); + // #endif + xTaskCreatePinnedToCore(blinkerLoopTask, + "blinkerLoopTask", + 8192, + NULL, + 3, + NULL, + ARDUINO_RUNNING_CORE); + } + + // #endif +#else + #error This code is intended to run on the ESP8266/ESP32 platform! Please check your Tools->Board setting. +#endif + +#endif + +#ifndef LED_BUILTIN + #if defined(ESP8266) || defined(ESP32) + #define LED_BUILTIN 2 + #else + #define LED_BUILTIN 13 + #endif +#endif + +#endif diff --git a/blinker-library/src/Blinker/.pydio b/blinker-library/src/Blinker/.pydio new file mode 100644 index 0000000..325830f --- /dev/null +++ b/blinker-library/src/Blinker/.pydio @@ -0,0 +1 @@ +6583c32d-f86b-494c-8899-859c9d7a2922 \ No newline at end of file diff --git a/blinker-library/src/Blinker/BlinkerATMaster.h b/blinker-library/src/Blinker/BlinkerATMaster.h new file mode 100644 index 0000000..829b86b --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerATMaster.h @@ -0,0 +1,184 @@ +#ifndef BLINKER_AT_MASTER_H +#define BLINKER_AT_MASTER_H + +#include "BlinkerDebug.h" +#include "BlinkerConfig.h" +#include "BlinkerUtility.h" + +enum blinker_at_m_state_t { + AT_M_NONE, + AT_M_RESP, + AT_M_OK, + AT_M_ERR +}; + +#define BLINKER_MAX_AT_MASTER_PARAM_NUM 6 + +#define BLINKER_MAX_AT_MASTER_DATA_SIZE 48 + +class BlinkerMasterAT +{ + public : + BlinkerMasterAT() {} + // : _isReq(false) + // {} + + void update(const String & data) { + // _data = data; + // BLINKER_LOG(BLINKER_F("update data: "), data); + serialize(data); + // return _isReq; + } + + blinker_at_m_state_t getState() { return _isReq; } + + String reqName() { return _reqName; } + + uint8_t paramNum() { return _paramNum; } + + String getParam(uint8_t num) { + if (num >= _paramNum) return ""; + else return _param[num]; + } + + private : + blinker_at_m_state_t _isReq; + uint8_t _paramNum; + // String _data; + char _reqName[32]; + char _param[BLINKER_MAX_AT_MASTER_PARAM_NUM][BLINKER_MAX_AT_MASTER_DATA_SIZE]; + + void serialize(const String & _data) { + BLINKER_LOG_ALL(BLINKER_F("serialize _data: "), _data); + + // _reqName = ""; + memset(_reqName, '\0', 32); + _isReq = AT_M_NONE; + int addr_start = _data.indexOf("+"); + int addr_end = 0; + + // BLINKER_LOG(BLINKER_F("serialize addr_start: "), addr_start); + // BLINKER_LOG(BLINKER_F("serialize addr_end: "), addr_end); + + if ((addr_start != -1) && STRING_contains_string(_data, ":")) { + addr_start = 0; + addr_end = _data.indexOf(":"); + + if (addr_end == -1) { + _isReq = AT_M_NONE; + return; + } + else { + strcpy(_reqName, _data.substring(addr_start + 1, addr_end).c_str()); + + BLINKER_LOG_ALL(BLINKER_F("serialize _reqName: "), _reqName); + } + + // _isReq = true; + + // BLINKER_LOG(BLINKER_F("serialize _data: "), _data); + + String serData; + uint16_t dataLen = _data.length(); + + addr_start = 0; + + for (_paramNum = 0; _paramNum < BLINKER_MAX_AT_MASTER_PARAM_NUM; _paramNum++) { + addr_start += addr_end; + addr_start += 1; + serData = _data.substring(addr_start, dataLen); + + addr_end = serData.indexOf(","); + + // BLINKER_LOG(BLINKER_F("serialize serData: "), serData); + // BLINKER_LOG(BLINKER_F("serialize addr_start: "), addr_start); + // BLINKER_LOG(BLINKER_F("serialize addr_end: "), addr_end); + + if (addr_end == -1) { + if (addr_start >= dataLen) { + _isReq = AT_M_NONE; + return; + } + + addr_end = serData.indexOf(" "); + + if (addr_end != -1) { + // _param[_paramNum] = serData.substring(0, addr_end); + if (addr_end != 0) + { + if (serData.substring(0, addr_end).length() < BLINKER_MAX_AT_MASTER_DATA_SIZE) + { + strcpy(_param[_paramNum], serData.substring(0, addr_end).c_str()); + } + _isReq = AT_M_RESP; + BLINKER_LOG_ALL(BLINKER_F("_param0["), _paramNum, \ + BLINKER_F("]: "), _param[_paramNum], + BLINKER_F(", addr_end: "), addr_end); + _paramNum++; + return; + } + else if (addr_end == 0 && serData.length() > 0) + { + serData = serData.substring(1, serData.length()); + + if (serData.substring(0, serData.length()).length() < BLINKER_MAX_AT_MASTER_DATA_SIZE) + { + strcpy(_param[_paramNum], serData.substring(0, serData.length()).c_str()); + } + _isReq = AT_M_RESP; + BLINKER_LOG_ALL(BLINKER_F("_param0["), _paramNum, \ + BLINKER_F("]: "), _param[_paramNum], + BLINKER_F(", addr_end: "), addr_end); + _paramNum++; + return; + } + } + + // _param[_paramNum] = serData; + if (serData.length() < BLINKER_MAX_AT_MASTER_DATA_SIZE) + { + strcpy(_param[_paramNum], serData.c_str()); + } + + // BLINKER_LOG_ALL(BLINKER_F("serialize serData: "), serData); + + BLINKER_LOG_ALL(BLINKER_F("_param1["), _paramNum, \ + BLINKER_F("]: "), _param[_paramNum], \ + " ", serData); + + // BLINKER_LOG_ALL(BLINKER_F("serialize serData: "), serData); + + _paramNum++; + _isReq = AT_M_RESP; + + return; + } + else { + // _param[_paramNum] = serData.substring(0, addr_end); + if (serData.substring(0, addr_end).length() < BLINKER_MAX_AT_MASTER_DATA_SIZE) + { + strcpy(_param[_paramNum], serData.substring(0, addr_end).c_str()); + } + } + BLINKER_LOG_ALL(BLINKER_F("_param["), _paramNum, \ + BLINKER_F("]: "), _param[_paramNum]); + } + _isReq = AT_M_RESP; + return; + } + else if (_data == BLINKER_CMD_OK) { + _isReq = AT_M_OK; + return; + } + else if (_data == BLINKER_CMD_ERROR) { + _isReq = AT_M_ERR; + return; + } + else { + _isReq = AT_M_NONE; + return; + } + } +}; + +#endif diff --git a/blinker-library/src/Blinker/BlinkerApi.h b/blinker-library/src/Blinker/BlinkerApi.h new file mode 100644 index 0000000..c92d7fe --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerApi.h @@ -0,0 +1,15494 @@ +#ifndef BLINKER_API_H +#define BLINKER_API_H + +#include + +#if defined(ESP8266) || defined(ESP32) + #include + #include + + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKE_HTTP) + #include "BlinkerAuto.h" + #endif + + #if defined(BLINKER_PRO) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) + #include "../Functions/BlinkerWlan.h" + #endif +#else + #include "../Functions/BlinkerTicker.h" +#endif + +#if defined(ESP8266) && !defined(BLINKER_BLE) + #include + + #if defined(BLINKER_WIFI) + #include + + static BearSSL::WiFiClientSecure client_s; + #endif + #if defined(BLINKER_WIFI_MULTI) + extern ESP8266WiFiMulti wifiMulti; + #endif +#elif defined(ESP32) && !defined(BLINKER_BLE) + #include + #if defined(BLINKER_WIFI_MULTI) + extern WiFiMulti wifiMulti; + #endif +#endif + +#if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKE_HTTP) + #include "BlinkerTimer.h" + #include "../Functions/BlinkerTimingTimer.h" + #include "../Functions/BlinkerOTA.h" +#elif defined(BLINKER_WIFI_SUBDEVICE) + #include "BlinkerTimer.h" + #include "../Functions/BlinkerTimingTimer.h" +#endif + +#if defined(BLINKER_AT_MQTT) + #include "BlinkerMQTTATBase.h" +#endif + +#if defined(BLINKER_MQTT_AT) + #include "BlinkerATMaster.h" + #ifndef ARDUINOJSON_VERSION_MAJOR + #include "../modules/ArduinoJson/ArduinoJson.h" + #endif +#endif + +#if defined (BLINKER_NB73_NBIOT) + #include "BlinkerATMaster.h" + #ifndef ARDUINOJSON_VERSION_MAJOR + #include "../modules/ArduinoJson/ArduinoJson.h" + #endif +#endif + +#if defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + #include "../Functions/BlinkerAIR202.h" + #include "../Functions/BlinkerHTTPAIR202.h" + // #include "../modules/base64/Base64.h" +#endif + +#if defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + // #include "Blinker/BlinkerAuto.h" + #include "Functions/BlinkerSIM7020.h" + #include "Functions/BlinkerHTTPSIM7020.h" +#endif + +#if defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_PRO_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) + // #include "Blinker/BlinkerAuto.h" + #include "Functions/BlinkerSIM7000.h" + #include "Functions/BlinkerHTTPSIM7000.h" +#endif + +#include "BlinkerApiBase.h" +#include "BlinkerProtocol.h" + +typedef BlinkerProtocol BProto; + +enum b_joystickaxis_t { + BLINKER_J_Xaxis, + BLINKER_J_Yaxis +}; + +enum b_ahrsattitude_t { + Yaw, + Pitch, + Roll +}; + +enum b_gps_t { + LONG, + LAT +}; + +enum b_rgb_t { + BLINKER_R, + BLINKER_G, + BLINKER_B, + BLINKER_BRIGHT +}; + +enum b_nbiot_status_t { + NB_INIT, + NB_WAIT_OK, + // NB_INITED, + NB_CGATT_REQ, + NB_CGATT_SUCCESS, + NB_CGATT_FAILED, + NB_MIPLC_REQ, + NB_MIPLC_SUCCESS, + NB_MIPLC_FAILED, + NB_MIPLD_SUCCESS, + NB_MIPLD_FAILED, + NB_MIPLADDOBJ, + NB_MIPLOPEN, + NB_MIPLOPEN_SUCCESS, + NB_MIPLOPEN_FAILED, + NB_MIPLDISCOVER, + NB_MIPLOBSERVE, + NB_FAILED, + NB_RESET +}; + +#if defined(BLINKER_PRO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_GATEWAY) + enum BlinkerStatus_t + { + PRO_WLAN_CONNECTING, + PRO_WLAN_CONNECTED, + // PRO_WLAN_DISCONNECTED, + PRO_WLAN_SMARTCONFIG_BEGIN, + PRO_WLAN_SMARTCONFIG_DONE, + PRO_WLAN_APCONFIG_BEGIN, + PRO_WLAN_APCONFIG_DONE, + PRO_DEV_AUTHCHECK_FAIL, + PRO_DEV_AUTHCHECK_SUCCESS, + PRO_DEV_REGISTER_FAIL, + PRO_DEV_REGISTER_SUCCESS, + PRO_DEV_INIT_SUCCESS, + PRO_DEV_CONNECTING, + PRO_DEV_CONNECTED, + PRO_DEV_DISCONNECTED + }; +#endif + +#if defined(BLINKER_MQTT_AUTO) + enum BlinkerStatus_t + { + AUTO_WLAN_CONNECTING, + AUTO_WLAN_CONNECTED, + // PRO_WLAN_DISCONNECTED, + AUTO_WLAN_SMARTCONFIG_BEGIN, + AUTO_WLAN_SMARTCONFIG_DONE, + AUTO_DEV_AUTHCHECK_FAIL, + AUTO_DEV_AUTHCHECK_SUCCESS, + AUTO_DEV_REGISTER_FAIL, + AUTO_DEV_REGISTER_SUCCESS, + AUTO_DEV_INIT_SUCCESS, + AUTO_DEV_CONNECTING, + AUTO_DEV_CONNECTED, + AUTO_DEV_DISCONNECTED + }; +#endif + +#if defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + enum BlinkerStatus_t + { + GPRS_DEV_POWER_CHECK, + GPRS_DEV_POWER_ON, + GPRS_DEV_AUTHCHECK_FAIL, + GPRS_DEV_AUTHCHECK_SUCCESS, + GPRS_DEV_REGISTER_FAIL, + GPRS_DEV_REGISTER_SUCCESS, + GPRS_DEV_INIT_SUCCESS, + GPRS_DEV_CONNECTING, + GPRS_DEV_CONNECTED, + GPRS_DEV_DISCONNECTED + }; +#endif + +#if defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) + enum BlinkerStatus_t + { + NBIOT_DEV_POWER_CHECK, + NBIOT_DEV_POWER_ON, + NBIOT_DEV_AUTHCHECK_FAIL, + NBIOT_DEV_AUTHCHECK_SUCCESS, + NBIOT_DEV_REGISTER_FAIL, + NBIOT_DEV_REGISTER_SUCCESS, + NBIOT_DEV_INIT_SUCCESS, + NBIOT_DEV_CONNECTING, + NBIOT_DEV_CONNECTED, + NBIOT_DEV_DISCONNECTED + }; +#endif + +class BlinkerApi : public BlinkerProtocol +{ + public : + void run(); + + template + void print(T n); + void print(); + + template + void println(T n) { print(n); } + void println() { print(); } + + template + void print(T1 n1, T2 n2, T3 n3); + + template + void println(T1 n1, T2 n2, T3 n3) { print(n1, n2, n3); } + + template + void printArray(T1 n1, const String &s2); + + // template + void printNumArray(char * _name, const String & data); + + template + void printObject(T1 n1, const String &s2); + + template + void print(T1 n1, const String &s2); + template + void print(T1 n1, const char str2[]); + template + void print(T1 n1, char c); + template + void print(T1 n1, unsigned char b); + template + void print(T1 n1, int n); + template + void print(T1 n1, unsigned int n); + template + void print(T1 n1, long n); + template + void print(T1 n1, unsigned long n); + template + void print(T1 n1, double n); + + template + void println(T1 n1, const String &s2) { print(n1, s2); } + template + void println(T1 n1, const char str2[]) { print(n1, str2); } + template + void println(T1 n1, char c) { print(n1, c); } + template + void println(T1 n1, unsigned char b) { print(n1, b); } + template + void println(T1 n1, int n) { print(n1, n); } + template + void println(T1 n1, unsigned int n) { print(n1, n); } + template + void println(T1 n1, long n) { print(n1, n); } + template + void println(T1 n1, unsigned long n) { print(n1, n); } + template + void println(T1 n1, double n) { print(n1, n); } + + template + void notify(T n); + void vibrate(uint16_t ms = 200); + void delay(unsigned long ms); + void attachAhrs(); + void detachAhrs(); + int16_t ahrs(b_ahrsattitude_t attitude) { return ahrsValue[attitude]; } + float gps(b_gps_t axis); + + #if defined(BLINKER_GPRS_AIR202) + String lang() + { + if (millis() - gps_air202_time > 60000*5 || gps_air202_time == 0) + { + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + + if (BLINKER_AIR202.getAMGSMLOC()) + { + gps_air202_time = millis(); + + strcpy(_LANG, BLINKER_AIR202.lang().c_str()); + strcpy(_LAT, BLINKER_AIR202.lat().c_str()); + } + } + + return _LANG; + } + String lat() + { + if (millis() - gps_air202_time > 60000*5 || gps_air202_time == 0) + { + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + + if (BLINKER_AIR202.getAMGSMLOC()) + { + gps_air202_time = millis(); + + strcpy(_LANG, BLINKER_AIR202.lang().c_str()); + strcpy(_LAT, BLINKER_AIR202.lat().c_str()); + } + } + + return _LAT; + } + #endif + + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_LOWPOWER_AIR202) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + + void setTimezone(float tz); + + float getTimezone() { + #if defined(BLINKER_WIFI_SUBDEVICE) + _timezone = mesh_timezone; + #endif + return _timezone; + } + int8_t second(); + int8_t minute(); + int8_t hour(); + int8_t mday(); + int8_t wday(); + int8_t month(); + int16_t year(); + int16_t yday(); + time_t time(); + int32_t dtime(); + time_t startTime(); + time_t runTime(); + + // template + // bool sms(const T& msg); + template + bool sms(const T& msg, const String & cel = ""); + template + bool push(const T& msg, const String & users = ""); + template + bool wechat(const T& msg); + template + bool wechat(const String & title, const String & state, const T& msg, const String & users = ""); + #if !defined(BLINKER_AT_MQTT) + void weather(uint32_t _city = 0); + void weatherForecast(uint32_t _city = 0); + void air(uint32_t _city = 0); + #else + String weather(uint32_t _city = 0); + String weatherForecast(uint32_t _city = 0); + String air(uint32_t _city = 0); + #endif + + void log(const String & msg); + void coordinate(float _long, float _lat); + + // void deviceHeartbeat(uint32_t heart_time = 600); + + #if defined(BLINKER_PRO_ESP) + bool eventWarn(const String & msg); + bool eventError(const String & msg); + bool eventMsg(const String & msg); + #endif + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + void loadTimer(); + void deleteTimer(); + void deleteCountdown(); + void deleteLoop(); + void deleteTiming(); + bool countdownState() { return _cdState; } + bool loopState() { return _lpState; } + bool timingState() { return taskCount ? true : false; } + #endif + + template + bool configUpdate(const T& msg); + void configGet(); + bool configDelete(); + template + void dataStorage(char _name[], const T& msg); + void RTDataStorage(char _name[], int msg); + void RTDataPrint(); + void timeSlotData(char _name[], int32_t msg); + void timeSlotData(char _name[], uint32_t msg); + void timeSlotData(char _name[], float msg); + void textData(const String & msg); + void jsonData(const String & msg); + void jsonDataGet(); + bool dataUpdate(); + void dataGet(); + void dataGet(const String & _type); + void dataGet(const String & _type, const String & _date); + bool dataDelete(); + bool dataDelete(const String & _type); + bool event(const String & _key, String _value = ""); + bool gps(float _long, float _lat); + + // bool bridge(char _name[]); + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + bool autoPull(); + void autoInit() { autoStart(); } + // void autoInput(const String & key, const String & state); + void autoInput(const String & key, float data); + void autoRun(); + + #if !defined(BLINKER_WIFI_SUBDEVICE) + void freshAttachBridge(char _key[], blinker_callback_with_string_arg_t _func); + uint8_t attachBridge(char _key[], blinker_callback_with_string_arg_t _func); + char * bridgeKey(uint8_t num); + char * bridgeName(uint8_t num); + void bridgeInit(); + + void bridgePrint(char * bName, const String & data); + #endif + #endif + + #if !defined(BLINKER_LOWPOWER_AIR202) + String freshSharers(); // NBIOT TODO + #endif + + #if !defined(BLINKER_WIFI_SUBDEVICE) + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + bool otaInit = false; + void loadOTA(); + void ota(); + String checkOTA(); + bool updateOTAStatus(int8_t status, const String & msg); + void otaStatus(int8_t status, const String & msg); + #endif + + #if defined(BLINKER_LOWPOWER) || defined(BLINKER_LOWPOWER_AIR202) + int32_t comFreqGet(); + bool comFreqUpdate(); + String comDataGet(); + bool comDateUpdate(); + #endif + + #endif + + #if !defined(BLINKER_LOWPOWER_AIR202) + void aligeniePrint(String & _msg); + void duerPrint(String & _msg, bool report = false); + void miotPrint(String & _msg); + #endif + + #endif + + #if defined(BLINKER_WIFI_SUBDEVICE) + uint32_t ntpFreshTime = 0; + time_t ntpGetTime = 0; + // void aligeniePrint(String & _msg); + // void duerPrint(String & _msg); + // void miotPrint(String & _msg); + #endif + + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_PRO_ESP) + + void attachRTData(char _name[], blinker_callback_t newFunction) + { + strcpy(_RTDataKey, _name); + _RTDataFunc = newFunction; + } + + #endif + + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_MQTT_AT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_SUBDEVICE) + + #if defined(BLINKER_ALIGENIE) + void attachAliGenieSetPowerState(blinker_callback_with_string_uint8_arg_t newFunction) + { _AliGeniePowerStateFunc_m = newFunction; } + void attachAliGenieSetPowerState(blinker_callback_with_string_arg_t newFunction) + { _AliGeniePowerStateFunc = newFunction; } + void attachAliGenieSetHSwingState(blinker_callback_with_string_arg_t newFunction) + { _AliGenieHSwingStateFunc = newFunction; } + void attachAliGenieSetVSwingState(blinker_callback_with_string_arg_t newFunction) + { _AliGenieVSwingStateFunc = newFunction; } + void attachAliGenieSetColor(blinker_callback_with_string_arg_t newFunction) + { _AliGenieSetColorFunc = newFunction; } + void attachAliGenieSetMode(blinker_callback_with_string_arg_t newFunction) + { _AliGenieSetModeFunc = newFunction; } + void attachAliGenieSetcMode(blinker_callback_with_string_arg_t newFunction) + { _AliGenieSetcModeFunc = newFunction; } + void attachAliGenieSetLevel(blinker_callback_with_string_arg_t newFunction) + { _AliGenieSetLevelFunc_str = newFunction; } + void attachAliGenieSetLevel(blinker_callback_with_uint8_arg_t newFunction) + { _AliGenieSetLevelFunc = newFunction; } + void attachAliGenieRelativeLevel(blinker_callback_with_int32_arg_t newFunction) + { _AliGenieSetRelativeLevelFunc = newFunction; } + void attachAliGenieSetTemp(blinker_callback_with_uint8_arg_t newFunction) + { _AliGenieSetTempFunc = newFunction; } + void attachAliGenieRelativeTemp(blinker_callback_with_int32_arg_t newFunction) + { _AliGenieSetRelativeTempFunc = newFunction; } + void attachAliGenieSetBrightness(blinker_callback_with_string_arg_t newFunction) + { _AliGenieSetBrightnessFunc = newFunction; } + void attachAliGenieRelativeBrightness(blinker_callback_with_int32_arg_t newFunction) + { _AliGenieSetRelativeBrightnessFunc = newFunction; } + void attachAliGenieSetColorTemperature(blinker_callback_with_int32_arg_t newFunction) + { _AliGenieSetColorTemperature = newFunction; } + void attachAliGenieRelativeColorTemperature(blinker_callback_with_int32_arg_t newFunction) + { _AliGenieSetRelativeColorTemperature = newFunction; } + void attachAliGenieQuery(blinker_callback_with_int32_uint8_arg_t newFunction) + { _AliGenieQueryFunc_m = newFunction; } + void attachAliGenieQuery(blinker_callback_with_int32_arg_t newFunction) + { _AliGenieQueryFunc = newFunction; } + #endif + + #if defined(BLINKER_DUEROS) + void attachDuerOSSetPowerState(blinker_callback_with_string_uint8_arg_t newFunction) + { _DuerOSPowerStateFunc_m = newFunction; } + void attachDuerOSSetPowerState(blinker_callback_with_string_arg_t newFunction) + { _DuerOSPowerStateFunc = newFunction; } + void attachDuerOSSetColor(blinker_callback_with_int32_arg_t newFunction) + { _DuerOSSetColorFunc = newFunction; } + void attachDuerOSSetMode(blinker_callback_with_string_arg_t newFunction) + { _DuerOSSetModeFunc = newFunction; } + void attachDuerOSSetcMode(blinker_callback_with_string_arg_t newFunction) + { _DuerOSSetcModeFunc = newFunction; } + void attachDuerOSSetLevel(blinker_callback_with_uint8_arg_t newFunction) + { _DuerOSSetLevelFunc = newFunction; } + void attachDuerOSRelativeLevel(blinker_callback_with_int32_arg_t newFunction) + { _DuerOSSetRelativeLevelFunc = newFunction; } + void attachDuerOSSetTemp(blinker_callback_with_uint8_arg_t newFunction) + { _DuerOSSetTempFunc = newFunction; } + void attachDuerOSRelativeTemp(blinker_callback_with_int32_arg_t newFunction) + { _DuerOSSetRelativeTempFunc = newFunction; } + void attachDuerOSSetBrightness(blinker_callback_with_string_arg_t newFunction) + { _DuerOSSetBrightnessFunc = newFunction; } + void attachDuerOSRelativeBrightness(blinker_callback_with_int32_arg_t newFunction) + { _DuerOSSetRelativeBrightnessFunc = newFunction; } + void attachDuerOSSetColorTemperature(blinker_callback_with_int32_arg_t newFunction) + { _DuerOSSetColorTemperature = newFunction; } + void attachDuerOSRelativeColorTemperature(blinker_callback_with_int32_arg_t newFunction) + { _DuerOSSetRelativeColorTemperature = newFunction; } + void attachDuerOSQuery(blinker_callback_with_int32_uint8_arg_t newFunction) + { _DuerOSQueryFunc_m = newFunction; } + void attachDuerOSQuery(blinker_callback_with_int32_arg_t newFunction) + { _DuerOSQueryFunc = newFunction; } + #endif + + #if defined(BLINKER_MIOT) + void attachMIOTSetPowerState(blinker_callback_with_string_uint8_arg_t newFunction) + { _MIOTPowerStateFunc_m = newFunction; } + void attachMIOTSetPowerState(blinker_callback_with_string_arg_t newFunction) + { _MIOTPowerStateFunc = newFunction; } + void attachMIOTSetHSwingState(blinker_callback_with_string_arg_t newFunction) + { _MIOTHSwingStateFunc = newFunction; } + void attachMIOTSetVSwingState(blinker_callback_with_string_arg_t newFunction) + { _MIOTVSwingStateFunc = newFunction; } + void attachMIOTSetECO(blinker_callback_with_string_arg_t newFunction) + { _MIOTECOFunc = newFunction; } + void attachMIOTSetAnion(blinker_callback_with_string_arg_t newFunction) + { _MIOTAnionFunc = newFunction; } + void attachMIOTSetHeater(blinker_callback_with_string_arg_t newFunction) + { _MIOTHeaterFunc = newFunction; } + void attachMIOTSetDryer(blinker_callback_with_string_arg_t newFunction) + { _MIOTDryerFunc = newFunction; } + void attachMIOTSetSleep(blinker_callback_with_string_arg_t newFunction) + { _MIOTSleepFunc = newFunction; } + void attachMIOTSetSoft(blinker_callback_with_string_arg_t newFunction) + { _MIOTSoftFunc = newFunction; } + void attachMIOTSetUV(blinker_callback_with_string_arg_t newFunction) + { _MIOTUVFunc = newFunction; } + void attachMIOTSetUNSB(blinker_callback_with_string_arg_t newFunction) + { _MIOTUNSBFunc = newFunction; } + + void attachMIOTSetMode(blinker_callback_with_string_string_arg_t newFunction) + { _MIOTSetModeFunc_m = newFunction; } + + void attachMIOTSetColor(blinker_callback_with_int32_arg_t newFunction) + { _MIOTSetColorFunc = newFunction; } + void attachMIOTSetMode(blinker_callback_with_uint8_arg_t newFunction) + { _MIOTSetModeFunc = newFunction; } + void attachMIOTSetLevel(blinker_callback_with_uint8_arg_t newFunction) + { _MIOTSetLevelFunc = newFunction; } + void attachMIOTSetTemp(blinker_callback_with_uint8_arg_t newFunction) + { _MIOTSetTempFunc = newFunction; } + void attachMIOTSetHumi(blinker_callback_with_uint8_arg_t newFunction) + { _MIOTSetHumiFunc = newFunction; } + // void attachMIOTSetcMode(blinker_callback_with_string_arg_t newFunction) + // { _MIOTSetcModeFunc = newFunction; } + void attachMIOTSetBrightness(blinker_callback_with_string_arg_t newFunction) + { _MIOTSetBrightnessFunc = newFunction; } + // void attachMIOTRelativeBrightness(blinker_callback_with_int32_arg_t newFunction) + // { _MIOTSetRelativeBrightnessFunc = newFunction; } + void attachMIOTSetColorTemperature(blinker_callback_with_int32_arg_t newFunction) + { _MIOTSetColorTemperature = newFunction; } + // void attachMIOTRelativeColorTemperature(blinker_callback_with_int32_arg_t newFunction) + // { _MIOTSetRelativeColorTemperature = newFunction; } + void attachMIOTQuery(blinker_callback_with_int32_uint8_arg_t newFunction) + { _MIOTQueryFunc_m = newFunction; } + void attachMIOTQuery(blinker_callback_with_int32_arg_t newFunction) + { _MIOTQueryFunc = newFunction; } + #endif + #endif + + // #if defined(BLINKER_WIFI_GATEWAY) + // void attachGatewayAvailable(blinker_callback_return_int_t newFunction) + // { _gatewayAvail = newFunction; } + // void attachGatewayRead(blinker_callback_return_string_t newFunction) + // { _gatewayRead = newFunction; } + // void attachGatewayPrint(blinker_callback_with_string_arg_t newFunction) + // { _gatewayPrint = newFunction; } + // #endif + + // #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || defined(BLINKER_MQTT_AT) + // void bridgePrint(char * bName, const String & data); + // void aligeniePrint(String & _msg); + // void duerPrint(String & _msg); + // #endif + + #if defined(BLINKER_MQTT_AT) || defined(BLINKER_NB73_NBIOT) + // class BlinkerMasterAT * _masterAT; + // void atRespOK(const String & _data, uint32_t timeout = BLINKER_STREAM_TIMEOUT*10); + void atResp(); + void parseATdata(); + #endif + + #if defined(BLINKER_NB73_NBIOT) + // void initCheck(uint32_t timeout = BLINKER_STREAM_TIMEOUT*10); + #endif + + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) + void reset() + { + BLINKER_LOG(BLINKER_F("Blinker reset...")); + char config_check[3] = {0}; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_WLAN_CHECK, config_check); + EEPROM.commit(); + EEPROM.end(); + + ESP.restart(); + } + #endif + + #if defined(BLINKER_MQTT_AT) + void initCheck(const String & _data, uint32_t timeout = BLINKER_STREAM_TIMEOUT*10); + int analogRead(); + void pinMode(uint8_t pin, uint8_t mode); + void digitalWrite(uint8_t pin, uint8_t val); + int digitalRead(uint8_t pin); + void setTimezone(float tz); + float getTimezone(); + int32_t atGetInt(const String & cmd); + template + String atGetString(const String & cmd, const T& msg); + time_t time() { return atGetInt(BLINKER_CMD_TIME_AT); } + // time_t dtime() { return atGetInt(BLINKER_CMD_D); } + int8_t second() { return atGetInt(BLINKER_CMD_SECOND); } + int8_t minute() { return atGetInt(BLINKER_CMD_MINUTE); } + int8_t hour() { return atGetInt(BLINKER_CMD_HOUR); } + int8_t mday() { return atGetInt(BLINKER_CMD_MDAY); } + int8_t wday() { return atGetInt(BLINKER_CMD_WDAY); } + int8_t month() { return atGetInt(BLINKER_CMD_MONTH); } + int16_t year() { return atGetInt(BLINKER_CMD_YEAR); } + int16_t yday() { return atGetInt(BLINKER_CMD_YDAY); } + void weather(uint32_t _city = 0); + void weatherForecast(uint32_t _city = 0); + void air(uint32_t _city = 0); + void log(const String & msg); + void coordinate(float _long, float _lat); + template + bool sms(const T& msg); + void reset(); + + void aligeniePrint(String & _msg); + void duerPrint(String & _msg, bool report = false); + #if !defined(BLINKER_GPRS_AIR202) && !defined(BLINKER_NBIOT_SIM7020) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7020) && !defined(BLINKER_NBIOT_SIM7000) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7000) + void miotPrint(String & _msg); + #endif + #endif + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_WIFI_SUBDEVICE) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) || defined(BLINKE_HTTP) + + // #if !defined(BLINKER_AT_MQTT) + void attachDataStorage(blinker_callback_t newFunction, uint32_t _time = 60, uint8_t d_times = BLINKER_DATA_UPDATE_COUNT) + { + _dataStorageFunc = newFunction; + if (_time < 5) _time = 5; + _autoStorageTime = _time; + _autoDataTime = millis(); + if (d_times > BLINKER_MAX_DATA_COUNT || d_times == 0) d_times = BLINKER_DATA_UPDATE_COUNT; + _dataTimes = d_times; + } + // #endif + + #if defined(BLINKER_LOWPOWER) || defined(BLINKER_LOWPOWER_AIR202) + void attachLowPower(blinker_callback_t newFunction, uint32_t _time) + { + _LowPowerFunc = newFunction; + _LowPowerFreq = _time; + } + + void attachSleep(blinker_callback_t newFunction) + { + _sleepFunc = newFunction; + } + #endif + + bool init() { return _isInit; } + + #endif + + void attachData(blinker_callback_with_string_arg_t newFunction) + { BProto::_availableFunc = newFunction; } + void attachHeartbeat(blinker_callback_t newFunction) + { _heartbeatFunc = newFunction; } + void attachSummary(blinker_callback_return_string_t newFunction) + { _summaryFunc = newFunction; } + void attachAir(blinker_callback_with_string_arg_t newFunction) + { _airFunc = newFunction; } + void attachWeather(blinker_callback_with_string_arg_t newFunction) + { _weatherFunc = newFunction; } + void attachWeatherForecast(blinker_callback_with_string_arg_t newFunction) + { _weather_forecast_Func = newFunction; } + void attachConfigGet(blinker_callback_with_string_arg_t newFunction) + { _configGetFunc = newFunction; } + void attachDataGet(blinker_callback_with_string_arg_t newFunction) + { _dataGetFunc = newFunction; } + + void freshAttachWidget(char _name[], blinker_callback_with_string_arg_t _func); + // #if defined(BLINKER_BLE) + void freshAttachWidget(char _name[], blinker_callback_with_joy_arg_t _func); + // #endif + void freshAttachWidget(char _name[], blinker_callback_with_rgb_arg_t _func); + void freshAttachWidget(char _name[], blinker_callback_with_int32_arg_t _func); + void freshAttachWidget(char _name[], blinker_callback_with_table_arg_t _func, blinker_callback_t _func2); + uint8_t attachWidget(char _name[], blinker_callback_with_string_arg_t _func); + // #if defined(BLINKER_BLE) + uint8_t attachWidget(char _name[], blinker_callback_with_joy_arg_t _func); + // #endif + uint8_t attachWidget(char _name[], blinker_callback_with_rgb_arg_t _func); + uint8_t attachWidget(char _name[], blinker_callback_with_int32_arg_t _func); + uint8_t attachWidget(char _name[], blinker_callback_with_table_arg_t _func, blinker_callback_t _func2); + void attachSwitch(blinker_callback_with_string_arg_t _func); + char * widgetName_str(uint8_t num); + // #if defined(BLINKER_BLE) + char * widgetName_joy(uint8_t num); + // #endif + char * widgetName_rgb(uint8_t num); + char * widgetName_int(uint8_t num); + char * widgetName_tab(uint8_t num); + + #if defined(BLINKER_PRO) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_WIFI_SUBDEVICE) + void attachParse(blinker_callback_with_json_arg_t newFunction) + { _parseFunc = newFunction; } + void attachClick(blinker_callback_t newFunction) + { _clickFunc = newFunction; } + void attachDoubleClick(blinker_callback_t newFunction) + { _doubleClickFunc = newFunction; } + void attachLongPressStart(blinker_callback_t newFunction) + { _longPressStartFunc = newFunction; } + void attachLongPressStop(blinker_callback_t newFunction) + { _longPressStopFunc = newFunction; } + void attachDuringLongPress(blinker_callback_t newFunction) + { _duringLongPressFunc = newFunction; } + #if defined(BLINKER_BUTTON_LONGPRESS_POWERDOWN) + void attachLongPressPowerdown(blinker_callback_t newFunction) + { _powerdownFunc = newFunction; } + void attachLongPressReset(blinker_callback_t newFunction) + { _resetFunc = newFunction; } + + uint16_t pressedTime(); + #endif + + #if defined(BLINKER_NO_BUTTON) + void attachNoButtonReset(blinker_callback_t newFunction) + { _noButtonResetFunc = newFunction; } + #endif + + #if !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) + void setType(const char* _type); + const char* type() { return _deviceType; } + const char* key() { return _vipKey; } + void reset(); + void tick(); + void checkRegister(const JsonObject& data); + + // bool init() { return _isInit; } + bool registered() { return BProto::authCheck(); } + #if defined(BLINKER_PRO) || defined(BLINKER_PRO_ESP) + BlinkerStatus_t status() { return _proStatus; } + #elif defined(BLINKER_MQTT_AUTO) + uint8_t status() { return _mqttAutoStatue; } + #endif + #endif + #endif + + #if defined(BLINKER_PRO_AIR202) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + void attachAir202Reset(blinker_callback_t newFunction) + { _resetAIRFunc = newFunction; } + #endif + + #if defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_QRCODE_NBIOT_SIM7020) + void attachSIM7020Reset(blinker_callback_t newFunction) + { _resetSIMFunc = newFunction; } + #endif + + #if defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + void attachSIM7000Reset(blinker_callback_t newFunction) + { _resetSIMFunc = newFunction; } + #endif + + #if defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) + void esptouchInit() { BProto::smartConfigType(); } + void apConfigInit() { BProto::apConfigType(); } + b_config_t configType() { return BProto::checkIsSmartConfig() ? BLINKER_SMART_CONFIG : BLINKER_AP_CONFIG; } + #endif + + #if defined(BLINKER_HTTP) + void subscribe() { BProto::subscribe(); } + #endif + + private : + bool _isNew = false; + #if defined(BLINKER_GPRS_AIR202) + char _LANG[14]; + char _LAT[14]; + uint32_t gps_air202_time = 0; + #endif + bool _fresh = false; + int16_t ahrsValue[3]; + float gpsValue[2]; + uint32_t gps_get_time; + + uint8_t _wCount_num = 0; + uint8_t _wCount_str = 0; + uint8_t _wCount_joy = 0; + uint8_t _wCount_rgb = 0; + uint8_t _wCount_int = 0; + uint8_t _wCount_tab = 0; + + class BlinkerWidgets_num * _Widgets_num[BLINKER_MAX_WIDGET_SIZE*2]; + class BlinkerWidgets_string * _Widgets_str[BLINKER_MAX_WIDGET_SIZE*2]; + // #if defined(BLINKER_BLE) + class BlinkerWidgets_joy * _Widgets_joy[BLINKER_MAX_WIDGET_SIZE/2]; + // #endif + class BlinkerWidgets_rgb * _Widgets_rgb[BLINKER_MAX_WIDGET_SIZE/2]; + class BlinkerWidgets_int32 * _Widgets_int[BLINKER_MAX_WIDGET_SIZE*2]; + class BlinkerWidgets_table * _Widgets_tab[BLINKER_MAX_WIDGET_SIZE*2]; + // class BlinkerWidgets_string * _BUILTIN_SWITCH; + BlinkerWidgets_string _BUILTIN_SWITCH = BlinkerWidgets_string(BLINKER_CMD_BUILTIN_SWITCH); + + bool _needInit = false; + + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_LOWPOWER_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_WIFI_SUBDEVICE) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) || defined(BLINKE_HTTP) + bool _isInit = false; + bool _isAuto = false; + bool _isAutoInit = false; + uint8_t _disconnectCount = 0; + uint32_t _disFreshTime = 0; + uint32_t _disconnectTime = 0; + uint32_t _refreshTime = 0; + uint32_t _reconTime = 0; + + #if defined(BLINKER_WIFI_SUBDEVICE) + bool _isNTPInit = &isTimeSet; + #else + bool _isNTPInit = false; + #endif + time_t _deviceStartTime = 0; + float _timezone = 8.0; + uint32_t _ntpStart; + + uint32_t _smsTime = 0; + uint32_t _pushTime = 0; + uint32_t _wechatTime = 0; + uint32_t _weatherTime = 0; + uint32_t _weather_forecast_Time = 0; + uint32_t _aqiTime = 0; + uint32_t _logTime = 0; + uint32_t _codTime = 0; + uint8_t data_dataCount = 0; + uint8_t data_rtDataCount = 0; + uint8_t data_timeSlotDataCount = 0; + uint32_t time_timeSlotData = 0; + uint8_t _aCount = 0; + uint8_t _bridgeCount = 0; + + uint32_t _cUpdateTime = 0; + uint32_t _dUpdateTime = 0; + uint32_t _cGetTime = 0; + uint32_t _cDelTime = 0; + uint32_t _dGetTime = 0; + uint32_t _dDelTime = 0; + uint32_t _autoPullTime = 0; + + uint32_t _autoUpdateTime = 0; + + uint8_t _serverTimes = 0; + uint32_t _serverTime = 0; + + #if defined(BLINKER_PRO_ESP) + uint32_t _eWarnTime = 0; + uint32_t _eErrTime = 0; + uint32_t _eMsgTime = 0; + #endif + + uint32_t _dHeartTime = 0; + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_LOWPOWER_AIR202)) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7020) && !defined(BLINKER_NBIOT_SIM7000) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7000) + char _cdAction[BLINKER_TIMER_COUNTDOWN_ACTION_SIZE]; + char _lpAction1[BLINKER_TIMER_LOOP_ACTION1_SIZE]; + char _lpAction2[BLINKER_TIMER_LOOP_ACTION2_SIZE]; + class BlinkerTimingTimer * timingTask[BLINKER_TIMING_TIMER_SIZE]; + class BlinkerBridge_key * _Bridge[BLINKER_MAX_BRIDGE_SIZE]; + #endif + + class BlinkerData * _Data[BLINKER_MAX_BLINKER_DATA_SIZE]; + class BlinkerRTData * _RTData[2]; + + class BlinkerTimeSlotData * _TimeSlotData[BLINKER_MAX_BLINKER_DATA_SIZE]; + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_LOWPOWER_AIR202)) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7020) && !defined(BLINKER_NBIOT_SIM7000) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7000) + class BlinkerAUTO * _AUTO[2]; + #if !defined(BLINKER_WIFI_SUBDEVICE) + BlinkerOTA _OTA; + #endif + #endif + #endif + + #if defined(BLINKER_PRO) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_WIFI_SUBDEVICE) + bool _isInitCheck = false; + bool _isConnBegin = false; + bool _getRegister = false; + // bool _isInit = false; + bool _isRegistered = false; + uint32_t _register_fresh = 0; + uint8_t _register_times = 0; + uint32_t _initTime; + #if defined(BLINKER_PRO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_GATEWAY) + BlinkerStatus_t _proStatus = PRO_WLAN_CONNECTING; + #elif defined(BLINKER_MQTT_AUTO) + BlinkerStatus_t _mqttAutoStatue = AUTO_WLAN_CONNECTING; + #endif + + #if defined(BLINKER_NO_BUTTON) + bool _isCheckPower = false; + uint8_t _power_count = 0; + uint32_t _reset_countdown = 0; + #endif + #endif + + #if defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) + bool _isConnBegin = false; + bool _getRegister = false; + // bool _isInit = false; + bool _isRegistered = false; + bool _isPowerOn = false; + uint32_t _register_fresh = 0; + uint32_t _initTime; + uint8_t _registerTimes = 0; + BlinkerStatus_t _gprsStatus = GPRS_DEV_POWER_CHECK; + + // bool _isNeedReset = false; + blinker_callback_t _resetAIRFunc = NULL; + + // String getIMEI(); + #endif + + #if defined(BLINKER_LOWPOWER_AIR202) + const char* _vipKey; + bool _isConnBegin = false; + bool _getRegister = false; + // bool _isInit = false; + bool _isRegistered = false; + bool _isPowerOn = false; + uint32_t _register_fresh = 0; + uint32_t _initTime; + uint8_t _registerTimes = 0; + BlinkerStatus_t _gprsStatus = GPRS_DEV_POWER_CHECK; + + blinker_callback_t _resetAIRFunc = NULL; + #endif + + #if defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) + bool _isConnBegin = false; + bool _getRegister = false; + // bool _isInit = false; + bool _isRegistered = false; + bool _isPowerOn = false; + uint32_t _register_fresh = 0; + uint32_t _initTime; + uint8_t _registerTimes = 0; + BlinkerStatus_t _nbiotStatus = NBIOT_DEV_POWER_CHECK; + + blinker_callback_t _resetSIMFunc = NULL; + + uint32_t _checkCrash = 0; + #endif + + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_PRO_ESP) + char _RTDataKey[16]; + blinker_callback_t _RTDataFunc = NULL; + Ticker _RTTicker; + #endif + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) ||\ + defined(BLINKER_MQTT_AT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_LOWPOWER_AIR202) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + + blinker_callback_with_string_uint8_arg_t _AliGeniePowerStateFunc_m = NULL; + blinker_callback_with_string_arg_t _AliGeniePowerStateFunc = NULL; + blinker_callback_with_string_arg_t _AliGenieHSwingStateFunc = NULL; + blinker_callback_with_string_arg_t _AliGenieVSwingStateFunc = NULL; + blinker_callback_with_string_arg_t _AliGenieSetColorFunc = NULL; + blinker_callback_with_string_arg_t _AliGenieSetModeFunc = NULL; + blinker_callback_with_string_arg_t _AliGenieSetcModeFunc = NULL; + blinker_callback_with_string_arg_t _AliGenieSetLevelFunc_str = NULL; + blinker_callback_with_uint8_arg_t _AliGenieSetLevelFunc = NULL; + blinker_callback_with_uint8_arg_t _AliGenieSetTempFunc = NULL; + blinker_callback_with_int32_arg_t _AliGenieSetRelativeLevelFunc = NULL; + blinker_callback_with_int32_arg_t _AliGenieSetRelativeTempFunc = NULL; + blinker_callback_with_string_arg_t _AliGenieSetBrightnessFunc = NULL; + blinker_callback_with_int32_arg_t _AliGenieSetRelativeBrightnessFunc = NULL; + blinker_callback_with_int32_arg_t _AliGenieSetColorTemperature = NULL; + blinker_callback_with_int32_arg_t _AliGenieSetRelativeColorTemperature = NULL; + blinker_callback_with_int32_uint8_arg_t _AliGenieQueryFunc_m = NULL; + blinker_callback_with_int32_arg_t _AliGenieQueryFunc = NULL; + + + blinker_callback_with_string_uint8_arg_t _DuerOSPowerStateFunc_m = NULL; + blinker_callback_with_string_arg_t _DuerOSPowerStateFunc = NULL; + blinker_callback_with_int32_arg_t _DuerOSSetColorFunc = NULL; + blinker_callback_with_string_arg_t _DuerOSSetModeFunc = NULL; + blinker_callback_with_string_arg_t _DuerOSSetcModeFunc = NULL; + blinker_callback_with_uint8_arg_t _DuerOSSetLevelFunc = NULL; + blinker_callback_with_int32_arg_t _DuerOSSetRelativeLevelFunc = NULL; + blinker_callback_with_uint8_arg_t _DuerOSSetTempFunc = NULL; + blinker_callback_with_int32_arg_t _DuerOSSetRelativeTempFunc = NULL; + blinker_callback_with_string_arg_t _DuerOSSetBrightnessFunc = NULL; + blinker_callback_with_int32_arg_t _DuerOSSetRelativeBrightnessFunc = NULL; + blinker_callback_with_int32_arg_t _DuerOSSetColorTemperature = NULL; + blinker_callback_with_int32_arg_t _DuerOSSetRelativeColorTemperature = NULL; + blinker_callback_with_int32_uint8_arg_t _DuerOSQueryFunc_m = NULL; + blinker_callback_with_int32_arg_t _DuerOSQueryFunc = NULL; + + blinker_callback_with_string_uint8_arg_t _MIOTPowerStateFunc_m = NULL; + blinker_callback_with_string_arg_t _MIOTPowerStateFunc = NULL; + blinker_callback_with_string_arg_t _MIOTHSwingStateFunc = NULL; + blinker_callback_with_string_arg_t _MIOTVSwingStateFunc = NULL; + blinker_callback_with_string_arg_t _MIOTECOFunc = NULL; + blinker_callback_with_string_arg_t _MIOTAnionFunc = NULL; + blinker_callback_with_string_arg_t _MIOTHeaterFunc = NULL; + blinker_callback_with_string_arg_t _MIOTDryerFunc = NULL; + blinker_callback_with_string_arg_t _MIOTSleepFunc = NULL; + blinker_callback_with_string_arg_t _MIOTSoftFunc = NULL; + blinker_callback_with_string_arg_t _MIOTUVFunc = NULL; + blinker_callback_with_string_arg_t _MIOTUNSBFunc = NULL; + blinker_callback_with_int32_arg_t _MIOTSetColorFunc = NULL; + blinker_callback_with_string_string_arg_t _MIOTSetModeFunc_m = NULL; + blinker_callback_with_uint8_arg_t _MIOTSetModeFunc = NULL; + blinker_callback_with_uint8_arg_t _MIOTSetLevelFunc = NULL; + blinker_callback_with_uint8_arg_t _MIOTSetTempFunc = NULL; + blinker_callback_with_uint8_arg_t _MIOTSetHumiFunc = NULL; + // blinker_callback_with_string_arg_t _MIOTSetcModeFunc = NULL; + blinker_callback_with_string_arg_t _MIOTSetBrightnessFunc = NULL; + // blinker_callback_with_int32_arg_t _MIOTSetRelativeBrightnessFunc = NULL; + blinker_callback_with_int32_arg_t _MIOTSetColorTemperature = NULL; + // blinker_callback_with_int32_arg_t _MIOTSetRelativeColorTemperature = NULL; + blinker_callback_with_int32_uint8_arg_t _MIOTQueryFunc_m = NULL; + blinker_callback_with_int32_arg_t _MIOTQueryFunc = NULL; + + // #if !defined(BLINKER_AT_MQTT) + blinker_callback_t _dataStorageFunc = NULL; + uint32_t _autoStorageTime = 60; + uint32_t _autoDataTime = 0; + uint8_t _dataTimes = BLINKER_MAX_DATA_COUNT; + // #endif + + #if defined(BLINKER_LOWPOWER) || defined(BLINKER_LOWPOWER_AIR202) + blinker_callback_t _LowPowerFunc = NULL; + uint32_t _LowPowerFreq = 10; + // char* _LowPowerData; + blinker_callback_t _sleepFunc = NULL; + #endif + #endif + + // #if defined(BLINKER_WIFI_GATEWAY) + // blinker_callback_return_int_t _gatewayAvail = NULL; + // blinker_callback_return_string_t _gatewayRead = NULL; + // blinker_callback_with_string_arg_t _gatewayPrint = NULL; + // #endif + + #if defined(BLINKER_MQTT_AT) || defined(BLINKER_NB73_NBIOT) + class BlinkerMasterAT * _masterAT; + void atRespOK(const String & _data, uint32_t timeout = BLINKER_STREAM_TIMEOUT*10); + // void initCheck(const String & _data, uint32_t timeout = BLINKER_STREAM_TIMEOUT*10); + #endif + + blinker_callback_t _heartbeatFunc = NULL; + blinker_callback_return_string_t _summaryFunc = NULL; + blinker_callback_with_string_arg_t _airFunc = NULL; + blinker_callback_with_string_arg_t _weatherFunc = NULL; + blinker_callback_with_string_arg_t _weather_forecast_Func = NULL; + blinker_callback_with_string_arg_t _configGetFunc = NULL; + blinker_callback_with_string_arg_t _dataGetFunc = NULL; + + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_PRO_ESP) + void rtParse(const JsonObject& data); + #endif + + void parse(char _data[], bool ex_data = false); + + bool deviceHeartbeat(uint32_t heart_time = BLINKER_DEVICE_HEARTBEAT_TIME); + + #if defined(BLINKER_ARDUINOJSON) + int16_t ahrs(b_ahrsattitude_t attitude, const JsonObject& data); + float gps(b_gps_t axis, const JsonObject& data); + + void heartBeat(const JsonObject& data); + void getVersion(const JsonObject& data); + void setSwitch(const JsonObject& data); + + // #if defined(BLINKER_WIFI_SUBDEVICE) + // void broadCast(const JsonObject& data); + // #endif + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) + void bridgeParse(char _bName[], uint8_t num, const JsonObject& data); + #endif + void strWidgetsParse(char _wName[], const JsonObject& data); + // #if defined(BLINKER_BLE) + void joyWidgetsParse(char _wName[], const JsonObject& data); + // #endif + void rgbWidgetsParse(char _wName[], const JsonObject& data); + void intWidgetsParse(char _wName[], const JsonObject& data); + void tabWidgetsParse(char _wName[], const JsonObject& data); + + void json_parse(const JsonObject& data); + #else + int16_t ahrs(b_ahrsattitude_t attitude, char data[]); + float gps(b_gps_t axis, char data[]); + + void heartBeat(char data[]); + void getVersion(char data[]); + void setSwitch(char data[]); + + void strWidgetsParse(char _wName[], char _data[]); + // #if defined(BLINKER_BLE) + void joyWidgetsParse(char _wName[], char _data[]); + // #endif + void rgbWidgetsParse(char _wName[], char _data[]); + void intWidgetsParse(char _wName[], char _data[]); + void tabWidgetsParse(char _wName[], char _data[]); + + void json_parse(char _data[]); + #endif + + #if defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + bool ntpInit() + { + if (!_isNTPInit) + { + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + // if (!BLINKER_AIR202.getAMGSMLOC()) return false; + if (!BLINKER_AIR202.getNTP()) return false; + + struct tm timeinfo; + + #if defined(ESP8266) || defined(__AVR__) + gmtime_r(&BLINKER_AIR202._ntpTime, &timeinfo); + #elif defined(ESP32) + localtime_r(&BLINKER_AIR202._ntpTime, &timeinfo); + #endif + + BLINKER_LOG_ALL(BLINKER_F("ntpInit Current time: "), asctime(&timeinfo)); + BLINKER_LOG_ALL(BLINKER_F("NTP time: "), BLINKER_AIR202._ntpTime - (int)(getTimezone()*3600)); + + _isNTPInit = true; + + return true; + } + return true; + } + + String blinkerServer(uint8_t _type, const String & msg, bool state = false) + { + switch (_type) + { + case BLINKER_CMD_SMS_NUMBER : + if (!checkSMS()) { + return BLINKER_CMD_FALSE; + } + + if ((!state && msg.length() > BLINKER_SMS_MAX_SEND_SIZE) || + (state && msg.length() > BLINKER_SMS_MAX_SEND_SIZE + 15)) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_PUSH_NUMBER : + if (!checkPUSH()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_WECHAT_NUMBER : + if (!checkWECHAT()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_WEATHER_NUMBER : + if (!checkWEATHER()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_WEATHER_FORECAST_NUMBER : + if (!checkWEATHERFORECAST()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_AQI_NUMBER : + if (!checkAQI()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_LOG_NUMBER : + if (!checkLOG()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_COD_NUMBER : + if (!checkCOD()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_BRIDGE_NUMBER : + break; + case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + if (!checkCUPDATE()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_CONFIG_GET_NUMBER : + if (!checkCGET()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_CONFIG_DELETE_NUMBER : + if (!checkCDEL()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_DATA_STORAGE_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_TIME_SLOT_DATA_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_TEXT_DATA_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_JSON_DATA_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_JSON_DATA_GET_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_DATA_GET_NUMBER : + if (!checkDataGet()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_DATA_DELETE_NUMBER : + if (!checkDataDel()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_AUTO_PULL_NUMBER : + if (!checkAutoPull()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_OTA_NUMBER : + break; + case BLINKER_CMD_OTA_STATUS_NUMBER : + break; + case BLINKER_CMD_FRESH_SHARERS_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_FREQ_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_DATA_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER : + break; + case BLINKER_CMD_EVENT_DATA_NUMBER : + break; + case BLINKER_CMD_GPS_DATA_NUMBER : + break; + case BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER : + break; + #if defined(BLINKER_PRO_ESP) + case BLINKER_CMD_EVENT_WARNING_NUMBER : + if (!checkEventWarn()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_EVENT_ERROR_NUMBER : + if (!checkEventErr()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_EVENT_MSG_NUMBER : + if (!checkEventMsg()) { + return BLINKER_CMD_FALSE; + } + break; + #endif + default : + return BLINKER_CMD_FALSE; + } + + BLINKER_LOG_ALL(BLINKER_F("message: "), msg); + + #ifndef BLINKER_LAN_DEBUG + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + const int httpsPort = 443; + #elif defined(BLINKER_LAN_DEBUG) + String host = BLINKER_F("http://192.168.0.105:8887"); + const int httpsPort = 8887; + #endif + + BlinkerHTTPAIR202 http(*stream, isHWS, listenFunc); + + String url_iot; + + int httpCode; + + String conType = BLINKER_F("Content-Type"); + String application = BLINKER_F("application/json;charset=utf-8"); + + BLINKER_LOG_ALL(BLINKER_F("blinker server begin")); + BLINKER_LOG_FreeHeap_ALL(); + + switch (_type) + { + case BLINKER_CMD_SMS_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/sms"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_PUSH_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/push"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + // return BLINKER_CMD_FALSE; + case BLINKER_CMD_WECHAT_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/wxMsg/"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + // return BLINKER_CMD_FALSE; + case BLINKER_CMD_WEATHER_NUMBER : + url_iot = BLINKER_F("/api/v2"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_AQI_NUMBER : + url_iot = BLINKER_F("/api/v2"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOG_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/cloud_storage/logs"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_COD_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/cloud_storage/coordinate"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_BRIDGE_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/userconfig"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_CONFIG_GET_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_CONFIG_DELETE_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_DATA_STORAGE_NUMBER : + // url_iot = BLINKER_F("/api/v1/user/device/cloudStorage/?"); + // url_iot += msg; + + // http.begin(host, url_iot); + + // powerCheck(); + + // httpCode = http.GET(); + + url_iot = BLINKER_F("/api/v1/user/device/cloudStorage/"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_TIME_SLOT_DATA_NUMBER : + // url_iot = BLINKER_F("/api/v1/user/device/cloudStorage/?"); + // url_iot += msg; + + // http.begin(host, url_iot); + + // powerCheck(); + + // httpCode = http.GET(); + + url_iot = BLINKER_F("/api/v1/storage/ts "); + #ifndef BLINKER_WITHOUT_SSL + http.begin("https://storage.diandeng.tech", url_iot); + #else + http.begin("http://storage.diandeng.tech", url_iot); + #endif + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_TEXT_DATA_NUMBER : + // url_iot = BLINKER_F("/api/v1/user/device/cloudStorage/?"); + // url_iot += msg; + + // http.begin(host, url_iot); + + // powerCheck(); + + // httpCode = http.GET(); + + url_iot = BLINKER_F("/api/v1/storage/text "); + #ifndef BLINKER_WITHOUT_SSL + http.begin("https://storage.diandeng.tech", url_iot); + #else + http.begin("http://storage.diandeng.tech", url_iot); + #endif + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_JSON_DATA_NUMBER : + // url_iot = BLINKER_F("/api/v1/user/device/cloudStorage/?"); + // url_iot += msg; + + // http.begin(host, url_iot); + + // powerCheck(); + + // httpCode = http.GET(); + + // url_iot = BLINKER_F("/api/v1/storage/object"); + // #ifndef BLINKER_WITHOUT_SSL + // http.begin("https://storage.diandeng.tech", url_iot); + // #else + // http.begin("http://storage.diandeng.tech", url_iot); + // #endif + + url_iot = BLINKER_F("/api/v1/user/device/cloud_storage/object"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_JSON_DATA_GET_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_DATA_GET_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_DATA_DELETE_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_AUTO_PULL_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_OTA_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_OTA_STATUS_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/ota/upgrade_status"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_FRESH_SHARERS_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_FREQ_GET_NUM : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_DATA_GET_NUM : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/lowpower/data"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_EVENT_DATA_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/event"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_GPS_DATA_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/gps"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + #if defined(BLINKER_PRO_ESP) + case BLINKER_CMD_EVENT_WARNING_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/event"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_EVENT_ERROR_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/event"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_EVENT_MSG_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/event"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + #endif + default : + return BLINKER_CMD_FALSE; + } + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + BLINKER_LOG_ALL(BLINKER_F("HTTPS payload: "), msg); + + if (httpCode) + { + BLINKER_LOG(BLINKER_F("[HTTP] ... success")); + + String payload = http.getString(); + + BLINKER_LOG_ALL(payload); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& data_rp = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject data_rp = jsonBuffer.as(); + + // if (data_rp.success()) + if (!error) + { + uint16_t msg_code = data_rp[BLINKER_CMD_MESSAGE]; + if (msg_code != 1000) + { + String _detail = data_rp[BLINKER_CMD_DETAIL]; + BLINKER_ERR_LOG(_detail); + } + else + { + // String _payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DATA]; + // payload = _payload; + + if (_type == BLINKER_CMD_BRIDGE_NUMBER) + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME].as(); + else if (_type == BLINKER_CMD_OTA_NUMBER || _type == BLINKER_CMD_FRESH_SHARERS_NUMBER) + payload = data_rp[BLINKER_CMD_DETAIL].as(); + else if (_type == BLINKER_CMD_LOWPOWER_FREQ_GET_NUM) + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_FREQ].as(); + else + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DATA].as(); + } + } + + BLINKER_LOG_ALL(BLINKER_F("payload: "), payload); + + switch (_type) { + case BLINKER_CMD_SMS_NUMBER : + _smsTime = millis(); + break; + case BLINKER_CMD_PUSH_NUMBER : + _pushTime = millis(); + break; + case BLINKER_CMD_WECHAT_NUMBER : + _wechatTime = millis(); + break; + // return BLINKER_CMD_FALSE; + case BLINKER_CMD_WEATHER_NUMBER : + _weatherTime = millis(); + if (_weatherFunc) _weatherFunc(payload); + break; + case BLINKER_CMD_WEATHER_FORECAST_NUMBER : + _weather_forecast_Time = millis(); + if (_weather_forecast_Func) _weather_forecast_Func(payload); + break; + case BLINKER_CMD_AQI_NUMBER : + _aqiTime = millis(); + if (_airFunc) _airFunc(payload); + break; + case BLINKER_CMD_LOG_NUMBER : + _logTime = millis(); + break; + case BLINKER_CMD_COD_NUMBER : + _codTime = millis(); + break; + case BLINKER_CMD_BRIDGE_NUMBER : + break; + case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + _cUpdateTime = millis(); + break; + case BLINKER_CMD_CONFIG_GET_NUMBER : + _cGetTime = millis(); + if (_configGetFunc) _configGetFunc(payload); + break; + case BLINKER_CMD_CONFIG_DELETE_NUMBER : + _cDelTime = millis(); + break; + case BLINKER_CMD_DATA_STORAGE_NUMBER : + _dUpdateTime = millis(); + break; + case BLINKER_CMD_TIME_SLOT_DATA_NUMBER : + _dUpdateTime = millis(); + break; + case BLINKER_CMD_TEXT_DATA_NUMBER : + _dUpdateTime = millis(); + break; + case BLINKER_CMD_JSON_DATA_NUMBER : + _dUpdateTime = millis(); + break; + case BLINKER_CMD_JSON_DATA_GET_NUMBER : + _dUpdateTime = millis(); + break; + case BLINKER_CMD_DATA_GET_NUMBER : + _dGetTime = millis(); + if (_dataGetFunc) _dataGetFunc(payload); + break; + case BLINKER_CMD_DATA_DELETE_NUMBER : + _dDelTime = millis(); + break; + case BLINKER_CMD_AUTO_PULL_NUMBER : + _autoPullTime = millis(); + break; + case BLINKER_CMD_OTA_NUMBER : + break; + case BLINKER_CMD_OTA_STATUS_NUMBER : + break; + case BLINKER_CMD_FRESH_SHARERS_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_FREQ_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_DATA_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER : + break; + case BLINKER_CMD_EVENT_DATA_NUMBER : + break; + case BLINKER_CMD_GPS_DATA_NUMBER : + break; + case BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER : + break; + #if defined(BLINKER_PRO_ESP) + case BLINKER_CMD_EVENT_WARNING_NUMBER : + _eWarnTime = millis(); + break; + case BLINKER_CMD_EVENT_ERROR_NUMBER : + _eErrTime = millis(); + break; + case BLINKER_CMD_EVENT_MSG_NUMBER : + _eMsgTime = millis(); + break; + #endif + default : + return BLINKER_CMD_FALSE; + } + + return payload; + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] ... failed")); + + return BLINKER_CMD_FALSE; + } + } + #endif + + #if defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) + bool ntpInit() + { + if (!_isNTPInit) + { + #if defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7020.getSNTP(getTimezone())) return false; + + struct tm timeinfo; + + #if defined(ESP8266) || defined(__AVR__) + gmtime_r(&BLINKER_SIM7020._ntpTime, &timeinfo); + #elif defined(ESP32) + localtime_r(&BLINKER_SIM7020._ntpTime, &timeinfo); + #endif + + BLINKER_LOG_ALL(BLINKER_F("Current time: "), asctime(&timeinfo)); + BLINKER_LOG_ALL(BLINKER_F("NTP time: "), BLINKER_SIM7020._ntpTime - (int)(getTimezone()*3600)); + + #elif defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7000.getSNTP(getTimezone())) return false; + + struct tm timeinfo; + + #if defined(ESP8266) || defined(__AVR__) + gmtime_r(&BLINKER_SIM7000._ntpTime, &timeinfo); + #elif defined(ESP32) + localtime_r(&BLINKER_SIM7000._ntpTime, &timeinfo); + #endif + + BLINKER_LOG_ALL(BLINKER_F("Current time: "), asctime(&timeinfo)); + BLINKER_LOG_ALL(BLINKER_F("NTP time: "), BLINKER_SIM7000._ntpTime - (int)(getTimezone()*3600)); + + #endif + _isNTPInit = true; + + return true; + } + return true; + } + + String blinkerServer(uint8_t _type, const String & msg, bool state = false) + { + switch (_type) + { + case BLINKER_CMD_SMS_NUMBER : + if (!checkSMS()) { + return BLINKER_CMD_FALSE; + } + + if ((!state && msg.length() > BLINKER_SMS_MAX_SEND_SIZE) || + (state && msg.length() > BLINKER_SMS_MAX_SEND_SIZE + 15)) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_PUSH_NUMBER : + if (!checkPUSH()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_WECHAT_NUMBER : + if (!checkWECHAT()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_WEATHER_NUMBER : + if (!checkWEATHER()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_WEATHER_FORECAST_NUMBER : + if (!checkWEATHERFORECAST()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_AQI_NUMBER : + if (!checkAQI()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_LOG_NUMBER : + if (!checkLOG()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_COD_NUMBER : + if (!checkCOD()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_BRIDGE_NUMBER : + break; + case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + if (!checkCUPDATE()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_CONFIG_GET_NUMBER : + if (!checkCGET()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_CONFIG_DELETE_NUMBER : + if (!checkCDEL()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_DATA_STORAGE_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_TIME_SLOT_DATA_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_TEXT_DATA_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_JSON_DATA_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_JSON_DATA_GET_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_DATA_GET_NUMBER : + if (!checkDataGet()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_DATA_DELETE_NUMBER : + if (!checkDataDel()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_AUTO_PULL_NUMBER : + if (!checkAutoPull()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_OTA_NUMBER : + break; + case BLINKER_CMD_OTA_STATUS_NUMBER : + break; + case BLINKER_CMD_FRESH_SHARERS_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_FREQ_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_DATA_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER : + break; + case BLINKER_CMD_EVENT_DATA_NUMBER : + break; + case BLINKER_CMD_GPS_DATA_NUMBER : + break; + case BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER : + break; + default : + return BLINKER_CMD_FALSE; + } + + BLINKER_LOG_ALL(BLINKER_F("message: "), msg); + + #ifndef BLINKER_LAN_DEBUG + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + const int httpsPort = 443; + #elif defined(BLINKER_LAN_DEBUG) + String host = BLINKER_F("http://192.168.0.105:8887"); + const int httpsPort = 8887; + #endif + + #if defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + BlinkerHTTPSIM7020 http(*stream, isHWS, listenFunc); + #elif defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerHTTPSIM7000 http(*stream, isHWS, listenFunc); + #endif + + String url_iot; + + int httpCode; + + // if (_type == BLINKER_CMD_SMS_NUMBER) { + // url_iot = String(host) + "/api/v1/user/device/sms"; + // } + String conType = BLINKER_F("Content-Type"); + String application = BLINKER_F("application/json;charset=utf-8"); + + BLINKER_LOG_ALL(BLINKER_F("blinker server begin")); + BLINKER_LOG_FreeHeap_ALL(); + + switch (_type) + { + case BLINKER_CMD_SMS_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/sms"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_PUSH_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/push"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + // return BLINKER_CMD_FALSE; + case BLINKER_CMD_WECHAT_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/wxMsg/"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + // return BLINKER_CMD_FALSE; + case BLINKER_CMD_WEATHER_NUMBER : + url_iot = BLINKER_F("/api/v3"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_WEATHER_FORECAST_NUMBER : + url_iot = BLINKER_F("/api/v3"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_AQI_NUMBER : + url_iot = BLINKER_F("/api/v3"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOG_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/cloud_storage/logs"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_COD_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/cloud_storage/coordinate"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_BRIDGE_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/userconfig"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_CONFIG_GET_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_CONFIG_DELETE_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_DATA_STORAGE_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/cloudStorage/"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_TIME_SLOT_DATA_NUMBER : + url_iot = BLINKER_F("/api/v1/storage/ts"); + #ifndef BLINKER_WITHOUT_SSL + http.begin("https://storage.diandeng.tech", url_iot); + #else + http.begin("http://storage.diandeng.tech", url_iot); + #endif + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_TEXT_DATA_NUMBER : + url_iot = BLINKER_F("/api/v1/storage/text"); + #ifndef BLINKER_WITHOUT_SSL + http.begin("https://storage.diandeng.tech", url_iot); + #else + http.begin("http://storage.diandeng.tech", url_iot); + #endif + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_JSON_DATA_NUMBER : + url_iot = BLINKER_F("/api/v1/storage/object"); + #ifndef BLINKER_WITHOUT_SSL + http.begin("https://storage.diandeng.tech", url_iot); + #else + http.begin("http://storage.diandeng.tech", url_iot); + #endif + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_DATA_GET_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_DATA_DELETE_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_AUTO_PULL_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_OTA_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_OTA_STATUS_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/ota/upgrade_status"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_FRESH_SHARERS_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_FREQ_GET_NUM : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_DATA_GET_NUM : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/lowpower/data"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_EVENT_DATA_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/event"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_GPS_DATA_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device/gps"); + + http.begin(host, url_iot); + + // http.addHeader(conType, application); + httpCode = http.POST(msg, conType, application); + break; + case BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER : + url_iot = BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + http.begin(host, url_iot); + + httpCode = http.GET(); + break; + default : + return BLINKER_CMD_FALSE; + } + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + BLINKER_LOG_ALL(BLINKER_F("HTTPS payload: "), msg); + + if (httpCode) + { + BLINKER_LOG(BLINKER_F("[HTTP] ... success")); + + String payload = http.getString(); + + BLINKER_LOG_ALL(payload); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& data_rp = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject data_rp = jsonBuffer.as(); + + // if (data_rp.success()) + if (!error) + { + uint16_t msg_code = data_rp[BLINKER_CMD_MESSAGE]; + if (msg_code != 1000) + { + String _detail = data_rp[BLINKER_CMD_DETAIL]; + BLINKER_ERR_LOG(_detail); + } + else + { + // String _payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DATA]; + // payload = _payload; + + if (_type == BLINKER_CMD_BRIDGE_NUMBER) + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME].as(); + else if (_type == BLINKER_CMD_OTA_NUMBER || _type == BLINKER_CMD_FRESH_SHARERS_NUMBER) + payload = data_rp[BLINKER_CMD_DETAIL].as(); + else if (_type == BLINKER_CMD_LOWPOWER_FREQ_GET_NUM) + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_FREQ].as(); + else if (_type == BLINKER_CMD_WEATHER_FORECAST_NUMBER || \ + _type == BLINKER_CMD_WEATHER_NUMBER || \ + _type == BLINKER_CMD_AQI_NUMBER) + payload = data_rp[BLINKER_CMD_DETAIL].as(); + else + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DATA].as(); + } + } + + BLINKER_LOG_ALL(BLINKER_F("payload: "), payload); + + switch (_type) { + case BLINKER_CMD_SMS_NUMBER : + _smsTime = millis(); + break; + case BLINKER_CMD_PUSH_NUMBER : + _pushTime = millis(); + break; + case BLINKER_CMD_WECHAT_NUMBER : + _wechatTime = millis(); + break; + // return BLINKER_CMD_FALSE; + case BLINKER_CMD_WEATHER_NUMBER : + _weatherTime = millis(); + if (_weatherFunc) _weatherFunc(payload); + break; + case BLINKER_CMD_WEATHER_FORECAST_NUMBER : + _weather_forecast_Time = millis(); + if (_weather_forecast_Func) _weather_forecast_Func(payload); + break; + case BLINKER_CMD_AQI_NUMBER : + _aqiTime = millis(); + if (_airFunc) _airFunc(payload); + break; + case BLINKER_CMD_LOG_NUMBER : + _logTime = millis(); + break; + case BLINKER_CMD_COD_NUMBER : + _codTime = millis(); + break; + case BLINKER_CMD_BRIDGE_NUMBER : + break; + case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + _cUpdateTime = millis(); + break; + case BLINKER_CMD_CONFIG_GET_NUMBER : + _cGetTime = millis(); + if (_configGetFunc) _configGetFunc(payload); + break; + case BLINKER_CMD_CONFIG_DELETE_NUMBER : + _cDelTime = millis(); + break; + case BLINKER_CMD_DATA_STORAGE_NUMBER : + _dUpdateTime = millis(); + break; + case BLINKER_CMD_TIME_SLOT_DATA_NUMBER : + _dUpdateTime = millis(); + break; + case BLINKER_CMD_TEXT_DATA_NUMBER : + _dUpdateTime = millis(); + break; + case BLINKER_CMD_JSON_DATA_NUMBER : + _dUpdateTime = millis(); + break; + case BLINKER_CMD_DATA_GET_NUMBER : + _dGetTime = millis(); + if (_dataGetFunc) _dataGetFunc(payload); + break; + case BLINKER_CMD_DATA_DELETE_NUMBER : + _dDelTime = millis(); + break; + case BLINKER_CMD_AUTO_PULL_NUMBER : + _autoPullTime = millis(); + break; + case BLINKER_CMD_OTA_NUMBER : + break; + case BLINKER_CMD_OTA_STATUS_NUMBER : + break; + case BLINKER_CMD_FRESH_SHARERS_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_FREQ_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_DATA_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER : + break; + case BLINKER_CMD_EVENT_DATA_NUMBER : + break; + case BLINKER_CMD_GPS_DATA_NUMBER : + break; + case BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER : + break; + default : + return BLINKER_CMD_FALSE; + } + + return payload; + } + else + { + BLINKER_LOG(BLINKER_F("[HTTP] ... failed")); + + return BLINKER_CMD_FALSE; + } + } + #endif + + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_LOWPOWER_AIR202) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + + void beginAuto(); + bool autoTrigged(uint32_t _id); + bool checkCanOTA(); + + #if !defined(BLINKER_WIFI_SUBDEVICE) + bool ntpInit(); + void freshNTP(); + void ntpConfig(); + #endif + + void saveCountDown(uint32_t _data, char _action[]); + void saveLoop(uint32_t _data, char _action1[], char _action2[]); + void loadCountdown(); + void loadLoop(); + void loadTiming(); + void checkOverlapping(uint8_t checkDays, uint16_t checkMins, uint8_t taskNum); + void freshTiming(uint8_t wDay, uint16_t nowMins); + void deleteTiming(uint8_t taskDel); + void addTimingTask(uint8_t taskSet, uint32_t timerData, const String & action); + + // #if defined(ESP32) + // uint8_t isErase; + // #endif + + void checkTimerErase(); + + String timerSetting(); + String countdownConfig(); + String loopConfig(); + String timingConfig(); + String getTimingCfg(uint8_t task); + bool timerManager(const JsonObject& data, bool _noSet = false); + bool checkTimer(); + + #endif + + bool checkServerLimit(); + bool checkSMS(); + bool checkPUSH(); + bool checkWECHAT(); + bool checkWEATHER(); + bool checkWEATHERFORECAST(); + bool checkAQI(); + bool checkLOG(); + bool checkCOD(); + bool checkCUPDATE(); + bool checkCGET(); + bool checkCDEL(); + bool checkDataUpdata(); + bool checkDataGet(); + bool checkDataDel(); + bool checkAutoPull(); + + #if defined(BLINKER_PRO_ESP) + bool checkEventWarn(); + bool checkEventErr(); + bool checkEventMsg(); + #endif + + #if !defined(BLINKER_LOWPOWER_AIR202) + void autoStart(); + bool autoManager(const JsonObject& data); + #endif + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + void shareParse(const JsonObject& data); + + #if !defined(BLINKER_WIFI_SUBDEVICE) + void otaParse(const JsonObject& data); + void numParse(const JsonObject& data); + #endif + #endif + + #if !defined(BLINKER_WIFI_SUBDEVICE) + + #if defined(BLINKER_GPRS_AIR202) + void shareParse(const JsonObject& data); + #endif + + #if !defined(BLINKER_LOWPOWER_AIR202) + String bridgeQuery(char * key); + #endif + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + + // String postServer(const String & url, const String & host, int port, const String & msg); + // String getServer(const String & url, const String & host, int port); + String blinkerServer(uint8_t _type, const String & msg, bool state = false); + + #endif + + uint32_t ntpFreshTime = 0; + time_t ntpGetTime = 0; + + #endif + #endif + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_MQTT_AT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + void aliParse(const String & _data); + void duerParse(const String & _data); + void miotParse(const String & _data); + #endif + + #if defined(BLINKER_AT_MQTT) + blinker_at_status_t _status = BL_BEGIN; + blinker_at_aligenie_t _aliType = ALI_NONE; + blinker_at_dueros_t _duerType = DUER_NONE; + uint8_t _wlanMode = BLINKER_CMD_COMCONFIG_NUM; + uint8_t pinDataNum = 0; + class BlinkerSlaverAT * _slaverAT; + class PinData * _pinData[BLINKER_MAX_PIN_NUM]; + + void parseATdata(); + String getMode(uint8_t mode); + bool serialAvailable(); + void serialPrint(const String & s); + void atHeartbeat(); + #endif + + #if defined(BLINKER_NB73_NBIOT) + #endif + + protected : + uint32_t log_time = 0; + void begin(); + + void needInit(); + + #if defined(BLINKER_AT_MQTT) + void atBegin(); + #endif + + #if defined(BLINKER_MQTT_AT) + void atInit(const char* _auth); + void atInit(const char* _auth, const char* _ssid, const char* _pswd); + #endif + + #if defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + const char* _vipKey; + #endif + #if defined(BLINKER_PRO) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_WIFI_SUBDEVICE) + #if !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) + #if !defined(BLINKER_WIFI_SUBDEVICE) + bool beginPro() { return wlanRun(); } + BlinkerWlan Bwlan; + #endif + void begin(const char* _type); + void begin(const char* _key, const char* _type); + + const char* _deviceType; + const char* _vipKey; + #endif + + blinker_callback_with_json_arg_t _parseFunc = NULL; + + #if defined(BLINKER_BUTTON_LONGPRESS_POWERDOWN) + blinker_callback_t _powerdownFunc = NULL; + blinker_callback_t _resetFunc = NULL; + #endif + // OneButton button1; + + int _pin; // hardware pin number. + int _debounceTicks; // number of ticks for debounce times. + int _clickTicks; // number of ticks that have to pass by before a click is detected + int _pressTicks; // number of ticks that have to pass by before a long button press is detected + + int _buttonReleased; + int _buttonPressed; + + bool _isLongPressed; + + // These variables will hold functions acting as event source. + blinker_callback_t _clickFunc; + blinker_callback_t _doubleClickFunc; + blinker_callback_t _pressFunc; + blinker_callback_t _longPressStartFunc; + blinker_callback_t _longPressStopFunc; + blinker_callback_t _duringLongPressFunc; + blinker_callback_t _noButtonResetFunc; + + // These variables that hold information across the upcoming tick calls. + // They are initialized once on program start and are updated every time the tick function is called. + int _state; + unsigned long _startTime; // will be set in state 1 + unsigned long _stopTime; // will be set in state 2 + + #if !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_WIFI_SUBDEVICE) + bool wlanRun() + { + #if defined(BLINKER_BUTTON) + tick(); + #endif + return Bwlan.run(); + } + + uint8_t wlanStatus() { return Bwlan.status(); } + #endif + + bool isPressed = false; + + void _click() { BLINKER_LOG_ALL(BLINKER_F("Button click.")); } // click + + void _doubleClick() { BLINKER_LOG_ALL(BLINKER_F("Button doubleclick.")); } // doubleclick1 + + void _longPressStart() + { + BLINKER_LOG_ALL(BLINKER_F("Button longPress start")); + // _longPressStartFunc(); + isPressed = true; + } // longPressStart + + void _longPress() + { + if (isPressed) + { + BLINKER_LOG_ALL(BLINKER_F("Button longPress...")); + isPressed = false; + }// _duringLongPressFunc(); + } // longPress + + void _longPressStop() + { + BLINKER_LOG_ALL(BLINKER_F("Button longPress stop")); + // _longPressStopFunc(); + // Bwlan.deleteConfig(); + // Bwlan.reset(); + // ESP.restart(); + // reset(); + + uint32_t _pressedTime = millis() - _startTime; + + BLINKER_LOG_ALL(BLINKER_F("_stopTime: "), millis(), BLINKER_F(" ,_startTime: "), _startTime); + BLINKER_LOG_ALL(BLINKER_F("long pressed time: "), _pressedTime); + + #if defined(BLINKER_BUTTON_LONGPRESS_POWERDOWN) + if (_pressedTime >= BLINKER_PRESSTIME_RESET) { + if (_resetFunc) { + _resetFunc(); + } + + reset(); + } + else { + BLINKER_LOG(BLINKER_F("BLINKER_PRESSTIME_POWERDOWN")); + + if (_powerdownFunc) { + _powerdownFunc(); + } + } + #else + // if (_resetFunc) { + // _resetFunc(); + // } + #if !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) + reset(); + #endif + #endif + } // longPressStop + + void buttonInit(int activeLow = true) + { + _pin = BLINKER_BUTTON_PIN; + + _debounceTicks = 50; // number of millisec that have to pass by before a click is assumed as safe. + _clickTicks = 600; // number of millisec that have to pass by before a click is detected. + _pressTicks = 1000; // number of millisec that have to pass by before a long button press is detected. + + _state = 0; // starting with state 0: waiting for button to be pressed + _isLongPressed = false; // Keep track of long press state + + if (activeLow) { + // the button connects the input pin to GND when pressed. + _buttonReleased = HIGH; // notPressed + _buttonPressed = LOW; + + // use the given pin as input and activate internal PULLUP resistor. + pinMode( _pin, INPUT_PULLUP ); + + } else { + // the button connects the input pin to VCC when pressed. + _buttonReleased = LOW; + _buttonPressed = HIGH; + + // use the given pin as input + pinMode(_pin, INPUT); + } // if + + _clickFunc = NULL; + _doubleClickFunc = NULL; + _pressFunc = NULL; + _longPressStartFunc = NULL; + _longPressStopFunc = NULL; + _duringLongPressFunc = NULL; + + // attachInterrupt(BLINKER_BUTTON_PIN, checkButton, CHANGE); + + BLINKER_LOG_ALL(BLINKER_F("Button initialled")); + } + + #endif + + uint32_t debug_time = 0; + + // #if defined(BLINKER_WIFI_SUBDEVICE) + // uint32_t broadcastTime = 0; + // bool needBroadcast = false; + // uint8_t broadcastTimes = 0; + // #endif + + #if defined(BLINKER_NB73_NBIOT) + uint32_t nb_run_time = 0; + + uint32_t nb_msgId = 0; + + uint32_t nb_online_time = 0; + + b_nbiot_status_t nbiot_status = NB_INIT; + + #define BLINKER_NB_OBJECT_ID 3300 + + void atInit(); + + bool checkOK(); + + void nbRun(); + #endif + + #if defined(BLINKER_GPRS_AIR202) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + Stream* stream; + bool isHWS = false; + blinker_callback_t listenFunc = NULL; + + void begin(const char* _type, Stream& s, bool isHardware, blinker_callback_t _func); + #if defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + void begin(const char* _auth, const char* _type, Stream& s, bool isHardware, blinker_callback_t _func); + #endif + void setType(const char* _type) + { + _deviceType = _type; + BLINKER_LOG_ALL(BLINKER_F("API deviceType: "), _type); + } + + const char* type() { return _deviceType; } + const char* _deviceType; + + String getIMEI(); + bool powerCheck(); + bool httpGET(const String & host, const String & uri, uint32_t time_out = 5000); + bool httpPOST(const String & _host, const String & _uri, + const String & _msg , const String & _type, + const String & _application, uint32_t time_out = 5000); + #endif + + #if defined(BLINKER_LOWPOWER_AIR202) + void begin(const char* _key, const char* _type, Stream& s, + bool isHardware, blinker_callback_t _func); + #endif +}; + +void BlinkerApi::begin() +{ + BLINKER_LOG(BLINKER_F("")); + #if defined(BLINKER_NO_LOGO) + BLINKER_LOG(BLINKER_F("blinker v"), BLINKER_VERSION, BLINKER_F("\n"), + BLINKER_F(" To better use blinker with your IoT project!\n"), + BLINKER_F(" Download latest blinker library here!\n"), + BLINKER_F(" => https://github.com/blinker-iot/blinker-library\n")); + #elif defined(BLINKER_LOGO_3D) + BLINKER_LOG(BLINKER_F("\n"), + BLINKER_F(" __ __ __\n"), + BLINKER_F("/\\ \\ /\\ \\ __ /\\ \\ v"), BLINKER_VERSION, BLINKER_F("\n"), + BLINKER_F("\\ \\ \\___ \\ \\ \\ /\\_\\ ___\\ \\ \\/'\\ __ _ __ \n"), + BLINKER_F(" \\ \\ '__`\\\\ \\ \\ \\/\\ \\ /' _ `\\ \\ , < /'__`\\/\\`'__\\ \n"), + BLINKER_F(" \\ \\ \\L\\ \\\\ \\ \\_\\ \\ \\/\\ \\/\\ \\ \\ \\\\`\\ /\\ __/\\ \\ \\./ \n"), + BLINKER_F(" \\ \\_,__/ \\ \\__\\\\ \\_\\ \\_\\ \\_\\ \\_\\ \\_\\ \\____\\\\ \\_\\ \n"), + BLINKER_F(" \\/___/ \\/__/ \\/_/\\/_/\\/_/\\/_/\\/_/\\/____/ \\/_/ \n"), + BLINKER_F(" To better use blinker with your IoT project!\n"), + BLINKER_F(" Download latest blinker library here!\n"), + BLINKER_F(" => https://github.com/blinker-iot/blinker-library\n")); + #else + BLINKER_LOG(BLINKER_F("\n"), + BLINKER_F(". . . v"), BLINKER_VERSION, BLINKER_F("\n"), + BLINKER_F("|-. | . ,-. | , ,-. ,-.\n"), + BLINKER_F("| | | | | | |< |-' |\n"), + BLINKER_F("`-' `' ' ' ' ' ` `-' '\n"), + BLINKER_F("To better use blinker with your IoT project!\n"), + BLINKER_F("Download latest blinker library here!\n"), + BLINKER_F("=> https://github.com/blinker-iot/blinker-library\n")); + #endif + + #if defined(BLINKER_OTA_VERSION_CODE) && (defined(BLINKER_MQTT) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_MQTT_AUTO) || defined(BLINKE_HTTP)) + if (strlen(BLINKER_OTA_VERSION_CODE) >= BLINKER_OTA_INFO_SIZE) + { + while(1) + { + BLINKER_ERR_LOG(BLINKER_F("The OTA version code you set is too long!")); + ::delay(10000); + } + } + #endif +} + +void BlinkerApi::needInit() +{ + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_LOWPOWER_AIR202) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) || defined(BLINKE_HTTP) + BLINKER_LOG_ALL(BLINKER_F("==== needInit ====")); + #if !defined(BLINKER_LOWPOWER_AIR202) + String _shareData = freshSharers(); + if (STRING_contains_string(_shareData, "users") == false) + { + _shareData = freshSharers(); + } + if (STRING_contains_string(_shareData, "users") == true) + { + BProto::sharers(_shareData); + } + #endif + + // push("Hello blinker!"); + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + loadTiming(); + #endif + + ::delay(100); + + // BProto::ping(); + // BProto::disconnect(); + // BProto::connect(); + + #if defined(BLINKER_LOWPOWER)// || defined(BLINKER_LOWPOWER_AIR202) + int32_t _freq_get = comFreqGet(); + + if (_freq_get < 1) _freq_get = comFreqGet(); + + if (_freq_get >= 1) _LowPowerFreq = _freq_get; + #endif + #endif + + #if defined(BLINKER_AT_MQTT) + String reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_BLINKER_MQTT; + reqData += BLINKER_F(":"); + reqData += BProto::deviceId(); + reqData += BLINKER_F(","); + reqData += BProto::uuid(); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + #endif +} + +#if defined(BLINKER_PRO) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_WIFI_SUBDEVICE) + void BlinkerApi::begin(const char* _type) + { + #if defined(BLINKER_NO_BUTTON) + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_POWER_ON_COUNT, _power_count); + _power_count += 1; + EEPROM.put(BLINKER_EEP_ADDR_POWER_ON_COUNT, _power_count); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG(BLINKER_F("_power_count: "), _power_count); + + _reset_countdown = millis(); + if (_power_count > 3) + { + if (_noButtonResetFunc) _noButtonResetFunc(); + } + #endif + + begin(); + + BLINKER_LOG_ALL(BLINKER_F( + "\n===========================================================" + "\n================= Blinker PRO mode init ! =================" + "\n EEPROM address 1280-1535 is used for PRO ESP Mode!" + "\n========= PLEASE AVOID USING THESE EEPROM ADDRESS! ========" + "\n===========================================================\n")); + + // BLINKER_LOG(BLINKER_F("Already used: "), BLINKER_ONE_AUTO_DATA_SIZE); + + #if defined(BLINKER_BUTTON) + #if defined(BLINKER_BUTTON_PULLDOWN) + buttonInit(false); + #else + buttonInit(); + #endif + #endif + + setType(_type); + } + + void BlinkerApi::begin(const char* _key, const char* _type) + { + _vipKey = _key; + begin(_type); + } +#endif + +#if defined(BLINKER_GPRS_AIR202) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) + void BlinkerApi::begin(const char* _type, Stream& s, + bool isHardware, blinker_callback_t _func) + { + begin(); + + setType(_type); + + stream = &s; isHWS = isHardware; + listenFunc = _func; + } + #if defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + void BlinkerApi::begin(const char* _auth, + const char* _type, + Stream& s, bool isHardware, + blinker_callback_t _func) + { + _vipKey = _auth; + setType(_type); + // begin(_type); + begin(); + + // setType(_type); + + stream = &s; isHWS = isHardware; + listenFunc = _func; + } + #endif +#endif + +#if defined(BLINKER_LOWPOWER_AIR202) + void BlinkerApi::begin(const char* _key, const char* _type, Stream& s, + bool isHardware, blinker_callback_t _func) + { + _vipKey = _key; + begin(); + + setType(_type); + + stream = &s; isHWS = isHardware; + listenFunc = _func; + } +#endif + +void BlinkerApi::run() +{ + // #if defined(BLINKER_LOWPOWER_AIR202) + // delayMicroseconds(1); + // #else + // BLINKER_LOG_ALL(BLINKER_F("BProto::run00001")); + #if defined(BLINKER_WIFI_SUBDEVICE) + #if defined(BLINKER_BUTTON) + tick(); + #endif + + #if defined(BLINKER_NO_BUTTON) + if (millis() > 5000 && !_isCheckPower) + { + _isCheckPower = true; + BLINKER_LOG_ALL(BLINKER_F("erase power count")); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_POWER_ON_COUNT, 0); + EEPROM.commit(); + EEPROM.end(); + } + + if (_power_count > 3) + { + if (millis() - _reset_countdown > 5000) + { + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_POWER_ON_COUNT, 0); + EEPROM.commit(); + EEPROM.end(); + + reset(); + } + } + #endif + + if (!_isConnBegin) + { + BProto::begin(key(), type()); + _isConnBegin = true; + } + #endif + + // BLINKER_LOG_ALL(BLINKER_F("BProto::run0001")); + + #if defined(BLINKER_PRO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_GATEWAY) + #if defined(BLINKER_NO_BUTTON) + if (millis() > 5000 && !_isCheckPower) + { + _isCheckPower = true; + BLINKER_LOG_ALL("erase power count"); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_POWER_ON_COUNT, 0); + EEPROM.commit(); + EEPROM.end(); + } + + if (_power_count > 3) + { + if (millis() - _reset_countdown > 5000) + { + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_POWER_ON_COUNT, 0); + EEPROM.commit(); + EEPROM.end(); + + reset(); + } + } + #endif + + if (!wlanRun()) + { + uint8_t wl_status = wlanStatus(); + + if (wl_status == BWL_SMARTCONFIG_BEGIN) { + _proStatus = PRO_WLAN_SMARTCONFIG_BEGIN; + } + else if (wl_status == BWL_SMARTCONFIG_DONE) { + _proStatus = PRO_WLAN_SMARTCONFIG_DONE; + } + else if (wl_status == BWL_APCONFIG_BEGIN) { + _proStatus = PRO_WLAN_APCONFIG_BEGIN; + } + else if (wl_status == BWL_APCONFIG_DONE) { + _proStatus = PRO_WLAN_APCONFIG_DONE; + } + else { + _proStatus = PRO_WLAN_CONNECTING; + } + return; + } + else + { + if (!_isConnBegin) + { + _proStatus = PRO_WLAN_CONNECTED; + + // if (checkCanOTA()) loadOTA(); + + #if defined(BLINKER_PRO) + BProto::begin(type()); + #elif defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) + BProto::begin(key(), type()); + #endif + _isConnBegin = true; + _initTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("conn begin, fresh _initTime: "), _initTime); + + // loadOTA(); + + if (BProto::authCheck()) + { + _proStatus = PRO_DEV_AUTHCHECK_SUCCESS; + + BLINKER_LOG_ALL(BLINKER_F("is auth, conn deviceRegister")); + + _isRegistered = BProto::deviceRegister(); + _getRegister = true; + + if (!_isRegistered) + { + _register_fresh = millis(); + + _proStatus = PRO_DEV_REGISTER_FAIL; + } + else + { + _proStatus = PRO_DEV_REGISTER_SUCCESS; + } + } + else + { + #if defined(BLINKER_WITHOUT_WS_REG) + _getRegister = true; + _isNew = true; + #endif + _proStatus = PRO_DEV_AUTHCHECK_FAIL; + + BLINKER_LOG_ALL(BLINKER_F("not auth, conn deviceRegister")); + } + + BLINKER_LOG_FreeHeap_ALL(); + } + } + + if (_getRegister) + { + if (_register_times < BLINKER_SERVER_CONNECT_LIMIT) + { + if (!_isRegistered && ((millis() - _register_fresh) > 5000 || \ + _register_fresh == 0)) + { + BLINKER_LOG_ALL(BLINKER_F("conn deviceRegister, _register_times: "), _register_times); + + _isRegistered = BProto::deviceRegister(); + + if (!_isRegistered) + { + _register_fresh = millis(); + _proStatus = PRO_DEV_REGISTER_FAIL; + + _register_times++; + } + else + { + _isRegistered = true; + _proStatus = PRO_DEV_REGISTER_SUCCESS; + + _register_times = 0; + } + } + } + else + { + if ((millis() - _register_fresh) >= (60000 * 5)) _register_times = 0; + } + } + + if (!BProto::init()) + { + // BLINKER_LOG_ALL(BLINKER_F("check init")); + + yield(); + + if ((millis() - _initTime) >= BLINKER_CHECK_AUTH_TIME && \ + (!_getRegister || _isNew)) + { + reset(); + } + } + else + { + if (!_isInit) + { + if (ntpInit()) + { + BLINKER_LOG_ALL(BLINKER_F("check ntp init")); + _isInit = true; + _isNew = false; + // strcpy(_authKey, conn.authKey()); + // strcpy(_deviceName, conn.deviceName()); + _proStatus = PRO_DEV_INIT_SUCCESS; + + uint32_t connect_time = millis(); + uint32_t time_slot = 0; + + if (checkCanOTA()) //loadOTA(); + { + uint8_t ota_check = _OTA.loadOTACheck(); + + if (ota_check == BLINKER_OTA_RUN) + { + _OTA.saveOTACheck(); + updateOTAStatus(10, "download firmware"); + + String otaData = checkOTA(); + + if (otaData != BLINKER_CMD_FALSE) + { + // DynamicJsonBuffer jsonBuffer; + // JsonObject& otaJson = jsonBuffer.parseObject(otaData); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, otaData); + JsonObject otaJson = jsonBuffer.as(); + + // if (!otaJson.success()) + if (error) + { + BLINKER_ERR_LOG_ALL(BLINKER_F("check ota data error")); + return; + } + + // String otaHost = otaJson["host"]; + // String otaUrl = otaJson["url"]; + // String otaFp = otaJson["fingerprint"]; + // String otaMD5 = otaJson["hash"]; + + // _OTA.config(otaHost, otaUrl, otaFp, otaMD5); + _OTA.config(otaJson["host"].as(), otaJson["url"].as(), otaJson["fingerprint"].as(), otaJson["hash"].as()); + + if (_OTA.update()) + { + // _OTA.saveVersion(); + // _OTA.clearOTACheck(); + + // updateOTAStatus(100); + + BProto::freshAlive(); + otaStatus(99, BLINKER_F("Firmware download sucessed")); + updateOTAStatus(99, BLINKER_F("Firmware download sucessed")); + ESP.restart(); + } + else + { + _OTA.clearOTACheck(); + + BProto::freshAlive(); + otaStatus(-2, BLINKER_F("Firmware download failed")); + updateOTAStatus(-2, BLINKER_F("Firmware download failed")); + } + } + } + } + + if (_needInit == false) + { + _needInit = true; + needInit(); + + #if defined(BLINKER_LOWPOWER) + break; + #endif + } + + while (time_slot < 30000) + { + time_slot = millis() - connect_time; + BProto::connect(); + yield(); + + if (BProto::mConnected()) + { + state = CONNECTED; + break; + } + } + // BProto::sharers(freshSharers()); + + beginAuto(); + } + } + else + { + if (state == CONNECTING && _proStatus != PRO_DEV_CONNECTING) { + _proStatus = PRO_DEV_CONNECTING; + } + else if (state == CONNECTED && _proStatus != PRO_DEV_CONNECTED) { + if (BProto::mConnected()) _proStatus = PRO_DEV_CONNECTED; + } + else if (state == DISCONNECTED && _proStatus != PRO_DEV_DISCONNECTED) { + _proStatus = PRO_DEV_DISCONNECTED; + } + } + } + + #endif + + // BLINKER_LOG_ALL(BLINKER_F("BProto::run001")); + + #if defined(BLINKER_MQTT_AUTO) + if (!wlanRun()) + { + uint8_t wl_status = wlanStatus(); + + if (wl_status == BWL_SMARTCONFIG_BEGIN) { + _mqttAutoStatue= AUTO_WLAN_SMARTCONFIG_BEGIN; + } + else if (wl_status == BWL_SMARTCONFIG_DONE) { + _mqttAutoStatue = AUTO_WLAN_SMARTCONFIG_DONE; + } + else { + _mqttAutoStatue = AUTO_WLAN_CONNECTING; + } + return; + } + else + { + // BLINKER_LOG_ALL(BLINKER_F("wlan connected, _isConnBegin: "), _isConnBegin); + if (!_isConnBegin) + { + _mqttAutoStatue = AUTO_WLAN_CONNECTED; + + // if (checkCanOTA()) loadOTA(); + + BProto::begin(key(), type()); + // if (_getRegister) + _isConnBegin = true; + _initTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("conn begin, fresh _initTime: "), _initTime); + + // if (_getRegister) _isConnBegin = true; + // loadOTA(); + + if (BProto::authCheck()) + { + _mqttAutoStatue = AUTO_DEV_AUTHCHECK_SUCCESS; + + BLINKER_LOG_ALL(BLINKER_F("is auth, conn deviceRegister")); + + _isRegistered = BProto::deviceRegister(); + _getRegister = true; + + if (!_isRegistered) + { + _register_fresh = millis(); + + _mqttAutoStatue = AUTO_DEV_REGISTER_FAIL; + + BLINKER_LOG_ALL(BLINKER_F("AUTO_DEV_REGISTER_FAIL")); + } + else + { + _mqttAutoStatue = AUTO_DEV_REGISTER_SUCCESS; + + BLINKER_LOG_ALL(BLINKER_F("AUTO_DEV_REGISTER_SUCCESS")); + } + } + else + { + #if defined(BLINKER_WITHOUT_WS_REG) + _getRegister = true; + _isNew = true; + #endif + _mqttAutoStatue = AUTO_DEV_AUTHCHECK_FAIL; + + BLINKER_LOG_ALL(BLINKER_F("not auth, conn deviceRegister")); + } + + BLINKER_LOG_FreeHeap_ALL(); + } + } + + if (_getRegister) + { + if (_register_times < BLINKER_SERVER_CONNECT_LIMIT) + { + if (!_isRegistered && ((millis() - _register_fresh) > 5000 || \ + _register_fresh == 0)) + { + BLINKER_LOG_ALL(BLINKER_F("conn deviceRegister, _register_times: "), _register_times); + + _isRegistered = BProto::deviceRegister(); + + if (!_isRegistered) + { + _register_fresh = millis(); + _mqttAutoStatue = AUTO_DEV_AUTHCHECK_FAIL; + + _register_times++; + } + else + { + _isRegistered = true; + _mqttAutoStatue = AUTO_DEV_REGISTER_SUCCESS; + + _register_times = 0; + } + } + } + else + { + if ((millis() - _register_fresh) >= (60000 * 5)) _register_times = 0; + } + } + + if (!BProto::init()) + { + yield(); + + if ((millis() - _initTime) >= BLINKER_CHECK_AUTH_TIME && \ + !_getRegister) + { + BLINKER_LOG_ALL(BLINKER_F("NOW RESET!!!")); + reset(); + } + } + else// (BProto::init()) + { + if (!_isInit) + { + BLINKER_LOG_ALL(BLINKER_F("ntpInit")); + if (ntpInit()) + { + _isInit = true; + // strcpy(_authKey, conn.authKey()); + // strcpy(_deviceName, conn.deviceName()); + _mqttAutoStatue = AUTO_DEV_INIT_SUCCESS; + + uint32_t connect_time = millis(); + uint32_t time_slot = 0; + + BLINKER_LOG_ALL(BLINKER_F("checkCanOTA")); + + // if (checkCanOTA()) loadOTA(); + + if (_needInit == false) + { + _needInit = true; + needInit(); + + #if defined(BLINKER_LOWPOWER) + break; + #endif + } + + while (time_slot < 30000) + { + time_slot = millis() - connect_time; + BProto::connect(); + yield(); + + if (BProto::mConnected()) + { + state = CONNECTED; + break; + } + } + // BProto::sharers(freshSharers()); + + beginAuto(); + } + } + else + { + if (state == CONNECTING && _mqttAutoStatue != AUTO_DEV_CONNECTING) { + _mqttAutoStatue = AUTO_DEV_CONNECTING; + } + else if (state == CONNECTED && _mqttAutoStatue != AUTO_DEV_CONNECTED) { + if (BProto::mConnected()) _mqttAutoStatue = AUTO_DEV_CONNECTED; + } + else if (state == DISCONNECTED && _mqttAutoStatue != AUTO_DEV_DISCONNECTED) { + _mqttAutoStatue = AUTO_DEV_DISCONNECTED; + } + } + } + #endif + + // BLINKER_LOG_ALL(BLINKER_F("BProto::run01")); + + #if defined(BLINKER_PRO) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) + ntpInit(); + checkTimer(); + + if (WiFi.status() != WL_CONNECTED) + { + return; + } + #endif + + // BLINKER_LOG_ALL(BLINKER_F("BProto::run0")); + // #if defined(BLINKE_HTTP) + // #endif + // ::delay(1000); + // if (WiFi.status() != WL_CONNECTED) + // { + // BLINKER_LOG_ALL(BLINKER_F("!WL_CONNECTED============")); + // return; + // } + // BLINKER_LOG_ALL(BLINKER_F("============WL_CONNECTED")); + + + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) + checkTimer(); + + if (!BProto::init()) { + ::delay(10); + // BLINKER_LOG_ALL(BLINKER_F("RETURN")); + + #if defined(BLINKER_AT_MQTT) + BProto::connect(); + #endif + return; + } + + if (!_isInit) + { + if (ntpInit()) + { + _isInit =true; + _disconnectTime = millis(); + + uint32_t connect_time = millis(); + uint32_t time_slot = 0; + + bridgeInit(); + + // if (checkCanOTA()) loadOTA(); + + if (_needInit == false) + { + _needInit = true; + needInit(); + + #if defined(BLINKER_LOWPOWER) + return; + #endif + } + + // while (time_slot < 30000) + // { + // time_slot = millis() - connect_time; + // BProto::connect(); + // yield(); + + // if (BProto::mConnected()) + // { + // state = CONNECTED; + // break; + // } + // } + + BLINKER_LOG_ALL(BLINKER_F("millis: "), millis(), + BLINKER_F(", connect_time: "), connect_time); + // BProto::sharers(freshSharers()); + + BLINKER_LOG_ALL(BLINKER_F("MQTT conn init success")); + + beginAuto(); + } + else + { + return; + } + + } + else { + ntpInit(); + } + + #if defined(BLINKER_WIFI_MULTI) + if (wifiMulti.run() != WL_CONNECTED) + { + if ((millis() - _reconTime) >= 10000 || \ + _reconTime == 0 ) + { + _reconTime = millis(); + BLINKER_LOG(BLINKER_F("WiFi disconnected! reconnecting!")); + } + + return; + } + #else + if (WiFi.status() != WL_CONNECTED) + { + if ((millis() - _reconTime) >= 10000 || \ + _reconTime == 0 ) + { + _reconTime = millis(); + BLINKER_LOG(BLINKER_F("WiFi disconnected! reconnecting!")); + WiFi.reconnect(); + } + + return; + } + #endif + #endif + + #if defined(BLINKER_NB73_NBIOT) + nbRun(); + #endif + + #if defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) + if (!_isPowerOn) + { + _gprsStatus = GPRS_DEV_POWER_CHECK; + + _isPowerOn = powerCheck(); + + return; + } + else + { + if (!_isConnBegin) + { + _gprsStatus = GPRS_DEV_POWER_ON; + + BProto::begin(type(), getIMEI()); + _isConnBegin = true; + _initTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("conn begin, fresh _initTime: "), _initTime); + + // if (authCheck()) + // { + // _gprsStatus = GPRS_DEV_AUTHCHECK_SUCCESS; + + // BLINKER_LOG_ALL(BLINKER_F("is auth, conn deviceRegister")); + + _isRegistered = BProto::deviceRegister(); + _getRegister = true; + + if (!_isRegistered) + { + _register_fresh = millis(); + + _gprsStatus = GPRS_DEV_REGISTER_FAIL; + + _registerTimes++; + } + else + { + _gprsStatus = GPRS_DEV_REGISTER_SUCCESS; + + _registerTimes = 0;; + } + // } + // else + // { + // _gprsStatus = GPRS_DEV_AUTHCHECK_FAIL; + + // BLINKER_LOG_ALL(BLINKER_F("not auth, conn deviceRegister")); + // } + + BLINKER_LOG_FreeHeap_ALL(); + } + } + + if (!BProto::init()) + { + yield(); + + if ((millis() - _initTime) >= 15000)// && + // !_isRegistered && _registerTimes < 6) + { + _isRegistered = BProto::deviceRegister(); + + if (!_isRegistered) + { + _register_fresh = millis(); + + _gprsStatus = GPRS_DEV_REGISTER_FAIL; + } + else + { + _gprsStatus = GPRS_DEV_REGISTER_SUCCESS; + } + + _registerTimes++; + } + } + else + { + if (!_isInit) + { + if (ntpInit()) //TBD + { + _isInit = true; + _gprsStatus = GPRS_DEV_INIT_SUCCESS; + + uint32_t connect_time = millis(); + uint32_t time_slot = 0; + + if (_needInit == false) + { + _needInit = true; + needInit(); + + #if defined(BLINKER_LOWPOWER) + return; + #endif + } + + while (time_slot < 30000) + { + time_slot = millis() - connect_time; + BProto::connect(); + yield(); + + if (BProto::mConnected()) + { + state = CONNECTED; + break; + } + } + } + } + else + { + if (state == CONNECTING && _gprsStatus != GPRS_DEV_CONNECTING) { + _gprsStatus = GPRS_DEV_CONNECTING; + } + else if (state == CONNECTED && _gprsStatus != GPRS_DEV_CONNECTED) { + if (BProto::mConnected()) _gprsStatus = GPRS_DEV_CONNECTED; + } + else if (state == DISCONNECTED && _gprsStatus != GPRS_DEV_DISCONNECTED) { + _gprsStatus = GPRS_DEV_DISCONNECTED; + } + } + } + + #endif + + #if defined(BLINKER_LOWPOWER_AIR202) + if (!_isPowerOn) + { + _gprsStatus = GPRS_DEV_POWER_CHECK; + + _isPowerOn = powerCheck(); + + return; + } + else + { + if (!_isConnBegin) + { + _gprsStatus = GPRS_DEV_POWER_ON; + + BProto::begin(_vipKey, type(), getIMEI()); + _isConnBegin = true; + _initTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("conn begin, fresh _initTime: "), _initTime); + + // if (authCheck()) + // { + // _gprsStatus = GPRS_DEV_AUTHCHECK_SUCCESS; + + // BLINKER_LOG_ALL(BLINKER_F("is auth, conn deviceRegister")); + + _isRegistered = BProto::deviceRegister(); + _getRegister = true; + + if (!_isRegistered) + { + _register_fresh = millis(); + + _gprsStatus = GPRS_DEV_REGISTER_FAIL; + + _registerTimes++; + } + else + { + _gprsStatus = GPRS_DEV_REGISTER_SUCCESS; + + _registerTimes = 0;; + } + // } + // else + // { + // _gprsStatus = GPRS_DEV_AUTHCHECK_FAIL; + + // BLINKER_LOG_ALL(BLINKER_F("not auth, conn deviceRegister")); + // } + + BLINKER_LOG_FreeHeap_ALL(); + } + } + + if (!BProto::init()) + { + yield(); + + if ((millis() - _initTime) >= 15000)// && \ + // !_isRegistered && _registerTimes < 6) + { + _isRegistered = BProto::deviceRegister(); + + if (!_isRegistered) + { + _register_fresh = millis(); + + _gprsStatus = GPRS_DEV_REGISTER_FAIL; + } + else + { + _gprsStatus = GPRS_DEV_REGISTER_SUCCESS; + } + + _registerTimes++; + } + } + else + { + if (!_isInit) + { + if (ntpInit()) //TBD + { + _isInit = true; + _gprsStatus = GPRS_DEV_INIT_SUCCESS; + + uint32_t connect_time = millis(); + uint32_t time_slot = 0; + + if (_needInit == false) + { + _needInit = true; + needInit(); + + #if defined(BLINKER_LOWPOWER) + return; + #endif + } + + while (time_slot < 30000) + { + time_slot = millis() - connect_time; + BProto::connect(); + yield(); + + if (BProto::connected()) + { + state = CONNECTED; + break; + } + } + } + } + else + { + if (state == CONNECTING && _gprsStatus != GPRS_DEV_CONNECTING) { + _gprsStatus = GPRS_DEV_CONNECTING; + } + else if (state == CONNECTED && _gprsStatus != GPRS_DEV_CONNECTED) { + if (BProto::connected()) _gprsStatus = GPRS_DEV_CONNECTED; + } + else if (state == DISCONNECTED && _gprsStatus != GPRS_DEV_DISCONNECTED) { + _gprsStatus = GPRS_DEV_DISCONNECTED; + } + } + + } + #endif + + #if defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) + if ((millis() - _checkCrash) >= 60000 || _checkCrash == 0) + { + BLINKER_LOG_ALL(BLINKER_F(">>>>>>check crash<<<<<<")); + + #if defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerSIM7000 BLINKER_SIM7xxx; + #else + BlinkerSIM7020 BLINKER_SIM7xxx; + #endif + BLINKER_SIM7xxx.setStream(*stream, isHWS, listenFunc); + + if (!BLINKER_SIM7xxx.isAlive()) + { + if (_resetSIMFunc) + { + _resetSIMFunc(); + + uint32_t reset_time = millis(); + + while (!BLINKER_SIM7xxx.available()) + { + + yield(); + + if ((millis() - reset_time) >= 60000 * 10) break; + } + + if (BLINKER_SIM7xxx.checkStream("NORMAL POWER DOWN")) + { + ::delay(5000); + _resetSIMFunc(); + powerCheck(); + } + } + } + + if (BLINKER_SIM7xxx.isReboot()) + { + if (_resetSIMFunc) + { + _resetSIMFunc(); + + ::delay(100); + + uint32_t reset_time = millis(); + + while (!BLINKER_SIM7xxx.available()) + { + + yield(); + + if ((millis() - reset_time) >= 6000) break; + } + + if (BLINKER_SIM7xxx.checkStream("NORMAL POWER DOWN")) + { + ::delay(5000); + _resetSIMFunc(); + powerCheck(); + } + } + } + + _checkCrash = millis(); + } + + if (!_isPowerOn) + { + _nbiotStatus = NBIOT_DEV_POWER_CHECK; + + _isPowerOn = powerCheck(); + + return; + } + else + { + if (!_isConnBegin) + { + _nbiotStatus = NBIOT_DEV_POWER_ON; + + #if defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BProto::begin(_vipKey, type(), getIMEI()); + #else + BProto::begin(type(), getIMEI()); + #endif + _isConnBegin = true; + _initTime = millis(); + + BLINKER_LOG_ALL(BLINKER_F("conn begin, fresh _initTime: "), _initTime); + + ::delay(5000); + // if (authCheck()) + // { + // _nbiotStatus = NBIOT_DEV_AUTHCHECK_SUCCESS; + + // BLINKER_LOG_ALL(BLINKER_F("is auth, conn deviceRegister")); + + _isRegistered = BProto::deviceRegister(); + _getRegister = true; + + if (!_isRegistered) + { + _register_fresh = millis(); + + _nbiotStatus = NBIOT_DEV_REGISTER_FAIL; + + _registerTimes++; + } + else + { + _nbiotStatus = NBIOT_DEV_REGISTER_SUCCESS; + + _registerTimes = 0;; + } + // } + // else + // { + // _nbiotStatus = NBIOT_DEV_AUTHCHECK_FAIL; + + // BLINKER_LOG_ALL(BLINKER_F("not auth, conn deviceRegister")); + // } + + BLINKER_LOG_FreeHeap_ALL(); + } + } + + if (!BProto::init()) + { + yield(); + + if ((millis() - _initTime) >= 15000)// && + // !_isRegistered && _registerTimes < 6) + { + _isRegistered = BProto::deviceRegister(); + + if (!_isRegistered) + { + _register_fresh = millis(); + + _nbiotStatus = NBIOT_DEV_REGISTER_FAIL; + } + else + { + _nbiotStatus = NBIOT_DEV_REGISTER_SUCCESS; + } + + _registerTimes++; + } + } + else + { + if (!_isInit) + { + if (ntpInit()) //TBD + { + _isInit = true; + _nbiotStatus = NBIOT_DEV_INIT_SUCCESS; + + uint32_t connect_time = millis(); + uint32_t time_slot = 0; + + if (_needInit == false) + { + _needInit = true; + needInit(); + + #if defined(BLINKER_LOWPOWER) + return; + #endif + } + + while (time_slot < 30000) + { + time_slot = millis() - connect_time; + BProto::connect(); + yield(); + + if (BProto::mConnected()) + { + state = CONNECTED; + break; + } + } + } + } + else + { + if (state == CONNECTING && _nbiotStatus != NBIOT_DEV_CONNECTING) { + _nbiotStatus = NBIOT_DEV_CONNECTING; + } + else if (state == CONNECTED && _nbiotStatus != NBIOT_DEV_CONNECTED) { + if (BProto::mConnected()) _nbiotStatus = NBIOT_DEV_CONNECTED; + } + else if (state == DISCONNECTED && _nbiotStatus != NBIOT_DEV_DISCONNECTED) { + _nbiotStatus = NBIOT_DEV_DISCONNECTED; + } + } + + } + #endif + + // BLINKER_LOG_ALL(BLINKER_F("BProto::run1")); + + #if defined(BLINKER_LOWPOWER) || defined(BLINKER_LOWPOWER_AIR202) + BLINKER_LOG_ALL(BLINKER_F("LOW POWER")); + + char _lp_data_get[1024]; + strcpy(_lp_data_get, comDataGet().c_str()); + if (_lp_data_get == BLINKER_CMD_FALSE) strcpy(_lp_data_get, ""); + else if (strcmp(_lp_data_get, "{}") == 0) strcpy(_lp_data_get, ""); + else + { + flush(); + parse(_lp_data_get); + + if (!_fresh) + { + if (BProto::_availableFunc) + { + BProto::_availableFunc(_lp_data_get); + flush(); + } + } + } + + if (_LowPowerFunc) _LowPowerFunc(); + + if (strlen(BProto::_sendBuf)) + { + if (!comDateUpdate()) comDateUpdate(); + } + // ::delay(60000); // sleep func TBD + if (_sleepFunc) _sleepFunc(); + return; + #endif + + // BLINKER_LOG_ALL(BLINKER_F("BProto::run")); + + // #if defined(BLINKER_LOWPOWER_AIR202) + // BProto::checkAutoFormat(); + // return; // TBD + // #endif + + bool conState = BProto::connect(); + + // delay(10); + + #if defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_WIFI_SUBDEVICE) + BProto::meshCheck(); + + if (!_isInit) + { + _isInit = BProto::init(); + + if (_isInit) + { + freshSharers(); + } + } + + #if defined(BLINKER_WIFI_SUBDEVICE) + if (BProto::meshAvail()) + { + BLINKER_LOG_ALL("meshAvail"); + + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, BProto::meshLastRead()); + JsonObject root = jsonBuffer.as(); + + if (error) + { + BProto::meshFlush(); + return; + } + + if (root.containsKey("aqi")) + { + if (_airFunc) + { + _airFunc(root["aqi"].as()); + } + } + else if (root.containsKey("weather")) + { + if (_weatherFunc) + { + _weatherFunc(root["weather"].as()); + } + } + else if (root.containsKey("weather")) + { + if (_weather_forecast_Func) + { + _weather_forecast_Func(root["weather_forecast"].as()); + } + } + else if (root.containsKey("configGet")) + { + if (_configGetFunc) + { + _configGetFunc(root["configGet"].as()); + } + } + else if (root.containsKey("dataGet")) + { + if (_dataGetFunc) + { + _dataGetFunc(root["dataGet"].as()); + } + } + else if (root.containsKey("autoPull")) + { + String payload; + serializeJson(root, payload); + + if (payload != BLINKER_CMD_FALSE) + { + // DynamicJsonBuffer jsonBuffer; + // JsonObject& autoJson = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + deserializeJson(jsonBuffer, payload); + JsonObject autoJson = jsonBuffer.as(); + + autoManager(autoJson); + } + } + else if (root.containsKey("freshSharers")) + { + String _shareData = root["freshSharers"].as(); + + if (STRING_contains_string(_shareData, "users") == true) + { + BProto::sharers(_shareData); + } + } + + BProto::meshFlush(); + } + #endif + #endif + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_WIFI_SUBDEVICE) || \ + defined(BLINKE_HTTP) + if (((millis() - _dHeartTime)/1000 >= BLINKER_DEVICE_HEARTBEAT_TIME) && _isInit) + { + deviceHeartbeat(); + _dHeartTime = millis(); + } + #endif + + // if (millis() - log_time >= 1000) + // { + // BLINKER_LOG_ALL(BLINKER_F("BProto::run1")); + // log_time += 1000; + // BLINKER_LOG_ALL(BLINKER_F("BProto::state: "), BProto::state); + // } + + switch (BProto::state) + { + // BLINKER_LOG_ALL(BLINKER_F("BProto::state: "), BProto::state); + case CONNECTING : + if (BProto::connect()) + { + BProto::state = CONNECTED; + + #if defined(BLINKER_MQTT) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_MQTT_AUTO) + _disconnectCount = 0; + #endif + } + else + { + #if defined(BLINKER_MQTT) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_MQTT_AUTO) + if (_isInit) + { + if (_disconnectCount == 0) + { + _disconnectCount++; + _disconnectTime = millis(); + _disFreshTime = millis(); + } + else + { + // if ((millis() > _disFreshTime) && (millis() - _disFreshTime) >= 5000) { + if ((millis() - _disFreshTime) >= BLINKER_MQTT_CONNECT_TIMESLOT) + { + _disFreshTime = millis(); + _disconnectCount++; + + if (_disconnectCount > 12) _disconnectCount = 12; + + BLINKER_LOG_ALL(BLINKER_F("_disFreshTime: "), _disFreshTime); + BLINKER_LOG_ALL(BLINKER_F("_disconnectCount: "), _disconnectCount); + } + } + } + #endif + } + break; + case CONNECTED : + #if defined(BLINKER_PRO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_GATEWAY) + if (!otaInit) + { + if (checkCanOTA()) loadOTA(); + otaInit = true; + } + #endif + + if (conState) + { + BProto::checkAvail(); + + if (BProto::isAvail) + { + parse(BProto::dataParse()); + } + + #if (defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_WIFI_GATEWAY)) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_SUBDEVICE) + #if defined(BLINKER_ALIGENIE) + if (BProto::checkAliAvail()) + { + aliParse(BProto::lastRead()); + } + #endif + + #if defined(BLINKER_DUEROS) + if (BProto::checkDuerAvail()) + { + duerParse(BProto::lastRead()); + } + #endif + + #if defined(BLINKER_MIOT) + if (BProto::checkMIOTAvail()) + { + miotParse(BProto::lastRead()); + } + #endif + #endif + + #if defined(BLINKER_MQTT_AT) + #if defined(BLINKER_ALIGENIE) + if (isAvail) + { + aliParse(BProto::lastRead()); + + if (STRING_contains_string(BProto::lastRead(), "AliGenie")) + { + flush(); + } + + } + #endif + + #if defined(BLINKER_DUEROS) + if (isAvail) + { + duerParse(BProto::lastRead()); + + if (STRING_contains_string(BProto::lastRead(), "DuerOS")) + { + flush(); + } + } + #endif + + #if defined(BLINKER_MIOT) + if (isAvail) + { + miotParse(BProto::lastRead()); + + if (STRING_contains_string(BProto::lastRead(), "MIOT")) + { + flush(); + } + } + #endif + #endif + + #if defined(BLINKER_AT_MQTT) + if (isAvail) + { + // BLINKER_LOG_ALL("isAvail"); + BProto::serialPrint(BProto::lastRead()); + } + + if (serialAvailable()) + { + BProto::mqttPrint(BProto::serialLastRead()); + } + + if (BProto::checkAliAvail()) + { + BProto::serialPrint(BProto::lastRead()); + } + + if (BProto::checkDuerAvail()) + { + BProto::serialPrint(BProto::lastRead()); + } + #endif + + if (BProto::availState) + { + BProto::availState = false; + + if (BProto::_availableFunc) + { + BProto::_availableFunc(BProto::lastRead()); + flush(); + } + } + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) + if (BProto::needFreshShare()) + { + String _shareData = freshSharers(); + if (STRING_contains_string(_shareData, "users") == false) + { + _shareData = freshSharers(); + } + if (STRING_contains_string(_shareData, "users") == true) + { + BProto::sharers(_shareData); + } + } + #endif + } + else + { + BProto::disconnect(); + BProto::state = CONNECTING; + + #if defined(BLINKER_MQTT) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_MQTT_AUTO) + if (_isInit) + { + if (_disconnectCount == 0) + { + _disconnectCount++; + _disconnectTime = millis(); + _disFreshTime = millis(); + } + else + { + if ((millis() - _disFreshTime) >= 5000) + { + _disFreshTime = millis(); + _disconnectCount++; + + if (_disconnectCount > 6) _disconnectCount = 6; + + BLINKER_LOG_ALL(BLINKER_F("_disFreshTime: "), _disFreshTime); + BLINKER_LOG_ALL(BLINKER_F("_disconnectCount: "), _disconnectCount); + + // ESP.restart(); + } + } + } + #endif + } + break; + case DISCONNECTED : + BProto::disconnect(); + BProto::state = CONNECTING; + break; + } + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_WIFI_SUBDEVICE) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + + #if !defined(BLINKER_GPRS_AIR202) && !defined(BLINKER_NBIOT_SIM7020) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000) + if (_isAuto && _isInit && state == CONNECTED && !_isAutoInit) + { + // if (autoPull()) _isAutoInit = true; + // else + // { + // if (autoPull()) _isAutoInit = true; + // } // TODO + } + #endif + + // #if !defined(BLINKER_AT_MQTT) + if (_dataStorageFunc) + { + if (millis() - _autoDataTime >= _autoStorageTime * 1000) + { + _dataStorageFunc(); + _autoDataTime += _autoStorageTime * 1000; + } + } + + if (millis() - _autoUpdateTime >= _autoStorageTime * _dataTimes * 1000) + { + // BLINKER_LOG_ALL("dataUpdate data_dataCount: ", data_dataCount); + // BLINKER_LOG_ALL("_isInit: ", _isInit); + + if ((data_dataCount || data_timeSlotDataCount) && _isInit)// && ESP.getFreeHeap() > 4000) + { + // if (dataUpdate()) _autoUpdateTime = millis(); + if (dataUpdate()) _autoUpdateTime = millis(); + else + { + #if defined(BLINKER_GPRS_AIR202) || defined(BLINKER_LOWPOWER_AIR202) + BLINKER_LOG_ALL("need reset!"); + if (_resetAIRFunc) _resetAIRFunc(); + #elif defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + // stream->println(BLINKER_CMD_CRESET_RESQ); + // ::delay(5000); + // BLINKER_LOG_ALL("need reset!"); + // if (_resetSIMFunc) _resetSIMFunc(); + #if defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerSIM7000 BLINKER_SIM7xxx; + #else + BlinkerSIM7020 BLINKER_SIM7xxx; + #endif + + BLINKER_SIM7xxx.setStream(*stream, isHWS, listenFunc); + if (_resetSIMFunc) + { + _resetSIMFunc(); + + ::delay(100); + + uint32_t reset_time = millis(); + + while (!BLINKER_SIM7xxx.available()) + { + + yield(); + + if ((millis() - reset_time) >= 6000) break; + } + + if (BLINKER_SIM7xxx.checkStream("NORMAL POWER DOWN")) + { + ::delay(5000); + _resetSIMFunc(); + powerCheck(); + } + } + _nbiotStatus = NBIOT_DEV_POWER_CHECK; + _isPowerOn = false; + // BProto::disconnect(); + #endif + _autoUpdateTime = millis() - 100000; + } + } + } + // #endif + #endif + + BProto::checkAutoFormat(); + // #endif +} + +#if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_PRO_ESP) +void BlinkerApi::rtParse(const JsonObject& data) +{ + String get_key = data[_RTDataKey][BLINKER_CMD_GET]; + // BLINKER_LOG_ALL(BLINKER_F("_RTDataKey: "), _RTDataKey); + BLINKER_LOG_ALL(BLINKER_F("get_key: "), get_key); + // BLINKER_LOG_ALL(BLINKER_F("strncmp: "), strncmp(_RTDataKey, get_key.c_str(), strlen(_RTDataKey)) == 0); + if (get_key != "null") + { + _fresh = true; + if (_RTDataFunc) + { + _RTTicker.once(15, _RTDataFunc); + } + } +} +#endif + +void BlinkerApi::parse(char _data[], bool ex_data) +{ + BLINKER_LOG_ALL(BLINKER_F("parse data: "), _data); + + if (!ex_data) + { + if (BProto::parseState()) + { + _fresh = false; + + #if defined(BLINKER_ARDUINOJSON) + BLINKER_LOG_ALL(BLINKER_F("defined BLINKER_ARDUINOJSON")); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(STRING_format(_data)); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, STRING_format(_data)); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + // #if defined(BLINKER_MQTT_AT) + // atResp(); + // #endif + return; + } + + #if defined(BLINKER_PRO) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) + checkRegister(root); + #endif + + // #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) + + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKE_HTTP) + timerManager(root); + // BLINKER_LOG_ALL(BLINKER_F("timerManager")); + #endif + + #if defined(BLINKER_GPRS_AIR202) + shareParse(root); + #endif + + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) + + #endif + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKE_HTTP) + shareParse(root); + autoManager(root); + + #if !defined(BLINKER_AT_MQTT) + rtParse(root); + #endif + #if !defined(BLINKER_WIFI_SUBDEVICE) + otaParse(root); + numParse(root); + + for (uint8_t bNum = 0; bNum < _bridgeCount; bNum++) + { + bridgeParse(_Bridge[bNum]->getName(), bNum, root); + } + #endif + #endif + + heartBeat(root); + getVersion(root); + + json_parse(root); + + ahrs(Yaw, root); + gps(LONG, root); + + // #if defined(BLINKER_WIFI_SUBDEVICE) + // broadCast(root); + // #endif + #else + BLINKER_LOG_ALL(BLINKER_F("ndef BLINKER_ARDUINOJSON")); + + #if defined(BLINKER_MQTT_AT) + // atResp(); + + if (STRING_contains_string(_data, "AliGenie") || \ + STRING_contains_string(_data, "DuerOS")) + return; + #endif + + heartBeat(_data); + getVersion(_data); + + json_parse(_data); + + ahrs(Yaw, _data); + gps(LONG, _data); + #endif + + if (_fresh) + { + BLINKER_LOG_ALL(BLINKER_F("_fresh need flush")); + BProto::isParsed(); + } + else + { + #if defined(BLINKER_PRO) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) + if (_parseFunc) { + if(_parseFunc(root)) { + BLINKER_LOG_ALL(BLINKER_F("_parseFunc(root) isParsed")); + _fresh = true; + BProto::isParsed(); + } + + BLINKER_LOG_ALL(BLINKER_F("run parse callback function")); + } + #endif + } + } + } + else + { + #if defined(BLINKER_ARDUINOJSON) + String arrayData = BLINKER_F("{\"data\":"); + arrayData += _data; + arrayData += BLINKER_F("}"); + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(arrayData); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, arrayData); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + arrayData = root["data"][0].as(); + + if (arrayData != "null") + { + for (uint8_t a_num = 0; a_num < BLINKER_MAX_WIDGET_SIZE; a_num++) + { + arrayData = root["data"][a_num].as(); + + if(arrayData != "null") { + // DynamicJsonBuffer _jsonBuffer; + // JsonObject& _array = _jsonBuffer.parseObject(arrayData); + DynamicJsonDocument jsonBuffer(1024); + deserializeJson(jsonBuffer, arrayData); + JsonObject _array = jsonBuffer.as(); + + json_parse(_array); + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKE_HTTP) + timerManager(_array, true); + #endif + + #if defined(BLINKER_PRO) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) + if (_parseFunc) { + if(_parseFunc(_array)) { + // _fresh = true; + // BProto::isParsed(); + } + + BLINKER_LOG_ALL(BLINKER_F("run parse callback function")); + } + #endif + } + else { + return; + } + } + } + else { + // JsonObject& root = jsonBuffer.parseObject(_data); + DeserializationError error = deserializeJson(jsonBuffer, _data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + json_parse(root); + + #if defined(BLINKER_PRO) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) + if (_parseFunc) { + if(_parseFunc(root)) { + // _fresh = true; + // BProto::isParsed(); + } + + BLINKER_LOG_ALL(BLINKER_F("run parse callback function")); + } + #endif + } + #else + json_parse(_data); + #endif + } +} + +void BlinkerApi::print() +{ + String _msg = BLINKER_F(""); + + // checkFormat(); + // strcpy(_sendBuf, _msg.c_str()); + // _print(_sendBuf); + // free(_sendBuf); + // autoFormat = false; + BProto::print(_msg); +} + +template +void BlinkerApi::print(T n) +{ + String _msg = BLINKER_F("\""); + _msg += STRING_format(n); + _msg += BLINKER_F("\""); + + // checkFormat(); + // strcpy(_sendBuf, _msg.c_str()); + // _print(_sendBuf); + // free(_sendBuf); + // autoFormat = false; + BProto::print(_msg); +} + +template +void BlinkerApi::print(T1 n1, T2 n2, T3 n3) +{ + String _msg = BLINKER_F("\""); + _msg += STRING_format(n1); + _msg += BLINKER_F("\":\""); + _msg += STRING_format(n2); + _msg += BLINKER_CMD_INTERSPACE; + _msg += STRING_format(n3); + _msg += BLINKER_F("\""); + + // checkFormat(); + // autoFormatData(STRING_format(n1), _msg); + // autoFormatFreshTime = millis(); + BProto::print(STRING_format(n1), _msg); +} + +template +void BlinkerApi::printArray(T1 n1, const String &s2) +{ + String _msg = BLINKER_F("\""); + _msg += STRING_format(n1); + _msg += BLINKER_F("\":"); + _msg += s2; + + // checkFormat(); + // autoFormatData(STRING_format(n1), _msg); + // autoFormatFreshTime = millis(); + BProto::print(STRING_format(n1), _msg); +} + +// template +void BlinkerApi::printNumArray(char * _name, const String & data) +{ + // String _msg = BLINKER_F("\""); + // _msg += STRING_format(n1); + // _msg += BLINKER_F("\":"); + // _msg += s2; + + // // checkFormat(); + // // autoFormatData(STRING_format(n1), _msg); + // // autoFormatFreshTime = millis(); + // BProto::print(STRING_format(n1), _msg); + + int8_t num = checkNum(_name, _Widgets_num, _wCount_num); + + if( num != BLINKER_OBJECT_NOT_AVAIL ) + { + if (_Widgets_num[num]->state()) + { + #if (defined(ESP8266) || defined(ESP32)) && \ + (defined(BLINKER_MQTT) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_PRO) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKE_HTTP)) + dataStorage(_name, data); + #endif + } + } +} + +template +void BlinkerApi::printObject(T1 n1, const String &s2) +{ + String _msg = BLINKER_F("\""); + _msg += STRING_format(n1); + _msg += BLINKER_F("\":"); + _msg += s2; + + // checkFormat(); + // autoFormatData(STRING_format(n1), _msg); + // autoFormatFreshTime = millis(); + BProto::print(STRING_format(n1), _msg); +} + +template +void BlinkerApi::print(T1 n1, const String &s2) +{ + String _msg = BLINKER_F("\""); + _msg += STRING_format(n1); + _msg += BLINKER_F("\":\""); + _msg += s2; + _msg += BLINKER_F("\""); + + // checkFormat(); + // autoFormatData(STRING_format(n1), _msg); + // autoFormatFreshTime = millis(); + BProto::print(STRING_format(n1), _msg); +} + +template +void BlinkerApi::print(T1 n1, const char str2[]) +{ + String _msg = BLINKER_F("\""); + _msg += STRING_format(n1); + _msg += BLINKER_F("\":\""); + _msg += STRING_format(str2); + _msg += BLINKER_F("\""); + + // checkFormat(); + // autoFormatData(STRING_format(n1), _msg); + // autoFormatFreshTime = millis(); + BProto::print(STRING_format(n1), _msg); +} + +template +void BlinkerApi::print(T1 n1, char c) +{ + String _msg = BLINKER_F("\""); + _msg += STRING_format(n1); + _msg += BLINKER_F("\":"); + _msg += STRING_format(c); + + // checkFormat(); + // autoFormatData(STRING_format(n1), _msg); + // autoFormatFreshTime = millis(); + BProto::print(STRING_format(n1), _msg); +} + +template +void BlinkerApi::print(T1 n1, unsigned char b) +{ + String _msg = BLINKER_F("\""); + _msg += STRING_format(n1); + _msg += BLINKER_F("\":"); + _msg += STRING_format(b); + + // checkFormat(); + // autoFormatData(STRING_format(n1), _msg); + // autoFormatFreshTime = millis(); + BProto::print(STRING_format(n1), _msg); +} + +template +void BlinkerApi::print(T1 n1, int n) +{ + String _msg = BLINKER_F("\""); + _msg += STRING_format(n1); + _msg += BLINKER_F("\":"); + _msg += STRING_format(n); + + // checkFormat(); + // autoFormatData(STRING_format(n1), _msg); + // autoFormatFreshTime = millis(); + BProto::print(STRING_format(n1), _msg); +} + +template +void BlinkerApi::print(T1 n1, unsigned int n) +{ + String _msg = BLINKER_F("\""); + _msg += STRING_format(n1); + _msg += BLINKER_F("\":"); + _msg += STRING_format(n); + + // checkFormat(); + // autoFormatData(STRING_format(n1), _msg); + // autoFormatFreshTime = millis(); + BProto::print(STRING_format(n1), _msg); +} + +template +void BlinkerApi::print(T1 n1, long n) +{ + String _msg = BLINKER_F("\""); + _msg += STRING_format(n1); + _msg += BLINKER_F("\":"); + _msg += STRING_format(n); + + // checkFormat(); + // autoFormatData(STRING_format(n1), _msg); + // autoFormatFreshTime = millis(); + BProto::print(STRING_format(n1), _msg); +} + +template +void BlinkerApi::print(T1 n1, unsigned long n) +{ + String _msg = BLINKER_F("\""); + _msg += STRING_format(n1); + _msg += BLINKER_F("\":"); + _msg += STRING_format(n); + + // checkFormat(); + // autoFormatData(STRING_format(n1), _msg); + // autoFormatFreshTime = millis(); + BProto::print(STRING_format(n1), _msg); +} + +template +void BlinkerApi::print(T1 n1, double n) +{ + String _msg = BLINKER_F("\""); + _msg += STRING_format(n1); + _msg += BLINKER_F("\":"); + _msg += STRING_format(n); + + // checkFormat(); + // autoFormatData(STRING_format(n1), _msg); + // autoFormatFreshTime = millis(); + BProto::print(STRING_format(n1), _msg); +} + +template +void BlinkerApi::notify(T n) +{ + print(BLINKER_CMD_NOTICE, STRING_format(n)); +} + +void BlinkerApi::vibrate(uint16_t ms) +{ + if (ms > 1000) ms = 1000; + + print(BLINKER_CMD_VIBRATE, ms); +} + +void BlinkerApi::delay(unsigned long ms) +{ + uint32_t start = micros(); + uint32_t __start = millis(); + unsigned long _ms = ms; + while (ms > 0) + { + run(); + + if ((micros() - start) >= 1000) + { + ms -= 1; + start += 1000; + } + + if ((millis() - __start) >= _ms) + { + ms = 0; + } + + yield(); + } +} + +void BlinkerApi::attachAhrs() +{ + bool state = false; + uint32_t startTime = millis(); + print(BLINKER_CMD_AHRS, BLINKER_CMD_ON); + while (!state) + { + while (!BProto::connected()) + { + run(); + if (BProto::connect()) + { + print(BLINKER_CMD_AHRS, BLINKER_CMD_ON); + BProto::printNow(); + break; + } + } + + ::delay(100); + + if (BProto::checkAvail()) + { + if (STRING_contains_string(BProto::dataParse(), BLINKER_CMD_AHRS)) + { + BLINKER_LOG(BLINKER_F("AHRS attach sucessed...")); + // parse(BProto::dataParse()); + state = true; + break; + } + else + { + BLINKER_LOG(BLINKER_F("AHRS attach failed...Try again")); + startTime = millis(); + // parse(BProto::dataParse()); + print(BLINKER_CMD_AHRS, BLINKER_CMD_ON); + BProto::printNow(); + } + } + else + { + if (millis() - startTime > BLINKER_CONNECT_TIMEOUT_MS) + { + BLINKER_LOG(BLINKER_F("AHRS attach failed...Try again")); + startTime = millis(); + print(BLINKER_CMD_AHRS, BLINKER_CMD_ON); + BProto::printNow(); + } + } + } +} + +void BlinkerApi::detachAhrs() +{ + print(BLINKER_CMD_AHRS, BLINKER_CMD_OFF); + ahrsValue[Yaw] = 0; + ahrsValue[Roll] = 0; + ahrsValue[Pitch] = 0; +} + +float BlinkerApi::gps(b_gps_t axis) +{ + if ((millis() - gps_get_time) >= BLINKER_GPS_MSG_LIMIT || \ + gps_get_time == 0) + { + print(BLINKER_CMD_GET, BLINKER_CMD_GPS); + BProto::printNow(); + delay(100); + } + + return gpsValue[axis]*1000000; +} + +#if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_LOWPOWER_AIR202) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + void BlinkerApi::setTimezone(float tz) + { + _timezone = tz; + _isNTPInit = false; + + #if defined(BLINKER_WIFI_GATEWAY) + BProto::setTimezone(tz); + #endif + } + + int8_t BlinkerApi::second() + { + if (_isNTPInit) + { + time_t _ntpGetTime; + + // if (ntpGetTime == 0 || (millis() - ntpFreshTime) >= 120000) + // { + // BLINKER_LOG_ALL(BLINKER_F("second (millis() - ntpFreshTime): "), (millis() - ntpFreshTime)); + // BLINKER_LOG_ALL(BLINKER_F("ntpGetTime: "), ntpGetTime); + // BLINKER_LOG_ALL((ntpGetTime == 0 || (millis() - ntpFreshTime) >= 600000)); + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + time_t now_ntp = ::time(nullptr); + #elif defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7020.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7020._ntpTime; + #elif defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7000.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7000._ntpTime; + #elif defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + // if (!BLINKER_AIR202.getAMGSMLOC(_timezone)) return -1; + if (!BLINKER_AIR202.getNTP()) return -1; + time_t now_ntp = BLINKER_AIR202._ntpTime; + #endif + + // if (now_ntp > ntpGetTime) + // { + _ntpGetTime = now_ntp + (int)_timezone*3600; + // } + // else + // { + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // } + + ntpGetTime = _ntpGetTime; + ntpFreshTime = millis(); + // } + // else + // { + // #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + // !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + // !defined(BLINKER_LOWPOWER_AIR202)) + // _ntpGetTime = ::time(nullptr) + (int)_timezone*3600; + // #else + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // #endif + // } + + struct tm timeinfo; + + #if defined(ESP8266) || defined(__AVR__) + gmtime_r(&_ntpGetTime, &timeinfo); + #elif defined(ESP32) + _ntpGetTime = _ntpGetTime - (int)_timezone*3600; + + localtime_r(&_ntpGetTime, &timeinfo); + #endif + + return timeinfo.tm_sec; + } + return -1; + } + /**< seconds after the minute - [ 0 to 59 ] */ + + int8_t BlinkerApi::minute() + { + if (_isNTPInit) + { + time_t _ntpGetTime; + + // if (ntpGetTime == 0 || (millis() - ntpFreshTime) >= 120000) + // { + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + time_t now_ntp = ::time(nullptr); + #elif defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7020.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7020._ntpTime; + #elif defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7000.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7000._ntpTime; + #elif defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + // if (!BLINKER_AIR202.getAMGSMLOC(_timezone)) return -1; + if (!BLINKER_AIR202.getNTP()) return -1; + time_t now_ntp = BLINKER_AIR202._ntpTime; + #endif + + // if (now_ntp > ntpGetTime) + // { + _ntpGetTime = now_ntp + (int)_timezone*3600; + // } + // else + // { + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // } + + ntpGetTime = _ntpGetTime; + ntpFreshTime = millis(); + // } + // else + // { + // #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + // !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + // !defined(BLINKER_LOWPOWER_AIR202)) + // _ntpGetTime = ::time(nullptr) + (int)_timezone*3600; + // #else + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // #endif + // } + + struct tm timeinfo; + #if defined(ESP8266) || defined(__AVR__) + gmtime_r(&_ntpGetTime, &timeinfo); + #elif defined(ESP32) + _ntpGetTime = _ntpGetTime - (int)_timezone*3600; + + localtime_r(&_ntpGetTime, &timeinfo); + #endif + + return timeinfo.tm_min; + } + return -1; + } + /**< minutes after the hour - [ 0 to 59 ] */ + + int8_t BlinkerApi::hour() + { + if (_isNTPInit) + { + time_t _ntpGetTime; + + // if (ntpGetTime == 0 || (millis() - ntpFreshTime) >= 120000) + // { + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + time_t now_ntp = ::time(nullptr); + #elif defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7020.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7020._ntpTime; + #elif defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7000.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7000._ntpTime; + #elif defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + // if (!BLINKER_AIR202.getAMGSMLOC(_timezone)) return -1; + if (!BLINKER_AIR202.getNTP()) return -1; + time_t now_ntp = BLINKER_AIR202._ntpTime; + #endif + + // if (now_ntp > ntpGetTime) + // { + _ntpGetTime = now_ntp + (int)_timezone*3600; + // } + // else + // { + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // } + + ntpGetTime = _ntpGetTime; + ntpFreshTime = millis(); + // } + // else + // { + // #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + // !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + // !defined(BLINKER_LOWPOWER_AIR202)) + // _ntpGetTime = ::time(nullptr) + (int)_timezone*3600; + // #else + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // #endif + // } + + struct tm timeinfo; + + #if defined(ESP8266) || defined(__AVR__) + gmtime_r(&_ntpGetTime, &timeinfo); + #elif defined(ESP32) + _ntpGetTime = _ntpGetTime - (int)_timezone*3600; + + localtime_r(&_ntpGetTime, &timeinfo); + #endif + + return timeinfo.tm_hour; + } + return -1; + } + /**< hours since midnight - [ 0 to 23 ] */ + + int8_t BlinkerApi::mday() + { + if (_isNTPInit) + { + time_t _ntpGetTime; + + // if (ntpGetTime == 0 || (millis() - ntpFreshTime) >= 120000) + // { + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + time_t now_ntp = ::time(nullptr); + #elif defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7020.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7020._ntpTime; + #elif defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7000.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7000._ntpTime; + #elif defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + // if (!BLINKER_AIR202.getAMGSMLOC(_timezone)) return -1; + if (!BLINKER_AIR202.getNTP()) return -1; + time_t now_ntp = BLINKER_AIR202._ntpTime; + #endif + + // if (now_ntp > ntpGetTime) + // { + _ntpGetTime = now_ntp + (int)_timezone*3600; + // } + // else + // { + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // } + + ntpGetTime = _ntpGetTime; + ntpFreshTime = millis(); + // } + // else + // { + // #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + // !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + // !defined(BLINKER_LOWPOWER_AIR202)) + // _ntpGetTime = ::time(nullptr) + (int)_timezone*3600; + // #else + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // #endif + // } + + struct tm timeinfo; + + #if defined(ESP8266) || defined(__AVR__) + gmtime_r(&_ntpGetTime, &timeinfo); + #elif defined(ESP32) + _ntpGetTime = _ntpGetTime - (int)_timezone*3600; + + localtime_r(&_ntpGetTime, &timeinfo); + #endif + + return timeinfo.tm_mday; + } + return -1; + } + /**< day of the month - [ 1 to 31 ] */ + + int8_t BlinkerApi::wday() + { + if (_isNTPInit) + { + time_t _ntpGetTime; + // if (ntpGetTime == 0 || (millis() - ntpFreshTime) >= 120000) + // { + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + time_t now_ntp = ::time(nullptr); + #elif defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7020.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7020._ntpTime; + #elif defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7000.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7000._ntpTime; + #elif defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + // if (!BLINKER_AIR202.getAMGSMLOC(_timezone)) return -1; + if (!BLINKER_AIR202.getNTP()) return -1; + time_t now_ntp = BLINKER_AIR202._ntpTime; + #endif + + // if (now_ntp > ntpGetTime) + // { + _ntpGetTime = now_ntp + (int)_timezone*3600; + // } + // else + // { + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // } + + ntpGetTime = _ntpGetTime; + ntpFreshTime = millis(); + // } + // else + // { + // #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + // !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + // !defined(BLINKER_LOWPOWER_AIR202)) + // _ntpGetTime = ::time(nullptr) + (int)_timezone*3600; + // #else + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // #endif + // } + + struct tm timeinfo; + + #if defined(ESP8266) || defined(__AVR__) + gmtime_r(&_ntpGetTime, &timeinfo); + #elif defined(ESP32) + _ntpGetTime = _ntpGetTime - (int)_timezone*3600; + + localtime_r(&_ntpGetTime, &timeinfo); + #endif + + return timeinfo.tm_wday; + } + return -1; + } + /**< days since Sunday - [ 0 to 6 ] */ + + int8_t BlinkerApi::month() + { + if (_isNTPInit) + { + time_t _ntpGetTime; + + // if (ntpGetTime == 0 || (millis() - ntpFreshTime) >= 120000) + // { + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + time_t now_ntp = ::time(nullptr); + #elif defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7020.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7020._ntpTime; + #elif defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7000.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7000._ntpTime; + #elif defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + // if (!BLINKER_AIR202.getAMGSMLOC(_timezone)) return -1; + if (!BLINKER_AIR202.getNTP()) return -1; + time_t now_ntp = BLINKER_AIR202._ntpTime; + #endif + + // if (now_ntp > ntpGetTime) + // { + _ntpGetTime = now_ntp + (int)_timezone*3600; + // } + // else + // { + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // } + + ntpGetTime = _ntpGetTime; + ntpFreshTime = millis(); + // } + // else + // { + // #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + // !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + // !defined(BLINKER_LOWPOWER_AIR202)) + // _ntpGetTime = ::time(nullptr) + (int)_timezone*3600; + // #else + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // #endif + // } + + struct tm timeinfo; + + #if defined(ESP8266) || defined(__AVR__) + gmtime_r(&_ntpGetTime, &timeinfo); + #elif defined(ESP32) + _ntpGetTime = _ntpGetTime - (int)_timezone*3600; + + localtime_r(&_ntpGetTime, &timeinfo); + #endif + + return timeinfo.tm_mon + 1; + } + return -1; + } + /**< months since January - [ 1 to 12 ] */ + + int16_t BlinkerApi::year() + { + if (_isNTPInit) + { + time_t _ntpGetTime; + + // if (ntpGetTime == 0 || (millis() - ntpFreshTime) >= 120000) + // { + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + time_t now_ntp = ::time(nullptr); + #elif defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7020.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7020._ntpTime; + #elif defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7000.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7000._ntpTime; + #elif defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + // if (!BLINKER_AIR202.getAMGSMLOC(_timezone)) return -1; + if (!BLINKER_AIR202.getNTP()) return -1; + time_t now_ntp = BLINKER_AIR202._ntpTime; + #endif + + // if (now_ntp > ntpGetTime) + // { + _ntpGetTime = now_ntp + (int)_timezone*3600; + // } + // else + // { + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // } + + ntpGetTime = _ntpGetTime; + ntpFreshTime = millis(); + // } + // else + // { + // #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + // !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + // !defined(BLINKER_LOWPOWER_AIR202)) + // _ntpGetTime = ::time(nullptr) + (int)_timezone*3600; + // #else + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // #endif + // } + + struct tm timeinfo; + + #if defined(ESP8266) || defined(__AVR__) + gmtime_r(&_ntpGetTime, &timeinfo); + #elif defined(ESP32) + _ntpGetTime = _ntpGetTime - (int)_timezone*3600; + + localtime_r(&_ntpGetTime, &timeinfo); + #endif + + return timeinfo.tm_year + 1900; + } + return -1; + } + /**< years since 1900 */ + + int16_t BlinkerApi::yday() + { + if (_isNTPInit) + { + time_t _ntpGetTime; + + // if (ntpGetTime == 0 || (millis() - ntpFreshTime) >= 120000) + // { + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + time_t now_ntp = ::time(nullptr); + #elif defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7020.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7020._ntpTime; + #elif defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7000.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7000._ntpTime; + #elif defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + // if (!BLINKER_AIR202.getAMGSMLOC(_timezone)) return -1; + if (!BLINKER_AIR202.getNTP()) return -1; + time_t now_ntp = BLINKER_AIR202._ntpTime; + #endif + + // if (now_ntp > ntpGetTime) + // { + _ntpGetTime = now_ntp + (int)_timezone*3600; + // } + // else + // { + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // } + + ntpGetTime = _ntpGetTime; + ntpFreshTime = millis(); + // } + // else + // { + // #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + // !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + // !defined(BLINKER_LOWPOWER_AIR202)) + // _ntpGetTime = ::time(nullptr) + (int)_timezone*3600; + // #else + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // #endif + // } + + struct tm timeinfo; + + #if defined(ESP8266) || defined(__AVR__) + gmtime_r(&_ntpGetTime, &timeinfo); + #elif defined(ESP32) + _ntpGetTime = _ntpGetTime - (int)_timezone*3600; + + localtime_r(&_ntpGetTime, &timeinfo); + #endif + + return timeinfo.tm_yday + 1; + } + return -1; + } + /**< days since January 1 - [ 1 to 366 ] */ + + time_t BlinkerApi::time() + { + if (_isNTPInit) + { + time_t _ntpGetTime; + + // if (ntpGetTime == 0 || (millis() - ntpFreshTime) >= 120000) + // { + // BLINKER_LOG_ALL(BLINKER_F("time (millis() - ntpFreshTime): "), (millis() - ntpFreshTime)); + // BLINKER_LOG_ALL(BLINKER_F("ntpGetTime: "), ntpGetTime); + // BLINKER_LOG_ALL((ntpGetTime == 0 || (millis() - ntpFreshTime) >= 600000)); + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + time_t now_ntp = ::time(nullptr); + #elif defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7020.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7020._ntpTime; + #elif defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7000.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7000._ntpTime; + #elif defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + // if (!BLINKER_AIR202.getAMGSMLOC(_timezone)) return -1; + if (!BLINKER_AIR202.getNTP()) return -1; + time_t now_ntp = BLINKER_AIR202._ntpTime; + #endif + + struct tm timeinfo; + + #if defined(ESP8266) || defined(__AVR__) + gmtime_r(&now_ntp, &timeinfo); + #elif defined(ESP32) + localtime_r(&now_ntp, &timeinfo); + #endif + + // if (now_ntp > ntpGetTime) + // { + _ntpGetTime = now_ntp;// - (int)_timezone*3600; + // } + // else + // { + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + + // BLINKER_LOG_ALL(BLINKER_F("millis() - ntpFreshTime1:"), (millis() - ntpFreshTime) / 1000); + // } + + ntpGetTime = _ntpGetTime; + ntpFreshTime = millis(); + + // #if defined(ESP32) + return _ntpGetTime; + // #else + // return _ntpGetTime - (int)(getTimezone()*3600); + // #endif + // } + // else + // { + // #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + // !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + // !defined(BLINKER_LOWPOWER_AIR202)) + // _ntpGetTime = ::time(nullptr); + // #else + // BLINKER_LOG_ALL("ntpGetTime: ", ntpGetTime); + // BLINKER_LOG_ALL("millis() - ntpFreshTime2:", (millis() - ntpFreshTime) / 1000); + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // #endif + + // // #if defined(ESP32) + // return _ntpGetTime; + // // #else + // // return _ntpGetTime - (int)(getTimezone()*3600); + // // #endif + // } + + } + return millis(); + } + + + int32_t BlinkerApi::dtime() + { + if (_isNTPInit) + { + time_t _ntpGetTime; + + // if (ntpGetTime == 0 || (millis() - ntpFreshTime) >= 120000) + // { + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + time_t now_ntp = ::time(nullptr); + #elif defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7020.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7020._ntpTime; + #elif defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + if (!BLINKER_SIM7000.getSNTP(getTimezone())) return -1; + time_t now_ntp = BLINKER_SIM7000._ntpTime; + #elif defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + // if (!BLINKER_AIR202.getAMGSMLOC(_timezone)) return -1; + if (!BLINKER_AIR202.getNTP()) return -1; + time_t now_ntp = BLINKER_AIR202._ntpTime; + #endif + + // if (now_ntp > ntpGetTime) + // { + _ntpGetTime = now_ntp + (int)_timezone*3600; + // } + // else + // { + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // } + + ntpGetTime = _ntpGetTime; + ntpFreshTime = millis(); + // } + // else + // { + // #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + // !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + // !defined(BLINKER_LOWPOWER_AIR202)) + // _ntpGetTime = ::time(nullptr) + (int)_timezone*3600; + // #else + // _ntpGetTime = ntpGetTime + ((millis() - ntpFreshTime) / 1000); + // #endif + // } + + struct tm timeinfo; + + #if defined(ESP8266) || defined(__AVR__) + gmtime_r(&_ntpGetTime, &timeinfo); + #elif defined(ESP32) + _ntpGetTime = _ntpGetTime - (int)_timezone*3600; + + localtime_r(&_ntpGetTime, &timeinfo); + #endif + + return timeinfo.tm_hour * 60 * 60 + timeinfo.tm_min * 60 + timeinfo.tm_sec; + } + return -1; + } + + time_t BlinkerApi::startTime() + { + if (_isNTPInit) return _deviceStartTime; + else return 0; + } + + time_t BlinkerApi::runTime() + { + if (_isNTPInit) + { + return time() - _deviceStartTime; + } + else + { + return millis()/1000; + } + } + + // template + // bool BlinkerApi::sms(const T& msg) + // { + // String _msg = STRING_format(msg); + + // #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + // defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + // defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + // defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + // defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + // defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + // defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + // defined(BLINKE_HTTP) + // String data = BLINKER_F("{\"deviceName\":\""); + // data += BProto::deviceName(); + // data += BLINKER_F("\",\"key\":\""); + // data += BProto::authKey(); + // data += BLINKER_F("\",\"msg\":\""); + // data += _msg; + // data += BLINKER_F("\"}"); + // #elif defined(BLINKER_WIFI) + // String data = BLINKER_F("{\"deviceName\":\""); + // data += macDeviceName(); + // data += BLINKER_F("\",\"msg\":\""); + // data += _msg; + // data += BLINKER_F("\"}"); + // #elif defined(BLINKER_WIFI_SUBDEVICE) + // String data = BLINKER_F("{\"sms\":\""); + // data += _msg; + // data += BLINKER_F("\"}"); + // #endif + + // if (_msg.length() > 20) { + // return false; + // } + + // #if defined(BLINKER_WIFI_SUBDEVICE) + // if (!checkSMS()) return false; + // _smsTime = millis(); + + // return BProto::subPrint(data); + // #else + // return blinkerServer(BLINKER_CMD_SMS_NUMBER, data) != "false"; + // #endif + // } + + template + bool BlinkerApi::sms(const T& msg, const String & cel) + { + String _msg = STRING_format(msg); + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + String data = BLINKER_F("{\"deviceName\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\",\"cel\":\""); + data += cel; + data += BLINKER_F("\",\"msg\":\""); + data += _msg; + data += BLINKER_F("\"}"); + #elif defined(BLINKER_WIFI) + String data = BLINKER_F("{\"deviceName\":\""); + data += macDeviceName(); + data += BLINKER_F("\",\"cel\":\""); + data += cel; + data += BLINKER_F("\",\"msg\":\""); + data += _msg; + data += BLINKER_F("\"}"); + #elif defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("{\"sms\":\""); + data += _msg; + data += BLINKER_F("\",\"cel\":\""); + data += cel; + data += BLINKER_F("\"}"); + #endif + + if (_msg.length() > 20) { + return false; + } + + #if defined(BLINKER_WIFI_SUBDEVICE) + if (!checkSMS()) return false; + _smsTime = millis(); + return BProto::subPrint(data); + #else + return blinkerServer(BLINKER_CMD_SMS_NUMBER, data) != "false"; + #endif + } + + template + bool BlinkerApi::push(const T& msg, const String & users) + { + String _msg = STRING_format(msg); + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + String data = BLINKER_F("{\"deviceName\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\",\"msg\":\""); + data += _msg; + data += BLINKER_F("\",\"receivers\":\""); + data += users; + data += BLINKER_F("\"}"); + #elif defined(BLINKER_WIFI) + String data = BLINKER_F("{\"deviceName\":\""); + data += macDeviceName(); + data += BLINKER_F("\",\"msg\":\""); + data += _msg; + data += BLINKER_F("\",\"receivers\":\""); + data += users; + data += BLINKER_F("\"}"); + #elif defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("{\"push\":\""); + data += _msg; + data += BLINKER_F("\"}"); + #endif + + #if defined(BLINKER_WIFI_SUBDEVICE) + if (!checkPUSH()) return false; + _pushTime = millis(); + return BProto::subPrint(data); + #else + return blinkerServer(BLINKER_CMD_PUSH_NUMBER, data) != "false"; + #endif + } + + template + bool BlinkerApi::wechat(const T& msg) + { + String _msg = STRING_format(msg); + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + String data = BLINKER_F("{\"deviceName\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\",\"msg\":\""); + data += _msg; + data += BLINKER_F("\"}"); + #elif defined(BLINKER_WIFI) + String data = BLINKER_F("{\"deviceName\":\""); + data += macDeviceName(); + data += BLINKER_F("\",\"msg\":\""); + data += _msg; + data += BLINKER_F("\"}"); + #elif defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("{\"wechat\":\""); + data += _msg; + data += BLINKER_F("\"}"); + #endif + + #if defined(BLINKER_WIFI_SUBDEVICE) + if (!checkWECHAT()) return false; + _wechatTime = millis(); + return BProto::subPrint(data); + #else + return blinkerServer(BLINKER_CMD_WECHAT_NUMBER, data) != "false"; + #endif + } + + template + bool BlinkerApi::wechat(const String & title, const String & state, const T& msg, const String & users) + { + String _msg = STRING_format(msg); + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + String data = BLINKER_F("{\"deviceName\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\",\"title\":\""); + data += title; + data += BLINKER_F("\",\"state\":\""); + data += state; + data += BLINKER_F("\",\"msg\":\""); + data += _msg; + data += BLINKER_F("\",\"receivers\":\""); + data += users; + data += BLINKER_F("\"}"); + #elif defined(BLINKER_WIFI) + String data = BLINKER_F("{\"deviceName\":\""); + data += macDeviceName(); + data += BLINKER_F("\",\"title\":\""); + data += title; + data += BLINKER_F("\",\"state\":\""); + data += state; + data += BLINKER_F("\",\"msg\":\""); + data += _msg; + data += BLINKER_F("\",\"receivers\":\""); + data += users; + data += BLINKER_F("\"}"); + #elif defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("{\"wechat\":\""); + data += _msg; + data += BLINKER_F("\",\"title\":\""); + data += title; + data += BLINKER_F("\",\"state\":\""); + data += state; + data += BLINKER_F("\"}"); + #endif + + #if defined(BLINKER_WIFI_SUBDEVICE) + if (!checkWECHAT()) return false; + _wechatTime = millis(); + return BProto::subPrint(data); + #else + return blinkerServer(BLINKER_CMD_WECHAT_NUMBER, data) != "false"; + #endif + } + + #if !defined(BLINKER_AT_MQTT) + void BlinkerApi::weather(uint32_t _city) + { + String data = BLINKER_F("/weather?"); + + if (_city != 0) + { + data += BLINKER_F("code="); + data += STRING_format(_city); + data += BLINKER_F("&"); + } + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + data += BLINKER_F("device="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::token(); + #elif defined(BLINKER_WIFI) + data += BLINKER_F("deviceName="); + data += macDeviceName(); + #endif + + // if (_city != BLINKER_CMD_DEFAULT) + // { + // data += BLINKER_F("&location="); + // data += _city; + // } + + #if defined(BLINKER_WIFI_SUBDEVICE) + data = BLINKER_F("{\"weather\":\""); + data += _city; + data += BLINKER_F("\"}"); + #endif + + #if defined(BLINKER_WIFI_SUBDEVICE) + if (!checkWECHAT()) return; + _wechatTime = millis(); + BProto::subPrint(data); + #else + blinkerServer(BLINKER_CMD_WEATHER_NUMBER, data); + #endif + } + + void BlinkerApi::weatherForecast(uint32_t _city) + { + String data = BLINKER_F("/forecast?"); + + if (_city != 0) + { + data += BLINKER_F("code="); + data += STRING_format(_city); + data += BLINKER_F("&"); + } + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + data += BLINKER_F("device="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::token(); + #elif defined(BLINKER_WIFI) + data += BLINKER_F("deviceName="); + data += macDeviceName(); + #endif + + // if (_city != BLINKER_CMD_DEFAULT) + // { + // data += BLINKER_F("&location="); + // data += _city; + // } + + #if defined(BLINKER_WIFI_SUBDEVICE) + data = BLINKER_F("{\"weather\":\""); + data += _city; + data += BLINKER_F("\"}"); + #endif + + #if defined(BLINKER_WIFI_SUBDEVICE) + if (!checkWECHAT()) return; + _wechatTime = millis(); + BProto::subPrint(data); + #else + blinkerServer(BLINKER_CMD_WEATHER_FORECAST_NUMBER, data); + #endif + } + + void BlinkerApi::air(uint32_t _city) + { + String data = BLINKER_F("/air?"); + + if (_city != 0) + { + data += BLINKER_F("code="); + data += STRING_format(_city); + data += BLINKER_F("&"); + } + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + data += BLINKER_F("device="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::token(); + #elif defined(BLINKER_WIFI) + data += BLINKER_F("deviceName="); + data += macDeviceName(); + #endif + + // if (_city != BLINKER_CMD_DEFAULT) + // { + // data += BLINKER_F("&location="); + // data += _city; + // } + + #if defined(BLINKER_WIFI_SUBDEVICE) + data = BLINKER_F("{\"aqi\":\""); + data += _city; + data += BLINKER_F("\"}"); + #endif + + #if defined(BLINKER_WIFI_SUBDEVICE) + if (!checkWECHAT()) return; + _wechatTime = millis(); + BProto::subPrint(data); + #else + blinkerServer(BLINKER_CMD_AQI_NUMBER, data); + #endif + } + + void BlinkerApi::log(const String & msg) + { + String data = BLINKER_F("{\"token\":\""); + data += BProto::token(); + data += BLINKER_F("\",\"device\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"data\":[["); + data += STRING_format(time()); + data += BLINKER_F(",\""); + data += msg; + data += BLINKER_F("\"]]}"); + + blinkerServer(BLINKER_CMD_LOG_NUMBER, data); + } + + void BlinkerApi::coordinate(float _long, float _lat) + { + String data = BLINKER_F("{\"token\":\""); + data += BProto::token(); + data += BLINKER_F("\",\"data\":[["); + data += STRING_format(time()); + data += BLINKER_F(",["); + data += STRING_format(_long); + data += BLINKER_F(","); + data += STRING_format(_lat); + data += BLINKER_F("]]]}"); + + blinkerServer(BLINKER_CMD_COD_NUMBER, data); + } + + #else + String BlinkerApi::weather(uint32_t _city) + { + String data = BLINKER_F("/weather?"); + + if (_city != 0) + { + data += BLINKER_F("code="); + data += STRING_format(_city); + data += BLINKER_F("&"); + } + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + data += BLINKER_F("device="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::token(); + #elif defined(BLINKER_WIFI) + data += BLINKER_F("device="); + data += macDeviceName(); + #endif + + // if (_city != BLINKER_CMD_DEFAULT) + // { + // data += BLINKER_F("&location="); + // data += _city; + // } + + #if defined(BLINKER_WIFI_SUBDEVICE) + data = BLINKER_F("{\"weather\":\""); + data += _city; + data += BLINKER_F("\"}"); + #endif + + #if defined(BLINKER_WIFI_SUBDEVICE) + if (!checkWECHAT()) return; + _wechatTime = millis(); + return BProto::subPrint(data); + #else + return blinkerServer(BLINKER_CMD_WEATHER_NUMBER, data); + #endif + } + + + String BlinkerApi::weatherForecast(uint32_t _city) + { + String data = BLINKER_F("/forecast?"); + + if (_city != 0) + { + data += BLINKER_F("code="); + data += STRING_format(_city); + data += BLINKER_F("&"); + } + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + data += BLINKER_F("device="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::token(); + #elif defined(BLINKER_WIFI) + data += BLINKER_F("device="); + data += macDeviceName(); + #endif + + // if (_city != BLINKER_CMD_DEFAULT) + // { + // data += BLINKER_F("&location="); + // data += _city; + // } + + #if defined(BLINKER_WIFI_SUBDEVICE) + data = BLINKER_F("{\"weather\":\""); + data += _city; + data += BLINKER_F("\"}"); + #endif + + #if defined(BLINKER_WIFI_SUBDEVICE) + if (!checkWECHAT()) return; + _wechatTime = millis(); + return BProto::subPrint(data); + #else + return blinkerServer(BLINKER_CMD_WEATHER_FORECAST_NUMBER, data); + #endif + } + + String BlinkerApi::air(uint32_t _city) + { + String data = BLINKER_F("/air?"); + + if (_city != 0) + { + data += BLINKER_F("code="); + data += STRING_format(_city); + data += BLINKER_F("&"); + } + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + data += BLINKER_F("device="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::token(); + #elif defined(BLINKER_WIFI) + data += BLINKER_F("device="); + data += macDeviceName(); + #endif + + // if (_city != BLINKER_CMD_DEFAULT) + // { + // data += BLINKER_F("&location="); + // data += _city; + // } + + #if defined(BLINKER_WIFI_SUBDEVICE) + data = BLINKER_F("{\"aqi\":\""); + data += _city; + data += BLINKER_F("\"}"); + #endif + + #if defined(BLINKER_WIFI_SUBDEVICE) + if (!checkWECHAT()) return; + _wechatTime = millis(); + return BProto::subPrint(data); + #else + return blinkerServer(BLINKER_CMD_AQI_NUMBER, data); + #endif + } + + void BlinkerApi::log(const String & msg) + { + String data = BLINKER_F("{\"token\":\""); + data += BProto::token(); + data += BLINKER_F("\",\"data\":[["); + data += STRING_format(time()); + data += BLINKER_F(","); + data += msg; + data += BLINKER_F("]]}"); + + blinkerServer(BLINKER_CMD_LOG_NUMBER, data); + } + + void BlinkerApi::coordinate(float _long, float _lat) + { + String data = BLINKER_F("{\"token\":\""); + data += BProto::token(); + data += BLINKER_F("\",\"data\":[["); + data += STRING_format(time()); + data += BLINKER_F(",["); + data += STRING_format(_long); + data += BLINKER_F(","); + data += STRING_format(_lat); + data += BLINKER_F("]]]}"); + + blinkerServer(BLINKER_CMD_COD_NUMBER, data); + } + + #endif + + bool BlinkerApi::deviceHeartbeat(uint32_t heart_time) + { + #if defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("{\"deviceHeartbeat\":"); + data += STRING_format(heart_time); + data += BLINKER_F("}"); + return BProto::subPrint(data); + #else + String data = BLINKER_F("/heartbeat?"); + data += BLINKER_F("deviceName="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::authKey(); + data += BLINKER_F("&heartbeat="); + data += STRING_format(heart_time); + + return blinkerServer(BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER, data) != BLINKER_CMD_FALSE; + #endif + } + + #if defined(BLINKER_PRO_ESP) + bool BlinkerApi::eventWarn(const String & msg) + { + #if defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("{\"eventWarn\":\""); + data += msg; + data += BLINKER_F("\"}"); + + if (!checkEventWarn()) return; + _eWarnTime = millis(); + return BProto::subPrint(data); + #else + String data = BLINKER_F("{\"deviceName\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\",\"msgType\":\"warning"); + data += BLINKER_F("\",\"msg\":\""); + data += msg; + data += BLINKER_F("\"}"); + + return blinkerServer(BLINKER_CMD_EVENT_WARNING_NUMBER, data) != BLINKER_CMD_FALSE; + #endif + } + + bool BlinkerApi::eventError(const String & msg) + { + #if defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("{\"eventError\":\""); + data += msg; + data += BLINKER_F("\"}"); + + if (!checkEventErr()) return; + _eErrTime = millis(); + return BProto::subPrint(data); + #else + String data = BLINKER_F("{\"deviceName\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\",\"msgType\":\"error"); + data += BLINKER_F("\",\"error\":\""); + data += msg; + data += BLINKER_F("\"}"); + + return blinkerServer(BLINKER_CMD_EVENT_ERROR_NUMBER, data) != BLINKER_CMD_FALSE; + #endif + } + + bool BlinkerApi::eventMsg(const String & msg) + { + #if defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("{\"eventMsg\":\""); + data += msg; + data += BLINKER_F("\"}"); + + if (!checkEventMsg()) return; + _eMsgTime = millis(); + return BProto::subPrint(data); + #else + String data = BLINKER_F("{\"deviceName\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\",\"msgType\":\"msg"); + data += BLINKER_F("\",\"msg\":\""); + data += msg; + data += BLINKER_F("\"}"); + + return blinkerServer(BLINKER_CMD_EVENT_MSG_NUMBER, data) != BLINKER_CMD_FALSE; + #endif + } + #endif + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + void BlinkerApi::loadTimer() + { + BLINKER_LOG(BLINKER_F( + "\n===========================================================" + "\n================== Blinker Timer loaded! ==================" + "\n EEPROM address 1536-2431 is used for Blinker Timer!" + "\n========= PLEASE AVOID USING THESE EEPROM ADDRESS! ========" + "\n===========================================================\n")); + + checkTimerErase(); + loadCountdown(); + loadLoop(); + } + + void BlinkerApi::deleteTimer() + { + EEPROM.begin(BLINKER_EEP_SIZE); + + EEPROM.put(BLINKER_EEP_ADDR_TIMER_COUNTDOWN, 0); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP, 0); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_TIMING_COUNT, 0); + + EEPROM.commit(); + EEPROM.end(); + } + + void BlinkerApi::deleteCountdown() + { + EEPROM.begin(BLINKER_EEP_SIZE); + + EEPROM.put(BLINKER_EEP_ADDR_TIMER_COUNTDOWN, 0); + + EEPROM.commit(); + EEPROM.end(); + } + + void BlinkerApi::deleteLoop() + { + EEPROM.begin(BLINKER_EEP_SIZE); + + EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP, 0); + + EEPROM.commit(); + EEPROM.end(); + } + + void BlinkerApi::deleteTiming() + { + EEPROM.begin(BLINKER_EEP_SIZE); + + EEPROM.put(BLINKER_EEP_ADDR_TIMER_TIMING_COUNT, 0); + + EEPROM.commit(); + EEPROM.end(); + } + #endif + + template + bool BlinkerApi::configUpdate(const T& msg) + { + String _msg = STRING_format(msg); + + #if !defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("{\"token\":\""); + data += BProto::token(); + data += BLINKER_F("\",\"data\":"); + data += _msg; + data += BLINKER_F("}"); + + if (_msg.length() > 256) return false; + + return blinkerServer(BLINKER_CMD_CONFIG_UPDATE_NUMBER, data) != "false"; + #else + String data = BLINKER_F("{\"configUpdate\":\""); + data += _msg; + data += BLINKER_F("\"}"); + + if (!checkCUPDATE()) return false; + _cUpdateTime = millis(); + + return BProto::subPrint(data); + #endif + } + + + void BlinkerApi::configGet() + { + #if !defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("/cloud_storage/object?token="); + data += BProto::token(); + + blinkerServer(BLINKER_CMD_CONFIG_GET_NUMBER, data); + #else + String data = BLINKER_F("{\"configGet\":\"default\"}"); + + if (!checkCGET()) return; + _cGetTime = millis(); + + BProto::subPrint(data); + #endif + } + + + bool BlinkerApi::configDelete() + { + #if !defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("/delete_userconfig?deviceName="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::authKey(); + + return blinkerServer(BLINKER_CMD_CONFIG_DELETE_NUMBER, data) != "false"; + #else + String data = BLINKER_F("{\"configDel\":\"default\"}"); + + if (!checkCDEL()) return false; + _cDelTime = millis(); + + return BProto::subPrint(data); + #endif + } + + template + void BlinkerApi::dataStorage(char _name[], const T& msg) + { + String _msg = STRING_format(msg); + + int8_t num = checkNum(_name, _Data, data_dataCount); + + time_t _time = time(); + uint8_t _second = second(); + time_t now_time = _time - _second; + + BLINKER_LOG_ALL(BLINKER_F("time: "), _time, BLINKER_F(",second: "), _second); + + BLINKER_LOG_ALL(BLINKER_F("now_time: "), now_time); + + now_time = now_time - now_time % 10; + + BLINKER_LOG_ALL(BLINKER_F("dataStorage num: "), num, BLINKER_F(" ,"), now_time); + BLINKER_LOG_ALL(BLINKER_F("dataStorage count: "), data_dataCount); + + String data_msg = String(msg); + + if (data_msg.length() > 10) return; + + if( num == BLINKER_OBJECT_NOT_AVAIL ) + { + if (data_dataCount == BLINKER_MAX_BLINKER_DATA_SIZE) + { + return; + } + _Data[data_dataCount] = new BlinkerData(); + _Data[data_dataCount]->name(_name); + // _Data[data_dataCount]->saveData(time(), _msg); + // if + _Data[data_dataCount]->saveData(data_msg, now_time, BLINKER_DATA_FREQ_TIME); + data_dataCount++; + // { + // dataUpdate(); + // } + + BLINKER_LOG_ALL(_name, BLINKER_F(" save: "), _msg, BLINKER_F(" time: "), now_time); + BLINKER_LOG_ALL(BLINKER_F("data_dataCount: "), data_dataCount); + } + else { + // _Data[num]->saveData(time(), _msg); + // if + _Data[num]->saveData(data_msg, now_time, BLINKER_DATA_FREQ_TIME); + // { + // dataUpdate(); + // } + + BLINKER_LOG_ALL(_name, BLINKER_F(" save: "), _msg, BLINKER_F(" time: "), now_time); + BLINKER_LOG_ALL(BLINKER_F("data_dataCount: "), data_dataCount); + } + } + + #if !defined(BLINKER_AT_MQTT) + void BlinkerApi::RTDataStorage(char _name[], int msg) + { + // String _msg = STRING_format(msg); + + int8_t num = checkNum(_name, _RTData, data_rtDataCount); + + time_t _time = time(); + // uint8_t _second = second(); + time_t now_time = _time;// - _second; + + // BLINKER_LOG_ALL(BLINKER_F("time: "), _time, BLINKER_F(",second: "), _second); + + BLINKER_LOG_ALL(BLINKER_F("now_time: "), now_time); + + // now_time = now_time - now_time % 10; + + BLINKER_LOG_ALL(BLINKER_F("dataStorage num: "), num, BLINKER_F(" ,"), now_time); + BLINKER_LOG_ALL(BLINKER_F("dataStorage count: "), data_rtDataCount); + + // String data_msg = String(msg); + + // if (data_msg.length() > 10) return; + + if( num == BLINKER_OBJECT_NOT_AVAIL ) + { + if (data_rtDataCount == 2) + { + return; + } + _RTData[data_rtDataCount] = new BlinkerRTData(); + _RTData[data_rtDataCount]->name(_name); + // _RTData[data_rtDataCount]->saveData(time(), _msg); + // if + _RTData[data_rtDataCount]->saveData(msg, now_time); + data_rtDataCount++; + // { + // dataUpdate(); + // } + + BLINKER_LOG_ALL(_name, BLINKER_F(" save: "), msg, BLINKER_F(" time: "), now_time); + BLINKER_LOG_ALL(BLINKER_F("data_rtDataCount: "), data_rtDataCount); + } + else { + // _RTData[num]->saveData(time(), _msg); + // if + _RTData[num]->saveData(msg, now_time); + // { + // dataUpdate(); + // } + + BLINKER_LOG_ALL(_name, BLINKER_F(" save: "), msg, BLINKER_F(" time: "), now_time); + BLINKER_LOG_ALL(BLINKER_F("data_rtDataCount: "), data_rtDataCount); + } + + + } + + void BlinkerApi::RTDataPrint() + { + String data = "{\"rt\":{"; + + for (uint8_t _num = 0; _num < data_rtDataCount; _num++) { + data += BLINKER_F("\""); + data += _RTData[_num]->getName(); + data += BLINKER_F("\":"); + data += _RTData[_num]->getData(); + if (_num < data_rtDataCount - 1) { + data += BLINKER_F(","); + } + + BLINKER_LOG_ALL(BLINKER_F("num: "), _num, \ + BLINKER_F(" name: "), _RTData[_num]->getName()); + + BLINKER_LOG_FreeHeap_ALL(); + } + + data += BLINKER_F("}}"); + + printObject(_RTDataKey, data); + } + #endif + + + void BlinkerApi::timeSlotData(char _name[], int32_t _data) + { + uint32_t now_time = time(); + + if (data_timeSlotDataCount == BLINKER_MAX_BLINKER_DATA_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("BLINKER MAX DATA STORAGE LIMIT!")); + return; + } + + BLINKER_LOG_ALL(BLINKER_F("timeSlotData save")); + + if (millis() - time_timeSlotData < 1000) + { + if (data_timeSlotDataCount != 0) + { + BLINKER_LOG_ALL(BLINKER_F("data_timeSlotDataCount != 0")); + _TimeSlotData[data_timeSlotDataCount - 1]->saveData(_name, _data, now_time); + } + else + { + BLINKER_LOG_ALL(BLINKER_F("data_timeSlotDataCount == 0")); + _TimeSlotData[data_timeSlotDataCount] = new BlinkerTimeSlotData(); + _TimeSlotData[data_timeSlotDataCount]->saveData(_name, _data, now_time); + data_timeSlotDataCount++; + } + + BLINKER_LOG_ALL(_name, BLINKER_F(" save: "), _data, BLINKER_F(" time: "), now_time); + BLINKER_LOG_ALL(BLINKER_F("data_timeSlotDataCount: "), data_timeSlotDataCount); + } + else + { + time_timeSlotData = millis(); + + _TimeSlotData[data_timeSlotDataCount] = new BlinkerTimeSlotData(); + _TimeSlotData[data_timeSlotDataCount]->saveData(_name, _data, now_time); + data_timeSlotDataCount++; + + BLINKER_LOG_ALL(_name, BLINKER_F(" save: "), _data, BLINKER_F(" time: "), now_time); + BLINKER_LOG_ALL(BLINKER_F("data_timeSlotDataCount: "), data_timeSlotDataCount); + } + } + + + void BlinkerApi::timeSlotData(char _name[], uint32_t _data) + { + uint32_t now_time = time(); + + if (data_timeSlotDataCount == BLINKER_MAX_BLINKER_DATA_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("BLINKER MAX DATA STORAGE LIMIT!")); + return; + } + + BLINKER_LOG_ALL(BLINKER_F("timeSlotData save")); + + if (millis() - time_timeSlotData < 1000) + { + if (data_timeSlotDataCount != 0) + { + BLINKER_LOG_ALL(BLINKER_F("data_timeSlotDataCount != 0")); + _TimeSlotData[data_timeSlotDataCount - 1]->saveData(_name, _data, now_time); + } + else + { + BLINKER_LOG_ALL(BLINKER_F("data_timeSlotDataCount == 0")); + _TimeSlotData[data_timeSlotDataCount] = new BlinkerTimeSlotData(); + _TimeSlotData[data_timeSlotDataCount]->saveData(_name, _data, now_time); + data_timeSlotDataCount++; + } + + BLINKER_LOG_ALL(_name, BLINKER_F(" save: "), _data, BLINKER_F(" time: "), now_time); + BLINKER_LOG_ALL(BLINKER_F("data_timeSlotDataCount: "), data_timeSlotDataCount); + } + else + { + time_timeSlotData = millis(); + + _TimeSlotData[data_timeSlotDataCount] = new BlinkerTimeSlotData(); + _TimeSlotData[data_timeSlotDataCount]->saveData(_name, _data, now_time); + data_timeSlotDataCount++; + + BLINKER_LOG_ALL(_name, BLINKER_F(" save: "), _data, BLINKER_F(" time: "), now_time); + BLINKER_LOG_ALL(BLINKER_F("data_timeSlotDataCount: "), data_timeSlotDataCount); + } + } + + + void BlinkerApi::timeSlotData(char _name[], float _data) + { + uint32_t now_time = time(); + + if (data_timeSlotDataCount == BLINKER_MAX_BLINKER_DATA_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("BLINKER MAX DATA STORAGE LIMIT!")); + return; + } + + BLINKER_LOG_ALL(BLINKER_F("timeSlotData save")); + + if (millis() - time_timeSlotData < 1000) + { + if (data_timeSlotDataCount != 0) + { + BLINKER_LOG_ALL(BLINKER_F("data_timeSlotDataCount != 0")); + _TimeSlotData[data_timeSlotDataCount - 1]->saveData(_name, _data, now_time); + } + else + { + BLINKER_LOG_ALL(BLINKER_F("data_timeSlotDataCount == 0")); + _TimeSlotData[data_timeSlotDataCount] = new BlinkerTimeSlotData(); + _TimeSlotData[data_timeSlotDataCount]->saveData(_name, _data, now_time); + data_timeSlotDataCount++; + } + + BLINKER_LOG_ALL(_name, BLINKER_F(" save: "), _data, BLINKER_F(" time: "), now_time); + BLINKER_LOG_ALL(BLINKER_F("data_timeSlotDataCount: "), data_timeSlotDataCount); + } + else + { + time_timeSlotData = millis(); + + _TimeSlotData[data_timeSlotDataCount] = new BlinkerTimeSlotData(); + _TimeSlotData[data_timeSlotDataCount]->saveData(_name, _data, now_time); + data_timeSlotDataCount++; + + BLINKER_LOG_ALL(_name, BLINKER_F(" save: "), _data, BLINKER_F(" time: "), now_time); + BLINKER_LOG_ALL(BLINKER_F("data_timeSlotDataCount: "), data_timeSlotDataCount); + } + } + + + void BlinkerApi::textData(const String & msg) + { + String data = BLINKER_F("{"); + + #if defined(BLINKER_PROTOCOL_HTTP_SERVER) + data += BLINKER_F("\"device\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\""); + #else + data += BLINKER_F("\"toStorage\":\"tt\""); + #endif + + data += BLINKER_F(",\"data\":\""); + data += msg; + data += BLINKER_F("\"}"); + + BLINKER_LOG_ALL(BLINKER_F("textData: "), data); + + #ifndef BLINKER_PROTOCOL_HTTP_SERVER + BProto::toServer((char *)data.c_str()); + #endif + + #if defined(BLINKER_PROTOCOL_HTTP_SERVER) + if (blinkerServer(BLINKER_CMD_TEXT_DATA_NUMBER, data) == "false") + { + // return false; + } + else + { + // return true; + } + #else + // return true; + #endif + } + + + void BlinkerApi::jsonData(const String & msg) + { + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, msg); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) + if (error) + { + BLINKER_ERR_LOG("Print data is not Json! ", msg); + return; + } + + String data = BLINKER_F("{"); + + #if defined(BLINKER_PROTOCOL_HTTP_SERVER) + data += BLINKER_F("\"device\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\""); + #else + data += BLINKER_F("\"toStorage\":\"ot\""); + #endif + + data += BLINKER_F(",\"data\":"); + data += msg; + data += BLINKER_F("}"); + + BLINKER_LOG_ALL(BLINKER_F("jsonData: "), data); + + #ifndef BLINKER_PROTOCOL_HTTP_SERVER + BProto::toServer((char *)data.c_str()); + #endif + + #if defined(BLINKER_PROTOCOL_HTTP_SERVER) + if (blinkerServer(BLINKER_CMD_JSON_DATA_NUMBER, data) == "false") + { + // return false; + } + else + { + // return true; + } + #else + // return true; + #endif + } + + + void BlinkerApi::jsonDataGet() + { + String data = BLINKER_F("/cloud_storage/object?token="); + data += BProto::token(); + + blinkerServer(BLINKER_CMD_JSON_DATA_GET_NUMBER, data); + } + + + bool BlinkerApi::dataUpdate() + { + BLINKER_LOG_ALL(BLINKER_F("dataUpdate: "), data_timeSlotDataCount); + + if (data_timeSlotDataCount > 0) + { + String data = BLINKER_F("{"); + + #if defined(BLINKER_PROTOCOL_HTTP_SERVER) + data += BLINKER_F("\"device\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\""); + #else + data += BLINKER_F("\"device\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"toStorage\":\"ts\""); + #endif + + data += BLINKER_F(",\"data\":["); + + for (uint8_t _num = 0; _num < data_timeSlotDataCount; _num++) { + data += _TimeSlotData[_num]->getData(); + if (_num < data_timeSlotDataCount - 1) { + data += BLINKER_F(","); + } + } + + data += BLINKER_F("]}"); + + BLINKER_LOG_ALL(BLINKER_F("dataUpdate: "), data); + + #ifndef BLINKER_PROTOCOL_HTTP_SERVER + BProto::toServer((char *)data.c_str()); + #endif + + for (uint8_t _num = 0; _num < data_timeSlotDataCount; _num++) + { + // _TimeSlotData[_num]->flush(); + free(_TimeSlotData[_num]); + } + + data_timeSlotDataCount = 0; + + #if defined(BLINKER_PROTOCOL_HTTP_SERVER) + if (blinkerServer(BLINKER_CMD_TIME_SLOT_DATA_NUMBER, data) == "false") + { + return false; + } + else + { + return true; + } + #else + return true; + #endif + } + + if (!data_dataCount) { + // BLINKER_ERR_LOG(BLINKER_F("none data storaged!")); + return false; + } + + // #if defined(BLINKER_GPRS_AIR202) + // String data = BLINKER_F("deviceName="); + // data += BProto::deviceName(); + // data += BLINKER_F("&key="); + // data += BProto::authKey(); + // data += BLINKER_F("&data="); + + // String _data_ = "{"; + + // for (uint8_t _num = 0; _num < data_dataCount; _num++) { + // _data_ += BLINKER_F("\""); + // _data_ += _Data[_num]->getName(); + // _data_ += BLINKER_F("\":"); + // _data_ += _Data[_num]->getData(); + // if (_num < data_dataCount - 1) { + // _data_ += BLINKER_F(","); + // } + + // BLINKER_LOG_ALL(BLINKER_F("num: "), _num, \ + // BLINKER_F(" name: "), _Data[_num]->getName()); + + // BLINKER_LOG_FreeHeap_ALL(); + // } + + // _data_ += "}"; + + // int encodedLen = base64_enc_len(_data_.length()); + // char encoded[encodedLen]; + // base64_encode(encoded, _data_.c_str(), _data_.length()); + // BLINKER_LOG_ALL(BLINKER_F("encoded: "), encoded); + + // data += encoded; + + // // data += BLINKER_F(""); + // #else + + #if !defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("{\"deviceName\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\",\"data\":{"); + // String _sdata; + #else + String data = BLINKER_F("{\"dataUpdate\":{"); + #endif + + BLINKER_LOG_FreeHeap_ALL(); + + // uint32_t now_time = time() - second(); + + for (uint8_t _num = 0; _num < data_dataCount; _num++) { + data += BLINKER_F("\""); + data += _Data[_num]->getName(); + data += BLINKER_F("\":"); + data += _Data[_num]->getData(); + if (_num < data_dataCount - 1) { + data += BLINKER_F(","); + } + + BLINKER_LOG_ALL(BLINKER_F("num: "), _num, \ + BLINKER_F(" name: "), _Data[_num]->getName()); + + BLINKER_LOG_FreeHeap_ALL(); + } + + data += BLINKER_F("}}"); + // #endif + + BLINKER_LOG_ALL(BLINKER_F("dataUpdate: "), data); + + BLINKER_LOG_FreeHeap_ALL(); + + // return true; + // + \ _msg + + // "\"}}"; + #if !defined(BLINKER_WIFI_SUBDEVICE) + if (blinkerServer(BLINKER_CMD_DATA_STORAGE_NUMBER, data) == "false") + #else + _dUpdateTime = millis(); + if (!BProto::subPrint(data)) + #endif + { + return false; + } + else + { + for (uint8_t _num = 0; _num < data_dataCount; _num++) + { + _Data[_num]->flush(); + } + + return true; + } + } + + + void BlinkerApi::dataGet() + { + #if !defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("/pull_cloudStorage?deviceName="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::authKey(); + + blinkerServer(BLINKER_CMD_DATA_GET_NUMBER, data); + #else + String data = BLINKER_F("{\"dataGet\":\"\"}"); + + if (!checkDataGet()) return; + _dGetTime = millis(); + + BProto::subPrint(data); + #endif + } + + + void BlinkerApi::dataGet(const String & _type) + { + #if !defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("/pull_cloudStorage?deviceName="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::authKey(); + data += BLINKER_F("&dataType="); + data += _type; + + blinkerServer(BLINKER_CMD_DATA_GET_NUMBER, data); + #else + String data = BLINKER_F("{\"dataGet\":\""); + data += _type; + data += BLINKER_F("\"}"); + + if (!checkDataGet()) return; + _dGetTime = millis(); + + BProto::subPrint(data); + #endif + } + + + void BlinkerApi::dataGet(const String & _type, const String & _date) + { + #if !defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("/pull_cloudStorage?deviceName="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::authKey(); + data += BLINKER_F("&dataType="); + data += _type; + data += BLINKER_F("&date="); + data += _date; + + blinkerServer(BLINKER_CMD_DATA_GET_NUMBER, data); + #else + String data = BLINKER_F("{\"dataGet\":\""); + data += _type; + data += BLINKER_F("\":\"date\":\""); + data += _date; + data += BLINKER_F("\"}"); + + if (!checkDataGet()) return; + _dGetTime = millis(); + + BProto::subPrint(data); + #endif + } + + + bool BlinkerApi::dataDelete() + { + #if !defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("/delete_cloudStorage?deviceName="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::authKey(); + + return blinkerServer(BLINKER_CMD_DATA_DELETE_NUMBER, data) != "false"; + #else + String data = BLINKER_F("{\"dataDel\":\"\"}"); + + if (!checkDataDel()) return false; + _dDelTime = millis(); + + return BProto::subPrint(data); + #endif + } + + + bool BlinkerApi::dataDelete(const String & _type) + { + #if !defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("/delete_cloudStorage?deviceName="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::authKey(); + data += BLINKER_F("&dataType="); + data += _type; + + return blinkerServer(BLINKER_CMD_DATA_DELETE_NUMBER, data) != "false"; + #else + String data = BLINKER_F("{\"dataDel\":\""); + data += _type; + data += BLINKER_F("\"}"); + + if (!checkDataDel()) return false; + _dDelTime = millis(); + + return BProto::subPrint(data); + #endif + } + + + bool BlinkerApi::event(const String & _key, String _value) + { + #if !defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("{\"deviceName\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\",\"eKey\":\""); + data += _key; + data += BLINKER_F("\",\"date\":\""); + data += STRING_format(time()); + data += BLINKER_F("\",\"value\":\""); + data += _value; + data += BLINKER_F("\"}"); + + return blinkerServer(BLINKER_CMD_EVENT_DATA_NUMBER, data) != "false"; + #else + String data = BLINKER_F("{\"eKey\":\""); + data += _key; + data += BLINKER_F("\",\"date\":\""); + data += STRING_format(time()); + data += BLINKER_F("\",\"value\":\""); + data += _value; + data += BLINKER_F("\"}"); + + return BProto::subPrint(data); + #endif + } + + + bool BlinkerApi::gps(float _long, float _lat) + { + #if !defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("{\"deviceName\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\",\"data\":["); + data += STRING_format(_long); + data += BLINKER_F(","); + data += STRING_format(_lat); + data += BLINKER_F(","); + data += STRING_format(time()); + data += BLINKER_F("]}"); + + return blinkerServer(BLINKER_CMD_GPS_DATA_NUMBER, data) != "false"; + #else + String data = BLINKER_F("{\"gpsUpdate\":["); + data += STRING_format(_long); + data += BLINKER_F(","); + data += STRING_format(_lat); + data += BLINKER_F(","); + data += STRING_format(time()); + data += BLINKER_F("]}"); + + return BProto::subPrint(data); + #endif + } + + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + bool BlinkerApi::autoPull() + { + #if !defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("/auto/pull?deviceName="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::authKey(); + + String payload = blinkerServer(BLINKER_CMD_AUTO_PULL_NUMBER, data); + + if (payload == BLINKER_CMD_FALSE) + { + return false; + } + else + { + // DynamicJsonBuffer jsonBuffer; + // JsonObject& autoJson = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(1024); + deserializeJson(jsonBuffer, payload); + JsonObject autoJson = jsonBuffer.as(); + + return autoManager(autoJson); + } + #else + String data = BLINKER_F("{\"autoPull\":\"\"}"); + + if (!checkAutoPull()) return false; + _autoPullTime = millis(); + + return BProto::subPrint(data); + #endif + } + + + // void BlinkerApi::autoInput(const String & key, const String & state) + // { + // if (!_isNTPInit) return; + + // int32_t nowTime = dtime(); + + // for (uint8_t _num = 0; _num < _aCount; _num++) + // { + // _AUTO[_num]->run(key, state, nowTime); + // } + // } + + + void BlinkerApi::autoInput(const String & key, float data) + { + if (!_isNTPInit) return; + + int32_t nowTime = dtime()/60; + + for (uint8_t _num = 0; _num < _aCount; _num++) + { + _AUTO[_num]->run(key, data, nowTime); + } + } + + + void BlinkerApi::autoRun() + { + for (uint8_t _num = 0; _num < _aCount; _num++) + { + if (_AUTO[_num]->isTrigged()) + { + if (autoTrigged(_AUTO[_num]->id())) + { + run(); + + BLINKER_LOG_ALL(BLINKER_F("trigged sucessed")); + + _AUTO[_num]->fresh(); + } + else + { + BLINKER_LOG_ALL(BLINKER_F("trigged failed")); + } + + run(); + } + } + } + + #if !defined(BLINKER_WIFI_SUBDEVICE) + + void BlinkerApi::freshAttachBridge(char _key[], blinker_callback_with_string_arg_t _func) + { + int8_t num = checkNum(_key, _Bridge, _bridgeCount); + if(num >= 0 ) _Bridge[num]->setFunc(_func); + } + + + uint8_t BlinkerApi::attachBridge(char _key[], blinker_callback_with_string_arg_t _func) + { + int8_t num = checkNum(_key, _Bridge, _bridgeCount); + + if (num == BLINKER_OBJECT_NOT_AVAIL) + { + if (_bridgeCount < BLINKER_MAX_BRIDGE_SIZE) + { + _Bridge[_bridgeCount] = new BlinkerBridge_key(_key, _func); + _bridgeCount++; + + BLINKER_LOG_ALL(BLINKER_F("new bridgeKey: "), _key, \ + BLINKER_F(" _bridgeCount: "), _bridgeCount); + return _bridgeCount; + } + else + { + return 0; + } + } + else if(num >= 0 ) + { + BLINKER_ERR_LOG(BLINKER_F("bridgeKey > "), _key, \ + BLINKER_F(" < has been registered, please register another name!")); + return 0; + } + else + { + return 0; + } + } + + + char * BlinkerApi::bridgeKey(uint8_t num) + { + if (num) return _Bridge[num - 1]->getKey(); + else return ""; + } + + + char * BlinkerApi::bridgeName(uint8_t num) + { + if (num) return _Bridge[num - 1]->getName(); + else return "false"; + } + + + void BlinkerApi::bridgeInit() + { + String register_r; + for (uint8_t num = 0; num < _bridgeCount; num++) + { + register_r = bridgeQuery(_Bridge[num]->getKey()); + BLINKER_LOG_ALL(BLINKER_F("bridgeQuery name: "), register_r); + if (strcmp(register_r.c_str(), BLINKER_CMD_FALSE) != 0) + { + _Bridge[num]->name(register_r); + } + } + } + + void BlinkerApi::bridgePrint(char * bName, const String & data) + { + BProto::bPrint(bName, data); + } + #endif + #endif + + #if !defined(BLINKER_LOWPOWER_AIR202) + String BlinkerApi::freshSharers() + { + #if !defined(BLINKER_WIFI_SUBDEVICE) + String data = BLINKER_F("/share/device?"); + data += BLINKER_F("deviceName="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::authKey(); + + return blinkerServer(BLINKER_CMD_FRESH_SHARERS_NUMBER, data); + #else + String data = BLINKER_F("{\"freshSharers\":\"\"}"); + + BProto::subPrint(data); + + return ""; + #endif + } + #endif + + #if !defined(BLINKER_WIFI_SUBDEVICE) + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + + void BlinkerApi::loadOTA() + { + // if (_OTA.loadOTACheck()) + // { + // if (!_OTA.loadVersion()) + // { + // _OTA.saveVersion(); + // } + // } + + ::delay(1000); + + BLINKER_LOG_ALL(BLINKER_F("OTA load: "), BLINKER_OTA_VERSION_CODE); + + uint8_t ota_check = _OTA.loadOTACheck(); + + if (ota_check == BLINKER_OTA_RUN) + { + _OTA.saveOTACheck(); + updateOTAStatus(10, "download firmware"); + + String otaData = checkOTA(); + + if (otaData != BLINKER_CMD_FALSE) + { + // DynamicJsonBuffer jsonBuffer; + // JsonObject& otaJson = jsonBuffer.parseObject(otaData); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, otaData); + JsonObject otaJson = jsonBuffer.as(); + + // if (!otaJson.success()) + if (error) + { + BLINKER_ERR_LOG_ALL(BLINKER_F("check ota data error")); + return; + } + + // String otaHost = otaJson["host"]; + // String otaUrl = otaJson["url"]; + // String otaFp = otaJson["fingerprint"]; + // String otaMD5 = otaJson["hash"]; + + // _OTA.config(otaHost, otaUrl, otaFp, otaMD5); + _OTA.config(otaJson["host"].as(), otaJson["url"].as(), otaJson["fingerprint"].as(), otaJson["hash"].as()); + + if (_OTA.update()) + { + // _OTA.saveVersion(); + // _OTA.clearOTACheck(); + + // updateOTAStatus(100); + + BProto::freshAlive(); + otaStatus(99, BLINKER_F("Firmware download sucessed")); + updateOTAStatus(99, BLINKER_F("Firmware download sucessed")); + ESP.restart(); + } + else + { + _OTA.clearOTACheck(); + + BProto::freshAlive(); + otaStatus(-2, BLINKER_F("Firmware download failed")); + updateOTAStatus(-2, BLINKER_F("Firmware download failed")); + } + } + } + else if (ota_check == BLINKER_OTA_START) + { + if (!_OTA.loadVersion()) + { + _OTA.saveVersion(); + _OTA.clearOTACheck(); + + BProto::freshAlive(); + otaStatus(100, BLINKER_F("Firmware update success")); + updateOTAStatus(100, BLINKER_F("Firmware update success")); + // ota failed + } + else + { + // _OTA.saveVersion(); + _OTA.clearOTACheck(); + + BProto::freshAlive(); + otaStatus(-2, BLINKER_F("Firmware download failed")); + updateOTAStatus(-2, BLINKER_F("Firmware download failed")); + // ota success + } + } + else if (ota_check == BLINKER_OTA_CLEAR) + { + // _OTA.saveVersion(); + // _OTA.clearOTACheck(); + + if (!_OTA.loadVersion()) _OTA.saveVersion(); + } + else + { + if (!_OTA.loadVersion()) + { + if (ota_check > 0) + { + // updateOTAStatus(100); + _OTA.clearOTACheck(); + _OTA.saveVersion(); + } + else + { + _OTA.saveVersion(); + } + } + else if (_OTA.loadVersion() && ota_check == 0) + { + // updateOTAStatus(-2); + _OTA.clearOTACheck(); + } + else + { + _OTA.clearOTACheck(); + } + } + + } + + + void BlinkerApi::ota() + { + if (checkCanOTA()) + { + _OTA.saveOTARun(); + + ::delay(100); + ESP.restart(); + + loadOTA(); + } + } + + + String BlinkerApi::checkOTA() + { + String data = BLINKER_F("/ota/upgrade?deviceName=");// + + data += STRING_format(BProto::deviceName()); + + return blinkerServer(BLINKER_CMD_OTA_NUMBER, data); + } + + + bool BlinkerApi::updateOTAStatus(int8_t status, const String & msg) + { + String data; + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || defined(BLINKE_HTTP) + data = BLINKER_F("{\"deviceName\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\",\"upgrade\":true,\"upgradeData\":{\"step\":\""); + data += STRING_format(status); + data += BLINKER_F("\",\"desc\":\""); + data += msg; + data += BLINKER_F("\"}}"); + #elif defined(BLINKER_WIFI) + return false; + #endif + + return blinkerServer(BLINKER_CMD_OTA_STATUS_NUMBER, data) != "false"; + } + + + void BlinkerApi::otaStatus(int8_t status, const String & msg) + { + String data; + + data = BLINKER_F("{\"step\":\""); + data += STRING_format(status); + data += BLINKER_F("\",\"desc\":\""); + data += msg; + data += BLINKER_F("\"}"); + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKE_HTTP) + print(BLINKER_CMD_VERSION, BLINKER_OTA_VERSION_CODE); + print(BLINKER_CMD_STATE, BLINKER_CMD_ONLINE); + printObject(BLINKER_F("upgradeData"), data); + BProto::printNow(); + #endif + } + #endif + + #if defined(BLINKER_LOWPOWER) || defined(BLINKER_LOWPOWER_AIR202) + int32_t BlinkerApi::comFreqGet() + { + String data = BLINKER_F("/lowpower?"); + data += BLINKER_F("deviceName="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::authKey(); + + int32_t _freq = blinkerServer(BLINKER_CMD_LOWPOWER_FREQ_GET_NUM, data).toInt(); + + if (_freq) return _freq; + else return -1; + } + + bool BlinkerApi::comFreqUpdate() + { + String data = BLINKER_F("/lowpower/modify?"); + data += BLINKER_F("deviceName="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::authKey(); + data += BLINKER_F("&freq="); + data += STRING_format(_LowPowerFreq); + + return blinkerServer(BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER, data) != "false"; + } + + String BlinkerApi::comDataGet() + { + String data = BLINKER_F("/lowpower/data?"); + data += BLINKER_F("deviceName="); + data += BProto::deviceName(); + data += BLINKER_F("&key="); + data += BProto::authKey(); + + return blinkerServer(BLINKER_CMD_LOWPOWER_DATA_GET_NUM, data); + } + + bool BlinkerApi::comDateUpdate() + { + String data = BLINKER_F("{\"deviceName\":\""); + data += BProto::deviceName(); + data += BLINKER_F("\",\"key\":\""); + data += BProto::authKey(); + data += BLINKER_F("\",\"data\":"); + data += BProto::_sendBuf; + data += BLINKER_F("}"); + + return blinkerServer(BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER, data) != "false"; + } + #endif + + #endif + + #if !defined(BLINKER_LOWPOWER_AIR202) + void BlinkerApi::aligeniePrint(String & _msg) + { + BLINKER_LOG_ALL(BLINKER_F("response to AliGenie: "), _msg); + + // BProto::aliPrint(_msg); + + if (_msg.length() <= BLINKER_MAX_SEND_SIZE) + { + // char* aliData = (char*)malloc((_msg.length()+1+128)*sizeof(char)); + // memcpy(aliData, '\0', _msg.length()+128); + // strcpy(aliData, _msg.c_str()); + BProto::aliPrint(_msg); + // free(aliData); + } + else + { + BLINKER_ERR_LOG(BLINKER_F("SEND DATA BYTES MAX THAN LIMIT!")); + } + } + + void BlinkerApi::duerPrint(String & _msg, bool report) + { + BLINKER_LOG_ALL(BLINKER_F("response to DuerOS: "), _msg); + + // BProto::aliPrint(_msg); + + if (_msg.length() <= BLINKER_MAX_SEND_SIZE) + { + // char* aliData = (char*)malloc((_msg.length()+1+128)*sizeof(char)); + // memcpy(aliData, '\0', _msg.length()+128); + // strcpy(aliData, _msg.c_str()); + BProto::duerPrint(_msg, report); + // free(aliData); + } + else + { + BLINKER_ERR_LOG(BLINKER_F("SEND DATA BYTES MAX THAN LIMIT!")); + } + } + + #if !defined(BLINKER_GPRS_AIR202) && !defined(BLINKER_NBIOT_SIM7020) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7020) && !defined(BLINKER_NBIOT_SIM7000) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7000) + void BlinkerApi::miotPrint(String & _msg) + { + BLINKER_LOG_ALL(BLINKER_F("response to MIOT: "), _msg); + + // BProto::aliPrint(_msg); + + if (_msg.length() <= BLINKER_MAX_SEND_SIZE) + { + // char* aliData = (char*)malloc((_msg.length()+1+128)*sizeof(char)); + // memcpy(aliData, '\0', _msg.length()+128); + // strcpy(aliData, _msg.c_str()); + BProto::miPrint(_msg); + // free(aliData); + } + else + { + BLINKER_ERR_LOG(BLINKER_F("SEND DATA BYTES MAX THAN LIMIT!")); + } + } + #endif + #endif + +#endif + +// #if defined(BLINKER_WIFI_SUBDEVICE) +// void BlinkerApi::aligeniePrint(String & _msg) +// { +// BLINKER_LOG_ALL(BLINKER_F("response to AliGenie: "), _msg); + +// if (_msg.length() <= BLINKER_MAX_SEND_SIZE) +// { +// BProto::aliPrint(_msg); +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("SEND DATA BYTES MAX THAN LIMIT!")); +// } +// } + +// void BlinkerApi::duerPrint(String & _msg) +// { +// BLINKER_LOG_ALL(BLINKER_F("response to DuerOS: "), _msg); + +// if (_msg.length() <= BLINKER_MAX_SEND_SIZE) +// { +// BProto::duerPrint(_msg); +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("SEND DATA BYTES MAX THAN LIMIT!")); +// } +// } + +// void BlinkerApi::miotPrint(String & _msg) +// { +// BLINKER_LOG_ALL(BLINKER_F("response to MIOT: "), _msg); + +// if (_msg.length() <= BLINKER_MAX_SEND_SIZE) +// { +// BProto::miPrint(_msg); +// } +// else +// { +// BLINKER_ERR_LOG(BLINKER_F("SEND DATA BYTES MAX THAN LIMIT!")); +// } +// } +// #endif + +void BlinkerApi::freshAttachWidget(char _name[], blinker_callback_with_string_arg_t _func) +{ + int8_t num = checkNum(_name, _Widgets_str, _wCount_str); + if(num >= 0 ) _Widgets_str[num]->setFunc(_func); +} + +// #if defined(BLINKER_BLE) + void BlinkerApi::freshAttachWidget(char _name[], blinker_callback_with_joy_arg_t _func) + { + int8_t num = checkNum(_name, _Widgets_joy, _wCount_joy); + if(num >= 0 ) _Widgets_joy[num]->setFunc(_func); + } +// #endif + +void BlinkerApi::freshAttachWidget(char _name[], blinker_callback_with_rgb_arg_t _func) +{ + int8_t num = checkNum(_name, _Widgets_rgb, _wCount_rgb); + if(num >= 0 ) _Widgets_rgb[num]->setFunc(_func); +} + +void BlinkerApi::freshAttachWidget(char _name[], blinker_callback_with_int32_arg_t _func) +{ + int8_t num = checkNum(_name, _Widgets_int, _wCount_int); + if(num >= 0 ) _Widgets_int[num]->setFunc(_func); +} + +void BlinkerApi::freshAttachWidget(char _name[], blinker_callback_with_table_arg_t _func, blinker_callback_t _func2) +{ + int8_t num = checkNum(_name, _Widgets_tab, _wCount_tab); + if(num >= 0 ) _Widgets_tab[num]->setFunc(_func, _func2); +} + +uint8_t BlinkerApi::attachWidget(char _name[], blinker_callback_with_string_arg_t _func) +{ + int8_t num = checkNum(_name, _Widgets_str, _wCount_str); + + if (num == BLINKER_OBJECT_NOT_AVAIL) + { + if (_wCount_str < BLINKER_MAX_WIDGET_SIZE*2) + { + _Widgets_str[_wCount_str] = new BlinkerWidgets_string(_name, _func); + _wCount_str++; + + BLINKER_LOG_ALL(BLINKER_F("new widgets: "), _name, \ + BLINKER_F(" _wCount_str: "), _wCount_str); + return _wCount_str; + } + else + { + return 0; + } + } + else if(num >= 0 ) + { + BLINKER_ERR_LOG(BLINKER_F("widgets name > "), _name, \ + BLINKER_F(" < has been registered, please register another name!")); + return 0; + } + else + { + return 0; + } +} + +// #if defined(BLINKER_BLE) + uint8_t BlinkerApi::attachWidget(char _name[], blinker_callback_with_joy_arg_t _func) + { + int8_t num = checkNum(_name, _Widgets_joy, _wCount_joy); + if (num == BLINKER_OBJECT_NOT_AVAIL) + { + if (_wCount_joy < BLINKER_MAX_WIDGET_SIZE/2) + { + _Widgets_joy[_wCount_joy] = new BlinkerWidgets_joy(_name, _func); + _wCount_joy++; + + BLINKER_LOG_ALL(BLINKER_F("new widgets: "), _name, \ + BLINKER_F(" _wCount_joy: "), _wCount_joy); + + return _wCount_joy; + } + else + { + return 0; + } + } + else if(num >= 0 ) + { + BLINKER_ERR_LOG(BLINKER_F("widgets name > "), _name, \ + BLINKER_F(" < has been registered, please register another name!")); + return 0; + } + else + { + return 0; + } + } +// #endif + +uint8_t BlinkerApi::attachWidget(char _name[], blinker_callback_with_rgb_arg_t _func) +{ + int8_t num = checkNum(_name, _Widgets_rgb, _wCount_rgb); + if (num == BLINKER_OBJECT_NOT_AVAIL) + { + if (_wCount_rgb < BLINKER_MAX_WIDGET_SIZE/2) + { + _Widgets_rgb[_wCount_rgb] = new BlinkerWidgets_rgb(_name, _func); + _wCount_rgb++; + + BLINKER_LOG_ALL(BLINKER_F("new widgets: "), _name, \ + BLINKER_F(" _wCount_rgb: "), _wCount_rgb); + + return _wCount_rgb; + } + else + { + return 0; + } + } + else if(num >= 0 ) + { + BLINKER_ERR_LOG(BLINKER_F("widgets name > "), _name, \ + BLINKER_F(" < has been registered, please register another name!")); + return 0; + } + else + { + return 0; + } +} + +uint8_t BlinkerApi::attachWidget(char _name[], blinker_callback_with_int32_arg_t _func) +{ + int8_t num = checkNum(_name, _Widgets_int, _wCount_int); + if (num == BLINKER_OBJECT_NOT_AVAIL) + { + if (_wCount_int < BLINKER_MAX_WIDGET_SIZE*2) + { + _Widgets_int[_wCount_int] = new BlinkerWidgets_int32(_name, _func); + _wCount_int++; + + BLINKER_LOG_ALL(BLINKER_F("new widgets: "), _name, \ + BLINKER_F(" _wCount_int: "), _wCount_int); + + return _wCount_int; + } + else + { + return 0; + } + } + else if(num >= 0 ) + { + BLINKER_ERR_LOG(BLINKER_F("widgets name > "), _name, \ + BLINKER_F(" < has been registered, please register another name!")); + return 0; + } + else + { + return 0; + } +} + +uint8_t BlinkerApi::attachWidget(char _name[], blinker_callback_with_table_arg_t _func, + blinker_callback_t _func2) +{ + int8_t num = checkNum(_name, _Widgets_tab, _wCount_tab); + if (num == BLINKER_OBJECT_NOT_AVAIL) + { + if (_wCount_tab < BLINKER_MAX_WIDGET_SIZE*2) + { + _Widgets_tab[_wCount_tab] = new BlinkerWidgets_table(_name, _func, _func2); + _wCount_tab++; + + BLINKER_LOG_ALL(BLINKER_F("new widgets: "), _name, \ + BLINKER_F(" _wCount_tab: "), _wCount_tab); + + return _wCount_tab; + } + else + { + return 0; + } + } + else if(num >= 0 ) + { + BLINKER_ERR_LOG(BLINKER_F("widgets name > "), _name, \ + BLINKER_F(" < has been registered, please register another name!")); + return 0; + } + else + { + return 0; + } +} + +void BlinkerApi::attachSwitch(blinker_callback_with_string_arg_t _func) +{ + // if (!_BUILTIN_SWITCH) + // { + // _BUILTIN_SWITCH = new BlinkerWidgets_string(BLINKER_CMD_BUILTIN_SWITCH, _func); + // } + // else + // { + // _BUILTIN_SWITCH->setFunc(_func); + // } + + _BUILTIN_SWITCH.setFunc(_func); +} + +char * BlinkerApi::widgetName_str(uint8_t num) +{ + if (num) return _Widgets_str[num - 1]->getName(); + else return ""; +} + +// #if defined(BLINKER_BLE) + char * BlinkerApi::widgetName_joy(uint8_t num) + { + if (num) return _Widgets_joy[num - 1]->getName(); + else return ""; + } +// #endif + +char * BlinkerApi::widgetName_rgb(uint8_t num) +{ + if (num) return _Widgets_rgb[num - 1]->getName(); + else return ""; +} + +char * BlinkerApi::widgetName_int(uint8_t num) +{ + if (num) return _Widgets_int[num - 1]->getName(); + else return ""; +} + +char * BlinkerApi::widgetName_tab(uint8_t num) +{ + if (num) return _Widgets_tab[num - 1]->getName(); + else return ""; +} + +#if defined(BLINKER_ARDUINOJSON) + int16_t BlinkerApi::ahrs(b_ahrsattitude_t attitude, const JsonObject& data) + { + if (data.containsKey(BLINKER_CMD_AHRS)) { + int16_t aAttiValue = data[BLINKER_CMD_AHRS][attitude]; + ahrsValue[Yaw] = data[BLINKER_CMD_AHRS][Yaw]; + ahrsValue[Roll] = data[BLINKER_CMD_AHRS][Roll]; + ahrsValue[Pitch] = data[BLINKER_CMD_AHRS][Pitch]; + BLINKER_LOG_ALL(BLINKER_F("ahrs isParsed")); + _fresh = true; + + return aAttiValue; + } + else { + return ahrsValue[attitude]; + } + } + + float BlinkerApi::gps(b_gps_t axis, const JsonObject& data) + { + // if (((millis() - gps_get_time) >= BLINKER_GPS_MSG_LIMIT || + // gps_get_time == 0) && !newData) + // { + // static_cast(this)->print(BLINKER_CMD_GET, BLINKER_CMD_GPS); + // static_cast(this)->printNow(); + // delay(100); + // } + + if (data.containsKey(BLINKER_CMD_GPS)) { + String gpsValue_LONG = data[BLINKER_CMD_GPS][LONG]; + String gpsValue_LAT = data[BLINKER_CMD_GPS][LAT]; + gpsValue[LONG] = gpsValue_LONG.toFloat(); + gpsValue[LAT] = gpsValue_LAT.toFloat(); + BLINKER_LOG_ALL(BLINKER_F("gps isParsed")); + _fresh = true; + + if (_fresh) { + BProto::isParsed(); + gps_get_time = millis(); + } + + return gpsValue[axis]*1000000; + } + else { + return gpsValue[axis]*1000000; + } + } + + void BlinkerApi::heartBeat(const JsonObject& data) + { + String state = data[BLINKER_CMD_GET]; + + // if (state.length()) + if (data.containsKey(BLINKER_CMD_GET)) + { + if (state == BLINKER_CMD_STATE) + { + #if defined(BLINKER_BLE) || defined(BLINKER_WIFI) + print(BLINKER_CMD_STATE, BLINKER_CMD_CONNECTED); + #else + print(BLINKER_CMD_STATE, BLINKER_CMD_ONLINE); + #endif + + #if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKE_HTTP) + String _timer = taskCount ? "1":"0"; + _timer += _cdState ? "1":"0"; + _timer += _lpState ? "1":"0"; + + BLINKER_LOG_ALL(BLINKER_F("timer codes: "), _timer); + + print(BLINKER_CMD_TIMER, _timer); + // static_cast(this)->printJson(timerSetting()); + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKE_HTTP) + print(BLINKER_CMD_VERSION, BLINKER_OTA_VERSION_CODE); + #endif + #endif + + if (_heartbeatFunc) { + _heartbeatFunc(); + } + + if (_summaryFunc) { + String summary_data = _summaryFunc(); + if (summary_data.length()) { + summary_data = summary_data.substring(0, BLINKER_MAX_SUMMARY_DATA_SIZE); + + BLINKER_LOG_ALL(BLINKER_F("summary_data: "), summary_data); + + print(BLINKER_CMD_SUMMARY, summary_data); + } + } + + BProto::checkState(false); + if (!BProto::printNow()) + { + #if defined(BLINKER_BLE) + print(BLINKER_CMD_STATE, BLINKER_CMD_CONNECTED); + #else + print(BLINKER_CMD_STATE, BLINKER_CMD_ONLINE); + #endif + + if (_summaryFunc) + { + String summary_data = _summaryFunc(); + if (summary_data.length()) + { + summary_data = summary_data.substring(0, BLINKER_MAX_SUMMARY_DATA_SIZE); + + BLINKER_LOG_ALL(BLINKER_F("summary_data: "), summary_data); + + print(BLINKER_CMD_SUMMARY, summary_data); + } + } + + BProto::checkState(false); + BProto::printNow(); + } + BLINKER_LOG_ALL(BLINKER_F("heartBeat isParsed 1")); + _fresh = true; + + #if defined(BLINKER_AT_MQTT) + atHeartbeat(); + #endif + } + } + } + + void BlinkerApi::getVersion(const JsonObject& data) + { + String state = data[BLINKER_CMD_GET]; + + // if (state.length()) + if (data.containsKey(BLINKER_CMD_GET)) + { + if (state == BLINKER_CMD_VERSION) + { + print(BLINKER_CMD_VERSION, BLINKER_OTA_VERSION_CODE); + BLINKER_LOG_ALL(BLINKER_F("getVersion isParsed")); + _fresh = true; + } + } + } + + void BlinkerApi::setSwitch(const JsonObject& data) + { + String state = data[BLINKER_CMD_BUILTIN_SWITCH]; + + // if (state.length()) + if (data.containsKey(BLINKER_CMD_BUILTIN_SWITCH)) + { + // if (_BUILTIN_SWITCH) + // { + // blinker_callback_with_string_arg_t sFunc = _BUILTIN_SWITCH->getFunc(); + + // if (sFunc) sFunc(state); + // } + blinker_callback_with_string_arg_t sFunc = _BUILTIN_SWITCH.getFunc(); + + if (sFunc) sFunc(state); + BLINKER_LOG_ALL(BLINKER_F("setSwitch isParsed")); + _fresh = true; + } + } + + // #if defined(BLINKER_WIFI_SUBDEVICE) + // void BlinkerApi::broadCast(const JsonObject& data) + // { + // if (data.containsKey(BLINKER_CMD_HELLO)) + // { + // if (data[BLINKER_CMD_HELLO] == BLINKER_CMD_WHOIS) + // { + // BLINKER_LOG_ALL(BLINKER_F("get device fresh broadCast")); + // BLINKER_LOG_ALL(BLINKER_F("broadCast isParsed")); + // _fresh = true; + // } + // } + // } + // #endif + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) + void BlinkerApi::bridgeParse(char _bName[], uint8_t num, const JsonObject& data) + { + BLINKER_LOG_ALL(BLINKER_F("_bridgeCount: "), _bridgeCount); + + BLINKER_LOG_ALL(BLINKER_F("data: "), _bridgeCount); + + // int8_t num = checkNum(_bName, _Bridge, _bridgeCount); + + BLINKER_LOG_ALL(BLINKER_F("bridgeParse num: "), num, ", name: ", _bName); + + if (!data.containsKey(BLINKER_CMD_FROMDEVICE)) + { + return; + } + + String _name = data[BLINKER_CMD_FROMDEVICE].as(); + + // if (data.containsKey(_bName)) + if (strncmp(_name.c_str(), _bName, _name.length()) == 0) + { + String state = data[BLINKER_CMD_DATA];//[_bName]; + + _fresh = true; + + BLINKER_LOG_ALL(BLINKER_F("bridgeParse: "), _bName); + + blinker_callback_with_string_arg_t nbFunc = _Bridge[num]->getFunc(); + + if (nbFunc) nbFunc(state); + } + } + #endif + + void BlinkerApi::strWidgetsParse(char _wName[], const JsonObject& data) + { + int8_t num = checkNum(_wName, _Widgets_str, _wCount_str); + + if (num == BLINKER_OBJECT_NOT_AVAIL) return; + + if (data.containsKey(_wName)) + { + String state = data[_wName]; + BLINKER_LOG_ALL(BLINKER_F("strWidgetsParse isParsed")); + _fresh = true; + + BLINKER_LOG_ALL(BLINKER_F("strWidgetsParse: "), _wName); + + blinker_callback_with_string_arg_t nbFunc = _Widgets_str[num]->getFunc(); + + if (nbFunc) nbFunc(state); + } + } + + // #if defined(BLINKER_BLE) + void BlinkerApi::joyWidgetsParse(char _wName[], const JsonObject& data) + { + int8_t num = checkNum(_wName, _Widgets_joy, _wCount_joy); + + if (num == BLINKER_OBJECT_NOT_AVAIL) return; + + if (data.containsKey(_wName)) + { + int16_t jxAxisValue = data[_wName][BLINKER_J_Xaxis]; + uint8_t jyAxisValue = data[_wName][BLINKER_J_Yaxis]; + BLINKER_LOG_ALL(BLINKER_F("joyWidgetsParse isParsed")); + _fresh = true; + + blinker_callback_with_joy_arg_t wFunc = _Widgets_joy[num]->getFunc(); + if (wFunc) wFunc(jxAxisValue, jyAxisValue); + } + } + // #endif + + void BlinkerApi::rgbWidgetsParse(char _wName[], const JsonObject& data) + { + int8_t num = checkNum(_wName, _Widgets_rgb, _wCount_rgb); + + if (num == BLINKER_OBJECT_NOT_AVAIL) return; + + if (data.containsKey(_wName)) + { + uint8_t _rValue = data[_wName][BLINKER_R]; + uint8_t _gValue = data[_wName][BLINKER_G]; + uint8_t _bValue = data[_wName][BLINKER_B]; + uint8_t _brightValue = data[_wName][BLINKER_BRIGHT]; + BLINKER_LOG_ALL(BLINKER_F("rgbWidgetsParse isParsed")); + _fresh = true; + + blinker_callback_with_rgb_arg_t wFunc = _Widgets_rgb[num]->getFunc(); + if (wFunc) wFunc(_rValue, _gValue, _bValue, _brightValue); + } + } + + void BlinkerApi::intWidgetsParse(char _wName[], const JsonObject& data) + { + int8_t num = checkNum(_wName, _Widgets_int, _wCount_int); + + if (num == BLINKER_OBJECT_NOT_AVAIL) return; + + if (data.containsKey(_wName)) { + int _number = data[_wName]; + BLINKER_LOG_ALL(BLINKER_F("intWidgetsParse isParsed")); + _fresh = true; + + blinker_callback_with_int32_arg_t wFunc = _Widgets_int[num]->getFunc(); + if (wFunc) { + wFunc(_number); + } + } + } + + void BlinkerApi::tabWidgetsParse(char _wName[], const JsonObject& data) + { + int8_t num = checkNum(_wName, _Widgets_tab, _wCount_tab); + + if (num == BLINKER_OBJECT_NOT_AVAIL) return; + + if (data.containsKey(_wName)) { + String _setData = data[_wName]; + + uint8_t _number = 0; + + blinker_callback_with_table_arg_t wFunc = _Widgets_tab[num]->getFunc(); + + for (uint8_t num = 0; num < 5; num++) + { + // BLINKER_LOG_ALL(BLINKER_F("num: "), _setData.substring(num, num + 1)); + + if (strcmp(_setData.substring(num, num + 1).c_str(), "1") == 0) + { + if (wFunc) { + switch (num) + { + case 0: + wFunc(BLINKER_CMD_TAB_0); + break; + case 1: + wFunc(BLINKER_CMD_TAB_1); + break; + case 2: + wFunc(BLINKER_CMD_TAB_2); + break; + case 3: + wFunc(BLINKER_CMD_TAB_3); + break; + case 4: + wFunc(BLINKER_CMD_TAB_4); + break; + default: + break; + } + } + } + } + + + // if (_setData == "10000") _number = BLINKER_CMD_TAB_0; + // else if (_setData == "01000") _number = BLINKER_CMD_TAB_1; + // else if (_setData == "00100") _number = BLINKER_CMD_TAB_2; + // else if (_setData == "00010") _number = BLINKER_CMD_TAB_3; + // else if (_setData == "00001") _number = BLINKER_CMD_TAB_4; + BLINKER_LOG_ALL(BLINKER_F("tabWidgetsParse isParsed")); + _fresh = true; + + blinker_callback_t wFunc2 = _Widgets_tab[num]->getFunc2(); + if (wFunc2) { + wFunc2(); + } + } + } + + void BlinkerApi::json_parse(const JsonObject& data) + { + setSwitch(data); + + for (uint8_t wNum = 0; wNum < _wCount_str; wNum++) { + strWidgetsParse(_Widgets_str[wNum]->getName(), data); + } + for (uint8_t wNum_int = 0; wNum_int < _wCount_int; wNum_int++) { + intWidgetsParse(_Widgets_int[wNum_int]->getName(), data); + } + for (uint8_t wNum_rgb = 0; wNum_rgb < _wCount_rgb; wNum_rgb++) { + rgbWidgetsParse(_Widgets_rgb[wNum_rgb]->getName(), data); + } + // #if defined(BLINKER_BLE) + for (uint8_t wNum_joy = 0; wNum_joy < _wCount_joy; wNum_joy++) { + joyWidgetsParse(_Widgets_joy[wNum_joy]->getName(), data); + } + // #endif + for (uint8_t wNum_tab = 0; wNum_tab < _wCount_tab; wNum_tab++) { + tabWidgetsParse(_Widgets_tab[wNum_tab]->getName(), data); + } + } + +#else + + int16_t BlinkerApi::ahrs(b_ahrsattitude_t attitude, char data[]) + { + int16_t aAttiValue = STRING_find_array_numberic_value(data, BLINKER_CMD_AHRS, attitude); + + if (aAttiValue != FIND_KEY_VALUE_FAILED) + { + ahrsValue[Yaw] = STRING_find_array_numberic_value(data, BLINKER_CMD_AHRS, Yaw); + ahrsValue[Roll] = STRING_find_array_numberic_value(data, BLINKER_CMD_AHRS, Roll); + ahrsValue[Pitch] = STRING_find_array_numberic_value(data, BLINKER_CMD_AHRS, Pitch); + BLINKER_LOG_ALL(BLINKER_F("ahrs isParsed")); + _fresh = true; + + return aAttiValue; + } + else { + return ahrsValue[attitude]; + } + } + + float BlinkerApi::gps(b_gps_t axis, char data[]) + { + // if (((millis() - gps_get_time) >= BLINKER_GPS_MSG_LIMIT || + // gps_get_time == 0) && !newData) + // { + // static_cast(this)->print(BLINKER_CMD_GET, BLINKER_CMD_GPS); + // static_cast(this)->printNow(); + // delay(100); + // } + + String axisValue = STRING_find_array_string_value(data, BLINKER_CMD_GPS, axis); + + if (axisValue != "") { + gpsValue[LONG] = STRING_find_array_string_value(data, BLINKER_CMD_GPS, LONG).toFloat(); + gpsValue[LAT] = STRING_find_array_string_value(data, BLINKER_CMD_GPS, LAT).toFloat(); + BLINKER_LOG_ALL(BLINKER_F("gps isParsed")); + _fresh = true; + + if (_fresh) { + BProto::isParsed(); + gps_get_time = millis(); + } + + return gpsValue[axis]*1000000; + } + else { + return gpsValue[axis]*1000000; + } + } + + void BlinkerApi::heartBeat(char data[]) + { + if (strstr(data, BLINKER_CMD_GET) && \ + strstr(data, BLINKER_CMD_STATE)) + { + #if defined(BLINKER_BLE) + print(BLINKER_CMD_STATE, BLINKER_CMD_CONNECTED); + #else + print(BLINKER_CMD_STATE, BLINKER_CMD_ONLINE); + #endif + + if (_heartbeatFunc) { + _heartbeatFunc(); + } + + if (_summaryFunc) + { + String summary_data = _summaryFunc(); + if (summary_data.length()) + { + summary_data = summary_data.substring(0, BLINKER_MAX_SUMMARY_DATA_SIZE); + + BLINKER_LOG_ALL(BLINKER_F("summary_data: "), summary_data); + + print(BLINKER_CMD_SUMMARY, summary_data); + } + } + + BProto::checkState(false); + if (!BProto::printNow()) + { + #if defined(BLINKER_BLE) + print(BLINKER_CMD_STATE, BLINKER_CMD_CONNECTED); + #else + print(BLINKER_CMD_STATE, BLINKER_CMD_ONLINE); + #endif + + if (_summaryFunc) + { + String summary_data = _summaryFunc(); + if (summary_data.length()) + { + summary_data = summary_data.substring(0, BLINKER_MAX_SUMMARY_DATA_SIZE); + + BLINKER_LOG_ALL(BLINKER_F("summary_data: "), summary_data); + + print(BLINKER_CMD_SUMMARY, summary_data); + } + } + + BProto::checkState(false); + BProto::printNow(); + } + BLINKER_LOG_ALL(BLINKER_F("heartBeat isParsed")); + _fresh = true; + + // #if defined(BLINKER_AT_MQTT) + // static_cast(this)->atHeartbeat(); + // #endif + } + } + + void BlinkerApi::getVersion(char data[]) + { + if (strstr(data, BLINKER_CMD_GET) && \ + strstr(data, BLINKER_CMD_VERSION)) + { + print(BLINKER_CMD_VERSION, BLINKER_VERSION); + BLINKER_LOG_ALL(BLINKER_F("getVersion isParsed")); + _fresh = true; + } + } + + void BlinkerApi::setSwitch(char data[]) + { + String state; + + if (STRING_find_string_value(data, state, BLINKER_CMD_BUILTIN_SWITCH)) + { + // if (_BUILTIN_SWITCH) + // { + // blinker_callback_with_string_arg_t sFunc = _BUILTIN_SWITCH->getFunc(); + + // if (sFunc) sFunc(state); + // } + blinker_callback_with_string_arg_t sFunc = _BUILTIN_SWITCH.getFunc(); + + if (sFunc) sFunc(state); + BLINKER_LOG_ALL(BLINKER_F("setSwitch isParsed")); + _fresh = true; + } + } + + void BlinkerApi::strWidgetsParse(char _wName[], char _data[]) + { + int8_t num = checkNum(_wName, _Widgets_str, _wCount_str); + + // BLINKER_LOG_ALL("====checkNum: ", num, " ===="); + // BLINKER_LOG_ALL("====_data: ", _data, " ===="); + + if (num == BLINKER_OBJECT_NOT_AVAIL) return; + + String state; + + if (STRING_find_string_value(_data, state, _wName)) + { + BLINKER_LOG_ALL(BLINKER_F("state: "), state); + BLINKER_LOG_ALL(BLINKER_F("strWidgetsParse isParsed")); + _fresh = true; + + blinker_callback_with_string_arg_t nbFunc = _Widgets_str[num]->getFunc(); + if (nbFunc) nbFunc(state); + } + } + + // #if defined(BLINKER_BLE) + void BlinkerApi::joyWidgetsParse(char _wName[], char _data[]) + { + int8_t num = checkNum(_wName, _Widgets_joy, _wCount_joy); + + if (num == BLINKER_OBJECT_NOT_AVAIL) return; + + int16_t jxAxisValue = STRING_find_array_numberic_value(_data, \ + _wName, BLINKER_J_Xaxis); + + if (jxAxisValue != FIND_KEY_VALUE_FAILED) + { + uint8_t jyAxisValue = STRING_find_array_numberic_value(_data, \ + _wName, BLINKER_J_Yaxis); + BLINKER_LOG_ALL(BLINKER_F("joyWidgetsParse isParsed")); + _fresh = true; + + blinker_callback_with_joy_arg_t wFunc = _Widgets_joy[num]->getFunc(); + + if (wFunc) wFunc(jxAxisValue, jyAxisValue); + } + } + // #endif + + void BlinkerApi::rgbWidgetsParse(char _wName[], char _data[]) + { + int8_t num = checkNum(_wName, _Widgets_rgb, _wCount_rgb); + + if (num == BLINKER_OBJECT_NOT_AVAIL) return; + + int16_t _rValue = STRING_find_array_numberic_value(_data, \ + _wName, BLINKER_R); + + if (_rValue != FIND_KEY_VALUE_FAILED) + { + uint8_t _gValue = STRING_find_array_numberic_value(_data, _wName, BLINKER_G); + uint8_t _bValue = STRING_find_array_numberic_value(_data, _wName, BLINKER_B); + uint8_t _brightValue = STRING_find_array_numberic_value(_data, _wName, BLINKER_BRIGHT); + BLINKER_LOG_ALL(BLINKER_F("rgbWidgetsParse isParsed")); + _fresh = true; + + blinker_callback_with_rgb_arg_t wFunc = _Widgets_rgb[num]->getFunc(); + + if (wFunc) wFunc(_rValue, _gValue, _bValue, _brightValue); + } + } + + void BlinkerApi::intWidgetsParse(char _wName[], char _data[]) + { + int8_t num = checkNum(_wName, _Widgets_int, _wCount_int); + + if (num == BLINKER_OBJECT_NOT_AVAIL) return; + + int _number = STRING_find_numberic_value(_data, _wName); + + if (_number != FIND_KEY_VALUE_FAILED) + { + BLINKER_LOG_ALL(BLINKER_F("intWidgetsParse isParsed")); + _fresh = true; + + blinker_callback_with_int32_arg_t wFunc = _Widgets_int[num]->getFunc(); + + if (wFunc) wFunc(_number); + } + } + + void BlinkerApi::tabWidgetsParse(char _wName[], char _data[]) + { + int8_t num = checkNum(_wName, _Widgets_tab, _wCount_tab); + + if (num == BLINKER_OBJECT_NOT_AVAIL) return; + + String _setData; + + if (STRING_find_string_value(_data, _setData, _wName)) + { + BLINKER_LOG_ALL(BLINKER_F("_setData: "), _setData); + BLINKER_LOG_ALL(BLINKER_F("tabWidgetsParse isParsed")); + _fresh = true; + + // uint8_t _number = 0; + + // if (_setData == "10000") _number = BLINKER_CMD_TAB_0; + // else if (_setData == "01000") _number = BLINKER_CMD_TAB_1; + // else if (_setData == "00100") _number = BLINKER_CMD_TAB_2; + // else if (_setData == "00010") _number = BLINKER_CMD_TAB_3; + // else if (_setData == "00001") _number = BLINKER_CMD_TAB_4; + + // blinker_callback_with_table_arg_t wFunc = _Widgets_tab[num]->getFunc(); + // if (wFunc) { + // wFunc(_number); + // } + + blinker_callback_with_table_arg_t wFunc = _Widgets_tab[num]->getFunc(); + + for (uint8_t num = 0; num < 5; num++) + { + // BLINKER_LOG_ALL(BLINKER_F("num: "), _setData.substring(num, num + 1)); + + if (strcmp(_setData.substring(num, num + 1).c_str(), "1") == 0) + { + if (wFunc) { + switch (num) + { + case 0: + wFunc(BLINKER_CMD_TAB_0); + break; + case 1: + wFunc(BLINKER_CMD_TAB_1); + break; + case 2: + wFunc(BLINKER_CMD_TAB_2); + break; + case 3: + wFunc(BLINKER_CMD_TAB_3); + break; + case 4: + wFunc(BLINKER_CMD_TAB_4); + break; + default: + break; + } + } + } + } + + blinker_callback_t wFunc2 = _Widgets_tab[num]->getFunc2(); + if (wFunc2) { + wFunc2(); + } + } + + // int _number = STRING_find_numberic_value(_data, _wName); + + // if (_number != FIND_KEY_VALUE_FAILED) + // { + // _fresh = true; + + // blinker_callback_with_table_arg_t wFunc = _Widgets_tab[num]->getFunc(); + + // if (wFunc) wFunc(_number); + // } + } + + void BlinkerApi::json_parse(char _data[]) + { + setSwitch(_data); + + BLINKER_LOG_ALL(BLINKER_F("====_wCount_str: "), _wCount_str, BLINKER_F(" ====")); + + for (uint8_t wNum = 0; wNum < _wCount_str; wNum++) { + strWidgetsParse(_Widgets_str[wNum]->getName(), _data); + } + for (uint8_t wNum_int = 0; wNum_int < _wCount_int; wNum_int++) { + intWidgetsParse(_Widgets_int[wNum_int]->getName(), _data); + } + for (uint8_t wNum_rgb = 0; wNum_rgb < _wCount_rgb; wNum_rgb++) { + rgbWidgetsParse(_Widgets_rgb[wNum_rgb]->getName(), _data); + } + // #if defined(BLINKER_BLE) + for (uint8_t wNum_joy = 0; wNum_joy < _wCount_joy; wNum_joy++) { + joyWidgetsParse(_Widgets_joy[wNum_joy]->getName(), _data); + } + // #endif + for (uint8_t wNum_tab = 0; wNum_tab < _wCount_tab; wNum_tab++) { + tabWidgetsParse(_Widgets_tab[wNum_tab]->getName(), _data); + } + } +#endif + +#if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_LOWPOWER_AIR202) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + + void BlinkerApi::beginAuto() + { + BLINKER_LOG(BLINKER_F("=======================================================")); + BLINKER_LOG(BLINKER_F("=========== Blinker Auto Control mode init! ===========")); + BLINKER_LOG(BLINKER_F(" EEPROM address 0-1279 is used for Auto Control!")); + BLINKER_LOG(BLINKER_F("======= PLEASE AVOID USING THESE EEPROM ADDRESS! ======")); + BLINKER_LOG(BLINKER_F("=======================================================")); + + // BLINKER_LOG(BLINKER_F("Already used: "), BLINKER_ONE_AUTO_DATA_SIZE); + + _isAuto = true; + // deserialization(); + // autoStart(); + + autoInit(); //TODO + } + + bool BlinkerApi::autoTrigged(uint32_t _id) + { + BLINKER_LOG_ALL(BLINKER_F("autoTrigged id: "), _id); + + return BProto::autoPrint(_id); + } + + bool BlinkerApi::checkCanOTA() + { + // #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || defined (BLINKER_AT_MQTT) + #if defined(ESP8266) + int boot_mode = (GPI >> 16) & 0xf; + if (boot_mode == 1) + { + // _setError(UPDATE_ERROR_BOOTSTRAP); + // return false; + BLINKER_ERR_LOG(BLINKER_F("===========================================================")); + BLINKER_ERR_LOG(BLINKER_F("Invalid bootstrapping state, reset ESP8266 before updating!")); + BLINKER_ERR_LOG(BLINKER_F("===========================================================")); + + return false; + } + #endif + // #endif + + return true; + } + + #if !defined(BLINKER_WIFI_SUBDEVICE) + bool BlinkerApi::ntpInit() + { + if (!_isNTPInit) + { + freshNTP(); + + if ((millis() - _ntpStart) > BLINKER_NTP_TIMEOUT) + { + _ntpStart = millis(); + } + else { + return false; + } + + ntpConfig(); + // String ntp1 = BLINKER_F("ntp1.aliyun.com"); + // String ntp2 = BLINKER_F("210.72.145.44"); + // String ntp3 = BLINKER_F("time.pool.aliyun.com"); + + // configTime((long)(_timezone * 3600), 0, + // ntp1.c_str(), ntp2.c_str(), ntp3.c_str()); + // configTime((long)(_timezone * 3600), 0, "ntp1.aliyun.com", "210.72.145.44", "time.pool.aliyun.com"); + + time_t now_ntp = ::time(nullptr); + + float _com_timezone = abs(getTimezone()); + if (_com_timezone < 1.0) _com_timezone = 1.0; + + if (now_ntp < _com_timezone * 3600 * 12) + { + ntpConfig(); + // configTime((long)(_timezone * 3600), 0, + // ntp1.c_str(), ntp2.c_str(), ntp3.c_str()); + // configTime((long)(_timezone * 3600), 0, "ntp1.aliyun.com", "210.72.145.44", "time.pool.aliyun.com"); + now_ntp = ::time(nullptr); + if (now_ntp < _com_timezone * 3600 * 12) + { + ::delay(50); + now_ntp = ::time(nullptr); + return false; + } + } + + struct tm timeinfo; + + #if defined(ESP8266) + gmtime_r(&now_ntp, &timeinfo); + #elif defined(ESP32) + localtime_r(&now_ntp, &timeinfo); + #endif + + BLINKER_LOG_ALL(BLINKER_F("Current time: "), asctime(&timeinfo)); + #if defined(ESP8266) + BLINKER_LOG_ALL(BLINKER_F("NTP time: "), now_ntp - (int)(getTimezone()*3600)); + #elif defined(ESP32) + BLINKER_LOG_ALL(BLINKER_F("NTP time: "), now_ntp); + #endif + + _isNTPInit = true; + + _deviceStartTime = time() - millis()/1000; + + return true; + } + return true; + } + + + void BlinkerApi:: freshNTP() + { + if (_isNTPInit) + { + time_t now_ntp = ::time(nullptr); + struct tm timeinfo; + #if defined(ESP8266) + gmtime_r(&now_ntp, &timeinfo); + #elif defined(ESP32) + localtime_r(&now_ntp, &timeinfo); + #endif + } + } + + + void BlinkerApi::ntpConfig() + { + // String ntp1 = BLINKER_F("ntp1.aliyun.com"); + // String ntp2 = BLINKER_F("210.72.145.44"); + // String ntp3 = BLINKER_F("time.pool.aliyun.com"); + + // configTime((long)(_timezone * 3600), 0, + // ntp1.c_str(), ntp2.c_str(), ntp3.c_str()); + + configTime((long)(getTimezone() * 3600), 0, "ntp1.aliyun.com", \ + "120.25.108.11", "time.pool.aliyun.com"); + } + #endif + + + void BlinkerApi::saveCountDown(uint32_t _data, char _action[]) + { + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_COUNTDOWN, _data); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_COUNTDOWN_ACTION, _action); + EEPROM.commit(); + EEPROM.end(); + } + + + void BlinkerApi::saveLoop(uint32_t _data, char _action1[], char _action2[]) + { + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP, _data); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP_ACTION1, _action1); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP_ACTION2, _action2); + EEPROM.commit(); + EEPROM.end(); + } + + + void BlinkerApi::loadCountdown() + { + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_TIMER_COUNTDOWN, _cdData); + EEPROM.get(BLINKER_EEP_ADDR_TIMER_COUNTDOWN_ACTION, _cdAction); + EEPROM.commit(); + EEPROM.end(); + + _cdState = _cdData >> 31; + _cdRunState = _cdData >> 30 & 0x0001; + _cdTime1 = _cdData >> 12 & 0x0FFF; + _cdTime2 = _cdData & 0x0FFF; + + if (_cdTime1 == 0) + { + _cdState = 0; + _cdRunState = 0; + } + + BLINKER_LOG_ALL(BLINKER_F("countdown state: "), _cdState ? "true" : "false"); + BLINKER_LOG_ALL(BLINKER_F("_cdRunState: "), _cdRunState); + BLINKER_LOG_ALL(BLINKER_F("_totalTime: "), _cdTime1); + BLINKER_LOG_ALL(BLINKER_F("_runTime: "), _cdTime2); + BLINKER_LOG_ALL(BLINKER_F("_action: "), _cdAction); + + if (_cdState && _cdRunState) + { + uint32_t _cdTime1_; + + if (_cdTime1 * 60 > BLINKER_ONE_HOUR_TIME) _cdTime1_ = BLINKER_ONE_HOUR_TIME; + else _cdTime1_ = _cdTime1 * 60; + + cdTicker.once(_cdTime1_, _cd_callback); + + _cdStart = millis(); + + BLINKER_LOG_ALL(BLINKER_F("countdown start!")); + } + } + + + void BlinkerApi::loadLoop() + { + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_TIMER_LOOP, _lpData); + EEPROM.get(BLINKER_EEP_ADDR_TIMER_LOOP_TRI, _lpTrigged_times); + EEPROM.get(BLINKER_EEP_ADDR_TIMER_LOOP_ACTION1, _lpAction1); + EEPROM.get(BLINKER_EEP_ADDR_TIMER_LOOP_ACTION2, _lpAction2); + EEPROM.commit(); + EEPROM.end(); + + _lpState = _lpData >> 31; + _lpRunState = _lpData >> 30 & 0x0001; + _lpTimes = _lpData >> 22 & 0x007F; + _lpTime1 = _lpData >> 11 & 0x07FF; + _lpTime2 = _lpData & 0x07FF; + + BLINKER_LOG_ALL(BLINKER_F("loop state: "), _lpState ? "true" : "false"); + BLINKER_LOG_ALL(BLINKER_F("_lpRunState: "), _lpRunState); + BLINKER_LOG_ALL(BLINKER_F("_times: "), _lpTimes); + BLINKER_LOG_ALL(BLINKER_F("_tri_times: "), _lpTrigged_times); + BLINKER_LOG_ALL(BLINKER_F("_time1: "), _lpTime1); + BLINKER_LOG_ALL(BLINKER_F("_action1: "), _lpAction1); + BLINKER_LOG_ALL(BLINKER_F("_time2: "), _lpTime2); + BLINKER_LOG_ALL(BLINKER_F("_action2: "), _lpAction2); + BLINKER_LOG_ALL(BLINKER_F("_lpData: "), _lpData); + + if (_lpState && _lpRunState && (_lpTimes == 0)) + { + _lpRun1 = true; + _lpStop = false; + + uint32_t _lpTime1_; + + if (_lpTime1 * 60 > BLINKER_ONE_HOUR_TIME) _lpTime1_ = BLINKER_ONE_HOUR_TIME; + else _lpTime1_ = _lpTime1 * 60; + + _lpTime1_start = millis(); + lpTicker.once(_lpTime1_, _lp_callback); + + BLINKER_LOG_ALL(BLINKER_F("loop start!")); + } + } + + + void BlinkerApi::loadTiming() + { + BLINKER_LOG_ALL(BLINKER_F("load timing")); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_TIMER_TIMING_COUNT, taskCount); + uint32_t _tmData; + char _tmAction_[BLINKER_TIMER_TIMING_ACTION_SIZE]; + + if (taskCount > BLINKER_TIMING_TIMER_SIZE) + { + taskCount = 0; + } + BLINKER_LOG_ALL(BLINKER_F("load timing taskCount: "), taskCount); + + for(uint8_t task = 0; task < taskCount; task++) + { + EEPROM.get(BLINKER_EEP_ADDR_TIMER_TIMING + task * BLINKER_ONE_TIMER_TIMING_SIZE + , _tmData); + EEPROM.get(BLINKER_EEP_ADDR_TIMER_TIMING + task * BLINKER_ONE_TIMER_TIMING_SIZE + + BLINKER_TIMER_TIMING_SIZE, _tmAction_); + + timingTask[task] = new BlinkerTimingTimer(_tmData, STRING_format(_tmAction_)); + + BLINKER_LOG_ALL(BLINKER_F("_tmData: "), _tmData); + BLINKER_LOG_ALL(BLINKER_F("_tmAction: "), STRING_format(_tmAction_)); + } + EEPROM.commit(); + EEPROM.end(); + + uint8_t wDay = wday(); + uint16_t nowMins = hour() * 60 + minute(); + + freshTiming(wDay, nowMins); + } + + + void BlinkerApi::checkOverlapping(uint8_t checkDays, uint16_t checkMins, uint8_t taskNum) + { + BLINKER_LOG_ALL(BLINKER_F("checkMins: "), checkMins); + BLINKER_LOG_ALL(BLINKER_F("checkDays: "), checkDays); + + char _tmAction[BLINKER_TIMER_TIMING_ACTION_SIZE]; + + for (uint8_t task = 0; task < taskCount; task++) + { + + BLINKER_LOG_ALL(BLINKER_F("getTime: "), timingTask[task]->getTime()); + BLINKER_LOG_ALL(BLINKER_F("isLoop: "), timingTask[task]->isLoop()); + BLINKER_LOG_ALL(BLINKER_F("state: "), timingTask[task]->state()); + BLINKER_LOG_ALL(BLINKER_F("isTimingDay: "), timingTask[task]->isTimingDay(checkDays)); + + if((timingTask[task]->getTime() == checkMins) && \ + !timingTask[task]->isLoop() && \ + timingTask[task]->state() && \ + timingTask[task]->isTimingDay(checkDays)) + { + + timingTask[task]->disableTask(); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_TIMING_COUNT, taskCount); + + EEPROM.put( BLINKER_EEP_ADDR_TIMER_TIMING + \ + task * BLINKER_ONE_TIMER_TIMING_SIZE, \ + timingTask[task]->getTimerData()); + + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("disable timerData: "), timingTask[task]->getTimerData()); + BLINKER_LOG_ALL(BLINKER_F("disableTask: "), task); + + strcpy(_tmAction, timingTask[task]->getAction()); + + if (task != taskNum) + { + #if defined(BLINKER_AT_MQTT) + BProto::serialPrint(_tmAction); + #else + parse(_tmAction, true); + #endif + } + } + else if((timingTask[task]->getTime() == checkMins) && \ + timingTask[task]->state() && \ + timingTask[task]->isTimingDay(checkDays)) + { + BLINKER_LOG(BLINKER_F("checkOverlapping, timing trigged, action is: "), _tmAction); + + strcpy(_tmAction, timingTask[task]->getAction()); + + if (task != taskNum) + { + #if defined(BLINKER_AT_MQTT) + BProto::serialPrint(_tmAction); + #else + parse(_tmAction, true); + #endif + } + } + } + } + + + void BlinkerApi::freshTiming(uint8_t wDay, uint16_t nowMins) + { + tmTicker.detach(); + + uint8_t cbackData; + uint8_t nextTask = BLINKER_TIMING_TIMER_SIZE; + // uint16_t timingMinsNext; + uint32_t apartSeconds = BLINKER_ONE_DAY_TIME; + uint32_t checkSeconds = BLINKER_ONE_DAY_TIME; + uint32_t nowSeconds = dtime(); + + BLINKER_LOG_ALL(BLINKER_F("freshTiming wDay: "), wDay, + BLINKER_F(", nowMins: "), nowMins, + BLINKER_F(", nowSeconds: "), nowSeconds); + + for (uint8_t task = 0; task < taskCount; task++) + { + if (timingTask[task]->isTimingDay(wDay) && timingTask[task]->state()) + { + if (timingTask[task]->getTime() > nowMins) + { + checkSeconds = timingTask[task]->getTime() * 60 - nowSeconds; + + // checkSeconds = checkSeconds / 60 / 30; + + if (checkSeconds <= apartSeconds) { + apartSeconds = checkSeconds; + nextTask = task; + } + } + } + + BLINKER_LOG_ALL(BLINKER_F("isTimingDay: "), timingTask[task]->isTimingDay(wDay)); + BLINKER_LOG_ALL(BLINKER_F("state: "), timingTask[task]->state()); + BLINKER_LOG_ALL(BLINKER_F("getTime: "), timingTask[task]->getTime()); + + BLINKER_LOG_ALL(BLINKER_F("for nextTask: "), nextTask, + BLINKER_F(" apartSeconds: "), apartSeconds, + BLINKER_F(" wDay: "), wDay); + } + + if (apartSeconds == BLINKER_ONE_DAY_TIME) + { + apartSeconds -= nowSeconds; + + // apartSeconds = apartSeconds / 60 / 30; + BLINKER_LOG_ALL(BLINKER_F("nextTask: "), nextTask, + BLINKER_F(" apartSeconds: "), apartSeconds, + BLINKER_F(" wDay: "), wDay); + + cbackData = nextTask; + } + else + { + BLINKER_LOG_ALL(BLINKER_F("nextTask: "), nextTask, + BLINKER_F(" apartSeconds: "), apartSeconds, + BLINKER_F(" wDay: "), wDay); + + cbackData = nextTask; + } + BLINKER_LOG_ALL(BLINKER_F("cbackData: "), cbackData); + + if (apartSeconds > BLINKER_ONE_HOUR_TIME) + { + apartSeconds = BLINKER_ONE_HOUR_TIME; + + BLINKER_LOG_ALL(BLINKER_F("change apartSeconds: "), apartSeconds); + } + + tmTicker.once(apartSeconds, timingHandle, cbackData); + } + + + void BlinkerApi::deleteTiming(uint8_t taskDel) + { + if (taskDel < taskCount) + { + // tmTicker.detach(); + + for (uint8_t task = taskDel; task < (taskCount - 1); task++) + { + // timingTask[task]->freshTimer(timingTask[task + 1]->getTimerData(), + // timingTask[task + 1]->getAction(), timingTask[task + 1]->getText()); + timingTask[task]->freshTimer(timingTask[task + 1]->getTimerData(), + timingTask[task + 1]->getAction()); + } + + delete timingTask[taskCount - 1]; + + taskCount--; + + BLINKER_LOG_ALL(BLINKER_F("delete task: "), taskDel, BLINKER_F(" success!")); + + uint8_t wDay = wday(); + uint16_t nowMins = hour() * 60 + minute(); + freshTiming(wDay, nowMins); + } + else + { + BLINKER_LOG_ALL(BLINKER_F("none task to delete!")); + } + } + + + void BlinkerApi::addTimingTask(uint8_t taskSet, uint32_t timerData, const String & action) + { + BLINKER_LOG_ALL(BLINKER_F("addTimingTask taskSet: "), taskSet); + BLINKER_LOG_ALL(BLINKER_F("addTimingTask timerData: "), timerData); + + if (taskSet <= taskCount && taskCount <= BLINKER_TIMING_TIMER_SIZE) + { + // tmTicker.detach(); + + if (taskSet == taskCount) + { + if (taskCount == BLINKER_TIMING_TIMER_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("timing timer task is full")); + return; + } + // timingTask[taskSet] = new BlinkerTimingTimer(timerData, action, text); + timingTask[taskSet] = new BlinkerTimingTimer(timerData, action); + taskCount++; + + BLINKER_LOG_ALL(BLINKER_F("new BlinkerTimingTimer")); + } + else + { + // timingTask[taskSet]->freshTimer(timerData, action, text); + timingTask[taskSet]->freshTimer(timerData, action); + + BLINKER_LOG_ALL(BLINKER_F("freshTimer")); + } + + // if (taskSet <= taskCount) taskCount++; + + BLINKER_LOG_ALL(BLINKER_F("taskCount: "), taskCount); + + uint8_t wDay = wday(); + uint16_t nowMins = hour() * 60 + minute(); + + freshTiming(wDay, nowMins); + } + else { + BLINKER_ERR_LOG(BLINKER_F("timing timer task is full")); + } + } + + + void BlinkerApi::checkTimerErase() + { + // #if defined(ESP8266) + static uint8_t isErase; + // #endif + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_TIMER_ERASE, isErase); + + if (isErase) + { + for (uint16_t _addr = BLINKER_EEP_ADDR_TIMER; + _addr < BLINKER_EEP_ADDR_TIMER_END; _addr++) + { + EEPROM.put(_addr, "\0"); + } + } + + EEPROM.commit(); + EEPROM.end(); + } + + + String BlinkerApi::timerSetting() + { + + String _data = BLINKER_F("\""); + _data += BLINKER_F(BLINKER_CMD_COUNTDOWN); + _data += BLINKER_F("\":"); + _data += STRING_format(_cdState ? "true" : "false"); + _data += BLINKER_F(",\""); + _data += BLINKER_F(BLINKER_CMD_LOOP); + _data += BLINKER_F("\":"); + _data += STRING_format(_lpState ? "true" : "false"); + _data += BLINKER_F(",\""); + _data += BLINKER_F(BLINKER_CMD_TIMING); + _data += BLINKER_F("\":"); + _data += STRING_format(taskCount ? "true" : "false"); + + + BLINKER_LOG_ALL(BLINKER_F("timerSetting: "), _data); + + return _data; + } + + + String BlinkerApi::countdownConfig() + { + String cdData; + + if (!_cdState) + { + cdData = BLINKER_F("{\""); + cdData += BLINKER_F(BLINKER_CMD_COUNTDOWN); + cdData += BLINKER_F("\":false}"); + } + else + { + if (_cdRunState) + { + cdData = BLINKER_F("{\""); + cdData += BLINKER_F(BLINKER_CMD_COUNTDOWN); + cdData += BLINKER_F("\":{\""); + cdData += BLINKER_F(BLINKER_CMD_RUN); + cdData += BLINKER_F("\":"); + cdData += STRING_format(_cdRunState ? 1 : 0); + cdData += BLINKER_F(",\""); + cdData += BLINKER_F(BLINKER_CMD_TOTALTIME); + cdData += BLINKER_F("\":"); + cdData += STRING_format(_cdTime1); + cdData += BLINKER_F(",\""); + cdData += BLINKER_F(BLINKER_CMD_RUNTIME); + cdData += BLINKER_F("\":"); + cdData += STRING_format((millis() - _cdStart) / 1000 / 60); + cdData += BLINKER_F(",\""); + cdData += BLINKER_F(BLINKER_CMD_ACTION); + cdData += BLINKER_F("\":"); + cdData += _cdAction; + cdData += BLINKER_F("}}"); + } + else + { + cdData = BLINKER_F("{\""); + cdData += BLINKER_F(BLINKER_CMD_COUNTDOWN); + cdData += BLINKER_F("\":{\""); + cdData += BLINKER_F(BLINKER_CMD_RUN); + cdData += BLINKER_F("\":"); + cdData += STRING_format(_cdRunState ? 1 : 0); + cdData += BLINKER_F(",\""); + cdData += BLINKER_F(BLINKER_CMD_TOTALTIME); + cdData += BLINKER_F("\":"); + cdData += STRING_format(_cdTime1); + cdData += BLINKER_F(",\""); + cdData += BLINKER_F(BLINKER_CMD_RUNTIME); + cdData += BLINKER_F("\":"); + cdData += STRING_format(_cdTime2); + cdData += BLINKER_F(",\""); + cdData += BLINKER_F(BLINKER_CMD_ACTION); + cdData += BLINKER_F("\":"); + cdData += _cdAction; + cdData += BLINKER_F("}}"); + } + } + + return cdData; + } + + + String BlinkerApi::timingConfig() + { + String timingTaskStr = BLINKER_F("{\""); + timingTaskStr += BLINKER_F(BLINKER_CMD_TIMING); + timingTaskStr += BLINKER_F("\":["); + + for (uint8_t task = 0; task < taskCount; task++) + { + //Serial.print(timingTask[task].getTimingCfg()); + timingTaskStr += getTimingCfg(task); + if (task + 1 < taskCount) + { + //Serial.println(","); + timingTaskStr += BLINKER_F(","); + } + // else { + // Serial.println(""); + // } + } + timingTaskStr += BLINKER_F("]}"); + + BLINKER_LOG_ALL(BLINKER_F("timingTaskStr: "), timingTaskStr); + + return timingTaskStr; + } + + + String BlinkerApi::getTimingCfg(uint8_t task) + { + String timingDayStr = BLINKER_F(""); + uint8_t timingDay = timingTask[task]->getTimingday(); + if (timingTask[task]->isLoop()) + { + for (uint8_t day = 0; day < 7; day++) + { + // timingDayStr += (timingDay & (uint8_t)pow(2,day)) ? String(day):String(""); + if ((timingDay >> day) & 0x01) { + timingDayStr += STRING_format(1); + // if (day < 6 && (timingDay >> (day + 1))) + // timingDayStr += STRING_format(","); + } + else { + timingDayStr += STRING_format(0); + } + // timingDayStr += String((day < 6) ? ((timingDay >> (day + 1)) ? ",":""):""); + } + + BLINKER_LOG_ALL(BLINKER_F("timingDayStr: "), timingDayStr); + + } + else { + timingDayStr = BLINKER_F("0000000"); + + BLINKER_LOG_ALL(BLINKER_F("timingDayStr: "), timingDay); + } + + String timingConfig = BLINKER_F("{\""); + timingConfig += BLINKER_F(BLINKER_CMD_TASK); + timingConfig += BLINKER_F("\":"); + timingConfig += STRING_format(task); + timingConfig += BLINKER_F(",\""); + timingConfig += BLINKER_F(BLINKER_CMD_ENABLE); + timingConfig += BLINKER_F("\":"); + timingConfig += STRING_format((timingTask[task]->state()) ? 1 : 0); + timingConfig += BLINKER_F(",\""); + timingConfig += BLINKER_F(BLINKER_CMD_DAY); + timingConfig += BLINKER_F("\":\""); + timingConfig += timingDayStr; + timingConfig += BLINKER_F("\",\""); + timingConfig += BLINKER_F(BLINKER_CMD_TIME); + timingConfig += BLINKER_F("\":"); + timingConfig += STRING_format(timingTask[task]->getTime()); + timingConfig += BLINKER_F(",\""); + timingConfig += BLINKER_F(BLINKER_CMD_ACTION); + timingConfig += BLINKER_F("\":"); + timingConfig += timingTask[task]->getAction(); + timingConfig += BLINKER_F("}"); + + return timingConfig; + } + + + String BlinkerApi::loopConfig() + { + String lpData; + if (!_lpState) { + lpData = BLINKER_F("{\""); + lpData += BLINKER_F(BLINKER_CMD_LOOP); + lpData += BLINKER_F("\":false}"); + } + else { + lpData = BLINKER_F("{\""); + lpData += BLINKER_F(BLINKER_CMD_LOOP); + lpData += BLINKER_F("\":{\""); + lpData += BLINKER_F(BLINKER_CMD_TIMES); + lpData += BLINKER_F("\":"); + lpData += STRING_format(_lpTimes); + lpData += BLINKER_F(",\""); + lpData += BLINKER_F(BLINKER_CMD_RUN); + lpData += BLINKER_F("\":"); + lpData += STRING_format(_lpRunState ? 1 : 0); + lpData += BLINKER_F(",\""); + lpData += BLINKER_F(BLINKER_CMD_TRIGGED); + lpData += BLINKER_F("\":"); + lpData += STRING_format(_lpTimes ? _lpTrigged_times : 0); + lpData += BLINKER_F(",\""); + lpData += BLINKER_F(BLINKER_CMD_TIME1); + lpData += BLINKER_F("\":"); + lpData += STRING_format(_lpTime1); + lpData += BLINKER_F(",\""); + lpData += BLINKER_F(BLINKER_CMD_ACTION1); + lpData += BLINKER_F("\":"); + lpData += _lpAction1; + lpData += BLINKER_F(",\""); + lpData += BLINKER_F(BLINKER_CMD_TIME2); + lpData += BLINKER_F("\":"); + lpData += STRING_format(_lpTime2); + lpData += BLINKER_F(",\""); + lpData += BLINKER_F(BLINKER_CMD_ACTION2); + lpData += BLINKER_F("\":"); + lpData += _lpAction2; + lpData += BLINKER_F("}}"); + } + + return lpData; + } + + + bool BlinkerApi::timerManager(const JsonObject& data, bool _noSet) + { + bool isSet = false; + bool isCount = false; + bool isLoop = false; + bool isTiming = false; + + if (!_noSet) + { + isSet = STRING_contains_string(BProto::dataParse(), BLINKER_CMD_SET); + isCount = STRING_contains_string(BProto::dataParse(), BLINKER_CMD_COUNTDOWN); + isLoop = STRING_contains_string(BProto::dataParse(), BLINKER_CMD_LOOP); + isTiming = STRING_contains_string(BProto::dataParse(), BLINKER_CMD_TIMING); + } + else { + isCount = data.containsKey(BLINKER_CMD_COUNTDOWN); + isLoop = data.containsKey(BLINKER_CMD_LOOP); + isTiming = data.containsKey(BLINKER_CMD_TIMING); + } + + if ((isSet || _noSet) && (isCount || isLoop || isTiming)) + { + BLINKER_LOG_ALL(BLINKER_F("timerManager isParsed")); + _fresh = true; + + BLINKER_LOG_ALL(BLINKER_F("get timer setting")); + + if (isCount) + { + + String _delete = data[BLINKER_CMD_SET][BLINKER_CMD_COUNTDOWN]; + + if (_delete == "dlt") _cdState = false; + else _cdState = true; + + if (_cdState) + { + if (isSet) + { + _cdRunState = data[BLINKER_CMD_SET][BLINKER_CMD_COUNTDOWN][BLINKER_CMD_RUN]; + } + else if(_noSet) + { + _cdRunState = data[BLINKER_CMD_COUNTDOWN][BLINKER_CMD_RUN]; + } + + BLINKER_LOG_ALL(BLINKER_F("countdown state: "), _cdState ? "true" : "false"); + + if (isSet) + { + // _cdRunState = data[BLINKER_CMD_SET][BLINKER_CMD_COUNTDOWN][BLINKER_CMD_STATE]; + // _cdRunState = _cdState; + int32_t _totalTime = data[BLINKER_CMD_SET][BLINKER_CMD_COUNTDOWN][BLINKER_CMD_TOTALTIME]; + // _totalTime = 60 * _totalTime; + int32_t _runTime = data[BLINKER_CMD_SET][BLINKER_CMD_COUNTDOWN][BLINKER_CMD_RUNTIME]; + // _runTime = 60 * _runTime; + String _action = data[BLINKER_CMD_SET][BLINKER_CMD_COUNTDOWN][BLINKER_CMD_ACTION]; + + if (_action.length() > BLINKER_TIMER_COUNTDOWN_ACTION_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("TIMER ACTION TOO LONG")); + return true; + } + + // BLINKER_ERR_LOG(BLINKER_F("TIMER ACTION: "), _action , BLINKER_F(", LEN: "), _action.length()); + + if (_cdRunState && _action != "null") + { + // _cdAction = _action; + strcpy(_cdAction, _action.c_str()); + _cdTime1 = _totalTime; + _cdTime2 = _runTime; + } + + if (!_cdRunState && _action == "null") + { + _cdTime2 += (millis() - _cdStart) / 1000 / 60; + } + // else if (_cdRunState && _action.length() == 0) { + // _cdTime2 = 0; + // } + + BLINKER_LOG_ALL(BLINKER_F("_cdRunState: "), _cdRunState); + } + else if (_noSet) + { + // _cdRunState = data[BLINKER_CMD_COUNTDOWN][BLINKER_CMD_STATE]; + // _cdRunState = _cdState; + int32_t _totalTime = data[BLINKER_CMD_COUNTDOWN][BLINKER_CMD_TOTALTIME]; + // _totalTime = 60 * _totalTime; + int32_t _runTime = data[BLINKER_CMD_COUNTDOWN][BLINKER_CMD_RUNTIME]; + // _runTime = 60 * _runTime; + String _action = data[BLINKER_CMD_COUNTDOWN][BLINKER_CMD_ACTION]; + + if (_action.length() > BLINKER_TIMER_COUNTDOWN_ACTION_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("TIMER ACTION TOO LONG")); + return true; + } + + if (_cdRunState && _action != "null") + { + // _cdAction = _action; + strcpy(_cdAction, _action.c_str()); + _cdTime1 = _totalTime; + _cdTime2 = _runTime; + } + + if (!_cdRunState && _action == "null") + { + _cdTime2 += (millis() - _cdStart) / 1000 / 60; + } + // else if (_cdRunState && _action.length() == 0) { + // _cdTime2 = 0; + // } + + BLINKER_LOG_ALL(BLINKER_F("_cdRunState: "), _cdRunState); + } + _cdData = _cdState << 31 | _cdRunState << 30 | _cdTime1 << 12 | _cdTime2; + + BLINKER_LOG_ALL(BLINKER_F("_totalTime: "), _cdTime1); + BLINKER_LOG_ALL(BLINKER_F("_runTime: "), _cdTime2); + BLINKER_LOG_ALL(BLINKER_F("_action: "), _cdAction); + BLINKER_LOG_ALL(BLINKER_F("_cdData: "), _cdData); + + // char _cdAction_[BLINKER_TIMER_COUNTDOWN_ACTION_SIZE]; + // strcpy(_cdAction_, _cdAction.c_str()); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_COUNTDOWN, _cdData); + // EEPROM.put(BLINKER_EEP_ADDR_TIMER_COUNTDOWN_ACTION, _cdAction_); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_COUNTDOWN_ACTION, _cdAction); + EEPROM.commit(); + EEPROM.end(); + + if (_cdState && _cdRunState) + { + // _cdTime1 = _cdTime1 - _cdTime2; + // _cdTime2 = 0; + + uint32_t _cdTime1_ = _cdTime1 - _cdTime2; + + if (_cdTime1_ * 60 > BLINKER_ONE_HOUR_TIME) _cdTime1_ = BLINKER_ONE_HOUR_TIME; + else _cdTime1_ = _cdTime1_ * 60; + + cdTicker.once(_cdTime1_, _cd_callback); + + _cdStart = millis(); + + BLINKER_LOG_ALL(BLINKER_F("countdown start! time: "), _cdTime1); + } + else + { + cdTicker.detach(); + } + } + else { + _cdRunState = 0; + _cdTime1 = 0; + _cdTime2 = 0; + // _cdAction = ""; + // memcpy(_cdAction, '\0', BLINKER_ACTION_SIZE); + + _cdData = _cdState << 15 | _cdRunState << 14 | (_cdTime1 - _cdTime2); + + BLINKER_LOG_ALL(BLINKER_F("countdown state: "), _cdState ? "true" : "false"); + BLINKER_LOG_ALL(BLINKER_F("_cdRunState: "), _cdRunState); + BLINKER_LOG_ALL(BLINKER_F("_totalTime: "), _cdTime1); + BLINKER_LOG_ALL(BLINKER_F("_runTime: "), _cdTime2); + BLINKER_LOG_ALL(BLINKER_F("_action: "), _cdAction); + BLINKER_LOG_ALL(BLINKER_F("_cdData: "), _cdData); + + // char _cdAction_[BLINKER_TIMER_COUNTDOWN_ACTION_SIZE]; + // strcpy(_cdAction_, _cdAction.c_str()); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_COUNTDOWN, _cdData); + // EEPROM.put(BLINKER_EEP_ADDR_TIMER_COUNTDOWN_ACTION, _cdAction_); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_COUNTDOWN_ACTION, _cdAction); + EEPROM.commit(); + EEPROM.end(); + + cdTicker.detach(); + } + + // static_cast(this)->checkState(false); + BProto::_timerPrint(countdownConfig()); + BProto::printNow(); + return true; + } + else if (isLoop) + { + _lpState = true; + + String _delete = data[BLINKER_CMD_SET][BLINKER_CMD_LOOP]; + + if (_delete == "dlt") _lpState = false; + else _lpState = true; + + if (_lpState) + { + if (isSet) + { + _lpRunState = data[BLINKER_CMD_SET][BLINKER_CMD_LOOP][BLINKER_CMD_RUN]; + } + else if (_noSet) + { + _lpRunState = data[BLINKER_CMD_LOOP][BLINKER_CMD_RUN]; + } + + BLINKER_LOG_ALL(BLINKER_F("loop state: "), _lpState ? "true" : "false"); + + if (isSet) + { + int8_t _times = data[BLINKER_CMD_SET][BLINKER_CMD_LOOP][BLINKER_CMD_TIMES]; + int8_t _tri_times = data[BLINKER_CMD_SET][BLINKER_CMD_LOOP][BLINKER_CMD_TRIGGED]; + // _lpRunState = data[BLINKER_CMD_SET][BLINKER_CMD_LOOP][BLINKER_CMD_STATE]; + // _lpRunState = _lpState; + int32_t _time1 = data[BLINKER_CMD_SET][BLINKER_CMD_LOOP][BLINKER_CMD_TIME1]; + // _time1 = 60 * _time1; + String _action1 = data[BLINKER_CMD_SET][BLINKER_CMD_LOOP][BLINKER_CMD_ACTION1]; + int32_t _time2 = data[BLINKER_CMD_SET][BLINKER_CMD_LOOP][BLINKER_CMD_TIME2]; + // _time2 = 60 * _time2; + String _action2 = data[BLINKER_CMD_SET][BLINKER_CMD_LOOP][BLINKER_CMD_ACTION2]; + + if (_action1.length() > BLINKER_TIMER_LOOP_ACTION1_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("TIMER ACTION TOO LONG")); + return true; + } + + if (_action2.length() > BLINKER_TIMER_LOOP_ACTION2_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("TIMER ACTION TOO LONG")); + return true; + } + + if (_lpRunState && _action2 != "null") + { + // _lpAction1 = _action1; + // _lpAction2 = _action2; + strcpy(_lpAction1, _action1.c_str()); + strcpy(_lpAction2, _action2.c_str()); + + _lpTimes = _times; + _lpTrigged_times = _tri_times; + _lpTime1 = _time1; + _lpTime2 = _time2; + } + + BLINKER_LOG_ALL(BLINKER_F("_lpRunState: "), _lpRunState); + + } + else if (_noSet) + { + int8_t _times = data[BLINKER_CMD_LOOP][BLINKER_CMD_TIMES]; + int8_t _tri_times = data[BLINKER_CMD_SET][BLINKER_CMD_LOOP][BLINKER_CMD_TRIGGED]; + // _lpRunState = data[BLINKER_CMD_LOOP][BLINKER_CMD_STATE]; + // _lpRunState = _lpState; + int32_t _time1 = data[BLINKER_CMD_LOOP][BLINKER_CMD_TIME1]; + // _time1 = 60 * _time1; + String _action1 = data[BLINKER_CMD_LOOP][BLINKER_CMD_ACTION1]; + int32_t _time2 = data[BLINKER_CMD_LOOP][BLINKER_CMD_TIME2]; + // _time2 = 60 * _time2; + String _action2 = data[BLINKER_CMD_LOOP][BLINKER_CMD_ACTION2]; + + if (_action1.length() > BLINKER_TIMER_LOOP_ACTION1_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("TIMER ACTION TOO LONG")); + return true; + } + + if (_action2.length() > BLINKER_TIMER_LOOP_ACTION2_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("TIMER ACTION TOO LONG")); + return true; + } + + if (_lpRunState && _action2 != "null") { + // _lpAction1 = _action1; + // _lpAction2 = _action2; + strcpy(_lpAction1, _action1.c_str()); + strcpy(_lpAction2, _action2.c_str()); + + _lpTimes = _times; + _lpTrigged_times = _tri_times; + _lpTime1 = _time1; + _lpTime2 = _time2; + } + + BLINKER_LOG_ALL(BLINKER_F("_lpRunState: "), _lpRunState); + } + + if (_lpTimes > 100) _lpTimes = 0; + + _lpData = _lpState << 31 | _lpRunState << 30 | _lpTimes << 22 | _lpTime1 << 11 | _lpTime2; + + BLINKER_LOG_ALL(BLINKER_F("_times: "), _lpTimes); + BLINKER_LOG_ALL(BLINKER_F("_tri_times: "), _lpTrigged_times); + BLINKER_LOG_ALL(BLINKER_F("_time1: "), _lpTime1); + BLINKER_LOG_ALL(BLINKER_F("_action1: "), _lpAction1); + BLINKER_LOG_ALL(BLINKER_F("_time2: "), _lpTime2); + BLINKER_LOG_ALL(BLINKER_F("_action2: "), _lpAction2); + BLINKER_LOG_ALL(BLINKER_F("_lpData: "), _lpData); + + // char _lpAction_1[BLINKER_TIMER_LOOP_ACTION1_SIZE]; + // char _lpAction_2[BLINKER_TIMER_LOOP_ACTION2_SIZE]; + // strcpy(_lpAction_1, _lpAction1.c_str()); + // strcpy(_lpAction_2, _lpAction2.c_str()); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP, _lpData); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP_TRI, _lpTrigged_times); + // EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP_ACTION1, _lpAction_1); + // EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP_ACTION2, _lpAction_2); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP_ACTION1, _lpAction1); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP_ACTION2, _lpAction2); + EEPROM.commit(); + EEPROM.end(); + + if (_lpState && _lpRunState) + { + _lpRun1 = true; + // _lpTrigged_times = 0; + _lpStop = false; + + uint32_t _lpTime1_; + + if (_lpTime1 * 60 > BLINKER_ONE_HOUR_TIME) _lpTime1_ = BLINKER_ONE_HOUR_TIME; + else _lpTime1_ = _lpTime1 * 60; + + _lpTime1_start = millis(); + lpTicker.once(_lpTime1_, _lp_callback); + + BLINKER_LOG_ALL(BLINKER_F("loop start!")); + } + else + { + lpTicker.detach(); + } + } + else + { + _lpRunState = 0; + _lpTimes = 0; + _lpTrigged_times = 0; + _lpTime1 = 0; + _lpTime2 = 0; + // _lpAction1 = ""; + // _lpAction2 = ""; + // memcpy(_lpAction1, '\0', BLINKER_ACTION_SIZE); + // memcpy(_lpAction2, '\0', BLINKER_ACTION_SIZE); + + _lpData = _lpState << 31 | _lpRunState << 30 | _lpTimes << 22 | _lpTime1 << 11 | _lpTime2; + + BLINKER_LOG_ALL(BLINKER_F("loop state: "), _lpState ? "true" : "false"); + BLINKER_LOG_ALL(BLINKER_F("_lpRunState: "), _lpRunState); + BLINKER_LOG_ALL(BLINKER_F("_times: "), _lpTimes); + BLINKER_LOG_ALL(BLINKER_F("_tri_times: "), _lpTrigged_times); + BLINKER_LOG_ALL(BLINKER_F("_time1: "), _lpTime1); + BLINKER_LOG_ALL(BLINKER_F("_action1: "), _lpAction1); + BLINKER_LOG_ALL(BLINKER_F("_time2: "), _lpTime2); + BLINKER_LOG_ALL(BLINKER_F("_action2: "), _lpAction2); + BLINKER_LOG_ALL(BLINKER_F("_lpData: "), _lpData); + + // char _lpAction_1[BLINKER_TIMER_LOOP_ACTION1_SIZE]; + // char _lpAction_2[BLINKER_TIMER_LOOP_ACTION2_SIZE]; + // strcpy(_lpAction_1, _lpAction1.c_str()); + // strcpy(_lpAction_2, _lpAction2.c_str()); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP, _lpData); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP_TRI, _lpTrigged_times); + // EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP_ACTION1, _lpAction_1); + // EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP_ACTION2, _lpAction_2); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP_ACTION1, _lpAction1); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_LOOP_ACTION2, _lpAction2); + EEPROM.commit(); + EEPROM.end(); + + lpTicker.detach(); + } + + BProto::_timerPrint(loopConfig()); + BProto::printNow(); + return true; + } + else if (isTiming) + { + bool isDelet = STRING_contains_string(BProto::dataParse(), BLINKER_CMD_DELETETASK); + + _tmState = true; + + if (isSet) + { + _tmRunState = data[BLINKER_CMD_SET][BLINKER_CMD_TIMING][0][BLINKER_CMD_ENABLE]; + } + else if (_noSet) + { + _tmRunState = data[BLINKER_CMD_TIMING][0][BLINKER_CMD_ENABLE]; + } + + BLINKER_LOG_ALL(BLINKER_F("timing state: "), _tmState ? "true" : "false"); + + int32_t _time; + String _action; + String _text; + uint8_t _task; + + if (isSet && !isDelet) + { + // _tmRunState = data[BLINKER_CMD_SET][BLINKER_CMD_TIMING][0][BLINKER_CMD_STATE]; + // _tmRunState = _tmState; + _time = data[BLINKER_CMD_SET][BLINKER_CMD_TIMING][0][BLINKER_CMD_TIME]; + // _time = 60 * _time; + String tm_action = data[BLINKER_CMD_SET][BLINKER_CMD_TIMING][0][BLINKER_CMD_ACTION]; + // String tm_text = data[BLINKER_CMD_SET][BLINKER_CMD_TIMING][0][BLINKER_CMD_TEXT]; + _task = data[BLINKER_CMD_SET][BLINKER_CMD_TIMING][0][BLINKER_CMD_TASK]; + + // _tmAction = _action; + + if (tm_action.length() > BLINKER_TIMER_TIMING_ACTION_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("TIMER ACTION TOO LONG")); + return true; + } + + _action = tm_action; + // _text = tm_text; + + // _tmTime = _time; + + String tm_day = data[BLINKER_CMD_SET][BLINKER_CMD_TIMING][0][BLINKER_CMD_DAY]; + + _timingDay = 0; + + if (tm_day.toInt() == 0) + { + if (60 * _time > dtime()) + { + _timingDay |= (0x01 << wday());//timeinfo.tm_wday(uint8_t)pow(2,timeinfo.tm_wday); + } + else { + _timingDay |= (0x01 << ((wday() + 1) % 7));//timeinfo.tm_wday(uint8_t)pow(2,(timeinfo.tm_wday + 1) % 7); + } + + _isTimingLoop = false; + + BLINKER_LOG_ALL(BLINKER_F("timingDay: "), _timingDay); + } + else + { + + _isTimingLoop = true; + + // uint8_t taskDay; + + for (uint8_t day = 0; day < 7; day++) + { + if (tm_day.substring(day, day+1) == "1") + { + _timingDay |= (0x01 << day); + + BLINKER_LOG_ALL(BLINKER_F("day: "), day, BLINKER_F(" timingDay: "), _timingDay); + } + } + } + + // if (data[BLINKER_CMD_SET][BLINKER_CMD_TIMING][0][BLINKER_CMD_DAY][0] == 7) { + // if (_tmTime2 > dtime()) { + // _timingDay |= (0x01 << wday());//timeinfo.tm_wday(uint8_t)pow(2,timeinfo.tm_wday); + // } + // else { + // _timingDay |= (0x01 << ((wday() + 1) % 7));//timeinfo.tm_wday(uint8_t)pow(2,(timeinfo.tm_wday + 1) % 7); + // } + + // _isTimingLoop = false; + // #ifdef BLINKER_DEBUG_ALL + // BLINKER_LOG(BLINKER_F("timingDay: "), _timingDay); + // #endif + // } + // else { + // uint8_t taskDay = data[BLINKER_CMD_SET][BLINKER_CMD_TIMING][0][BLINKER_CMD_DAY][0]; + // _timingDay |= (0x01 << taskDay);//(uint8_t)pow(2,taskDay); + // #ifdef BLINKER_DEBUG_ALL + // BLINKER_LOG(BLINKER_F("day: "), taskDay, BLINKER_F(" timingDay: "), _timingDay); + // #endif + + // for (uint8_t day = 1;day < 7;day++) { + // taskDay = data[BLINKER_CMD_SET][BLINKER_CMD_TIMING][0][BLINKER_CMD_DAY][day]; + // if (taskDay > 0) { + // _timingDay |= (0x01 << taskDay);//(uint8_t)pow(2,taskDay); + // #ifdef BLINKER_DEBUG_ALL + // BLINKER_LOG(BLINKER_F("day: "), taskDay, BLINKER_F(" timingDay: "), _timingDay); + // #endif + // } + // } + + // _isTimingLoop = true; + // } + + BLINKER_LOG_ALL(BLINKER_F("timingDay: "), _timingDay); + // BLINKER_LOG_ALL(BLINKER_F("_text: "), _text); + BLINKER_LOG_ALL(BLINKER_F("_tmRunState: "), _tmRunState); + BLINKER_LOG_ALL(BLINKER_F("_isTimingLoop: "), _isTimingLoop ? "true":"false"); + BLINKER_LOG_ALL(BLINKER_F("_time: "), _time); + BLINKER_LOG_ALL(BLINKER_F("_action: "), _action); + + uint32_t _timerData = _isTimingLoop << 31 | _tmRunState << 23 | _timingDay << 11 | _time; + + // addTimingTask(_task, _timerData, _action, _text); + addTimingTask(_task, _timerData, _action); + } + else if (_noSet) + { + // _tmRunState = data[BLINKER_CMD_SET][BLINKER_CMD_TIMING][0][BLINKER_CMD_STATE]; + // _tmRunState = _tmState; + _time = data[BLINKER_CMD_TIMING][0][BLINKER_CMD_TIME]; + // _time = 60 * _time; + String tm_action = data[BLINKER_CMD_TIMING][0][BLINKER_CMD_ACTION]; + // String tm_text = data[BLINKER_CMD_SET][BLINKER_CMD_TIMING][0][BLINKER_CMD_TEXT]; + _task = data[BLINKER_CMD_TIMING][0][BLINKER_CMD_TASK]; + + // _tmAction = _action; + + if (tm_action.length() > BLINKER_TIMER_TIMING_ACTION_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("TIMER ACTION TOO LONG")); + return true; + } + + _action = tm_action; + // _text = tm_text; + + // _tmTime = _time; + + String tm_day = data[BLINKER_CMD_TIMING][0][BLINKER_CMD_DAY]; + + if (tm_day.toInt() == 0) + { + if (60 * _time > dtime()) + { + _timingDay |= (0x01 << wday());//timeinfo.tm_wday(uint8_t)pow(2,timeinfo.tm_wday); + } + else { + _timingDay |= (0x01 << ((wday() + 1) % 7));//timeinfo.tm_wday(uint8_t)pow(2,(timeinfo.tm_wday + 1) % 7); + } + + _isTimingLoop = false; + + BLINKER_LOG_ALL(BLINKER_F("timingDay: "), _timingDay); + } + else + { + // uint8_t taskDay; + + _isTimingLoop = true; + + for (uint8_t day = 0; day < 7; day++) + { + if (tm_day.substring(day, day+1) == "1") + { + _timingDay |= (0x01 << day); + + BLINKER_LOG_ALL(BLINKER_F("day: "), day, BLINKER_F(" timingDay: "), _timingDay); + } + } + } + + // if (data[BLINKER_CMD_TIMING][0][BLINKER_CMD_DAY][0] == 7) { + // if (_tmTime2 > dtime()) { + // _timingDay |= (0x01 << wday());//timeinfo.tm_wday(uint8_t)pow(2,timeinfo.tm_wday); + // } + // else { + // _timingDay |= (0x01 << ((wday() + 1) % 7));//timeinfo.tm_wday(uint8_t)pow(2,(timeinfo.tm_wday + 1) % 7); + // } + + // _isTimingLoop = false; + // #ifdef BLINKER_DEBUG_ALL + // BLINKER_LOG(BLINKER_F("timingDay: "), _timingDay); + // #endif + // } + // else { + // uint8_t taskDay = data[BLINKER_CMD_TIMING][0][BLINKER_CMD_DAY][0]; + // _timingDay |= (0x01 << taskDay);//(uint8_t)pow(2,taskDay); + // #ifdef BLINKER_DEBUG_ALL + // BLINKER_LOG(BLINKER_F("day: "), taskDay, BLINKER_F(" timingDay: "), _timingDay); + // #endif + + // for (uint8_t day = 1;day < 7;day++) { + // taskDay = data[BLINKER_CMD_TIMING][0][BLINKER_CMD_DAY][day]; + // if (taskDay > 0) { + // _timingDay |= (0x01 << taskDay);//(uint8_t)pow(2,taskDay); + // #ifdef BLINKER_DEBUG_ALL + // BLINKER_LOG(BLINKER_F("day: "), taskDay, BLINKER_F(" timingDay: "), _timingDay); + // #endif + // } + // } + + // _isTimingLoop = true; + // } + + BLINKER_LOG_ALL(BLINKER_F("timingDay: "), _timingDay); + // BLINKER_LOG_ALL(BLINKER_F("_text: "), _text); + BLINKER_LOG_ALL(BLINKER_F("_tmRunState: "), _tmRunState); + BLINKER_LOG_ALL(BLINKER_F("_isTimingLoop: "), _isTimingLoop ? "true":"false"); + BLINKER_LOG_ALL(BLINKER_F("_time: "), _time); + BLINKER_LOG_ALL(BLINKER_F("_action: "), _action); + + uint32_t _timerData = _isTimingLoop << 31 | _tmRunState << 23 | _timingDay << 11 | _time; + + // addTimingTask(_task, _timerData, _action, _text); + addTimingTask(_task, _timerData, _action); + } + else if (isDelet) + { + uint8_t _delTask = data[BLINKER_CMD_SET][BLINKER_CMD_TIMING][0][BLINKER_CMD_DELETETASK]; + + deleteTiming(_delTask); + } + + char _tmAction_[BLINKER_TIMER_TIMING_ACTION_SIZE]; + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_TIMING_COUNT, taskCount); + for(uint8_t task = 0; task < taskCount; task++) + { + strcpy(_tmAction_, timingTask[task]->getAction()); + + EEPROM.put(BLINKER_EEP_ADDR_TIMER_TIMING + task * BLINKER_ONE_TIMER_TIMING_SIZE + , timingTask[task]->getTimerData()); + EEPROM.put(BLINKER_EEP_ADDR_TIMER_TIMING + task * BLINKER_ONE_TIMER_TIMING_SIZE + + BLINKER_TIMER_TIMING_SIZE, _tmAction_); + + BLINKER_LOG_ALL(BLINKER_F("getTimerData: "), timingTask[task]->getTimerData()); + BLINKER_LOG_ALL(BLINKER_F("_tmAction_: "), _tmAction_); + } + EEPROM.commit(); + EEPROM.end(); + + BProto::_timerPrint(timingConfig()); + BProto::printNow(); + + BLINKER_LOG_FreeHeap_ALL(); + + return true; + } + } + else if (data.containsKey(BLINKER_CMD_GET)) + { + String get_timer = data[BLINKER_CMD_GET]; + + if (get_timer == BLINKER_CMD_TIMER) + { + BProto::_timerPrint(timerSetting()); + BProto::printNow(); + BLINKER_LOG_ALL(BLINKER_F("timerManager1 isParsed")); + _fresh = true; + return true; + } + else if (get_timer == BLINKER_CMD_COUNTDOWN) + { + BProto::_timerPrint(countdownConfig()); + BProto::printNow(); + BLINKER_LOG_ALL(BLINKER_F("timerManager2 isParsed")); + _fresh = true; + return true; + } + else if (get_timer == BLINKER_CMD_LOOP) + { + BProto::_timerPrint(loopConfig()); + BProto::printNow(); + BLINKER_LOG_ALL(BLINKER_F("timerManager3 isParsed")); + _fresh = true; + return true; + } + else if (get_timer == BLINKER_CMD_TIMING) + { + BProto::_timerPrint(timingConfig()); + BProto::printNow(); + BLINKER_LOG_ALL(BLINKER_F("timerManager4 isParsed")); + _fresh = true; + return true; + } + } + else + { + return false; + } + + return false; + } + + + bool BlinkerApi::checkTimer() + { + if (_cdTrigged) + { + _cdTrigged = false; + + // _cdRunState = false; + _cdState = false; + // _cdData |= _cdRunState << 14; + // _cdData = _cdState << 15 | _cdRunState << 14 | (_cdTime1 - _cdTime2); + _cdData = _cdState << 31 | _cdRunState << 30 | _cdTime1 << 12 | _cdTime2; + saveCountDown(_cdData, _cdAction); + + BLINKER_LOG_ALL(BLINKER_F("countdown trigged, action is: "), _cdAction); + + // _parse(_cdAction); + + #if defined(BLINKER_AT_MQTT) + BProto::serialPrint(_cdAction); + #else + parse(_cdAction, true); + #endif + } + if (_lpTrigged) + { + _lpTrigged = false; + + if (_lpStop) + { + // _lpRunState = false; + _lpState = false; + // _lpData |= _lpRunState << 30; + _lpData = _lpState << 31 | _lpRunState << 30 | _lpTimes << 22 | _lpTime1 << 11 | _lpTime2; + saveLoop(_lpData, _lpAction1, _lpAction2); + } + + if (_lpRun1) + { + BLINKER_LOG_ALL(BLINKER_F("loop trigged, action is: "), _lpAction2); + // _parse(_lpAction2); + + #if defined(BLINKER_AT_MQTT) + BProto::serialPrint(_lpAction2); + #else + parse(_lpAction2, true); + #endif + } + else + { + + BLINKER_LOG_ALL(BLINKER_F("loop trigged, action is: "), _lpAction1); + // _parse(_lpAction1); + + #if defined(BLINKER_AT_MQTT) + BProto::serialPrint(_lpAction1); + #else + parse(_lpAction1, true); + #endif + } + } + if (_tmTrigged) + { + _tmTrigged = false; + + // if (_tmRun1) { + // #ifdef BLINKER_DEBUG_ALL + // BLINKER_LOG(BLINKER_F("timing trigged, action is: "), _tmAction2); + // #endif + // // _parse(_tmAction2); + // parse(_tmAction2, true); + // } + // else { + // #ifdef BLINKER_DEBUG_ALL + // BLINKER_LOG(BLINKER_F("timing trigged, action is: "), _tmAction1); + // #endif + // // _parse(_tmAction1); + // parse(_tmAction1, true); + // } + + uint8_t wDay = wday(); + + BLINKER_LOG_ALL(hour(), ":", minute(), ":", second()); + + uint16_t nowMins = hour() * 60 + minute(); + + if (triggedTask < BLINKER_TIMING_TIMER_SIZE && \ + nowMins != timingTask[triggedTask]->getTime()) + { + BLINKER_LOG_ALL(BLINKER_F("timing trigged, now minutes check error!")); + + freshTiming(wDay, nowMins); + + return false; + } + + if (triggedTask < BLINKER_TIMING_TIMER_SIZE) + { + // String _tmAction = timingTask[triggedTask]->getAction(); + char _tmAction[BLINKER_TIMER_TIMING_ACTION_SIZE]; + + strcpy(_tmAction, timingTask[triggedTask]->getAction()); + + BLINKER_LOG(BLINKER_F("timing trigged, action is: "), _tmAction); + + #if defined(BLINKER_AT_MQTT) + BProto::serialPrint(_tmAction); + #else + parse(_tmAction, true); + #endif + + checkOverlapping(wDay, timingTask[triggedTask]->getTime(), triggedTask); + + freshTiming(wDay, timingTask[triggedTask]->getTime()); + + return true; + } + else + { + BLINKER_LOG_ALL(BLINKER_F("timing trigged, none action")); + + freshTiming(wDay, 0); + + return false; + } + } + + return false; + } + + #endif + + bool BlinkerApi::checkServerLimit() + { + if ((millis() - _serverTime) < 60 * 60 * 1000) + { + if (_serverTimes > BLINKER_PRINT_MSG_LIMIT) + { + BLINKER_ERR_LOG(BLINKER_F("SERVER NOT ALIVE OR MSG LIMIT")); + + return false; + } + else + { + _serverTimes++; + return true; + } + } + else + { + _serverTimes = 0; + _serverTime = millis(); + return true; + } + } + + bool BlinkerApi::checkSMS() + { + if (!checkServerLimit()) return false; + + if ((millis() - _smsTime) >= BLINKER_SMS_MSG_LIMIT || \ + _smsTime == 0) return true; + else return false; + } + + + bool BlinkerApi::checkPUSH() + { + if (!checkServerLimit()) return false; + + if ((millis() - _pushTime) >= BLINKER_PUSH_MSG_LIMIT || \ + _pushTime == 0) return true; + else return false; + } + + + bool BlinkerApi::checkWECHAT() + { + if (!checkServerLimit()) return false; + + if ((millis() - _wechatTime) >= BLINKER_WECHAT_MSG_LIMIT || \ + _wechatTime == 0) return true; + else return false; + } + + + bool BlinkerApi::checkWEATHER() + { + if (!checkServerLimit()) return false; + + if ((millis() - _weatherTime) >= BLINKER_WEATHER_MSG_LIMIT || \ + _weatherTime == 0) return true; + else return false; + } + + + bool BlinkerApi::checkWEATHERFORECAST() + { + if (!checkServerLimit()) return false; + + if ((millis() - _weather_forecast_Time) >= BLINKER_WEATHER_MSG_LIMIT || \ + _weather_forecast_Time == 0) return true; + else return false; + } + + + bool BlinkerApi::checkAQI() + { + if (!checkServerLimit()) return false; + + if ((millis() - _aqiTime) >= BLINKER_AQI_MSG_LIMIT || \ + _aqiTime == 0) return true; + else return false; + } + + + bool BlinkerApi::checkLOG() + { + if (!checkServerLimit()) return false; + + if ((millis() - _logTime) >= BLINKER_LOG_MSG_LIMIT || \ + _logTime == 0) return true; + else return false; + } + + bool BlinkerApi::checkCOD() + { + if (!checkServerLimit()) return false; + + if ((millis() - _codTime) >= BLINKER_COD_MSG_LIMIT || \ + _codTime == 0) return true; + else return false; + } + + bool BlinkerApi::checkCUPDATE() + { + if ((millis() - _cUpdateTime) >= BLINKER_CONFIG_UPDATE_LIMIT || \ + _cUpdateTime == 0) return true; + else return false; + } + + + bool BlinkerApi::checkCGET() + { + if (!checkServerLimit()) return false; + + if ((millis() - _cGetTime) >= BLINKER_CONFIG_GET_LIMIT || \ + _cGetTime == 0) return true; + else return false; + } + + + bool BlinkerApi::checkCDEL() + { + if (!checkServerLimit()) return false; + + if ((millis() - _cDelTime) >= BLINKER_CONFIG_GET_LIMIT || \ + _cDelTime == 0) return true; + else return false; + } + + + bool BlinkerApi::checkDataUpdata() + { + if ((millis() - _dUpdateTime) >= BLINKER_CONFIG_UPDATE_LIMIT || \ + _dUpdateTime == 0) return true; + else return false; + } + + + bool BlinkerApi::checkDataGet() + { + if (!checkServerLimit()) return false; + + if ((millis() - _dGetTime) >= BLINKER_CONFIG_UPDATE_LIMIT || \ + _dGetTime == 0) return true; + else return false; + } + + + bool BlinkerApi::checkDataDel() + { + if (!checkServerLimit()) return false; + + if ((millis() - _dDelTime) >= BLINKER_CONFIG_UPDATE_LIMIT || \ + _dDelTime == 0) return true; + else return false; + } + + bool BlinkerApi::checkAutoPull() + { + if ((millis() - _autoPullTime) >= 60000 || \ + _autoPullTime == 0) return true; + else return false; + } + + #if defined(BLINKER_PRO_ESP) + bool BlinkerApi::checkEventWarn() + { + if ((millis() - _eWarnTime) >= 60000 || \ + _eWarnTime == 0) return true; + else return false; + } + + bool BlinkerApi::checkEventErr() + { + if ((millis() - _eErrTime) >= 60000 || \ + _eErrTime == 0) return true; + else return false; + } + + bool BlinkerApi::checkEventMsg() + { + if ((millis() - _eMsgTime) >= 60000 || \ + _eMsgTime == 0) return true; + else return false; + } + #endif + + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + void BlinkerApi::autoStart() + { + // autoPull(); + + BLINKER_LOG_ALL(BLINKER_F("_______autoStart_______")); + uint8_t checkData; + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_CHECK, checkData); + if (checkData != BLINKER_CHECK_DATA) + { + for (uint16_t _addr = BLINKER_EEP_ADDR_AUTO_START; + _addr < BLINKER_EEP_ADDR_AUTO_START + + BLINKER_ONE_AUTO_DATA_SIZE * 2; _addr++) + { + EEPROM.put(_addr, "\0"); + } + EEPROM.put(BLINKER_EEP_ADDR_CHECK, BLINKER_CHECK_DATA); + EEPROM.commit(); + EEPROM.end(); + return; + } + EEPROM.get(BLINKER_EEP_ADDR_AUTONUM, _aCount); + if (_aCount > 2) + { + _aCount = 0; + EEPROM.put(BLINKER_EEP_ADDR_AUTONUM, _aCount); + } + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("_aCount: "), _aCount); + + if (_aCount) + { + for (uint8_t _num = 0; _num < _aCount; _num++) + { + BLINKER_LOG_ALL(BLINKER_F("new BlinkerAUTO() _num: "), _num); + + _AUTO[_num] = new BlinkerAUTO(); + _AUTO[_num]->setNum(_num); + _AUTO[_num]->deserialization(); + } + } + } + + + bool BlinkerApi::autoManager(const JsonObject& data) + { + // String set; + bool isSet = false; + bool isAuto = false; + + // isSet = STRING_contains_string(static_cast(this)->dataParse(), BLINKER_CMD_SET); + // isAuto = STRING_contains_string(static_cast(this)->dataParse(), BLINKER_CMD_AUTO); + isSet = data.containsKey(BLINKER_CMD_SET); + String aData = data[BLINKER_CMD_SET][BLINKER_CMD_AUTO].as(); + // const char* aDataArray = data[BLINKER_CMD_SET][BLINKER_CMD_AUTO][0]; + + // if (aData.length()) isAuto = true; + if (aData != "null") isAuto = true; + + BLINKER_LOG_ALL(BLINKER_F("autoManager begin: "), isAuto, " ", isSet); + + // if (aDataArray && !isAuto) + if (!isAuto) + { + for (uint8_t num = 0; num < 2; num++) + { + unsigned long _autoId = data[BLINKER_CMD_AUTO][num][BLINKER_CMD_AUTOID]; + String arrayData = data[BLINKER_CMD_AUTO][num]; + + if (_aCount) + { + for (uint8_t _num = 0; _num < _aCount; _num++) + { + if (_AUTO[_num]->id() == _autoId) { + // _AUTO[_num]->manager(arrayData); + return true; + } + } + if (_aCount == 1) + { + _AUTO[_aCount] = new BlinkerAUTO(); + _AUTO[_aCount]->setNum(_aCount); + // _AUTO[_aCount]->manager(arrayData); + + // _aCount = 1; + _aCount++; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_AUTONUM, _aCount); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("_aCount: "), _aCount); + // static_cast(this)->_print(autoData(), false); + // return true; + } + else + { + // _AUTO[_aCount - 1]->manager(arrayData); + // return true; + } + } + else + { + _AUTO[_aCount] = new BlinkerAUTO(); + _AUTO[_aCount]->setNum(_aCount); + // _AUTO[_aCount]->manager(arrayData); + + _aCount = 1; + // _aCount++; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_AUTONUM, _aCount); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("_aCount: "), _aCount); + // static_cast(this)->_print(autoData(), false); + // return true; + } + } + return true; + } + else if (isSet && isAuto) + { + // BLINKER_LOG_ALL(BLINKER_F("timerManager5 isParsed")); + _fresh = true; + + BLINKER_LOG_ALL(BLINKER_F("get auto setting")); + + // bool isDelet = STRING_contains_string(BProto::dataParse(), BLINKER_CMD_DELETID); + String isTriggedArray = data[BLINKER_CMD_SET][BLINKER_CMD_AUTO] + [BLINKER_CMD_ACTION][0]; + + // if (isDelet) + // { + // // uint32_t _autoId = STRING_find_numberic_value(static_cast(this)->dataParse(), BLINKER_CMD_DELETID); + // uint32_t _autoId = data[BLINKER_CMD_SET][BLINKER_CMD_AUTO][BLINKER_CMD_DELETE]; + + // if (_aCount) + // { + // for (uint8_t _num = 0; _num < _aCount; _num++) + // { + // if (_AUTO[_num]->id() == _autoId) + // { + // // _AUTO[_num]->manager(static_cast(this)->dataParse()); + // for (uint8_t a_num = _num; a_num < _aCount; a_num++) + // { + // if (a_num < _aCount - 1) + // { + // _AUTO[a_num]->setNum(a_num + 1); + // _AUTO[a_num]->deserialization(); + // _AUTO[a_num]->setNum(a_num); + // _AUTO[a_num]->serialization(); + // } + // else{ + // _num = _aCount; + // } + // } + // _aCount--; + + // EEPROM.begin(BLINKER_EEP_SIZE); + // EEPROM.put(BLINKER_EEP_ADDR_AUTONUM, _aCount); + // EEPROM.commit(); + // EEPROM.end(); + + // BLINKER_LOG_ALL(BLINKER_F("_aCount: "), _aCount); + + // return true; + // } + // } + // } + // } + // else if(isTriggedArray != "null") + // { + // for (uint8_t a_num = 0; a_num < BLINKER_MAX_WIDGET_SIZE; a_num++) + // { + // String _autoData_array = data[BLINKER_CMD_SET][BLINKER_CMD_AUTO] + // [BLINKER_CMD_ACTION][a_num]; + + // if(_autoData_array != "null") + // { + // // DynamicJsonBuffer _jsonBuffer; + // // JsonObject& _array = _jsonBuffer.parseObject(_autoData_array); + // DynamicJsonDocument jsonBuffer(1024); + // deserializeJson(jsonBuffer, _autoData_array); + // JsonObject _array = jsonBuffer.as(); + + // json_parse(_array); + // #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + // !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + // !defined(BLINKER_LOWPOWER_AIR202)) + // timerManager(_array, true); + // #endif + // } + // else + // { + // // a_num = BLINKER_MAX_WIDGET_SIZE; + // return true; + // } + // } + // } + if (isTriggedArray != "null") + { + BLINKER_LOG_ALL(BLINKER_F("_auto trigged action: "), isTriggedArray); + + for (uint8_t a_num = 0; a_num < BLINKER_MAX_WIDGET_SIZE; a_num++) + { + String _autoData_array = data[BLINKER_CMD_SET][BLINKER_CMD_AUTO] + [BLINKER_CMD_ACTION][a_num]; + + if(_autoData_array != "null") + { + _fresh = false; + // DynamicJsonBuffer _jsonBuffer; + // JsonObject& _array = _jsonBuffer.parseObject(_autoData_array); + DynamicJsonDocument jsonBuffer(1024); + deserializeJson(jsonBuffer, _autoData_array); + JsonObject _array = jsonBuffer.as(); + + json_parse(_array); + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + timerManager(_array, true); + #endif + + if (_fresh) + { + BProto::isParsed(); + } + else + { + #if defined(BLINKER_PRO) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) + if (_parseFunc) { + if(_parseFunc(_array)) { + BLINKER_LOG_ALL(BLINKER_F("_parseFunc(_array) isParsed")); + _fresh = true; + BProto::isParsed(); + } + + BLINKER_LOG_ALL(BLINKER_F("run parse callback function")); + } + #endif + } + } + else + { + // a_num = BLINKER_MAX_WIDGET_SIZE; + return true; + } + } + } + else + { + // uint32_t _autoId = STRING_find_numberic_value(static_cast(this)->dataParse(), BLINKER_CMD_AUTOID); + String get_autoId = data[BLINKER_CMD_SET][BLINKER_CMD_AUTO][BLINKER_CMD_ID].as(); + String del_autoId = data[BLINKER_CMD_SET][BLINKER_CMD_AUTO][BLINKER_CMD_DELETE].as(); + // _autoId = get_autoId.toInt(); + + BLINKER_LOG_ALL(BLINKER_F("get_autoId: "), strtoul(get_autoId.c_str(),NULL,10)); + BLINKER_LOG_ALL(BLINKER_F("del_autoId: "), strtoul(del_autoId.c_str(),NULL,10)); + BLINKER_LOG_ALL(BLINKER_F("_aCount: "), _aCount); + // _aCount = 0; + + if (_aCount && strtoul(del_autoId.c_str(),NULL,10) == 0) + { + for (uint8_t _num = 0; _num < _aCount; _num++) + { + BLINKER_LOG_ALL(BLINKER_F("check _autoId: "), _AUTO[_num]->id(), " ", _AUTO[_num]->id() == strtoul(get_autoId.c_str(),NULL,10)); + if (_AUTO[_num]->id() == strtoul(get_autoId.c_str(),NULL,10)) + { + _AUTO[_num]->manager(data); + return true; + } + } + if (_aCount == 1) + { + _AUTO[_aCount] = new BlinkerAUTO(); + _AUTO[_aCount]->setNum(_aCount); + _AUTO[_aCount]->manager(data); + + // _aCount = 1; + _aCount++; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_AUTONUM, _aCount); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("_aCount: "), _aCount); + + // static_cast(this)->_print(autoData(), false); + // return true; + } + else + { + _AUTO[0]->setNum(1); + _AUTO[0]->deserialization(); + _AUTO[0]->setNum(0); + _AUTO[0]->serialization(); + + _AUTO[1] = new BlinkerAUTO(); + _AUTO[1]->setNum(1); + _AUTO[1]->manager(data); + // return true; + } + } + else if (_aCount == 0 && strtoul(del_autoId.c_str(),NULL,10) == 0) + { + _AUTO[_aCount] = new BlinkerAUTO(); + _AUTO[_aCount]->setNum(_aCount); + _AUTO[_aCount]->manager(data); + + _aCount = 1; + // _aCount++; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_AUTONUM, _aCount); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("_aCount: "), _aCount); + + // static_cast(this)->_print(autoData(), false); + // return true; + } + else if (strtoul(del_autoId.c_str(),NULL,10) != 0) + { + for (uint8_t _num = 0; _num < _aCount; _num++) + { + BLINKER_LOG_ALL(BLINKER_F("check _autoId: "), _AUTO[_num]->id(), " ", _AUTO[_num]->id() == strtoul(del_autoId.c_str(),NULL,10)); + if (_AUTO[_num]->id() == strtoul(del_autoId.c_str(),NULL,10)) + { + if (_num == 0) + { + _AUTO[1]->setNum(0); + _AUTO[1]->serialization(); + + _AUTO[0]->deserialization(); + + free(_AUTO[1]); + + _aCount--; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_AUTONUM, _aCount); + EEPROM.commit(); + EEPROM.end(); + } + else + { + free(_AUTO[1]); + _aCount--; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_AUTONUM, _aCount); + EEPROM.commit(); + EEPROM.end(); + } + + } + } + } + } + return true; + } + else + { + return false; + } + } + + void BlinkerApi::shareParse(const JsonObject& data) + { + if (data.containsKey(BLINKER_CMD_SET)) + { + String value = data[BLINKER_CMD_SET]; + + // DynamicJsonBuffer jsonBufferSet; + // JsonObject& rootSet = jsonBufferSet.parseObject(value); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, value); + JsonObject rootSet = jsonBuffer.as(); + + // if (!rootSet.success()) + if (error) + { + // BLINKER_ERR_LOG_ALL("Json error"); + return; + } + + if (rootSet.containsKey(BLINKER_CMD_SHARE)) + { + BLINKER_LOG_ALL(BLINKER_F("shareParse isParsed")); + _fresh = true; + + #if !defined(BLINKER_WIFI_SUBDEVICE) + // BProto::sharers(freshSharers()); + String _shareData = freshSharers(); + if (STRING_contains_string(_shareData, "users") == false) + { + _shareData = freshSharers(); + } + if (STRING_contains_string(_shareData, "users") == true) + { + BProto::sharers(_shareData); + } + BProto::connect(); + #else + freshSharers(); + #endif + } + } + } + + #if !defined(BLINKER_WIFI_SUBDEVICE) + void BlinkerApi::otaParse(const JsonObject& data) + { + if (data.containsKey(BLINKER_CMD_SET)) + { + String value = data[BLINKER_CMD_SET]; + + // DynamicJsonBuffer jsonBufferSet; + // JsonObject& rootSet = jsonBufferSet.parseObject(value); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, value); + JsonObject rootSet = jsonBuffer.as(); + + // if (!rootSet.success()) + if (error) + { + // BLINKER_ERR_LOG_ALL("Json error"); + return; + } + + if (rootSet.containsKey(BLINKER_CMD_UPGRADE)) + { + BLINKER_LOG_ALL(BLINKER_F("otaParse isParsed")); + _fresh = true; + + ota(); + } + } + } + + void BlinkerApi::numParse(const JsonObject& data) + { + if (data.containsKey(BLINKER_CMD_SET)) + { + String value = data[BLINKER_CMD_SET]; + + // DynamicJsonBuffer jsonBufferSet; + // JsonObject& rootSet = jsonBufferSet.parseObject(value); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, value); + JsonObject rootSet = jsonBuffer.as(); + + // if (!rootSet.success()) + if (error) + { + // BLINKER_ERR_LOG_ALL("Json error"); + return; + } + + if (rootSet.containsKey(BLINKER_CMD_AUTO_UPDATE_KEY)) + { + BLINKER_LOG_ALL(BLINKER_F("numParse isParsed")); + _fresh = true; + + String _name_ = rootSet[BLINKER_CMD_AUTO_UPDATE_KEY]; + + char _name[16]; + + strcpy(_name, _name_.c_str()); + + int8_t num = checkNum(_name, _Widgets_num, _wCount_num); + + if( num == BLINKER_OBJECT_NOT_AVAIL ) + { + _Widgets_num[_wCount_num] = new BlinkerWidgets_num(_name); + _wCount_num++; + } + else + { + _Widgets_num[num]->setState(true); + } + } + else if (rootSet.containsKey(BLINKER_CMD_CANCEL_UPDATE_KEY)) + { + BLINKER_LOG_ALL(BLINKER_F("numParse2 isParsed")); + _fresh = true; + + String _name_ = rootSet[BLINKER_CMD_AUTO_UPDATE_KEY]; + + char _name[16]; + + strcpy(_name, _name_.c_str()); + + int8_t num = checkNum(_name, _Widgets_num, _wCount_num); + + if( num == BLINKER_OBJECT_NOT_AVAIL ) + { + _Widgets_num[num]->setState(false); + } + } + } + } + + #endif + + #endif + + #if defined(BLINKER_GPRS_AIR202) + void BlinkerApi::shareParse(const JsonObject& data) + { + if (data.containsKey(BLINKER_CMD_SET)) + { + String value = data[BLINKER_CMD_SET]; + + // DynamicJsonBuffer jsonBufferSet; + // JsonObject& rootSet = jsonBufferSet.parseObject(value); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, value); + JsonObject rootSet = jsonBuffer.as(); + + // if (!rootSet.success()) + if (error) + { + // BLINKER_ERR_LOG_ALL("Json error"); + return; + } + + if (rootSet.containsKey(BLINKER_CMD_SHARE)) + { + BLINKER_LOG_ALL(BLINKER_F("shareParse isParsed")); + _fresh = true; + + // BProto::sharers(freshSharers()); + String _shareData = freshSharers(); + if (STRING_contains_string(_shareData, "users") == false) + { + _shareData = freshSharers(); + } + if (STRING_contains_string(_shareData, "users") == true) + { + BProto::sharers(_shareData); + } + BProto::connect(); + } + } + } + #endif + + #if !defined(BLINKER_WIFI_SUBDEVICE) + + #if !defined(BLINKER_LOWPOWER_AIR202) + String BlinkerApi::bridgeQuery(char * key) + { + String data = BLINKER_F("/query?"); + data += BLINKER_F("deviceName="); + data += BProto::deviceName(); + data += BLINKER_F("&bridgeKey="); + data += STRING_format(key); + + return blinkerServer(BLINKER_CMD_BRIDGE_NUMBER, data); + } + #endif + + #if (!defined(BLINKER_NBIOT_SIM7020) && !defined(BLINKER_GPRS_AIR202) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_LOWPOWER_AIR202) && !defined(BLINKER_QRCODE_NBIOT_SIM7020) && \ + !defined(BLINKER_NBIOT_SIM7000) && !defined(BLINKER_QRCODE_NBIOT_SIM7000)) + + // String BlinkerApi::postServer(const String & url, const String & host, int port, const String & msg) + // { + + // String client_msg; + + // client_msg = BLINKER_F("POST "); + // client_msg += url; + // client_msg += BLINKER_F(" HTTP/1.1\r\nHost: "); + // client_msg += host; + // client_msg += BLINKER_F(":"); + // client_msg += STRING_format(port); + // client_msg += BLINKER_F("\r\nContent-Type: application/json;charset=utf-8\r\nContent-Length: "); + // client_msg += STRING_format(msg.length()); + // client_msg += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); + // client_msg += msg; + // client_msg += BLINKER_F("\r\n"); + + // // client_s.print(client_msg); + + // BLINKER_LOG_ALL(BLINKER_F("client_msg: "), client_msg); + + // return client_msg; + // } + + + // String BlinkerApi::getServer(const String & url, const String & host, int port) + // { + // String client_msg; + + // client_msg = BLINKER_F("GET "); + // client_msg += url; + // client_msg += BLINKER_F(" HTTP/1.1\r\nHost: "); + // client_msg += host; + // client_msg += BLINKER_F(":"); + // client_msg += STRING_format(port); + // client_msg += BLINKER_F("\r\nConnection: close\r\n\r\n"); + + // // client_s.print(client_msg); + + // BLINKER_LOG_ALL(BLINKER_F("client_msg: "), client_msg); + + // return client_msg; + // } + + + String BlinkerApi::blinkerServer(uint8_t _type, const String & msg, bool state) + { + // if (ESP.getFreeHeap() < 4000) return BLINKER_CMD_FALSE; + + switch (_type) + { + case BLINKER_CMD_SMS_NUMBER : + if (!checkSMS()) { + return BLINKER_CMD_FALSE; + } + + if ((!state && msg.length() > BLINKER_SMS_MAX_SEND_SIZE) || + (state && msg.length() > BLINKER_SMS_MAX_SEND_SIZE + 15)) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_PUSH_NUMBER : + if (!checkPUSH()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_WECHAT_NUMBER : + if (!checkWECHAT()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_WEATHER_NUMBER : + if (!checkWEATHER()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_WEATHER_FORECAST_NUMBER : + if (!checkWEATHERFORECAST()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_AQI_NUMBER : + if (!checkAQI()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_LOG_NUMBER : + if (!checkLOG()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_COD_NUMBER : + if (!checkCOD()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_BRIDGE_NUMBER : + break; + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKE_HTTP) + case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + if (!checkCUPDATE()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_CONFIG_GET_NUMBER : + if (!checkCGET()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_CONFIG_DELETE_NUMBER : + if (!checkCDEL()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_DATA_STORAGE_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_TIME_SLOT_DATA_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_TEXT_DATA_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_JSON_DATA_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_JSON_DATA_GET_NUMBER : + // if (!checkDataUpdata()) { + // return BLINKER_CMD_FALSE; + // } + break; + case BLINKER_CMD_DATA_GET_NUMBER : + if (!checkDataGet()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_DATA_DELETE_NUMBER : + if (!checkDataDel()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_AUTO_PULL_NUMBER : + if (!checkAutoPull()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_OTA_NUMBER : + break; + case BLINKER_CMD_OTA_STATUS_NUMBER : + break; + case BLINKER_CMD_FRESH_SHARERS_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_FREQ_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_DATA_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER : + break; + case BLINKER_CMD_EVENT_DATA_NUMBER : + break; + case BLINKER_CMD_GPS_DATA_NUMBER : + break; + case BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER : + break; + #if defined(BLINKER_PRO_ESP) + case BLINKER_CMD_EVENT_WARNING_NUMBER : + if (!checkEventWarn()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_EVENT_ERROR_NUMBER : + if (!checkEventErr()) { + return BLINKER_CMD_FALSE; + } + break; + case BLINKER_CMD_EVENT_MSG_NUMBER : + if (!checkEventMsg()) { + return BLINKER_CMD_FALSE; + } + break; + #endif + #endif + default : + return BLINKER_CMD_FALSE; + } + + BLINKER_LOG_ALL(BLINKER_F("message: "), msg); + + #ifndef BLINKER_LAN_DEBUG + const int httpsPort = 443; + #elif defined(BLINKER_LAN_DEBUG) + const int httpsPort = 9090; + #endif + + // #if defined(ESP8266) + // #ifndef BLINKER_LAN_DEBUG + // String host = BLINKER_F(BLINKER_SERVER_HOST); + // #elif defined(BLINKER_LAN_DEBUG) + // String host = BLINKER_F("192.168.1.121"); + // #endif + // String fingerprint = BLINKER_F("84 5f a4 8a 70 5e 79 7e f5 b3 b4 20 45 c8 35 55 72 f6 85 5a"); + // #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) + // #ifndef BLINKER_LAN_DEBUG + // // #if defined(BLINKER_MQTT) + // extern BearSSL::WiFiClientSecure client_mqtt; + // // #elif defined(BLINKER_PRO) + // // extern BearSSL::WiFiClientSecure client_pro; + // // #elif defined(BLINKER_AT_MQTT) + // // extern BearSSL::WiFiClientSecure client_mqtt_at; + // // #endif + // BearSSL::WiFiClientSecure *client_s; + + // client_s = new BearSSL::WiFiClientSecure(); + // // extern WiFiClientSecure client_mqtt; + // #elif defined(BLINKER_LAN_DEBUG) + // WiFiClient *client_s; + // client_s = new WiFiClient(); + // #endif + // #endif + + // // #if defined(BLINKER_WIFI) + // // BearSSL::WiFiClientSecure client_s; + // // #endif + + // BLINKER_LOG_ALL(BLINKER_F("connecting to "), host); + + // uint8_t connet_times = 0; + + // #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) + // client_mqtt.stop(); + // // #elif defined(BLINKER_PRO) + // // client_pro.stop(); + // // #elif defined(BLINKER_AT_MQTT) + // // client_mqtt_at.stop(); + // #endif + + // ::delay(100); + + // bool mfln = client_s->probeMaxFragmentLength(host, httpsPort, 1024); + // if (mfln) { + // client_s->setBufferSizes(1024, 1024); + // } + + // // client_s.setFingerprint(fingerprint.c_str()); + + // client_s->setInsecure(); + + // // while (1) { + // bool cl_connected = false; + // if (!client_s->connect(host, httpsPort)) { + // // #ifdef BLINKER_DEBUG_ALL + // BLINKER_ERR_LOG(BLINKER_F("server connection failed")); + // // #endif + // // return BLINKER_CMD_FALSE; + + // // connet_times++; + // ::delay(1000); + // } + // else { + // BLINKER_LOG_ALL(BLINKER_F("connection succeed")); + // // return true; + // cl_connected = true; + + // // break; + // } + + // // if (connet_times >= 4 && !cl_connected) return BLINKER_CMD_FALSE; + // // } + + // String url; + // // String client_msg; + + // switch (_type) { + // case BLINKER_CMD_SMS_NUMBER : + // url = BLINKER_F("/api/v1/user/device/sms"); + // client_s->print(postServer(url, host, httpsPort, msg)); + // break; + // case BLINKER_CMD_PUSH_NUMBER : + // url = BLINKER_F("/api/v1/user/device/push"); + // client_s->print(postServer(url, host, httpsPort, msg)); + // break; + // case BLINKER_CMD_WECHAT_NUMBER : + // url = BLINKER_F("/api/v1/user/device/wxMsg/"); + // client_s->print(postServer(url, host, httpsPort, msg)); + // // return BLINKER_CMD_FALSE; + // break; + // case BLINKER_CMD_WEATHER_NUMBER : + // url = BLINKER_F("/api/v1"); + // url += msg; + // client_s->print(getServer(url, host, httpsPort)); + // break; + // case BLINKER_CMD_AQI_NUMBER : + // url = BLINKER_F("/api/v1"); + // url += msg; + // client_s->print(getServer(url, host, httpsPort)); + // break; + // case BLINKER_CMD_BRIDGE_NUMBER : + // url = BLINKER_F("/api/v1/user/device"); + // url += msg; + // client_s->print(getServer(url, host, httpsPort)); + // break; + // #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) + // case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + // url = BLINKER_F("/api/v1/user/device/userconfig"); + // client_s->print(postServer(url, host, httpsPort, msg)); + // break; + // case BLINKER_CMD_CONFIG_GET_NUMBER : + // url = BLINKER_F("/api/v1/user/device"); + // url += msg; + // client_s->print(getServer(url, host, httpsPort)); + // break; + // case BLINKER_CMD_CONFIG_DELETE_NUMBER : + // url = BLINKER_F("/api/v1/user/device"); + // url += msg; + // client_s->print(getServer(url, host, httpsPort)); + // break; + // case BLINKER_CMD_DATA_STORAGE_NUMBER : + // url = BLINKER_F("/api/v1/user/device/cloudStorage/"); + // client_s->print(postServer(url, host, httpsPort, msg)); + // break; + // case BLINKER_CMD_DATA_GET_NUMBER : + // url = BLINKER_F("/api/v1/user/device"); + // url += msg; + // client_s->print(getServer(url, host, httpsPort)); + // break; + // case BLINKER_CMD_DATA_DELETE_NUMBER : + // url = BLINKER_F("/api/v1/user/device"); + // url += msg; + // client_s->print(getServer(url, host, httpsPort)); + // break; + // case BLINKER_CMD_AUTO_PULL_NUMBER : + // url = BLINKER_F("/api/v1/user/device"); + // url += msg; + // client_s->print(getServer(url, host, httpsPort)); + // break; + // case BLINKER_CMD_OTA_NUMBER : + // url = BLINKER_F("/api/v1/user/device"); + // url += msg; + // client_s->print(getServer(url, host, httpsPort)); + // break; + // case BLINKER_CMD_OTA_STATUS_NUMBER : + // url = BLINKER_F("/api/v1/user/device/ota/upgrade_status"); + // // url += msg; + // client_s->print(postServer(url, host, httpsPort, msg)); + // break; + // case BLINKER_CMD_FRESH_SHARERS_NUMBER : + // url = BLINKER_F("/api/v1/user/device"); + // url += msg; + // client_s->print(getServer(url, host, httpsPort)); + // break; + // #endif + // default : + // return BLINKER_CMD_FALSE; + // } + + // unsigned long timeout = millis(); + // while (client_s->available() == 0) + // { + // if (millis() - timeout > 5000) + // { + // BLINKER_LOG_ALL(BLINKER_F(">>> Client Timeout !")); + // client_s->stop(); + // return BLINKER_CMD_FALSE; + // } + // } + + // // Read all the lines of the reply from server and print them to Serial + // String _dataGet; + // String lastGet; + // String lengthOfJson; + // while (client_s->available()) + // { + // // String line = client_s.readStringUntil('\r'); + // _dataGet = client_s->readStringUntil('\n'); + + // if (_dataGet.startsWith("Content-Length: ")) + // { + // int addr_start = _dataGet.indexOf(' '); + // int addr_end = _dataGet.indexOf('\0', addr_start + 1); + // lengthOfJson = _dataGet.substring(addr_start + 1, addr_end); + // } + + // if (_dataGet == "\r") + // { + // BLINKER_LOG_ALL(BLINKER_F("headers received")); + // break; + // } + // } + + // for(int i=0;iread(); + // } + + // _dataGet = lastGet; + + // BLINKER_LOG_ALL(BLINKER_F("_dataGet: "), _dataGet); + + // client_s->stop(); + // client_s->flush(); + + // free(client_s); + + // // client_mqtt.setInsecure(); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& data_rp = jsonBuffer.parseObject(_dataGet); + + // if (data_rp.success()) + // { + // uint16_t msg_code = data_rp[BLINKER_CMD_MESSAGE]; + // if (msg_code != 1000) + // { + // String _detail = data_rp[BLINKER_CMD_DETAIL]; + // BLINKER_ERR_LOG(_detail); + // } + // else + // { + // // String _dataGet_ = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DATA]; + // if (_type == BLINKER_CMD_BRIDGE_NUMBER) + // _dataGet = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME].as(); + // else if (_type == BLINKER_CMD_OTA_NUMBER || _type == BLINKER_CMD_FRESH_SHARERS_NUMBER) + // _dataGet = data_rp[BLINKER_CMD_DETAIL].as(); + // else + // _dataGet = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DATA].as(); + // } + // } + + // BLINKER_LOG_ALL(BLINKER_F("_dataGet: "), _dataGet); + + // switch (_type) + // { + // case BLINKER_CMD_SMS_NUMBER : + // _smsTime = millis(); + // break; + // case BLINKER_CMD_PUSH_NUMBER : + // _pushTime = millis(); + // break; + // case BLINKER_CMD_WECHAT_NUMBER : + // _wechatTime = millis(); + // break; + // // return BLINKER_CMD_FALSE; + // case BLINKER_CMD_WEATHER_NUMBER : + // _weatherTime = millis(); + // break; + // case BLINKER_CMD_AQI_NUMBER : + // _aqiTime = millis(); + // break; + // case BLINKER_CMD_BRIDGE_NUMBER : + // break; + // #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) + // case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + // _cUpdateTime = millis(); + // break; + // case BLINKER_CMD_CONFIG_GET_NUMBER : + // _cGetTime = millis(); + // break; + // case BLINKER_CMD_CONFIG_DELETE_NUMBER : + // _cDelTime = millis(); + // break; + // case BLINKER_CMD_DATA_STORAGE_NUMBER : + // _dUpdateTime = millis(); + // break; + // case BLINKER_CMD_DATA_GET_NUMBER : + // _dGetTime = millis(); + // break; + // case BLINKER_CMD_DATA_DELETE_NUMBER : + // _dDelTime = millis(); + // break; + // case BLINKER_CMD_AUTO_PULL_NUMBER : + // _autoPullTime = millis(); + // break; + // case BLINKER_CMD_OTA_NUMBER : + // break; + // case BLINKER_CMD_OTA_STATUS_NUMBER : + // break; + // case BLINKER_CMD_FRESH_SHARERS_NUMBER : + // break; + // #endif + // default : + // return BLINKER_CMD_FALSE; + // } + + // return _dataGet; + // #elif defined(ESP32) + #ifndef BLINKER_LAN_DEBUG + String host = BLINKER_F(BLINKER_SERVER_HTTPS); + #elif defined(BLINKER_LAN_DEBUG) + String host = BLINKER_F("http://192.168.0.105:8887"); + #endif + + // const char* ca = + // "-----BEGIN CERTIFICATE-----\n" + // "MIIEgDCCA2igAwIBAgIQDKTfhr9lmWbWUT0hjX36oDANBgkqhkiG9w0BAQsFADBy\n" + // "MQswCQYDVQQGEwJDTjElMCMGA1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywg\n" + // "SW5jLjEdMBsGA1UECxMURG9tYWluIFZhbGlkYXRlZCBTU0wxHTAbBgNVBAMTFFRy\n" + // "dXN0QXNpYSBUTFMgUlNBIENBMB4XDTE4MDEwNDAwMDAwMFoXDTE5MDEwNDEyMDAw\n" + // "MFowGDEWMBQGA1UEAxMNaW90ZGV2LmNsei5tZTCCASIwDQYJKoZIhvcNAQEBBQAD\n" + // "ggEPADCCAQoCggEBALbOFn7cJ2I/FKMJqIaEr38n4kCuJCCeNf1bWdWvOizmU2A8\n" + // "QeTAr5e6Q3GKeJRdPnc8xXhqkTm4LOhgdZB8KzuVZARtu23D4vj4sVzxgC/zwJlZ\n" + // "MRMxN+cqI37kXE8gGKW46l2H9vcukylJX+cx/tjWDfS2YuyXdFuS/RjhCxLgXzbS\n" + // "cve1W0oBZnBPRSMV0kgxTWj7hEGZNWKIzK95BSCiMN59b+XEu3NWGRb/VzSAiJEy\n" + // "Hy9DcDPBC9TEg+p5itHtdMhy2gq1OwsPgl9HUT0xmDATSNEV2RB3vwviNfu9/Eif\n" + // "ObhsV078zf30TqdiESqISEB68gJ0Otru67ePoTkCAwEAAaOCAWowggFmMB8GA1Ud\n" + // "IwQYMBaAFH/TmfOgRw4xAFZWIo63zJ7dygGKMB0GA1UdDgQWBBR/KLqnke61779P\n" + // "xc9htonQwLOxPDAYBgNVHREEETAPgg1pb3RkZXYuY2x6Lm1lMA4GA1UdDwEB/wQE\n" + // "AwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwTAYDVR0gBEUwQzA3\n" + // "BglghkgBhv1sAQIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQu\n" + // "Y29tL0NQUzAIBgZngQwBAgEwgYEGCCsGAQUFBwEBBHUwczAlBggrBgEFBQcwAYYZ\n" + // "aHR0cDovL29jc3AyLmRpZ2ljZXJ0LmNvbTBKBggrBgEFBQcwAoY+aHR0cDovL2Nh\n" + // "Y2VydHMuZGlnaXRhbGNlcnR2YWxpZGF0aW9uLmNvbS9UcnVzdEFzaWFUTFNSU0FD\n" + // "QS5jcnQwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAhtM4eyrWB14ajJpQ\n" + // "ibZ5FbzVuvv2Le0FOSoss7UFCDJUYiz2LiV8yOhL4KTY+oVVkqHaYtcFS1CYZNzj\n" + // "6xWcqYZJ+pgsto3WBEgNEEe0uLSiTW6M10hm0LFW9Det3k8fqwSlljqMha3gkpZ6\n" + // "8WB0f2clXOuC+f1SxAOymnGUsSqbU0eFSgevcOIBKR7Hr3YXBXH3jjED76Q52OMS\n" + // "ucfOM9/HB3jN8o/ioQbkI7xyd/DUQtzK6hSArEoYRl3p5H2P4fr9XqmpoZV3i3gQ\n" + // "oOdVycVtpLunyUoVAB2DcOElfDxxXCvDH3XsgoIU216VY03MCaUZf7kZ2GiNL+UX\n" + // "9UBd0Q==\n" + // "-----END CERTIFICATE-----\n"; + // #endif + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + extern BearSSL::WiFiClientSecure client_mqtt; + client_mqtt.stop(); + + std::unique_ptrclient_s(new BearSSL::WiFiClientSecure); + + // client_s->setFingerprint(fingerprint); + client_s->setInsecure(); + #else + WiFiClient client_s; + #endif + #endif + + HTTPClient http; + + String url_iot; + + int httpCode; + + // if (_type == BLINKER_CMD_SMS_NUMBER) { + // url_iot = String(host) + "/api/v1/user/device/sms"; + // } + String conType = BLINKER_F("Content-Type"); + String application = BLINKER_F("application/json;charset=utf-8"); + + BLINKER_LOG_ALL(BLINKER_F("blinker server begin")); + BLINKER_LOG_FreeHeap_ALL(); + + switch (_type) { + case BLINKER_CMD_SMS_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/sms"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_PUSH_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/push"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + // return BLINKER_CMD_FALSE; + case BLINKER_CMD_WECHAT_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/wxMsg/"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + // return BLINKER_CMD_FALSE; + case BLINKER_CMD_WEATHER_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v3"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_WEATHER_FORECAST_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v3"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_AQI_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v3"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOG_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/cloud_storage/logs"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_COD_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/cloud_storage/coordinate"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_BRIDGE_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKE_HTTP) + case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/cloud_storage/object"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_CONFIG_GET_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_CONFIG_DELETE_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_DATA_STORAGE_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/cloudStorage/"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_TIME_SLOT_DATA_NUMBER : + // url_iot = host; + // #ifndef BLINKER_WITHOUT_SSL + // url_iot = BLINKER_F("https://storage.diandeng.tech/api/v1/storage/ts"); + // #else + // url_iot = BLINKER_F("http://storage.diandeng.tech/api/v1/storage/ts"); + // #endif + + + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/cloud_storage/object"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_TEXT_DATA_NUMBER : + // url_iot = host; + #ifndef BLINKER_WITHOUT_SSL + url_iot = BLINKER_F("https://storage.diandeng.tech/api/v1/storage/tt"); + #else + url_iot = BLINKER_F("http://storage.diandeng.tech/api/v1/storage/tt"); + #endif + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_JSON_DATA_NUMBER : + // url_iot = host; + #ifndef BLINKER_WITHOUT_SSL + url_iot = BLINKER_F("https://storage.diandeng.tech/api/v1/storage/ot"); + #else + url_iot = BLINKER_F("http://storage.diandeng.tech/api/v1/storage/ot"); + #endif + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_DATA_GET_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_DATA_DELETE_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_AUTO_PULL_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_OTA_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_OTA_STATUS_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/ota/upgrade_status"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_FRESH_SHARERS_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_FREQ_GET_NUM : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_DATA_GET_NUM : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + case BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/lowpower/data"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_EVENT_DATA_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/event"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_GPS_DATA_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/gps"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device"); + url_iot += msg; + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + httpCode = http.GET(); + break; + #if defined(BLINKER_PRO_ESP) + case BLINKER_CMD_EVENT_WARNING_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/event"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_EVENT_ERROR_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/event"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + case BLINKER_CMD_EVENT_MSG_NUMBER : + url_iot = host; + url_iot += BLINKER_F("/api/v1/user/device/event"); + + #if defined(ESP8266) + #ifndef BLINKER_WITHOUT_SSL + http.begin(*client_s, url_iot); + #else + http.begin(client_s, url_iot); + #endif + #else + http.begin(url_iot); + #endif + + http.addHeader(conType, application); + httpCode = http.POST(msg); + break; + #endif + #endif + default : + return BLINKER_CMD_FALSE; + } + + BLINKER_LOG_ALL(BLINKER_F("HTTPS begin: "), url_iot); + + // http.begin(url_iot, ca); TODO + // http.begin(url_iot); + + // http.addHeader("Content-Type", "application/json"); + + // httpCode = http.POST(msg); + + BLINKER_LOG_ALL(BLINKER_F("HTTPS payload: "), msg); + + if (httpCode > 0) + { + BLINKER_LOG_ALL(BLINKER_F("[HTTP] status... code: "), httpCode); + + String payload; + if (httpCode == HTTP_CODE_OK) { + payload = http.getString(); + + BLINKER_LOG_ALL(payload); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& data_rp = jsonBuffer.parseObject(payload); + DynamicJsonDocument jsonBuffer(2048); + DeserializationError error = deserializeJson(jsonBuffer, payload); + JsonObject data_rp = jsonBuffer.as(); + + // if (data_rp.success()) + if (!error) + { + uint16_t msg_code = data_rp[BLINKER_CMD_MESSAGE]; + if (msg_code != 1000) + { + String _detail = data_rp[BLINKER_CMD_DETAIL]; + BLINKER_ERR_LOG(_detail); + } + else + { + BLINKER_LOG_ALL(BLINKER_F("_type: "), _type); + // String _payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DATA]; + // payload = _payload; + + if (_type == BLINKER_CMD_BRIDGE_NUMBER) + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DEVICENAME].as(); + else if (_type == BLINKER_CMD_OTA_NUMBER || _type == BLINKER_CMD_FRESH_SHARERS_NUMBER) + payload = data_rp[BLINKER_CMD_DETAIL].as(); + else if (_type == BLINKER_CMD_LOWPOWER_FREQ_GET_NUM) + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_FREQ].as(); + else if (_type == BLINKER_CMD_WEATHER_FORECAST_NUMBER || \ + _type == BLINKER_CMD_WEATHER_NUMBER || \ + _type == BLINKER_CMD_AQI_NUMBER || \ + _type == BLINKER_CMD_CONFIG_GET_NUMBER) + payload = data_rp[BLINKER_CMD_DETAIL].as(); + else + payload = data_rp[BLINKER_CMD_DETAIL][BLINKER_CMD_DATA].as(); + } + } + + BLINKER_LOG_ALL(BLINKER_F("payload: "), payload); + + switch (_type) { + case BLINKER_CMD_SMS_NUMBER : + _smsTime = millis(); + break; + case BLINKER_CMD_PUSH_NUMBER : + _pushTime = millis(); + break; + case BLINKER_CMD_WECHAT_NUMBER : + _wechatTime = millis(); + break; + // return BLINKER_CMD_FALSE; + case BLINKER_CMD_WEATHER_NUMBER : + _weatherTime = millis(); + if (_weatherFunc) _weatherFunc(payload); + break; + case BLINKER_CMD_WEATHER_FORECAST_NUMBER : + _weather_forecast_Time = millis(); + if (_weather_forecast_Func) _weather_forecast_Func(payload); + break; + case BLINKER_CMD_AQI_NUMBER : + _aqiTime = millis(); + if (_airFunc) _airFunc(payload); + break; + case BLINKER_CMD_LOG_NUMBER : + _logTime = millis(); + break; + case BLINKER_CMD_COD_NUMBER : + _codTime = millis(); + break; + case BLINKER_CMD_BRIDGE_NUMBER : + break; + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKE_HTTP) + case BLINKER_CMD_CONFIG_UPDATE_NUMBER : + _cUpdateTime = millis(); + break; + case BLINKER_CMD_CONFIG_GET_NUMBER : + _cGetTime = millis(); + if (_configGetFunc) _configGetFunc(payload); + break; + case BLINKER_CMD_CONFIG_DELETE_NUMBER : + _cDelTime = millis(); + break; + case BLINKER_CMD_DATA_STORAGE_NUMBER : + _dUpdateTime = millis(); + break; + case BLINKER_CMD_TIME_SLOT_DATA_NUMBER : + _dUpdateTime = millis(); + break; + case BLINKER_CMD_TEXT_DATA_NUMBER : + _dUpdateTime = millis(); + break; + case BLINKER_CMD_JSON_DATA_NUMBER : + _dUpdateTime = millis(); + break; + case BLINKER_CMD_JSON_DATA_GET_NUMBER : + // _dUpdateTime = millis(); + break; + case BLINKER_CMD_DATA_GET_NUMBER : + _dGetTime = millis(); + if (_dataGetFunc) _dataGetFunc(payload); + break; + case BLINKER_CMD_DATA_DELETE_NUMBER : + _dDelTime = millis(); + break; + case BLINKER_CMD_AUTO_PULL_NUMBER : + _autoPullTime = millis(); + break; + case BLINKER_CMD_OTA_NUMBER : + break; + case BLINKER_CMD_OTA_STATUS_NUMBER : + break; + case BLINKER_CMD_FRESH_SHARERS_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_FREQ_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER : + break; + case BLINKER_CMD_LOWPOWER_DATA_GET_NUM : + break; + case BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER : + break; + case BLINKER_CMD_EVENT_DATA_NUMBER : + break; + case BLINKER_CMD_GPS_DATA_NUMBER : + break; + case BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER : + break; + #if defined(BLINKER_PRO_ESP) + case BLINKER_CMD_EVENT_WARNING_NUMBER : + _eWarnTime = millis(); + break; + case BLINKER_CMD_EVENT_ERROR_NUMBER : + _eErrTime = millis(); + break; + case BLINKER_CMD_EVENT_MSG_NUMBER : + _eMsgTime = millis(); + break; + #endif + #endif + default : + return BLINKER_CMD_FALSE; + } + } + + http.end(); + + return payload; + } + else { + BLINKER_LOG_ALL(BLINKER_F("[HTTP] ... failed, error: "), http.errorToString(httpCode).c_str()); + String payload = http.getString(); + BLINKER_LOG_ALL(payload); + + if (_type == BLINKER_CMD_SMS_NUMBER) { + _smsTime = millis(); + } + http.end(); + return BLINKER_CMD_FALSE; + } + // #endif + } + + #endif + + #endif + +#endif + +#if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + + void BlinkerApi::aliParse(const String & _data) + { + BLINKER_LOG_ALL(BLINKER_F("AliGenie parse data: "), _data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(_data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, _data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + if (root.containsKey(BLINKER_CMD_GET)) + { + String value = root[BLINKER_CMD_GET]; + + bool query_set = false; + + if(_AliGenieQueryFunc) query_set = true; + if(_AliGenieQueryFunc_m) query_set = true; + + if (!query_set) + { + BLINKER_ERR_LOG("None query function set!"); + } + + if (value == BLINKER_CMD_STATE){ + uint8_t setNum = root[BLINKER_CMD_NUM]; + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_ALL_NUMBER); + if (_AliGenieQueryFunc_m) _AliGenieQueryFunc_m(BLINKER_CMD_QUERY_ALL_NUMBER, setNum); + } + else if (value == BLINKER_CMD_POWERSTATE) { + uint8_t setNum = root[BLINKER_CMD_NUM]; + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_POWERSTATE_NUMBER); + if (_AliGenieQueryFunc_m) _AliGenieQueryFunc_m(BLINKER_CMD_QUERY_POWERSTATE_NUMBER, setNum); + } + else if (value == BLINKER_CMD_COLOR) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_COLOR_NUMBER); + } + else if (value == BLINKER_CMD_COLOR_) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_COLOR_NUMBER); + } + else if (value == BLINKER_CMD_COLORTEMP) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_COLORTEMP_NUMBER); + } + else if (value == BLINKER_CMD_BRIGHTNESS) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_BRIGHTNESS_NUMBER); + } + else if (value == BLINKER_CMD_TEMP) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_TEMP_NUMBER); + } + else if (value == BLINKER_CMD_HUMI) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_HUMI_NUMBER); + } + else if (value == BLINKER_CMD_PM25) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_PM25_NUMBER); + } + else if (value == BLINKER_CMD_MODE) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_MODE_NUMBER); + } + } + else if (root.containsKey(BLINKER_CMD_SET)) { + String value = root[BLINKER_CMD_SET]; + + // DynamicJsonBuffer jsonBufferSet; + // JsonObject& rootSet = jsonBufferSet.parseObject(value); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, value); + JsonObject rootSet = jsonBuffer.as(); + + // if (!rootSet.success()) + if (error) + { + // BLINKER_ERR_LOG_ALL("Json error"); + return; + } + + // BLINKER_LOG_ALL("Json parse success"); + + if (rootSet.containsKey(BLINKER_CMD_POWERSTATE)) { + String setValue = rootSet[BLINKER_CMD_POWERSTATE]; + uint8_t setNum = rootSet[BLINKER_CMD_NUM]; + + if (_AliGeniePowerStateFunc) _AliGeniePowerStateFunc(setValue); + if (_AliGeniePowerStateFunc_m) _AliGeniePowerStateFunc_m(setValue, setNum); + } + else if (rootSet.containsKey(BLINKER_CMD_HSTATE)) { + String setValue = rootSet[BLINKER_CMD_HSTATE]; + + if (_AliGenieHSwingStateFunc) _AliGenieHSwingStateFunc(setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_VSTATE)) { + String setValue = rootSet[BLINKER_CMD_VSTATE]; + + if (_AliGenieVSwingStateFunc) _AliGenieVSwingStateFunc(setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_COLOR)) { + String setValue = rootSet[BLINKER_CMD_COLOR]; + + if (_AliGenieSetColorFunc) _AliGenieSetColorFunc(setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_COLOR_)) { + String setValue = rootSet[BLINKER_CMD_COLOR_]; + + if (_AliGenieSetColorFunc) _AliGenieSetColorFunc(setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_BRIGHTNESS)) { + String setValue = rootSet[BLINKER_CMD_BRIGHTNESS]; + + if (_AliGenieSetBrightnessFunc) _AliGenieSetBrightnessFunc(setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_UPBRIGHTNESS)) { + String setValue = rootSet[BLINKER_CMD_UPBRIGHTNESS]; + + if (_AliGenieSetRelativeBrightnessFunc) _AliGenieSetRelativeBrightnessFunc(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_DOWNBRIGHTNESS)) { + String setValue = rootSet[BLINKER_CMD_DOWNBRIGHTNESS]; + + if (_AliGenieSetRelativeBrightnessFunc) _AliGenieSetRelativeBrightnessFunc(- setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_COLORTEMP)) { + String setValue = rootSet[BLINKER_CMD_COLORTEMP]; + + if (_AliGenieSetColorTemperature) _AliGenieSetColorTemperature(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_UPCOLORTEMP)) { + String setValue = rootSet[BLINKER_CMD_UPCOLORTEMP]; + + if (_AliGenieSetRelativeColorTemperature) _AliGenieSetRelativeColorTemperature(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_DOWNCOLORTEMP)) { + String setValue = rootSet[BLINKER_CMD_DOWNCOLORTEMP]; + + if (_AliGenieSetRelativeColorTemperature) _AliGenieSetRelativeColorTemperature(- setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_MODE)) { + String setMode = rootSet[BLINKER_CMD_MODE]; + + if (_AliGenieSetModeFunc) _AliGenieSetModeFunc(setMode); + } + else if (rootSet.containsKey(BLINKER_CMD_CANCELMODE)) { + String setcMode = rootSet[BLINKER_CMD_CANCELMODE]; + + if (_AliGenieSetcModeFunc) _AliGenieSetcModeFunc(setcMode); + } + else if (rootSet.containsKey(BLINKER_CMD_LEVEL)) { + String setLevel = rootSet[BLINKER_CMD_LEVEL]; + + if (_AliGenieSetLevelFunc_str) _AliGenieSetLevelFunc_str(setLevel); + if (_AliGenieSetLevelFunc) _AliGenieSetLevelFunc(setLevel.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_TEMP)) { + String setValue = rootSet[BLINKER_CMD_TEMP]; + + if (_AliGenieSetTempFunc) _AliGenieSetTempFunc(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_LEVEL_UP)) { + String setValue = rootSet[BLINKER_CMD_LEVEL_UP]; + + if (_AliGenieSetRelativeLevelFunc) _AliGenieSetRelativeLevelFunc(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_LEVEL_DW)) { + String setValue = rootSet[BLINKER_CMD_LEVEL_DW]; + + if (_AliGenieSetRelativeLevelFunc) _AliGenieSetRelativeLevelFunc(- setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_TEMP_UP)) { + String setValue = rootSet[BLINKER_CMD_TEMP_UP]; + + if (_AliGenieSetRelativeTempFunc) _AliGenieSetRelativeTempFunc(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_TEMP_DW)) { + String setValue = rootSet[BLINKER_CMD_TEMP_DW]; + + if (_AliGenieSetRelativeTempFunc) _AliGenieSetRelativeTempFunc(- setValue.toInt()); + } + } + } + + + void BlinkerApi::duerParse(const String & _data) + { + BLINKER_LOG_ALL(BLINKER_F("DuerOS parse data: "), _data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(_data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, _data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + if (root.containsKey(BLINKER_CMD_GET)) + { + String value = root[BLINKER_CMD_GET]; + + bool query_set = false; + + if(_DuerOSQueryFunc) query_set = true; + if(_DuerOSQueryFunc_m) query_set = true; + + if (!query_set) + { + BLINKER_ERR_LOG("None query function set!"); + } + + if (value == BLINKER_CMD_POWERSTATE) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_POWERSTATE_NUMBER); + } + else if (value == BLINKER_CMD_AQI) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_AQI_NUMBER); + } + else if (value == BLINKER_CMD_PM25) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_PM25_NUMBER); + } + else if (value == BLINKER_CMD_PM10) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_PM10_NUMBER); + } + else if (value == BLINKER_CMD_CO2) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_CO2_NUMBER); + } + else if (value == BLINKER_CMD_TEMP) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_TEMP_NUMBER); + } + else if (value == BLINKER_CMD_HUMI) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_HUMI_NUMBER); + } + else if (value == BLINKER_CMD_MODE) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_MODE_NUMBER); + } + else if (value == BLINKER_CMD_TIME_ALL) { + uint8_t setNum = root[BLINKER_CMD_NUM]; + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_TIME_NUMBER); + if (_DuerOSQueryFunc_m) _DuerOSQueryFunc_m(BLINKER_CMD_QUERY_TIME_NUMBER, setNum); + } + } + else if (root.containsKey(BLINKER_CMD_SET)) { + String value = root[BLINKER_CMD_SET]; + + // DynamicJsonBuffer jsonBufferSet; + // JsonObject& rootSet = jsonBufferSet.parseObject(value); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, value); + JsonObject rootSet = jsonBuffer.as(); + + // if (!rootSet.success()) + if (error) + { + // BLINKER_ERR_LOG_ALL("Json error"); + return; + } + + // BLINKER_LOG_ALL("Json parse success"); + + if (rootSet.containsKey(BLINKER_CMD_POWERSTATE)) { + String setValue = rootSet[BLINKER_CMD_POWERSTATE]; + uint8_t setNum = rootSet[BLINKER_CMD_NUM]; + + if (_DuerOSPowerStateFunc) _DuerOSPowerStateFunc(setValue); + if (_DuerOSPowerStateFunc_m) _DuerOSPowerStateFunc_m(setValue, setNum); + } + else if (rootSet.containsKey(BLINKER_CMD_COLOR)) { + String setValue = rootSet[BLINKER_CMD_COLOR]; + + if (_DuerOSSetColorFunc) _DuerOSSetColorFunc(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_COLOR_)) { + String setValue = rootSet[BLINKER_CMD_COLOR_]; + + if (_DuerOSSetColorFunc) _DuerOSSetColorFunc(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_BRIGHTNESS)) { + String setValue = rootSet[BLINKER_CMD_BRIGHTNESS]; + + if (_DuerOSSetBrightnessFunc) _DuerOSSetBrightnessFunc(setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_UPBRIGHTNESS)) { + String setValue = rootSet[BLINKER_CMD_UPBRIGHTNESS]; + + if (_DuerOSSetRelativeBrightnessFunc) _DuerOSSetRelativeBrightnessFunc(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_DOWNBRIGHTNESS)) { + String setValue = rootSet[BLINKER_CMD_DOWNBRIGHTNESS]; + + if (_DuerOSSetRelativeBrightnessFunc) _DuerOSSetRelativeBrightnessFunc(- setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_COLORTEMP)) { + String setValue = rootSet[BLINKER_CMD_COLORTEMP]; + + if (_DuerOSSetColorTemperature) _DuerOSSetColorTemperature(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_UPCOLORTEMP)) { + String setValue = rootSet[BLINKER_CMD_UPCOLORTEMP]; + + if (_DuerOSSetRelativeColorTemperature) _DuerOSSetRelativeColorTemperature(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_DOWNCOLORTEMP)) { + String setValue = rootSet[BLINKER_CMD_DOWNCOLORTEMP]; + + if (_DuerOSSetRelativeColorTemperature) _DuerOSSetRelativeColorTemperature(- setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_MODE)) { + String setMode = rootSet[BLINKER_CMD_MODE]; + + if (_DuerOSSetModeFunc) _DuerOSSetModeFunc(setMode); + } + else if (rootSet.containsKey(BLINKER_CMD_CANCELMODE)) { + String setcMode = rootSet[BLINKER_CMD_CANCELMODE]; + + if (_DuerOSSetcModeFunc) _DuerOSSetcModeFunc(setcMode); + } + else if (rootSet.containsKey(BLINKER_CMD_LEVEL)) { + String setValue = rootSet[BLINKER_CMD_LEVEL]; + + if (_DuerOSSetLevelFunc) _DuerOSSetLevelFunc(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_LEVEL_UP)) { + String setValue = rootSet[BLINKER_CMD_LEVEL_UP]; + + if (_DuerOSSetRelativeLevelFunc) _DuerOSSetRelativeLevelFunc(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_LEVEL_DW)) { + String setValue = rootSet[BLINKER_CMD_LEVEL_DW]; + + if (_DuerOSSetRelativeLevelFunc) _DuerOSSetRelativeLevelFunc(-setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_TEMP)) { + String setValue = rootSet[BLINKER_CMD_TEMP]; + + if (_DuerOSSetTempFunc) _DuerOSSetTempFunc(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_TEMP_UP)) { + String setValue = rootSet[BLINKER_CMD_TEMP_UP]; + + if (_DuerOSSetRelativeTempFunc) _DuerOSSetRelativeTempFunc(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_TEMP_DW)) { + String setValue = rootSet[BLINKER_CMD_TEMP_DW]; + + if (_DuerOSSetRelativeTempFunc) _DuerOSSetRelativeTempFunc(-setValue.toInt()); + } + } + } + + + void BlinkerApi::miotParse(const String & _data) + { + BLINKER_LOG_ALL(BLINKER_F("MIOT parse data: "), _data); + + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(_data); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, _data); + JsonObject root = jsonBuffer.as(); + + // if (!root.success()) return; + if (error) return; + + if (root.containsKey(BLINKER_CMD_GET)) + { + String value = root[BLINKER_CMD_GET]; + + bool query_set = false; + + if(_MIOTQueryFunc) query_set = true; + if(_MIOTQueryFunc_m) query_set = true; + + if (!query_set) + { + BLINKER_ERR_LOG("None query function set!"); + } + + if (value == BLINKER_CMD_STATE){ + uint8_t setNum = root[BLINKER_CMD_NUM]; + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_ALL_NUMBER); + if (_MIOTQueryFunc_m) _MIOTQueryFunc_m(BLINKER_CMD_QUERY_ALL_NUMBER, setNum); + } + else if (value == BLINKER_CMD_POWERSTATE1) { + uint8_t setNum = root[BLINKER_CMD_NUM]; + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_POWERSTATE_NUMBER); + if (_MIOTQueryFunc_m) _MIOTQueryFunc_m(BLINKER_CMD_QUERY_POWERSTATE_NUMBER, setNum); + } + else if (value == BLINKER_CMD_COLOR) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_COLOR_NUMBER); + } + else if (value == BLINKER_CMD_COLOR_) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_COLOR_NUMBER); + } + else if (value == BLINKER_CMD_COLORTEMP) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_COLORTEMP_NUMBER); + } + else if (value == BLINKER_CMD_BRIGHTNESS) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_BRIGHTNESS_NUMBER); + } + else if (value == BLINKER_CMD_TEMP) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_TEMP_NUMBER); + } + else if (value == BLINKER_CMD_HUMI) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_HUMI_NUMBER); + } + else if (value == BLINKER_CMD_PM25) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_PM25_NUMBER); + } + else if (value == BLINKER_CMD_MODE) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_MODE_NUMBER); + } + } + else if (root.containsKey(BLINKER_CMD_SET)) { + String value = root[BLINKER_CMD_SET]; + + // DynamicJsonBuffer jsonBufferSet; + // JsonObject& rootSet = jsonBufferSet.parseObject(value); + DynamicJsonDocument jsonBuffer(1024); + DeserializationError error = deserializeJson(jsonBuffer, value); + JsonObject rootSet = jsonBuffer.as(); + + // if (!rootSet.success()) + if (error) + { + // BLINKER_ERR_LOG_ALL("Json error"); + return; + } + + // BLINKER_LOG_ALL("Json parse success"); + + if (rootSet.containsKey(BLINKER_CMD_POWERSTATE1)) { + String setValue = rootSet[BLINKER_CMD_POWERSTATE1]; + uint8_t setNum = rootSet[BLINKER_CMD_NUM]; + + // if (setValue == "true") setValue = "on"; + // else setValue = "off"; + + if (_MIOTPowerStateFunc) _MIOTPowerStateFunc(setValue); + if (_MIOTPowerStateFunc_m) _MIOTPowerStateFunc_m(setValue, setNum); + } + else if (rootSet.containsKey(BLINKER_CMD_HSTATE)) { + String setValue = rootSet[BLINKER_CMD_HSTATE]; + + // if (setValue == "true") setValue = "on"; + // else setValue = "off"; + + if (_MIOTHSwingStateFunc) _MIOTHSwingStateFunc(setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_VSTATE)) { + String setValue = rootSet[BLINKER_CMD_VSTATE]; + + // if (setValue == "true") setValue = "on"; + // else setValue = "off"; + + if (_MIOTVSwingStateFunc) _MIOTVSwingStateFunc(setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_ECO)) { + String setValue = rootSet[BLINKER_CMD_ECO]; + + // if (setValue == "true") setValue = "on"; + // else setValue = "off"; + + // if (_MIOTECOFunc) _MIOTECOFunc(setValue); + if (_MIOTSetModeFunc_m) _MIOTSetModeFunc_m(BLINKER_CMD_ECO, setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_ANION)) { + String setValue = rootSet[BLINKER_CMD_ANION]; + + // if (setValue == "true") setValue = "on"; + // else setValue = "off"; + + // if (_MIOTAnionFunc) _MIOTAnionFunc(setValue); + if (_MIOTSetModeFunc_m) _MIOTSetModeFunc_m(BLINKER_CMD_ECO, setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_HEATER)) { + String setValue = rootSet[BLINKER_CMD_HEATER]; + + // if (setValue == "true") setValue = "on"; + // else setValue = "off"; + + // if (_MIOTHeaterFunc) _MIOTHeaterFunc(setValue); + if (_MIOTSetModeFunc_m) _MIOTSetModeFunc_m(BLINKER_CMD_ECO, setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_DRYER)) { + String setValue = rootSet[BLINKER_CMD_DRYER]; + + // if (setValue == "true") setValue = "on"; + // else setValue = "off"; + + // if (_MIOTDryerFunc) _MIOTDryerFunc(setValue); + if (_MIOTSetModeFunc_m) _MIOTSetModeFunc_m(BLINKER_CMD_ECO, setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_SLEEP)) { + String setValue = rootSet[BLINKER_CMD_SLEEP]; + + // if (setValue == "true") setValue = "on"; + // else setValue = "off"; + + // if (_MIOTSleepFunc) _MIOTSleepFunc(setValue); + if (_MIOTSetModeFunc_m) _MIOTSetModeFunc_m(BLINKER_CMD_ECO, setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_SOFT)) { + String setValue = rootSet[BLINKER_CMD_SOFT]; + + // if (setValue == "true") setValue = "on"; + // else setValue = "off"; + + // if (_MIOTSoftFunc) _MIOTSoftFunc(setValue); + if (_MIOTSetModeFunc_m) _MIOTSetModeFunc_m(BLINKER_CMD_ECO, setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_UV)) { + String setValue = rootSet[BLINKER_CMD_UV]; + + // if (setValue == "true") setValue = "on"; + // else setValue = "off"; + + // if (_MIOTUVFunc) _MIOTUVFunc(setValue); + if (_MIOTSetModeFunc_m) _MIOTSetModeFunc_m(BLINKER_CMD_ECO, setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_UNSB)) { + String setValue = rootSet[BLINKER_CMD_UNSB]; + + // if (setValue == "true") setValue = "on"; + // else setValue = "off"; + + // if (_MIOTUNSBFunc) _MIOTUNSBFunc(setValue); + if (_MIOTSetModeFunc_m) _MIOTSetModeFunc_m(BLINKER_CMD_ECO, setValue); + } + else if (rootSet.containsKey(BLINKER_CMD_COLOR)) { + String setValue = rootSet[BLINKER_CMD_COLOR]; + + if (_MIOTSetColorFunc) _MIOTSetColorFunc(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_COLOR_)) { + String setValue = rootSet[BLINKER_CMD_COLOR_]; + + if (_MIOTSetColorFunc) _MIOTSetColorFunc(setValue.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_BRIGHTNESS)) { + String setValue = rootSet[BLINKER_CMD_BRIGHTNESS]; + + if (_MIOTSetBrightnessFunc) _MIOTSetBrightnessFunc(setValue); + } + // else if (rootSet.containsKey(BLINKER_CMD_UPBRIGHTNESS)) { + // String setValue = rootSet[BLINKER_CMD_UPBRIGHTNESS]; + + // if (_MIOTSetRelativeBrightnessFunc) _MIOTSetRelativeBrightnessFunc(setValue.toInt()); + // } + // else if (rootSet.containsKey(BLINKER_CMD_DOWNBRIGHTNESS)) { + // String setValue = rootSet[BLINKER_CMD_DOWNBRIGHTNESS]; + + // if (_MIOTSetRelativeBrightnessFunc) _MIOTSetRelativeBrightnessFunc(- setValue.toInt()); + // } + else if (rootSet.containsKey(BLINKER_CMD_COLORTEMP)) { + String setValue = rootSet[BLINKER_CMD_COLORTEMP]; + + if (_MIOTSetColorTemperature) _MIOTSetColorTemperature(setValue.toInt()); + } + // else if (rootSet.containsKey(BLINKER_CMD_UPCOLORTEMP)) { + // String setValue = rootSet[BLINKER_CMD_UPCOLORTEMP]; + + // if (_MIOTSetRelativeColorTemperature) _MIOTSetRelativeColorTemperature(setValue.toInt()); + // } + // else if (rootSet.containsKey(BLINKER_CMD_DOWNCOLORTEMP)) { + // String setValue = rootSet[BLINKER_CMD_DOWNCOLORTEMP]; + + // if (_MIOTSetRelativeColorTemperature) _MIOTSetRelativeColorTemperature(- setValue.toInt()); + // } + else if (rootSet.containsKey(BLINKER_CMD_MODE)) { + String setMode = rootSet[BLINKER_CMD_MODE]; + + if (_MIOTSetModeFunc) _MIOTSetModeFunc(setMode.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_LEVEL)) { + String setLevel = rootSet[BLINKER_CMD_LEVEL]; + + if (_MIOTSetLevelFunc) _MIOTSetLevelFunc(setLevel.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_TEMP)) { + String setTemp = rootSet[BLINKER_CMD_TEMP]; + + if (_MIOTSetTempFunc) _MIOTSetTempFunc(setTemp.toInt()); + } + else if (rootSet.containsKey(BLINKER_CMD_HUMI)) { + String setHumi = rootSet[BLINKER_CMD_HUMI]; + + if (_MIOTSetHumiFunc) _MIOTSetHumiFunc(setHumi.toInt()); + } + // else if (rootSet.containsKey(BLINKER_CMD_CANCELMODE)) { + // String setcMode = rootSet[BLINKER_CMD_CANCELMODE]; + + // if (_MIOTSetcModeFunc) _MIOTSetcModeFunc(setcMode); + // } + } + } +#endif + + +#if defined(BLINKER_MQTT_AT) + void BlinkerApi::aliParse(const String & _data) + { + BLINKER_LOG_ALL(BLINKER_F("AliGenie parse data: "), _data); + + if (STRING_contains_string(_data, "AliGenie")) + { + String value = ""; + if (STRING_find_string_value(_data, value, BLINKER_CMD_GET)) + { + bool query_set = false; + + if(_AliGenieQueryFunc) query_set = true; + if(_AliGenieQueryFunc_m) query_set = true; + + if (!query_set) + { + BLINKER_ERR_LOG("None query function set!"); + } + + if (value == BLINKER_CMD_STATE) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_ALL_NUMBER); + } + else if (value == BLINKER_CMD_POWERSTATE) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_POWERSTATE_NUMBER); + } + else if (value == BLINKER_CMD_COLOR) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_COLOR_NUMBER); + } + else if (value == BLINKER_CMD_COLOR_) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_COLOR_NUMBER); + } + else if (value == BLINKER_CMD_COLORTEMP) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_COLORTEMP_NUMBER); + } + else if (value == BLINKER_CMD_BRIGHTNESS) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_BRIGHTNESS_NUMBER); + } + else if (value == BLINKER_CMD_TEMP) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_TEMP_NUMBER); + } + else if (value == BLINKER_CMD_HUMI) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_HUMI_NUMBER); + } + else if (value == BLINKER_CMD_PM25) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_PM25_NUMBER); + } + else if (value == BLINKER_CMD_MODE) { + if (_AliGenieQueryFunc) _AliGenieQueryFunc(BLINKER_CMD_QUERY_MODE_NUMBER); + } + } + else if (STRING_contains_string(_data, BLINKER_CMD_SET)) + { + if (STRING_find_string_value(_data, value, BLINKER_CMD_POWERSTATE)) + { + if (_AliGeniePowerStateFunc) _AliGeniePowerStateFunc(value); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_COLOR)) + { + if (_AliGenieSetColorFunc) _AliGenieSetColorFunc(value); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_COLOR_)) + { + if (_AliGenieSetColorFunc) _AliGenieSetColorFunc(value); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_BRIGHTNESS)) + { + if (_AliGenieSetBrightnessFunc) _AliGenieSetBrightnessFunc(value); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_UPBRIGHTNESS)) + { + if (_AliGenieSetRelativeBrightnessFunc) _AliGenieSetRelativeBrightnessFunc(value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_DOWNBRIGHTNESS)) + { + if (_AliGenieSetRelativeBrightnessFunc) _AliGenieSetRelativeBrightnessFunc(- value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_COLORTEMP)) + { + if (_AliGenieSetColorTemperature) _AliGenieSetColorTemperature(value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_UPCOLORTEMP)) + { + if (_AliGenieSetRelativeColorTemperature) _AliGenieSetRelativeColorTemperature(value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_DOWNCOLORTEMP)) + { + if (_AliGenieSetRelativeColorTemperature) _AliGenieSetRelativeColorTemperature(- value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_MODE)) + { + if (_AliGenieSetModeFunc) _AliGenieSetModeFunc(value); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_CANCELMODE)) + { + if (_AliGenieSetcModeFunc) _AliGenieSetcModeFunc(value); + } + } + } + } + + + void BlinkerApi::duerParse(const String & _data) + { + BLINKER_LOG_ALL(BLINKER_F("DuerOS parse data: "), _data); + + if (STRING_contains_string(_data, "DuerOS")) + { + String value = ""; + if (STRING_find_string_value(_data, value, BLINKER_CMD_GET)) + { + bool query_set = false; + + if(_DuerOSQueryFunc) query_set = true; + if(_DuerOSQueryFunc_m) query_set = true; + + if (!query_set) + { + BLINKER_ERR_LOG("None query function set!"); + } + + if (value == BLINKER_CMD_STATE) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_ALL_NUMBER); + } + else if (value == BLINKER_CMD_POWERSTATE) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_POWERSTATE_NUMBER); + } + else if (value == BLINKER_CMD_COLOR) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_COLOR_NUMBER); + } + else if (value == BLINKER_CMD_COLORTEMP) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_COLORTEMP_NUMBER); + } + else if (value == BLINKER_CMD_BRIGHTNESS) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_BRIGHTNESS_NUMBER); + } + else if (value == BLINKER_CMD_TEMP) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_TEMP_NUMBER); + } + else if (value == BLINKER_CMD_HUMI) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_HUMI_NUMBER); + } + else if (value == BLINKER_CMD_PM25) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_PM25_NUMBER); + } + else if (value == BLINKER_CMD_MODE) { + if (_DuerOSQueryFunc) _DuerOSQueryFunc(BLINKER_CMD_QUERY_MODE_NUMBER); + } + } + else if (STRING_contains_string(_data, BLINKER_CMD_SET)) + { + if (STRING_find_string_value(_data, value, BLINKER_CMD_POWERSTATE)) + { + if (_DuerOSPowerStateFunc) _DuerOSPowerStateFunc(value); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_COLOR)) + { + if (_DuerOSSetColorFunc) _DuerOSSetColorFunc(value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_BRIGHTNESS)) + { + if (_DuerOSSetBrightnessFunc) _DuerOSSetBrightnessFunc(value); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_UPBRIGHTNESS)) + { + if (_DuerOSSetRelativeBrightnessFunc) _DuerOSSetRelativeBrightnessFunc(value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_DOWNBRIGHTNESS)) + { + if (_DuerOSSetRelativeBrightnessFunc) _DuerOSSetRelativeBrightnessFunc(- value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_COLORTEMP)) + { + if (_DuerOSSetColorTemperature) _DuerOSSetColorTemperature(value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_UPCOLORTEMP)) + { + if (_DuerOSSetRelativeColorTemperature) _DuerOSSetRelativeColorTemperature(value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_DOWNCOLORTEMP)) + { + if (_DuerOSSetRelativeColorTemperature) _DuerOSSetRelativeColorTemperature(- value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_MODE)) + { + if (_DuerOSSetModeFunc) _DuerOSSetModeFunc(value); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_CANCELMODE)) + { + if (_DuerOSSetcModeFunc) _DuerOSSetcModeFunc(value); + } + } + } + } + + + void BlinkerApi::miotParse(const String & _data) + { + BLINKER_LOG_ALL(BLINKER_F("MIOT parse data: "), _data); + + if (STRING_contains_string(_data, "MIOT")) + { + String value = ""; + if (STRING_find_string_value(_data, value, BLINKER_CMD_GET)) + { + bool query_set = false; + + if(_MIOTQueryFunc) query_set = true; + if(_MIOTQueryFunc_m) query_set = true; + + if (!query_set) + { + BLINKER_ERR_LOG("None query function set!"); + } + + if (value == BLINKER_CMD_STATE) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_ALL_NUMBER); + } + else if (value == BLINKER_CMD_POWERSTATE) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_POWERSTATE_NUMBER); + } + else if (value == BLINKER_CMD_COLOR) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_COLOR_NUMBER); + } + else if (value == BLINKER_CMD_COLOR_) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_COLOR_NUMBER); + } + else if (value == BLINKER_CMD_COLORTEMP) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_COLORTEMP_NUMBER); + } + else if (value == BLINKER_CMD_BRIGHTNESS) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_BRIGHTNESS_NUMBER); + } + else if (value == BLINKER_CMD_TEMP) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_TEMP_NUMBER); + } + else if (value == BLINKER_CMD_HUMI) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_HUMI_NUMBER); + } + else if (value == BLINKER_CMD_PM25) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_PM25_NUMBER); + } + else if (value == BLINKER_CMD_MODE) { + if (_MIOTQueryFunc) _MIOTQueryFunc(BLINKER_CMD_QUERY_MODE_NUMBER); + } + } + else if (STRING_contains_string(_data, BLINKER_CMD_SET)) + { + if (STRING_find_string_value(_data, value, BLINKER_CMD_POWERSTATE)) + { + if (value == "true") value = "on"; + else value = "off"; + + if (_MIOTPowerStateFunc) _MIOTPowerStateFunc(value); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_COLOR)) + { + if (_MIOTSetColorFunc) _MIOTSetColorFunc(value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_COLOR_)) + { + if (_MIOTSetColorFunc) _MIOTSetColorFunc(value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_BRIGHTNESS)) + { + if (_MIOTSetBrightnessFunc) _MIOTSetBrightnessFunc(value); + } + // else if (STRING_find_string_value(_data, value, BLINKER_CMD_UPBRIGHTNESS)) + // { + // if (_MIOTSetRelativeBrightnessFunc) _MIOTSetRelativeBrightnessFunc(value.toInt()); + // } + // else if (STRING_find_string_value(_data, value, BLINKER_CMD_DOWNBRIGHTNESS)) + // { + // if (_MIOTSetRelativeBrightnessFunc) _MIOTSetRelativeBrightnessFunc(- value.toInt()); + // } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_COLORTEMP)) + { + if (_MIOTSetColorTemperature) _MIOTSetColorTemperature(value.toInt()); + } + // else if (STRING_find_string_value(_data, value, BLINKER_CMD_UPCOLORTEMP)) + // { + // if (_MIOTSetRelativeColorTemperature) _MIOTSetRelativeColorTemperature(value.toInt()); + // } + // else if (STRING_find_string_value(_data, value, BLINKER_CMD_DOWNCOLORTEMP)) + // { + // if (_MIOTSetRelativeColorTemperature) _MIOTSetRelativeColorTemperature(- value.toInt()); + // } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_MODE)) + { + if (_MIOTSetModeFunc) _MIOTSetModeFunc(value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_LEVEL)) + { + if (_MIOTSetLevelFunc) _MIOTSetLevelFunc(value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_TEMP)) + { + if (_MIOTSetTempFunc) _MIOTSetTempFunc(value.toInt()); + } + else if (STRING_find_string_value(_data, value, BLINKER_CMD_HUMI)) + { + if (_MIOTSetHumiFunc) _MIOTSetHumiFunc(value.toInt()); + } + // else if (STRING_find_string_value(_data, value, BLINKER_CMD_CANCELMODE)) + // { + // if (_MIOTSetcModeFunc) _MIOTSetcModeFunc(value); + // } + } + } + } +#endif + +#if defined(BLINKER_AT_MQTT) + void BlinkerApi::atBegin() + { + while (_status == BL_BEGIN) + { + serialAvailable(); + } + } + + void BlinkerApi::parseATdata() + { + String reqData; + + if (_slaverAT->cmd() == BLINKER_CMD_AT) { + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_RST) { + BProto::serialPrint(BLINKER_CMD_OK); + ::delay(100); + ESP.restart(); + } + else if (_slaverAT->cmd() == BLINKER_CMD_GMR) { + // reqData = "+" + STRING_format(BLINKER_CMD_GMR) + + // "=," + + // "[,,]"; + BProto::serialPrint(BLINKER_ESP_AT_VERSION); + BProto::serialPrint(BLINKER_VERSION); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_UART_CUR) { + blinker_at_state_t at_state = _slaverAT->state(); + + BLINKER_LOG(at_state); + + switch (at_state) + { + case AT_NONE: + // BProto::serialPrint(); + break; + case AT_TEST: + reqData = BLINKER_CMD_AT;// + + reqData += BLINKER_F("+"); + reqData += BLINKER_CMD_UART_CUR;// + + reqData += BLINKER_F("=,,,"); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_QUERY: + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_UART_CUR; + reqData += BLINKER_F(":"); + reqData += STRING_format(serialSet >> 8 & 0x00FFFFFF); + reqData += BLINKER_F(","); + reqData += STRING_format(serialSet >> 4 & 0x0F); + reqData += BLINKER_F(","); + reqData += STRING_format(serialSet >> 2 & 0x03); + reqData += BLINKER_F(","); + reqData += STRING_format(serialSet & 0x03); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_SETTING: + BLINKER_LOG_ALL(BLINKER_F("SER_BAUD: "), _slaverAT->getParam(SER_BAUD)); + BLINKER_LOG_ALL(BLINKER_F("SER_DBIT: "), _slaverAT->getParam(SER_DBIT)); + BLINKER_LOG_ALL(BLINKER_F("SER_SBIT: "), _slaverAT->getParam(SER_SBIT)); + BLINKER_LOG_ALL(BLINKER_F("SER_PRIT: "), _slaverAT->getParam(SER_PRIT)); + if (BLINKER_UART_PARAM_NUM != _slaverAT->paramNum()) return; + + serialSet = (_slaverAT->getParam(SER_BAUD)).toInt() << 8 | + (_slaverAT->getParam(SER_DBIT)).toInt() << 4 | + (_slaverAT->getParam(SER_SBIT)).toInt() << 2 | + (_slaverAT->getParam(SER_PRIT)).toInt(); + + ss_cfg = serConfig(); + + BLINKER_LOG_ALL(BLINKER_F("SER_PRIT: "), serialSet); + + BProto::serialPrint(BLINKER_CMD_OK); + + // if (isHWS) { + Serial.begin(serialSet >> 8 & 0x00FFFFFF, ss_cfg); + // } + // else { + // SSerialBLE->begin(serialSet >> 8 & 0x00FFFFFF, ss_cfg); + // } + break; + case AT_ACTION: + // BProto::serialPrint(); + break; + default : + break; + } + } + else if (_slaverAT->cmd() == BLINKER_CMD_UART_DEF) { + blinker_at_state_t at_state = _slaverAT->state(); + + BLINKER_LOG(at_state); + + switch (at_state) + { + case AT_NONE: + // BProto::serialPrint(); + break; + case AT_TEST: + reqData = BLINKER_CMD_AT; + reqData += BLINKER_F("+"); + reqData += BLINKER_CMD_UART_DEF; + reqData += BLINKER_F("=,,,"); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_QUERY: + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_UART_DEF; + reqData += BLINKER_F(":"); + reqData += STRING_format(serialSet >> 8 & 0x00FFFFFF); + reqData += BLINKER_F(","); + reqData += STRING_format(serialSet >> 4 & 0x0F); + reqData += BLINKER_F(","); + reqData += STRING_format(serialSet >> 2 & 0x03); + reqData += BLINKER_F(","); + reqData += STRING_format(serialSet & 0x03); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_SETTING: + BLINKER_LOG_ALL(BLINKER_F("SER_BAUD: "), _slaverAT->getParam(SER_BAUD)); + BLINKER_LOG_ALL(BLINKER_F("SER_DBIT: "), _slaverAT->getParam(SER_DBIT)); + BLINKER_LOG_ALL(BLINKER_F("SER_SBIT: "), _slaverAT->getParam(SER_SBIT)); + BLINKER_LOG_ALL(BLINKER_F("SER_PRIT: "), _slaverAT->getParam(SER_PRIT)); + + if (BLINKER_UART_PARAM_NUM != _slaverAT->paramNum()) return; + + serialSet = (_slaverAT->getParam(SER_BAUD)).toInt() << 8 | + (_slaverAT->getParam(SER_DBIT)).toInt() << 4 | + (_slaverAT->getParam(SER_SBIT)).toInt() << 2 | + (_slaverAT->getParam(SER_PRIT)).toInt(); + + ss_cfg = serConfig(); + + BLINKER_LOG_ALL(BLINKER_F("SER_PRIT: "), serialSet); + + BProto::serialPrint(BLINKER_CMD_OK); + + // if (isHWS) { + Serial.begin(serialSet >> 8 & 0x00FFFFFF, ss_cfg); + // } + // else { + // SSerialBLE->begin(serialSet >> 8 & 0x00FFFFFF, ss_cfg); + // } + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_SERIALCFG, serialSet); + EEPROM.commit(); + EEPROM.end(); + break; + case AT_ACTION: + // BProto::serialPrint(); + break; + default : + break; + } + } + else if (_slaverAT->cmd() == BLINKER_CMD_RAM && _slaverAT->state() == AT_QUERY) { + reqData = BLINKER_F("+"); + reqData += BLINKER_F(BLINKER_CMD_RAM); + reqData += BLINKER_F(":"); + reqData += STRING_format(BLINKER_FreeHeap()); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_ADC && _slaverAT->state() == AT_QUERY) { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_ADC; + reqData += BLINKER_F(":"); + reqData += STRING_format(analogRead(A0)); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_IOSETCFG && _slaverAT->state() == AT_SETTING) { + BLINKER_LOG_ALL(BLINKER_F("PIN_SET: "), _slaverAT->getParam(PIN_SET)); + BLINKER_LOG_ALL(BLINKER_F("PIN_MODE: "), _slaverAT->getParam(PIN_MODE)); + BLINKER_LOG_ALL(BLINKER_F("PIN_PULLSTATE: "), _slaverAT->getParam(PIN_PULLSTATE)); + + if (BLINKER_IOSETCFG_PARAM_NUM != _slaverAT->paramNum()) return; + + uint8_t set_pin = (_slaverAT->getParam(PIN_SET)).toInt(); + uint8_t set_mode = (_slaverAT->getParam(PIN_MODE)).toInt(); + uint8_t set_pull = (_slaverAT->getParam(PIN_PULLSTATE)).toInt(); + + if (set_pin >= BLINKER_MAX_PIN_NUM || + set_mode > BLINKER_IO_OUTPUT_NUM || + set_pull > 2) + { + return; + } + + if (pinDataNum == 0) { + _pinData[pinDataNum] = new PinData(set_pin, set_mode, set_pull); + pinDataNum++; + } + else { + bool _isSet = false; + for (uint8_t _num = 0; _num < pinDataNum; _num++) + { + if (_pinData[_num]->checkPin(set_pin)) + { + _isSet = true; + _pinData[_num]->fresh(set_mode, set_pull); + } + } + if (!_isSet) { + _pinData[pinDataNum] = new PinData(set_pin, set_mode, set_pull); + pinDataNum++; + } + } + + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_IOGETCFG && _slaverAT->state() == AT_SETTING) { + BLINKER_LOG_ALL(BLINKER_F("PIN_SET: "), _slaverAT->getParam(PIN_SET)); + + if (BLINKER_IOGETCFG_PARAM_NUM != _slaverAT->paramNum()) return; + + uint8_t set_pin = (_slaverAT->getParam(PIN_SET)).toInt(); + + if (set_pin >= BLINKER_MAX_PIN_NUM) return; + + bool _isGet = false; + for (uint8_t _num = 0; _num < pinDataNum; _num++) + { + if (_pinData[_num]->checkPin(set_pin)) + { + _isGet = true; + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_IOGETCFG; + reqData += BLINKER_F(":"); + reqData += _pinData[_num]->data(); + BProto::serialPrint(reqData); + } + } + if (!_isGet) { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_IOGETCFG; + reqData += BLINKER_F(":"); + reqData += _slaverAT->getParam(PIN_SET); + reqData += BLINKER_F(",2,0"); + BProto::serialPrint(reqData); + } + + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_GPIOWRITE && _slaverAT->state() == AT_SETTING) { + BLINKER_LOG_ALL(BLINKER_F("IO_PIN: "), _slaverAT->getParam(IO_PIN)); + BLINKER_LOG_ALL(BLINKER_F("IO_LVL: "), _slaverAT->getParam(IO_LVL)); + + if (BLINKER_GPIOWRITE_PARAM_NUM != _slaverAT->paramNum()) return; + + uint8_t set_pin = (_slaverAT->getParam(IO_PIN)).toInt(); + uint8_t set_lvl = (_slaverAT->getParam(IO_LVL)).toInt(); + + if (set_pin >= BLINKER_MAX_PIN_NUM) return; + + // bool _isSet = false; + for (uint8_t _num = 0; _num < pinDataNum; _num++) + { + if (_pinData[_num]->checkPin(set_pin)) + { + if (_pinData[_num]->getMode() == BLINKER_IO_OUTPUT_NUM) + { + if (set_lvl <= 1) { + digitalWrite(set_pin, set_lvl ? HIGH : LOW); + BProto::serialPrint(BLINKER_CMD_OK); + return; + } + } + } + } + + BProto::serialPrint(BLINKER_CMD_ERROR); + } + else if (_slaverAT->cmd() == BLINKER_CMD_GPIOWREAD && _slaverAT->state() == AT_SETTING) { + BLINKER_LOG_ALL(BLINKER_F("IO_PIN: "), _slaverAT->getParam(IO_PIN)); + + if (BLINKER_GPIOREAD_PARAM_NUM != _slaverAT->paramNum()) return; + + uint8_t set_pin = (_slaverAT->getParam(IO_PIN)).toInt(); + + if (set_pin >= BLINKER_MAX_PIN_NUM) + { + BProto::serialPrint(BLINKER_CMD_ERROR); + return; + } + + // bool _isSet = false; + for (uint8_t _num = 0; _num < pinDataNum; _num++) + { + if (_pinData[_num]->checkPin(set_pin)) + { + // if (_pinData[_num]->getMode() == BLINKER_IO_INPUT_NUM) + // { + // if (set_lvl <= 1) { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_GPIOWREAD; + reqData += BLINKER_F(":"); + reqData += STRING_format(set_pin); + reqData += BLINKER_F(","); + reqData += STRING_format(_pinData[_num]->getMode()); + reqData += BLINKER_F(","); + reqData += STRING_format(digitalRead(set_pin)); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + return; + // } + // } + } + } + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_GPIOWREAD; + reqData += BLINKER_F(":"); + reqData += STRING_format(set_pin); + reqData += BLINKER_F(",3,"); + reqData += STRING_format(digitalRead(set_pin)); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + // BProto::serialPrint(BLINKER_CMD_ERROR); + } + else if (_slaverAT->cmd() == BLINKER_CMD_BLINKER_MQTT) { + // BProto::serialPrint(BLINKER_CMD_OK); + + BLINKER_LOG(BLINKER_CMD_BLINKER_MQTT); + + blinker_at_state_t at_state = _slaverAT->state(); + + BLINKER_LOG(at_state); + + switch (at_state) + { + case AT_NONE: + // BProto::serialPrint(); + break; + case AT_TEST: + reqData = BLINKER_CMD_AT; + reqData += BLINKER_F("+"); + reqData += BLINKER_CMD_BLINKER_MQTT; + reqData += BLINKER_F("=,"); + reqData += BLINKER_F("[,,]"); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_QUERY: + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_BLINKER_MQTT; + reqData += BLINKER_F(":"); + reqData += STRING_format(_wlanMode); + reqData += BLINKER_F(","); + reqData += STRING_format(BProto::authKey()); + reqData += BLINKER_F(","); + reqData += WiFi.SSID(); + reqData += BLINKER_F(","); + reqData += WiFi.psk(); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_SETTING: + BLINKER_LOG_ALL(BLINKER_F("MQTT_CONFIG_MODE: "), _slaverAT->getParam(MQTT_CONFIG_MODE)); + BLINKER_LOG_ALL(BLINKER_F("MQTT_AUTH_KEY: "), _slaverAT->getParam(MQTT_AUTH_KEY)); + BLINKER_LOG_ALL(BLINKER_F("MQTT_WIFI_SSID: "), _slaverAT->getParam(MQTT_WIFI_SSID)); + BLINKER_LOG_ALL(BLINKER_F("MQTT_WIFI_PSWD: "), _slaverAT->getParam(MQTT_WIFI_PSWD)); + + if ((_slaverAT->getParam(MQTT_CONFIG_MODE)).toInt() == BLINKER_CMD_COMCONFIG_NUM) + { + BLINKER_LOG_ALL(BLINKER_F("BLINKER_CMD_COMWLAN")); + + if (BLINKER_COMWLAN_PARAM_NUM != _slaverAT->paramNum()) return; + + if (_status == BL_INITED) + { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_BLINKER_MQTT; + reqData += BLINKER_F(":"); + reqData += BProto::deviceId(); + reqData += BLINKER_F(","); + reqData += BProto::uuid(); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + return; + } + + BProto::connectWiFi((_slaverAT->getParam(MQTT_WIFI_SSID)).c_str(), + (_slaverAT->getParam(MQTT_WIFI_PSWD)).c_str()); + + BProto::begin((_slaverAT->getParam(MQTT_AUTH_KEY)).c_str()); + _status = BL_INITED; + _wlanMode = BLINKER_CMD_COMCONFIG_NUM; + } + else if ((_slaverAT->getParam(MQTT_CONFIG_MODE)).toInt() == BLINKER_CMD_SMARTCONFIG_NUM) + { + BLINKER_LOG_ALL(BLINKER_F("BLINKER_CMD_SMARTCONFIG")); + + if (BLINKER_SMCFG_PARAM_NUM != _slaverAT->paramNum()) return; + + if (_status == BL_INITED) + { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_BLINKER_MQTT; + reqData += BLINKER_F(":"); + reqData += BProto::deviceId(); + reqData += BLINKER_F(","); + reqData += BProto::uuid(); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + return; + } + + // if (!BProto::autoInit()) + BProto::smartconfig(); + + BProto::begin((_slaverAT->getParam(MQTT_AUTH_KEY)).c_str()); + _status = BL_INITED; + _wlanMode = BLINKER_CMD_SMARTCONFIG_NUM; + } + else if ((_slaverAT->getParam(MQTT_CONFIG_MODE)).toInt() == BLINKER_CMD_APCONFIG_NUM) + { + BLINKER_LOG(BLINKER_F("BLINKER_CMD_APCONFIG")); + + if (BLINKER_APCFG_PARAM_NUM != _slaverAT->paramNum()) return; + + if (_status == BL_INITED) + { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_BLINKER_MQTT; + reqData += BLINKER_F(":"); + reqData += BProto::deviceId(); + reqData += BLINKER_F(","); + reqData += BProto::uuid(); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + return; + } + + if (!BProto::autoInit()) + { + BProto::softAPinit(); + // while(WiFi.status() != WL_CONNECTED) { + // BProto::serverClient(); + + // ::delay(10); + // } + } + + BProto::begin((_slaverAT->getParam(MQTT_AUTH_KEY)).c_str()); + _status = BL_INITED; + _wlanMode = BLINKER_CMD_APCONFIG_NUM; + } + else { + return; + } + + // reqData = BLINKER_F("+"); + // reqData += BLINKER_CMD_BLINKER_MQTT; + // reqData += BLINKER_F(":"); + // reqData += BProto::deviceId(); + // reqData += BLINKER_F(","); + // reqData += BProto::uuid(); + // BProto::serialPrint(reqData); + // BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_ACTION: + // BProto::serialPrint(); + break; + default : + break; + } + } + else if (_slaverAT->cmd() == BLINKER_CMD_BLINKER_ALIGENIE) { + // BProto::serialPrint(BLINKER_CMD_OK); + + BLINKER_LOG(BLINKER_CMD_BLINKER_ALIGENIE); + + blinker_at_state_t at_state = _slaverAT->state(); + + BLINKER_LOG_ALL(at_state); + + switch (at_state) + { + case AT_NONE: + // BProto::serialPrint(); + break; + case AT_TEST: + reqData = BLINKER_CMD_AT; + reqData += BLINKER_F("+"); + reqData += BLINKER_CMD_BLINKER_ALIGENIE; + reqData += BLINKER_F("="); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_QUERY: + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_BLINKER_ALIGENIE; + reqData += BLINKER_F(":"); + reqData += STRING_format(_aliType); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_SETTING: + BLINKER_LOG_ALL(BLINKER_F("BLINKER_ALIGENIE_CFG_NUM: "), _slaverAT->getParam(BLINKER_ALIGENIE_CFG_NUM)); + + if (BLINKER_ALIGENIE_PARAM_NUM != _slaverAT->paramNum()) return; + + if ((_slaverAT->getParam(BLINKER_ALIGENIE_CFG_NUM)).toInt() == ALI_LIGHT) + { + BLINKER_LOG_ALL(BLINKER_F("ALI_LIGHT")); + _aliType = ALI_LIGHT; + } + else if ((_slaverAT->getParam(BLINKER_ALIGENIE_CFG_NUM)).toInt() == ALI_OUTLET) + { + BLINKER_LOG_ALL(BLINKER_F("ALI_OUTLET")); + _aliType = ALI_OUTLET; + } + else if ((_slaverAT->getParam(BLINKER_ALIGENIE_CFG_NUM)).toInt() == ALI_SENSOR) + { + BLINKER_LOG_ALL(BLINKER_F("ALI_SENSOR")); + _aliType = ALI_SENSOR; + } + else { + BLINKER_LOG_ALL(BLINKER_F("ALI_NONE")); + _aliType = ALI_NONE; + } + BProto::aligenieType(_aliType); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_ACTION: + // BProto::serialPrint(); + break; + default : + break; + } + } + else if (_slaverAT->cmd() == BLINKER_CMD_BLINKER_DUEROS) { + // BProto::serialPrint(BLINKER_CMD_OK); + + BLINKER_LOG(BLINKER_CMD_BLINKER_DUEROS); + + blinker_at_state_t at_state = _slaverAT->state(); + + BLINKER_LOG_ALL(at_state); + + switch (at_state) + { + case AT_NONE: + // BProto::serialPrint(); + break; + case AT_TEST: + reqData = BLINKER_CMD_AT; + reqData += BLINKER_F("+"); + reqData += BLINKER_CMD_BLINKER_DUEROS; + reqData += BLINKER_F("="); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_QUERY: + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_BLINKER_DUEROS; + reqData += BLINKER_F(":"); + reqData += STRING_format(_duerType); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_SETTING: + BLINKER_LOG_ALL(BLINKER_F("BLINKER_DUEROS_CFG_NUM: "), _slaverAT->getParam(BLINKER_ALIGENIE_CFG_NUM)); + + if (BLINKER_DUEROS_PARAM_NUM != _slaverAT->paramNum()) return; + + if ((_slaverAT->getParam(BLINKER_DUEROS_CFG_NUM)).toInt() == ALI_LIGHT) + { + BLINKER_LOG_ALL(BLINKER_F("DUER_LIGHT")); + _duerType = DUER_LIGHT; + } + else if ((_slaverAT->getParam(BLINKER_ALIGENIE_CFG_NUM)).toInt() == ALI_OUTLET) + { + BLINKER_LOG_ALL(BLINKER_F("DUER_OUTLET")); + _duerType = DUER_OUTLET; + } + else if ((_slaverAT->getParam(BLINKER_ALIGENIE_CFG_NUM)).toInt() == ALI_SENSOR) + { + BLINKER_LOG_ALL(BLINKER_F("DUER_SENSOR")); + _duerType = DUER_SENSOR; + } + else { + BLINKER_LOG_ALL(BLINKER_F("DUER_NONE")); + _duerType = DUER_NONE; + } + BProto::duerType(_duerType); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_ACTION: + // BProto::serialPrint(); + break; + default : + break; + } + } + else if (_slaverAT->cmd() == BLINKER_CMD_TIMEZONE) { + + BLINKER_LOG(BLINKER_CMD_TIMEZONE); + + blinker_at_state_t at_state = _slaverAT->state(); + + BLINKER_LOG(at_state); + + switch (at_state) + { + case AT_NONE: + // BProto::serialPrint(); + break; + case AT_TEST: + reqData = BLINKER_CMD_AT; + reqData += BLINKER_F("+"); + reqData += BLINKER_CMD_TIMEZONE; + reqData += BLINKER_F("="); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_QUERY: + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_BLINKER_MQTT; + reqData += BLINKER_F(":"); + reqData += STRING_format(getTimezone()); + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_SETTING: + BLINKER_LOG_ALL(BLINKER_F("BLINKER_TIMEZONE_CFG_NUM: "), _slaverAT->getParam(BLINKER_TIMEZONE_CFG_NUM)); + + if (BLINKER_TIMEZONE_PARAM_NUM != _slaverAT->paramNum()) return; + + setTimezone((_slaverAT->getParam(BLINKER_TIMEZONE_CFG_NUM)).toFloat()); + + BProto::serialPrint(BLINKER_CMD_OK); + break; + case AT_ACTION: + // BProto::serialPrint(); + break; + default : + break; + } + } + else if (_slaverAT->cmd() == BLINKER_CMD_TIME_AT && _slaverAT->state() == AT_QUERY) { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_TIME_AT; + reqData += BLINKER_F(":"); + reqData += STRING_format(time()); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_SECOND && _slaverAT->state() == AT_QUERY) { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_SECOND; + reqData += BLINKER_F(":"); + reqData += STRING_format(second()); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_SECOND && _slaverAT->state() == AT_QUERY) { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_SECOND; + reqData += BLINKER_F(":"); + reqData += STRING_format(second()); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_MINUTE && _slaverAT->state() == AT_QUERY) { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_MINUTE; + reqData += BLINKER_F(":"); + reqData += STRING_format(minute()); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_HOUR && _slaverAT->state() == AT_QUERY) { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_HOUR; + reqData += BLINKER_F(":"); + reqData += STRING_format(hour()); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_WDAY && _slaverAT->state() == AT_QUERY) { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_WDAY; + reqData += BLINKER_F(":"); + reqData += STRING_format(wday()); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_MDAY && _slaverAT->state() == AT_QUERY) { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_MDAY; + reqData += BLINKER_F(":"); + reqData += STRING_format(mday()); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_YDAY && _slaverAT->state() == AT_QUERY) { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_YDAY; + reqData += BLINKER_F(":"); + reqData += STRING_format(yday()); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_MONTH && _slaverAT->state() == AT_QUERY) { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_MONTH; + reqData += BLINKER_F(":"); + reqData += STRING_format(month()); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_YEAR && _slaverAT->state() == AT_QUERY) { + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_YEAR; + reqData += BLINKER_F(":"); + reqData += STRING_format(year()); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_WEATHER_AT && _slaverAT->state() == AT_SETTING) { + if (1 != _slaverAT->paramNum()) return; + + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_WEATHER_AT; + reqData += BLINKER_F(":"); + reqData += STRING_format(weather(_slaverAT->getParam(0).toInt())); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_AQI_AT && _slaverAT->state() == AT_SETTING) { + if (1 != _slaverAT->paramNum()) return; + + reqData = BLINKER_F("+"); + reqData += BLINKER_CMD_AQI_AT; + reqData += BLINKER_F(":"); + reqData += STRING_format(air(_slaverAT->getParam(0).toInt())); + + BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_NOTICE_AT && _slaverAT->state() == AT_SETTING) { + if (1 != _slaverAT->paramNum()) return; + + // reqData = "+" + STRING_format(BLINKER_CMD_NOTICE_AT) + + // ":" + STRING_format(aqi(_slaverAT->getParam(0))); + notify(_slaverAT->getParam(0)); + // BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + else if (_slaverAT->cmd() == BLINKER_CMD_SMS_AT && _slaverAT->state() == AT_SETTING) { + if (1 != _slaverAT->paramNum()) return; + + // reqData = "+" + STRING_format(BLINKER_CMD_NOTICE_AT) + + // ":" + STRING_format(aqi(_slaverAT->getParam(0))); + sms(_slaverAT->getParam(0)); + // BProto::serialPrint(reqData); + BProto::serialPrint(BLINKER_CMD_OK); + } + } + + String BlinkerApi::getMode(uint8_t mode) + { + switch (mode) + { + case BLINKER_CMD_COMCONFIG_NUM : + return BLINKER_CMD_COMCONFIG; + case BLINKER_CMD_SMARTCONFIG_NUM : + return BLINKER_CMD_SMARTCONFIG; + case BLINKER_CMD_APCONFIG_NUM : + return BLINKER_CMD_APCONFIG; + default : + return BLINKER_CMD_COMCONFIG; + } + } + + bool BlinkerApi::serialAvailable() + { + if (BProto::serialAvailable()) + { + _slaverAT = new BlinkerSlaverAT(); + + _slaverAT->update(BProto::serialLastRead()); + + BLINKER_LOG_ALL(BLINKER_F("state: "), _slaverAT->state()); + BLINKER_LOG_ALL(BLINKER_F("cmd: "), _slaverAT->cmd()); + BLINKER_LOG_ALL(BLINKER_F("paramNum: "), _slaverAT->paramNum()); + + if (_slaverAT->state()) + { + parseATdata(); + + free(_slaverAT); + + return false; + } + + free(_slaverAT); + + return true; + } + else + { + return false; + } + } + + void BlinkerApi::serialPrint(const String & s) + { + BProto::serialPrint(s); + } + + void BlinkerApi::atHeartbeat() + { + BProto::serialPrint(BProto::lastRead()); + } +#endif + +#if defined(BLINKER_MQTT_AT) || defined(BLINKER_NB73_NBIOT) + + void BlinkerApi::atRespOK(const String & _data, uint32_t timeout) + { + bool _isAlive = false; + uint32_t _now_time = millis(); + while (!_isAlive) { + BProto::print(_data); + BProto::printNow(); + // _now_time = millis(); + + while((millis() - _now_time) < timeout) + { + run(); + + if (BProto::isAvail) + { + if (strcmp((BProto::dataParse()), BLINKER_CMD_OK) == 0) + { + _isAlive = true; + + BLINKER_LOG(BLINKER_F("dataParse: "), BProto::dataParse()); + BLINKER_LOG(BLINKER_F("strlen: "), strlen(BProto::dataParse())); + BLINKER_LOG(BLINKER_F("strlen: "), strlen(BLINKER_CMD_OK)); + BProto::flush(); + + return; + } + + BLINKER_LOG(BLINKER_F("dataParse: "), BProto::dataParse()); + BLINKER_LOG(BLINKER_F("strlen: "), strlen(BProto::dataParse())); + BLINKER_LOG(BLINKER_F("strlen: "), strlen(BLINKER_CMD_OK)); + BProto::flush(); + } + ::delay(10); + } + + _now_time += timeout; + } + + // return _isAlive; + } + + + void BlinkerApi::atResp() + { + if (strcmp(BProto::dataParse(), BLINKER_CMD_OK) == 0 || + strcmp(BProto::dataParse(), BLINKER_CMD_ERROR) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("atResp isParsed")); + _fresh = true; + // BProto::flushAll(); + } + } + + + void BlinkerApi::parseATdata() + { + uint32_t at_start = millis(); + // while (!BProto::available()) + while (!BProto::isAvail) + { + run(); + ::delay(1); + if (millis() - at_start > BLINKER_AT_MSG_TIMEOUT) break; + } + + BLINKER_LOG_ALL(BLINKER_F("parseATdata")); + + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(BProto::dataParse())); + + BLINKER_LOG_ALL(BLINKER_F("getState: "), _masterAT->getState()); + BLINKER_LOG_ALL(BLINKER_F("reqName: "), _masterAT->reqName()); + BLINKER_LOG_ALL(BLINKER_F("paramNum: "), _masterAT->paramNum()); + + BProto::flush(); + } +#endif + +#if defined(BLINKER_NB73_NBIOT) + +#endif + +#if defined(BLINKER_MQTT_AT) + void BlinkerApi::initCheck(const String & _data, uint32_t timeout) + { + BProto::connect(); + + atRespOK(BLINKER_CMD_AT); + + #if defined(BLINKER_ALIGENIE_LIGHT) + atRespOK(BLINKER_CMD_AT + STRING_format("+") + \ + BLINKER_CMD_BLINKER_ALIGENIE + STRING_format("=1")); + #elif defined(BLINKER_ALIGENIE_OUTLET) + atRespOK(BLINKER_CMD_AT + STRING_format("+") + \ + BLINKER_CMD_BLINKER_ALIGENIE + STRING_format("=2")); + #elif defined(BLINKER_ALIGENIE_SENSOR) + atRespOK(BLINKER_CMD_AT + STRING_format("+") + \ + BLINKER_CMD_BLINKER_ALIGENIE + STRING_format("=3")); + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + atRespOK(BLINKER_CMD_AT + STRING_format("+") + \ + BLINKER_CMD_BLINKER_DUEROS + STRING_format("=1")); + #elif defined(BLINKER_DUEROS_OUTLET) + atRespOK(BLINKER_CMD_AT + STRING_format("+") + \ + BLINKER_CMD_BLINKER_DUEROS + STRING_format("=2")); + #elif defined(BLINKER_DUEROS_SENSOR) + atRespOK(BLINKER_CMD_AT + STRING_format("+") + \ + BLINKER_CMD_BLINKER_DUEROS + STRING_format("=3")); + #endif + + String cmd_start = BLINKER_F(BLINKER_CMD_AT); + cmd_start += BLINKER_F("+"); + cmd_start += BLINKER_F(BLINKER_CMD_BLINKER_MQTT); + cmd_start += BLINKER_F("="); + + #if defined(BLINKER_ESP_SMARTCONFIG) + cmd_start += BLINKER_F("1,"); + #elif defined(BLINKER_APCONFIG) + cmd_start += BLINKER_F("2,"); + #else + cmd_start += BLINKER_F("0,"); + #endif + + cmd_start += _data; + + ::delay(100); + + BProto::print(cmd_start);//cmd_start + _data); + BProto::printNow(); + + bool _isInit = false; + while (!_isInit) { + ::delay(1); + run(); + + // if (BProto::available()) + if (BProto::isAvail) + { + // if (!_masterAT) { + _masterAT = new BlinkerMasterAT(); + + _masterAT->update(STRING_format(BProto::dataParse())); + // } + // else { + // _masterAT->update(STRING_format(BProto::dataParse())); + // } + + BLINKER_LOG_ALL(BLINKER_F("getState: "), _masterAT->getState()); + BLINKER_LOG_ALL(BLINKER_F("reqName: "), _masterAT->reqName()); + BLINKER_LOG_ALL(BLINKER_F("paramNum: "), _masterAT->paramNum()); + + BLINKER_LOG_FreeHeap(); + + if (_masterAT->reqName() == BLINKER_CMD_BLINKER_MQTT && + _masterAT->paramNum() == 2) + { + _isInit = true; + BLINKER_LOG_ALL(BLINKER_F("ESP AT init")); + } + + free(_masterAT); + } + } + } + + + int BlinkerApi::analogRead() + { + BProto::print(BLINKER_CMD_AT + STRING_format("+") + \ + BLINKER_CMD_ADC + "?"); + BProto::printNow(); + + parseATdata(); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_ADC) { + + int a_read = _masterAT->getParam(0).toInt(); + free(_masterAT); + + return a_read; + } + else { + free(_masterAT); + + return 0; + } + } + + + void BlinkerApi::pinMode(uint8_t pin, uint8_t mode) + { + String pin_data = BLINKER_CMD_AT + STRING_format("+") + \ + BLINKER_CMD_IOSETCFG + "=" + \ + STRING_format(pin) + ","; + switch (mode) + { + case INPUT : + pin_data += BLINKER_F("0,0"); + break; + case OUTPUT : + pin_data += BLINKER_F("1,0"); + break; + case INPUT_PULLUP : + pin_data += BLINKER_F("0,1"); + break; + #if defined(ESP8266) + case INPUT_PULLDOWN_16 : + pin_data += BLINKER_F("0,2"); + break; + #elif defined(ESP32) + case INPUT_PULLDOWN : + pin_data += BLINKER_F("0,2"); + break; + #endif + default : + pin_data += BLINKER_F("0,0"); + break; + } + + // parseATdata(); + // free(_masterAT); + } + + + void BlinkerApi::digitalWrite(uint8_t pin, uint8_t val) + { + BProto::print(BLINKER_CMD_AT + STRING_format("+") + \ + BLINKER_CMD_GPIOWRITE + "=" + \ + STRING_format(pin) + "," + \ + STRING_format(val ? 0 : 1)); + + BProto::printNow(); + + // parseATdata(); + } + + + int BlinkerApi::digitalRead(uint8_t pin) + { + BProto::print(BLINKER_CMD_AT + STRING_format("+") + \ + BLINKER_CMD_GPIOWREAD + "=" + \ + STRING_format(pin)); + + BProto::printNow(); + + parseATdata(); + // free(_masterAT); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_GPIOWREAD) { + + int d_read = _masterAT->getParam(2).toInt(); + free(_masterAT); + + return d_read; + } + else { + free(_masterAT); + + return 0; + } + } + + + void BlinkerApi::setTimezone(float tz) + { + BProto::print(BLINKER_CMD_AT + STRING_format("+") + \ + BLINKER_CMD_TIMEZONE + "=" + \ + STRING_format(tz)); + + BProto::printNow(); + } + + + float BlinkerApi::getTimezone() + { + BProto::print(BLINKER_CMD_AT + STRING_format("+") + \ + BLINKER_CMD_TIMEZONE + "?"); + + BProto::printNow(); + + parseATdata(); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_TIMEZONE) { + + float tz_read = _masterAT->getParam(0).toFloat(); + free(_masterAT); + + return tz_read; + } + else { + free(_masterAT); + + return 8.0; + } + } + + + int32_t BlinkerApi::atGetInt(const String & cmd) + { + BProto::print(BLINKER_CMD_AT + STRING_format("+") + cmd + "?"); + + BProto::printNow(); + + parseATdata(); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == cmd) { + + int32_t at_read = _masterAT->getParam(0).toInt(); + free(_masterAT); + + return at_read; + } + else { + free(_masterAT); + + return 0; + } + } + + + template + String BlinkerApi::atGetString(const String & cmd, const T& msg) + { + BProto::print(BLINKER_CMD_AT + STRING_format("+") + \ + cmd + "=" + STRING_format(msg)); + + BProto::printNow(); + + parseATdata(); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == cmd) { + + String at_read = _masterAT->getParam(0); + free(_masterAT); + + return at_read; + } + else { + free(_masterAT); + + return ""; + } + } + + + void BlinkerApi::weather(uint32_t _city) + { + if (_weatherFunc) + { + _weatherFunc(atGetString(BLINKER_CMD_WEATHER_AT, _city)); + } + } + + + void BlinkerApi::weatherForecast(uint32_t _city) + { + if (_weather_forecast_Func) + { + _weather_forecast_Func(atGetString(BLINKER_CMD_WEATHER_FORECAST_AT, _city)); + } + } + + + void BlinkerApi::air(uint32_t _city) + { + if (_airFunc) + { + _airFunc(atGetString(BLINKER_CMD_AQI_AT, _city)); + } + } + + + template + bool BlinkerApi::sms(const T& msg) + { + return atGetString(BLINKER_CMD_SMS_AT, msg); + } + + + void BlinkerApi::reset() + { + BProto::print(BLINKER_CMD_AT + STRING_format("+") + BLINKER_CMD_RST); + + BProto::printNow(); + } + + void BlinkerApi::aligeniePrint(String & _msg) + { + BLINKER_LOG_ALL(BLINKER_F("response to AliGenie: "), _msg); + + // BProto::aliPrint(_msg); + + if (_msg.length() <= BLINKER_MAX_SEND_SIZE) + { + // char* aliData = (char*)malloc((_msg.length()+1+128)*sizeof(char)); + // memcpy(aliData, '\0', _msg.length()+128); + // strcpy(aliData, _msg.c_str()); + BProto::aliPrint(_msg); + // free(aliData); + } + else + { + BLINKER_ERR_LOG(BLINKER_F("SEND DATA BYTES MAX THAN LIMIT!")); + } + } + + void BlinkerApi::duerPrint(String & _msg, bool report) + { + BLINKER_LOG_ALL(BLINKER_F("response to DuerOS: "), _msg); + + // BProto::aliPrint(_msg); + + if (_msg.length() <= BLINKER_MAX_SEND_SIZE) + { + // char* aliData = (char*)malloc((_msg.length()+1+128)*sizeof(char)); + // memcpy(aliData, '\0', _msg.length()+128); + // strcpy(aliData, _msg.c_str()); + BProto::duerPrint(_msg); + // free(aliData); + } + else + { + BLINKER_ERR_LOG(BLINKER_F("SEND DATA BYTES MAX THAN LIMIT!")); + } + } + + void BlinkerApi::miotPrint(String & _msg) + { + BLINKER_LOG_ALL(BLINKER_F("response to MIOT: "), _msg); + + // BProto::aliPrint(_msg); + + if (_msg.length() <= BLINKER_MAX_SEND_SIZE) + { + // char* aliData = (char*)malloc((_msg.length()+1+128)*sizeof(char)); + // memcpy(aliData, '\0', _msg.length()+128); + // strcpy(aliData, _msg.c_str()); + BProto::miPrint(_msg); + // free(aliData); + } + else + { + BLINKER_ERR_LOG(BLINKER_F("SEND DATA BYTES MAX THAN LIMIT!")); + } + } +#endif + +#if defined(BLINKER_MQTT_AT) + // void BlinkerApi::freshAlive() + // { + // BProto::freshAlive(); + // } + + void BlinkerApi::atInit(const char* _auth) + { + // strcpy(_authKey, _auth); + + initCheck(STRING_format(_auth)); + } + + void BlinkerApi::atInit(const char* _auth, const char* _ssid, const char* _pswd) + { + // strcpy(_authKey, _auth); + + String init_data = STRING_format(_auth); + init_data += BLINKER_F(","); + init_data += STRING_format(_ssid); + init_data += BLINKER_F(","); + init_data += STRING_format(_pswd); + + initCheck(init_data); + } +#endif + +#if defined(BLINKER_PRO) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_WIFI_SUBDEVICE) + #if defined(BLINKER_BUTTON_LONGPRESS_POWERDOWN) + + uint16_t BlinkerApi::pressedTime() + { + uint32_t _pressedTime = millis() - _startTime; + + if (_isLongPressed) + { + if (_pressedTime >= BLINKER_PRESSTIME_RESET) return BLINKER_PRESSTIME_RESET; + else return _pressedTime; + } + else { + return 0; + } + } + #endif + + + void BlinkerApi::checkRegister(const JsonObject& data) + { + String _type = data[BLINKER_CMD_REGISTER]; + + // if (_type.length() > 0) + if (data.containsKey(BLINKER_CMD_REGISTER)) + { + if (_type == STRING_format(_deviceType)) + { + _getRegister = true; + + _isNew = true; + + _register_fresh = millis(); + + BLINKER_LOG_ALL(BLINKER_F("getRegister!")); + + print(BLINKER_CMD_MESSAGE, "success"); + } + else + { + BLINKER_LOG_ALL(BLINKER_F("not getRegister!")); + + print(BLINKER_CMD_MESSAGE, "deviceType check fail"); + } + BProto::printNow(); + BLINKER_LOG_ALL(BLINKER_F("checkRegister isParsed")); + _fresh = true; + } + + // _fresh = true; + } + + void BlinkerApi::setType(const char* _type) + { + _deviceType = _type; + #if !defined(BLINKER_WIFI_SUBDEVICE) + Bwlan.setType(_type); + #endif + BLINKER_LOG_ALL(BLINKER_F("API deviceType: "), _type); + } + + void BlinkerApi::reset() + { + BLINKER_LOG(BLINKER_F("Blinker reset...")); + char _authCheck = 0x00; + char _uuid[BLINKER_AUUID_SIZE] = {0}; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_AUTH_CHECK, _authCheck); + EEPROM.put(BLINKER_EEP_ADDR_AUUID, _uuid); + EEPROM.commit(); + EEPROM.end(); + #if !defined(BLINKER_WIFI_SUBDEVICE) + Bwlan.deleteConfig(); + Bwlan.reset(); + #endif + ESP.restart(); + } + + + void BlinkerApi::tick() + { + // Detect the input information + int buttonLevel = digitalRead(_pin); // current button signal. + unsigned long now = millis(); // current (relative) time in msecs. + + // Implementation of the state machine + if (_state == 0) { // waiting for menu pin being pressed. + if (buttonLevel == _buttonPressed) { + _state = 1; // step to state 1 + _startTime = now; // remember starting time + } // if + + } else if (_state == 1) { // waiting for menu pin being released. + + if ((buttonLevel == _buttonReleased) && ((unsigned long)(now - _startTime) < _debounceTicks)) { + // button was released to quickly so I assume some debouncing. + // go back to state 0 without calling a function. + _state = 0; + + } else if (buttonLevel == _buttonReleased) { + _state = 2; // step to state 2 + _stopTime = now; // remember stopping time + + } else if ((buttonLevel == _buttonPressed) && ((unsigned long)(now - _startTime) > _pressTicks)) { + _isLongPressed = true; // Keep track of long press state + if (_pressFunc) _pressFunc(); + _longPressStart(); + if (_longPressStartFunc) _longPressStartFunc(); + _longPress(); + if (_duringLongPressFunc) _duringLongPressFunc(); + _state = 6; // step to state 6 + + } else { + // wait. Stay in this state. + } // if + + } else if (_state == 2) { // waiting for menu pin being pressed the second time or timeout. + // if (_doubleClickFunc == NULL || (unsigned long)(now - _startTime) > _clickTicks) { + if ((unsigned long)(now - _startTime) > _clickTicks) { + // this was only a single short click + _click(); + if (_clickFunc) _clickFunc(); + _state = 0; // restart. + + } else if ((buttonLevel == _buttonPressed) && ((unsigned long)(now - _stopTime) > _debounceTicks)) { + _state = 3; // step to state 3 + _startTime = now; // remember starting time + } // if + + } else if (_state == 3) { // waiting for menu pin being released finally. + // Stay here for at least _debounceTicks because else we might end up in state 1 if the + // button bounces for too long. + if (buttonLevel == _buttonReleased && ((unsigned long)(now - _startTime) > _debounceTicks)) { + // this was a 2 click sequence. + _doubleClick(); + if (_doubleClickFunc) _doubleClickFunc(); + _state = 0; // restart. + } // if + + } else if (_state == 6) { // waiting for menu pin being release after long press. + if (buttonLevel == _buttonReleased) { + _isLongPressed = false; // Keep track of long press state + _longPressStop(); + if(_longPressStopFunc) _longPressStopFunc(); + _state = 0; // restart. + } else { + // button is being long pressed + _isLongPressed = true; // Keep track of long press state + _longPress(); + if (_duringLongPressFunc) _duringLongPressFunc(); + } // if + + } // if + + // BLINKER_LOG("_state: ", _state); + } +#endif + +#if defined(BLINKER_NB73_NBIOT) + void BlinkerApi::atInit() + { + // initCheck(); + // atRespOK(BLINKER_CMD_AT); + } + + bool BlinkerApi::checkOK() + { + if (BProto::isAvail) + { + if (strcmp((BProto::dataParse()), BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("get response OK")); + return true; + } + } + + return false; + } + + void BlinkerApi::nbRun() + { + switch (nbiot_status) + { + case NB_INIT : + if (nb_run_time == 0 || millis() - nb_run_time > 5000) + { + nb_run_time = millis(); + + BProto::print(BLINKER_CMD_AT); + BProto::printNow(); + } + + // if (BProto::isAvail) + // { + // if (strcmp((BProto::dataParse()), BLINKER_CMD_OK) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("dataParse: "), BProto::dataParse()); + // BLINKER_LOG_ALL(BLINKER_F("strlen: "), strlen(BProto::dataParse())); + // BLINKER_LOG_ALL(BLINKER_F("strlen: "), strlen(BLINKER_CMD_OK)); + // BProto::flush(); + + // BProto::print(BLINKER_CMD_NB_CGATT); + // BProto::printNow(); + + // nbiot_status = NB_INITED; + + // nb_run_time = millis(); + // } + // } + if (checkOK()) + { + BProto::flush(); + + BProto::print(BLINKER_CMD_NB_CGATT); + BProto::printNow(); + + nbiot_status = NB_INITED; + + nb_run_time = millis(); + } + break; + // case NB_WAIT_OK : + // break; + case NB_INITED : + if (BProto::isAvail) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(BProto::dataParse())); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CGATT) + { + if (_masterAT->getParam(0).toInt() == 1) + { + BLINKER_LOG_ALL(BLINKER_F("NB_CGATT_REQ")); + nbiot_status = NB_CGATT_REQ; + } + else + { + BLINKER_LOG_ALL(BLINKER_F("NB_CGATT_FAILED")); + nbiot_status = NB_FAILED; + } + } + else if (BProto::dataParse() == BLINKER_CMD_OK) + { + BLINKER_LOG_ALL(BLINKER_F("get cmd OK")); + } + else + { + BLINKER_LOG_ALL(BLINKER_F("NB_CGATT_FAILED")); + nbiot_status = NB_FAILED; + } + + nb_run_time = millis(); + + free(_masterAT); + } + else if (millis() - nb_run_time > BLINKER_NB_STREAM_TIMEOUT) + { + nbiot_status = NB_FAILED; + } + break; + case NB_CGATT_REQ : + if (checkOK()) + { + BLINKER_LOG_ALL(BLINKER_F("NB_CGATT_SUCCESS")); + nbiot_status = NB_CGATT_SUCCESS; + BProto::print(BLINKER_CMD_NB_MIPLCREATE); + BProto::printNow(); + + nb_run_time = millis(); + } + else if (millis() - nb_run_time > BLINKER_NB_STREAM_TIMEOUT) + { + nbiot_status = NB_FAILED; + } + break; + case NB_FAILED : + BProto::print(BLINKER_CMD_NB_RESET); + BProto::printNow(); + + nbiot_status = NB_RESET; + nb_run_time = millis(); + break; + case NB_RESET : + if (millis() - nb_run_time >= 10000) + { + nbiot_status = NB_INIT; + nb_run_time = millis(); + } + break; + case NB_CGATT_SUCCESS : + if (BProto::isAvail) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(BProto::dataParse())); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_MIPLCREATE) + { + if (_masterAT->getParam(0).toInt() == 0) + { + // BProto::print(STRING_format(BLINKER_CMD_NB_MIPLADDOBJ) + "=0," + STRING_format(BLINKER_NB_OBJECT_ID) + ",1,1,2,1"); + // BProto::printNow(); + + BLINKER_LOG_ALL(BLINKER_F("NB_MIPLC_REQ, next NB_MIPLADDOBJ")); + nbiot_status = NB_MIPLC_REQ; + } + else + { + BProto::print(BLINKER_CMD_NB_MIPLDELETE); + BProto::printNow(); + + BLINKER_LOG_ALL(BLINKER_F("NB_MIPLC_FAILED")); + nbiot_status = NB_MIPLC_FAILED; + } + } + else if (BProto::dataParse() == BLINKER_CMD_OK) + { + BLINKER_LOG_ALL(BLINKER_F("get cmd OK")); + } + else + { + BProto::print(BLINKER_CMD_NB_MIPLDELETE); + BProto::printNow(); + + BLINKER_LOG_ALL(BLINKER_F("NB_MIPLC_FAILED")); + nbiot_status = NB_MIPLC_FAILED; + } + + nb_run_time = millis(); + + free(_masterAT); + } + + else if (millis() - nb_run_time > BLINKER_NB_STREAM_TIMEOUT) + { + nbiot_status = NB_FAILED; + } + break; + case NB_MIPLC_REQ : + if (checkOK()) + { + BLINKER_LOG_ALL(BLINKER_F("NB_MIPLC_SUCCESS")); + nbiot_status = NB_MIPLC_SUCCESS; + BProto::print(STRING_format(BLINKER_CMD_NB_MIPLADDOBJ) + "=0," + STRING_format(BLINKER_NB_OBJECT_ID) + ",1,1,2,1"); + BProto::printNow(); + + nb_run_time = millis(); + } + else if (millis() - nb_run_time > BLINKER_NB_STREAM_TIMEOUT) + { + nbiot_status = NB_FAILED; + } + break; + case NB_MIPLC_FAILED : + if (BProto::isAvail) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(BProto::dataParse())); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_MIPLEVENT) + { + if (_masterAT->getParam(0).toInt() == 0) + { + BProto::print(BLINKER_CMD_NB_MIPLCREATE); + BProto::printNow(); + + BLINKER_LOG_ALL(BLINKER_F("NB_MIPLD_SUCCESS")); + nbiot_status = NB_CGATT_SUCCESS; + } + else + { + BLINKER_LOG_ALL(BLINKER_F("NB_MIPLD_FAILED")); + nbiot_status = NB_CGATT_FAILED; + } + } + else if (BProto::dataParse() == BLINKER_CMD_OK) + { + BLINKER_LOG_ALL(BLINKER_F("get cmd OK")); + } + else + { + BLINKER_LOG_ALL(BLINKER_F("NB_MIPLD_FAILED")); + nbiot_status = NB_CGATT_FAILED; + } + + nb_run_time = millis(); + + free(_masterAT); + } + else if (millis() - nb_run_time > BLINKER_NB_STREAM_TIMEOUT) + { + nbiot_status = NB_FAILED; + } + break; + case NB_MIPLADDOBJ : + if (BProto::isAvail) + { + if (BProto::dataParse() == BLINKER_CMD_OK) + { + BProto::print(STRING_format(BLINKER_CMD_NB_MIPLOPEN) + "=0,3000"); + BProto::printNow(); + + BLINKER_LOG_ALL(BLINKER_F("NB_MIPLADDOBJ success, next NB_MIPLOPEN")); + nbiot_status = NB_MIPLOPEN; + } + } + break; + case NB_MIPLOPEN : + if (BProto::isAvail) + { + if (BProto::dataParse() == BLINKER_CMD_NB_EVENT_6) + { + BLINKER_LOG_ALL(BLINKER_F("NB_MIPLOPEN success")); + nbiot_status = NB_MIPLOPEN_SUCCESS; + + nb_run_time = millis(); + nb_online_time = millis(); + } + } + else if (millis() - nb_run_time > BLINKER_NB_STREAM_TIMEOUT) + { + nbiot_status = NB_FAILED; + } + break; + case NB_MIPLOPEN_SUCCESS : + if (BProto::isAvail) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(BProto::dataParse())); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_MIPLOBSERVE) + { + BProto::print(STRING_format(BLINKER_CMD_AT) + STRING_format(BLINKER_CMD_MIPLOBSERVE) + "=" + _masterAT->getParam(0) + "," + _masterAT->getParam(1) + ",1"); + BProto::printNow(); + + nb_msgId = _masterAT->getParam(1).toInt(); + + nbiot_status = NB_MIPLOBSERVE; + } + + nb_run_time = millis(); + + free(_masterAT); + } + else if (millis() - nb_run_time > BLINKER_NB_STREAM_TIMEOUT) + { + nbiot_status = NB_FAILED; + } + break; + case NB_MIPLOBSERVE : + if (BProto::isAvail) + { + if (BProto::dataParse() == BLINKER_CMD_OK) + { + } + } + break; + default: + break; + } + } +#endif + +#if defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + bool BlinkerApi::powerCheck() + { + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + + return BLINKER_AIR202.powerCheck(); + } + + String BlinkerApi::getIMEI() + { + BlinkerAIR202 BLINKER_AIR202; + BLINKER_AIR202.setStream(*stream, isHWS, listenFunc); + + // BLINKER_AIR202.getICCID(); + // BLINKER_AIR202.getAMGSMLOC();// TBD + // BLINKER_AIR202.powerCheck(); + + return BLINKER_AIR202.getIMEI(); + } +#endif + +#if defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) + bool BlinkerApi::powerCheck() + { + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + + return BLINKER_SIM7020.powerCheck(); + } + + String BlinkerApi::getIMEI() + { + BlinkerSIM7020 BLINKER_SIM7020; + BLINKER_SIM7020.setStream(*stream, isHWS, listenFunc); + + // BLINKER_AIR202.getICCID(); + // BLINKER_AIR202.getAMGSMLOC();// TBD + // BLINKER_AIR202.powerCheck(); + + return BLINKER_SIM7020.getIMEI(); + } +#endif + +#if defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_PRO_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) + bool BlinkerApi::powerCheck() + { + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + + return BLINKER_SIM7000.powerCheck(); + } + + String BlinkerApi::getIMEI() + { + BlinkerSIM7000 BLINKER_SIM7000; + BLINKER_SIM7000.setStream(*stream, isHWS, listenFunc); + + // BLINKER_AIR202.getICCID(); + // BLINKER_AIR202.getAMGSMLOC();// TBD + // BLINKER_AIR202.powerCheck(); + + return BLINKER_SIM7000.getIMEI(); + } +#endif + +#endif diff --git a/blinker-library/src/Blinker/BlinkerApiBase.h b/blinker-library/src/Blinker/BlinkerApiBase.h new file mode 100644 index 0000000..104aa5d --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerApiBase.h @@ -0,0 +1,706 @@ +#ifndef BLINKER_API_BASE_H +#define BLINKER_API_BASE_H + +#include "BlinkerDebug.h" +#include "BlinkerConfig.h" +#include "BlinkerUtility.h" + +template +int8_t checkNum(char * name, T * c, uint8_t count) +{ + BLINKER_LOG_ALL(BLINKER_F("checkNum count: "), count); + for (uint8_t cNum = 0; cNum < count; cNum++) + { + // BLINKER_LOG_ALL(BLINKER_F("checkName: "), name, BLINKER_F(", name: "), c[cNum]->getName()); + // BLINKER_LOG_ALL(BLINKER_F("is strcmp: "), strcmp(name, c[cNum]->getName()) == 0); + // BLINKER_LOG_ALL(BLINKER_F("is equal: "), name == c[cNum]->getName()); + if (c[cNum]->checkName(name)) return cNum; + } + + return BLINKER_OBJECT_NOT_AVAIL; +} + +class BlinkerWidgets_num +{ + public : + BlinkerWidgets_num(char * _name) + { + wName = (char*)malloc((strlen(_name)+1)*sizeof(char)); + strcpy(wName, _name); + + autoUpdate = true; + } + + char * getName() { return wName; } + + bool checkName(char * name) { + return strcmp(name, wName) == 0; + } + + void setState(bool state) { autoUpdate = state; } + + bool state() { return autoUpdate; } + + private : + char *wName; + bool autoUpdate = false; +}; + +class BlinkerWidgets_string +{ + public : + BlinkerWidgets_string(char * _name, blinker_callback_with_string_arg_t _func = NULL) + { + wName = (char*)malloc((strlen(_name)+1)*sizeof(char)); + strcpy(wName, _name); + + wfunc = _func; + } + + char * getName() { return wName; } + void setFunc(blinker_callback_with_string_arg_t _func) { wfunc = _func; } + blinker_callback_with_string_arg_t getFunc() { return wfunc; } + bool checkName(char * name) { + return strcmp(name, wName) == 0; + } + + private : + char *wName; + blinker_callback_with_string_arg_t wfunc; +}; + +class BlinkerWidgets_int32 +{ + public : + BlinkerWidgets_int32(char * _name, blinker_callback_with_int32_arg_t _func = NULL) + { + wName = (char*)malloc((strlen(_name)+1)*sizeof(char)); + strcpy(wName, _name); + + wfunc = _func; + } + + char * getName() { return wName; } + void setFunc(blinker_callback_with_int32_arg_t _func) { wfunc = _func; } + blinker_callback_with_int32_arg_t getFunc() { return wfunc; } + bool checkName(char * name) { + return strcmp(name, wName) == 0; + } + + private : + char *wName; + blinker_callback_with_int32_arg_t wfunc; +}; + +class BlinkerWidgets_rgb +{ + public : + BlinkerWidgets_rgb(char * _name, blinker_callback_with_rgb_arg_t _func = NULL) + { + wName = (char*)malloc((strlen(_name)+1)*sizeof(char)); + strcpy(wName, _name); + + wfunc = _func; + } + + char * getName() { return wName; } + void setFunc(blinker_callback_with_rgb_arg_t _func) { wfunc = _func; } + blinker_callback_with_rgb_arg_t getFunc() { return wfunc; } + bool checkName(char * name) { + return strcmp(name, wName) == 0; + } + + private : + char *wName; + blinker_callback_with_rgb_arg_t wfunc; +}; + +class BlinkerWidgets_joy +{ + public : + BlinkerWidgets_joy(char * _name, blinker_callback_with_joy_arg_t _func = NULL) + { + wName = (char*)malloc((strlen(_name)+1)*sizeof(char)); + strcpy(wName, _name); + + wfunc = _func; + } + + char * getName() { return wName; } + void setFunc(blinker_callback_with_joy_arg_t _func) { wfunc = _func; } + blinker_callback_with_joy_arg_t getFunc() { return wfunc; } + bool checkName(char * name) { + return strcmp(name, wName) == 0; + } + + private : + char *wName; + blinker_callback_with_joy_arg_t wfunc; +}; + +class BlinkerWidgets_table +{ + public : + BlinkerWidgets_table(char * _name, + blinker_callback_with_table_arg_t _func = NULL, + blinker_callback_t _func2 = NULL) + { + wName = (char*)malloc((strlen(_name)+1)*sizeof(char)); + strcpy(wName, _name); + + wfunc = _func; + wfunc2 = _func2; + } + + char * getName() { return wName; } + void setFunc(blinker_callback_with_table_arg_t _func, blinker_callback_t _func2) + { wfunc = _func; wfunc2 = _func2; } + blinker_callback_with_table_arg_t getFunc() { return wfunc; } + blinker_callback_t getFunc2() { return wfunc2; } + bool checkName(char * name) { + return strcmp(name, wName) == 0; + } + + private : + char *wName; + blinker_callback_with_table_arg_t wfunc; + blinker_callback_t wfunc2; +}; + +#if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_WIFI_SUBDEVICE) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) || defined(BLINKE_HTTP) + class BlinkerBridge_key + { + public : + BlinkerBridge_key(char * _key, blinker_callback_with_string_arg_t _func = NULL) + { + bKey = (char*)malloc((strlen(_key)+1)*sizeof(char)); + strcpy(bKey, _key); + + wfunc = _func; + } + + char * getKey() { return bKey; } + void setFunc(blinker_callback_with_string_arg_t _func) { wfunc = _func; } + blinker_callback_with_string_arg_t getFunc() { return wfunc; } + bool checkName(char * _key) { return strcmp(_key, bKey) == 0; } + char * getName() + { + if (_register) return bName; + else return "false"; + } + void name(const String & name) + { + _register = true; + bName = (char*)malloc((name.length()+1)*sizeof(char)); + strcpy(bName, name.c_str()); + } + + private : + char *bKey; + char *bName; + bool _register = false; + blinker_callback_with_string_arg_t wfunc; + // public : + // BlinkerBridge() {} + + // void name(char name[]) + // { + // _bName = (char*)malloc((strlen(name)+1)*sizeof(char)); + // strcpy(_bName, name); + // } + // char * getName() { return _bName; } + // void freshBridge(const String & name) + // { + // bridgeName = (char*)malloc((name.length()+1)*sizeof(char)); + // strcpy(bridgeName, name.c_str()); + // } + // char * getBridge() { return bridgeName; } + // bool checkName(char name[]) { return strcmp(_bName, name) == 0; } + + // private : + // char *_bName; + // char *bridgeName; + }; + + union BlinkerDataType + { + int32_t int_data; + uint32_t uint_data; + float float_data; + }; + + class BlinkerTimeSlotData + { + public : + BlinkerTimeSlotData() + : time_data(0) + , key_count(0) + {} + + int8_t checkNum(char name[], uint8_t count) + { + BLINKER_LOG_ALL(BLINKER_F("checkNum count: "), count); + for (uint8_t cNum = 0; cNum < count; cNum++) + { + // BLINKER_LOG_ALL(BLINKER_F("checkName: "), name, BLINKER_F(", name: "), c[cNum]->getName()); + // BLINKER_LOG_ALL(BLINKER_F("is strcmp: "), strcmp(name, c[cNum]->getName()) == 0); + // BLINKER_LOG_ALL(BLINKER_F("is equal: "), name == c[cNum]->getName()); + if (strcmp(name, keys[cNum]) == 0) return cNum; + } + + return BLINKER_OBJECT_NOT_AVAIL; + } + + void saveData(char key[], int32_t data, time_t now_time) + { + if (key_count == 0) time_data = now_time; + + int8_t num = checkNum(key, key_count); + + // int32_t format_data; + + if (num == BLINKER_OBJECT_NOT_AVAIL) + { + if (key_count < 6) + { + strcpy(keys[key_count], key); + data_type[key_count] = BLINKER_INT_DATA; + datas[key_count].int_data = data; + // for(uint8_t i=0; i<4; i++){ + // *(&datas[key_count][0] + i) = *((uint8_t *)&data + i); + // } + // datas[key_count][4] = BLINKER_INT_DATA; + + // for(uint8_t i=0; i<4; i++){ + // *((uint8_t *)&format_data + i) = *(&datas[key_count][0] + i); + // } + + BLINKER_LOG_ALL(BLINKER_F("new key: "), key, \ + BLINKER_F(" key_count: "), key_count, \ + BLINKER_F(" data: "), datas[key_count].int_data, \ + BLINKER_F(" data_type: "), data_type[key_count]); + + key_count++; + } + } + } + + void saveData(char key[], uint32_t data, time_t now_time) + { + if (key_count == 0) time_data = now_time; + + int8_t num = checkNum(key, key_count); + + uint32_t format_data; + + if (num == BLINKER_OBJECT_NOT_AVAIL) + { + if (key_count < 6) + { + strcpy(keys[key_count], key); + data_type[key_count] = BLINKER_UINT_DATA; + datas[key_count].uint_data = data; + // for(uint8_t i=0; i<4; i++){ + // *(&datas[key_count][0] + i) = *((uint8_t *)&data + i); + // } + // datas[key_count][4] = BLINKER_INT_DATA; + + // for(uint8_t i=0; i<4; i++){ + // *((uint8_t *)&format_data + i) = *(&datas[key_count][0] + i); + // } + + BLINKER_LOG_ALL(BLINKER_F("new key: "), key, \ + BLINKER_F(" key_count: "), key_count, \ + BLINKER_F(" data: "), datas[key_count].uint_data, \ + BLINKER_F(" data_type: "), data_type[key_count]); + + key_count++; + } + } + } + + void saveData(char key[], float data, time_t now_time) + { + if (key_count == 0) time_data = now_time; + + int8_t num = checkNum(key, key_count); + + float format_data; + + if (num == BLINKER_OBJECT_NOT_AVAIL) + { + if (key_count < 6) + { + strcpy(keys[key_count], key); + data_type[key_count] = BLINKER_FLOAT_DATA; + datas[key_count].float_data = data; + // for(uint8_t i=0; i<4; i++){ + // *(&datas[key_count][0] + i) = *((uint8_t *)&data + i); + // } + // datas[key_count][4] = BLINKER_INT_DATA; + + // for(uint8_t i=0; i<4; i++){ + // *((uint8_t *)&format_data + i) = *(&datas[key_count][0] + i); + // } + + BLINKER_LOG_ALL(BLINKER_F("new key: "), key, \ + BLINKER_F(" key_count: "), key_count, \ + BLINKER_F(" data: "), datas[key_count].float_data, \ + BLINKER_F(" data_type: "), data_type[key_count]); + + key_count++; + } + } + } + + String getData() + { + int32_t int_data; + uint32_t uint_data; + float float_data; + + BLINKER_LOG_FreeHeap_ALL(); + + String _data = BLINKER_F("{\"date\":"); + _data += STRING_format(time_data); + + for(uint8_t num = 0; num < key_count; num++) + { + _data += BLINKER_F(",\""); + _data += keys[num]; + _data += BLINKER_F("\":"); + // _data += keys[num]; + BLINKER_LOG_ALL(BLINKER_F("datas["), num, + BLINKER_F("].data_type: "), + data_type[num]); + + if (data_type[num] == BLINKER_INT_DATA) + { + // for(uint8_t i=0; i<4; i++){ + // *((uint8_t *)&int_data + i) = *(&datas[key_count][0] + i); + // } + + _data += STRING_format(datas[num].int_data); + + BLINKER_LOG_ALL(BLINKER_F("datas[num].int_data: "), datas[num].int_data); + } + else if (data_type[num] == BLINKER_UINT_DATA) + { + // for(uint8_t i=0; i<4; i++){ + // *((uint8_t *)&uint_data + i) = *(&datas[key_count][0] + i); + // } + + _data += STRING_format(datas[num].uint_data); + + BLINKER_LOG_ALL(BLINKER_F("datas[num].int_data: "), datas[num].uint_data); + } + else if (data_type[num] == BLINKER_FLOAT_DATA) + { + // for(uint8_t i=0; i<4; i++){ + // *((uint8_t *)&float_data + i) = *(&datas[key_count][0] + i); + // } + + _data += STRING_format(datas[num].float_data); + + BLINKER_LOG_ALL(BLINKER_F("datas[num].int_data: "), datas[num].float_data); + } + } + + _data += STRING_format("}"); + + return _data; + } + + void flush() + { + key_count = 0; + time_data = 0; + } + + // for(uint8_t i=0;i<4;i++){ + // *(&test[0] + i) = *((uint8_t *)&testt + i); // 逐个字节单元进行复制 + // Serial.println(*((uint8_t *)&testt + i)); + // } + + private : + time_t time_data; + uint8_t key_count; + uint8_t data_type[6]; + char keys[6][15]; + BlinkerDataType datas[6]; + }; + + class BlinkerData + { + public : + BlinkerData() + // : _dname(NULL) + { + // data = (char*)malloc((256)*sizeof(char)); + // memcpy(data,"\0",128); + for(uint8_t num = 0; num < BLINKER_MAX_DATA_COUNT; num++) + { + time_data[num] = 0; + memset(data[num], '\0', 10); + } + } + + void name(const String & name) { _dname = name; } + + String getName() { return _dname; } + + bool saveData(const String & _data, time_t now_time, uint32_t _limit) { + if (dataCount > 0) + { + if (now_time - latest_time < _limit) return false; + } + + latest_time = now_time; + + if (dataCount >= BLINKER_MAX_DATA_COUNT) + { + dataCount = BLINKER_MAX_DATA_COUNT; + + for (uint8_t num = 0; num < dataCount - 1; num++) { + time_data[num] = time_data[num + 1]; + strcpy(data[num], data[num+1]); + } + time_data[dataCount - 1] = now_time; + strcpy(data[dataCount - 1], _data.c_str()); + } + else + { + time_data[dataCount] = now_time; + strcpy(data[dataCount], _data.c_str()); + dataCount++; + } + + // String _data_; + + // if (strlen(data)) _data_ = STRING_format(data); + + // if (dataCount == 6) { + // _data_ += BLINKER_F(",["); + // _data_ += STRING_format(now_time); + // _data_ += BLINKER_F(","); + // _data_ += _data; + // _data_ += BLINKER_F("]"); + + // _data_ = "{\"data\":[" + STRING_format(_data_); + // _data_ += BLINKER_F("]}"); + + // DynamicJsonBuffer jsonDataBuffer; + // JsonObject& dataArray = jsonDataBuffer.parseObject(_data_); + + // for (uint8_t num = 0; num < dataCount; num++) { + // dataArray["data"][num][0] = dataArray["data"][num+1][0]; + // dataArray["data"][num][1] = dataArray["data"][num+1][1]; + // } + + // _data_ = BLINKER_F(""); + // for (uint8_t num = 0; num < dataCount; num++) + // { + // String data_get = dataArray["data"][num]; + + // _data_ += data_get; + + // if (num != dataCount - 1) _data_ += BLINKER_F(","); + // } + + // if (_data_.length() < 128) + // { + // strcpy(data, _data_.c_str()); + // } + // } + // else + // { + // if (_data_.length()) + // { + // _data_ += BLINKER_F(","); + // } + + // _data_ += BLINKER_F("["); + // _data_ += STRING_format(now_time); + // _data_ += BLINKER_F(","); + // _data_ += _data; + // _data_ += BLINKER_F("]"); + + // if (_data_.length() < 128) { + // strcpy(data, _data_.c_str()); + // dataCount++; + // } + // } + BLINKER_LOG_ALL(BLINKER_F("saveData: "), _data); + BLINKER_LOG_ALL(BLINKER_F("saveData dataCount: "), dataCount); + + return true; + } + + String getData() { + // BLINKER_LOG_ALL(BLINKER_F("getData data: "), data); + + String _data_ = BLINKER_F("[");//{\"data\": + // _data_ += STRING_format(data); + for (uint8_t num = 0; num < dataCount; num++) { + _data_ += "["; + _data_ += String(time_data[num]); + _data_ += ","; + _data_ += data[num]; + _data_ += "]"; + if (num + 1 < dataCount) + { + _data_ += ","; + } + + // time_data[num] = latest_time; + // memcpy(data[num], "\0", 10); + } + _data_ += BLINKER_F("]");//} + + // dataCount = 0; + + // DynamicJsonBuffer jsonDataBuffer; + // JsonObject& dataArray = jsonDataBuffer.parseObject(_data_); + + // uint32_t now_millis = millis(); + + // for (uint8_t num = dataCount; num > 0; num--) { + // uint8_t data_time = dataArray["data"][num][0]; + // uint32_t real_time = now_time - (dataCount - data_time - 1)*60; + // dataArray["data"][num-1][0] = real_time; + + // BLINKER_LOG_ALL(BLINKER_F("data_time: "), data_time, + // BLINKER_F(" now_time: "), now_time, + // BLINKER_F(" real_time: "), real_time); + // } + + // String _data_decode = dataArray["data"]; + + BLINKER_LOG_ALL(BLINKER_F("getData _data_: "), _data_); + + return _data_; + } + + bool checkName(const String & name) { return ((_dname == name) ? true : false); } + + void flush() + { + for (uint8_t num = 0; num < dataCount; num++) { + time_data[num] = latest_time; + memset(data[num], '\0', 10); + } + + dataCount = 0; + } + + private : + uint8_t dataCount = 0; + time_t latest_time = 0; + String _dname; + // char * data; + time_t time_data[BLINKER_MAX_DATA_COUNT]; + char data[BLINKER_MAX_DATA_COUNT][10]; + }; + + class BlinkerRTData + { + public : + BlinkerRTData() + // : _dname(NULL) + { + // data = (char*)malloc((256)*sizeof(char)); + // memcpy(data,"\0",128); + for(uint8_t num = 0; num < 15; num++) + { + time_data[num] = 0; + data[num] = 0; + } + } + + void name(const char* _name) { _dname = _name; } + + const char* getName() { return _dname; } + + bool saveData(int _data, time_t now_time) { + // if (dataCount > 0) + // { + // if (now_time - latest_time < _limit) return false; + // } + + latest_time = now_time; + + if (dataCount >= 15) + { + dataCount = 15; + + for (uint8_t num = 0; num < dataCount - 1; num++) { + time_data[num] = time_data[num + 1]; + data[num] = data[num+1]; + } + time_data[dataCount - 1] = now_time; + data[dataCount - 1] = _data; + } + else + { + time_data[dataCount] = now_time; + data[dataCount] = _data; + dataCount++; + } + BLINKER_LOG_ALL(BLINKER_F("saveData: "), _data); + BLINKER_LOG_ALL(BLINKER_F("saveData dataCount: "), dataCount); + + return true; + } + + String getData() { + // BLINKER_LOG_ALL(BLINKER_F("getData data: "), data); + + String _data_ = BLINKER_F("["); + for (uint8_t num = 0; num < dataCount; num++) { + _data_ += "{\"date\":"; + _data_ += String(time_data[num]); + _data_ += ",\"value\":"; + _data_ += data[num]; + _data_ += "}"; + if (num + 1 < dataCount) + { + _data_ += ","; + } + } + _data_ += BLINKER_F("]"); + + BLINKER_LOG_ALL(BLINKER_F("getData _data_: "), _data_); + + return _data_; + } + + bool checkName(const char* name) { return strncmp(name, _dname, strlen(name)) == 0; } + + void flush() + { + for (uint8_t num = 0; num < dataCount; num++) { + time_data[num] = latest_time; + data[num] = 0; + } + + dataCount = 0; + } + + private : + uint8_t dataCount = 0; + time_t latest_time = 0; + // char * data; + time_t time_data[15]; + int data[15]; + const char* _dname; + }; +#endif + +#endif diff --git a/blinker-library/src/Blinker/BlinkerAuto.h b/blinker-library/src/Blinker/BlinkerAuto.h new file mode 100644 index 0000000..f64c12f --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerAuto.h @@ -0,0 +1,1025 @@ +#ifndef BLINKER_AUTO_H +#define BLINKER_AUTO_H + +#if ((defined(ESP8266) || defined(ESP32)) && \ + (defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_SUBDEVICE) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) || defined(BLINKE_HTTP))) + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include + +// #include "Blinker/BlinkerAuto.h" +#include "BlinkerConfig.h" +#include "BlinkerDebug.h" +#include "BlinkerUtility.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "../modules/ArduinoJson/ArduinoJson.h" +#endif + +class BlinkerAUTO +{ + public : + BlinkerAUTO() + : _haveAuto(false) + , _autoState(false) + , _trigged(false) + {} + + void run(const String & key, float data, int32_t nowTime); + void run(const String & key, const String & state, int32_t nowTime); + void manager(const JsonObject& data); + void deserialization(); + void serialization(); + void setNum(uint8_t num) { a_num = num; } + bool isTrigged() + { + return _trigged; + // if (_trigged) + // { + // if (millis() - _last_tri_time >= 6000 || _last_tri_time == 0) + // { + // _last_tri_time = millis(); + // return true; + // } + // } + // return false; + } + void fresh(); + unsigned long id() { return _autoId; } + + private : + uint8_t a_num; + time_t _last_tri_time; + + // { + // "auto":{ + // "enable":true,//_autoState + // "id":123456,//_autoId + // "mode":"or",//_logicType + // "time": { + // "day": "1111111", + // "range": [540, 1260], + // }, + // "triggers": + // [ + // { + // "source":"humi", + // "operator":"<",//_targetState|_compareType + // "value":40, + // "duration":10 + // } + // ] + // } + // } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + // | | | | | | _time1 0-1440min 11 | _time2 0-1440min 11 + // | | | | | _duration 0-60min 6 + // | | | | _targetState|_compareType on/off|less/equal/greater 2 + // | | | _targetState|_compareType on/off|less/equal/greater + // | + // | logic_type state/numberic 2 + // | + // autoData + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + // | | | | | | | _time1 0-1440min 11 | _time2 0-1440min 11 + // | | | | | | _duration 0-3600s 12 + // | | | | |day 7 + // | | | | _targetState|_compareType less/equal/greater 2 + // | | |_logicType and/or 1 + // | | _autoState true/false 1 + // | _haveAuto 1 + // | + // autoData + // typestatexxxxxx + bool _haveAuto; + bool _autoState; + unsigned long _autoId = 0; + uint8_t _logicType; + uint8_t _compareType; + uint8_t _day = 0; + // uint8_t _autoData[6]; + + uint16_t _start_time; + uint16_t _end_time; + uint16_t _duration; + + // uint8_t logic_type[2]; + char _targetKey[12]; + float _targetState; + // float _targetData[2]; + // uint8_t _compareType[2]; + // bool _targetState[2]; + // uint32_t _time1[2]; + // uint32_t _time2[2]; + // uint32_t _duration[2]; + uint32_t _treTime; + bool isRecord; + bool _isTrigged; + bool _trigged; + + void triggerCheck(const String & state); +}; + +void BlinkerAUTO::run(const String & key, float data, int32_t nowTime) +{ + BLINKER_LOG_ALL(BLINKER_F("BlinkerAUTO run key: "), key, + BLINKER_F(" ,data: "), data, + BLINKER_F(" ,nowTime: "), nowTime, + BLINKER_F(" ,autoId: "), _autoId); + + // static uint8_t _num; + // for (uint8_t _num = 0; _num < _targetNum; _num++) + // { + if (!_autoState) return; + + if (key != STRING_format(_targetKey)) return; + + if (_start_time < _end_time) + { + if (!(nowTime >= _start_time && nowTime <= _end_time)) + { + BLINKER_LOG_ALL(BLINKER_F("out of time slot: "), nowTime); + return; + } + } + else if (_start_time > _end_time) + { + if (nowTime > _start_time && nowTime < _end_time) + { + BLINKER_LOG_ALL(BLINKER_F("out of time slot: "), nowTime); + return; + } + } + + if (_logicType == BLINKER_TYPE_OR || _logicType == BLINKER_TYPE_AND) + { + switch (_compareType) + { + case BLINKER_COMPARE_LESS: + if (data < _targetState) + { + if (!_isTrigged) { + triggerCheck("less"); + } + } + else + { + _isTrigged = false; + isRecord = false; + _trigged = false; + } + break; + case BLINKER_COMPARE_EQUAL: + if (data == _targetState) + { + if (!_isTrigged) + { + triggerCheck("equal"); + } + } + else + { + _isTrigged = false; + isRecord = false; + _trigged = false; + } + break; + case BLINKER_COMPARE_GREATER: + if (data > _targetState) + { + if (!_isTrigged) + { + triggerCheck("greater"); + } + } + else + { + _isTrigged = false; + isRecord = false; + _trigged = false; + } + break; + default: + break; + } + } + // } +} + +// void BlinkerAUTO::run(const String & key, const String & state, int32_t nowTime) +// { +// BLINKER_LOG_ALL(BLINKER_F("BlinkerAUTO run key: "), key, \ +// BLINKER_F(" state: "), state, \ +// BLINKER_F(" nowTime: "), nowTime); + +// // for (uint8_t _num = 0; _num < _targetNum; _num++) +// // { +// if (!_autoState) return; + +// if (key != STRING_format(_targetKey)) return; + +// if (_time1 < _time2) +// { +// if (!(nowTime >= _time1 && nowTime <= _time2)) +// { +// BLINKER_LOG_ALL(BLINKER_F("out of time slot: "), nowTime); +// return; +// } +// } +// else if (_time1 > _time2) +// { +// if (nowTime > _time1 && nowTime < _time2) +// { +// BLINKER_LOG_ALL(BLINKER_F("out of time slot: "), nowTime); +// return; +// } +// } + +// if (_logicType == BLINKER_TYPE_OR || _logicType == BLINKER_TYPE_AND) +// { +// if (state == BLINKER_CMD_ON) +// { +// if (_targetState) +// { +// if (!_isTrigged) +// { +// triggerCheck("on"); +// } +// } +// else +// { +// _isTrigged = false; +// isRecord = false; +// _trigged = false; +// } +// } +// else if (state == BLINKER_CMD_OFF) +// { +// if (!_targetState) +// { +// if (!_isTrigged) +// { +// triggerCheck("off"); +// } +// } +// else +// { +// _isTrigged = false; +// isRecord = false; +// _trigged = false; +// } +// } +// } +// // else if (_logicType == BLINKER_TYPE_OR && \ +// // logic_type[_num] == BLINKER_TYPE_STATE) +// // { +// // if (state == BLINKER_CMD_ON) +// // { +// // if (_targetState[_num]) +// // { +// // if (!_isTrigged[_num]) +// // { +// // triggerCheck("on", _num); +// // } +// // } +// // else +// // { +// // _isTrigged[_num] = false; +// // isRecord[_num] = false; +// // _trigged = false; +// // } +// // } +// // else if (state == BLINKER_CMD_OFF) +// // { +// // if (!_targetState[_num]) +// // { +// // if (!_isTrigged[_num]) +// // { +// // triggerCheck("off", _num); +// // } +// // } +// // else +// // { +// // _isTrigged[_num] = false; +// // isRecord[_num] = false; +// // _trigged = false; +// // } +// // } +// // } +// // } +// } + +void BlinkerAUTO::manager(const JsonObject& root) +{ + // DynamicJsonBuffer jsonBuffer; + // JsonObject& root = jsonBuffer.parseObject(data); + // BLINKER_LOG_ALL(BLINKER_F("auto state: "), data); + + // DynamicJsonDocument jsonBuffer(1024); + // deserializeJson(jsonBuffer, data); + // JsonObject root = jsonBuffer.as(); + + _autoState = root[BLINKER_CMD_SET][BLINKER_CMD_AUTO]["enable"].as(); + + _haveAuto = true; + + BLINKER_LOG_ALL(BLINKER_F("===============================================")); + BLINKER_LOG_ALL(BLINKER_F("auto state: "), _autoState); + + String get_autoId = root[BLINKER_CMD_SET][BLINKER_CMD_AUTO][BLINKER_CMD_ID].as(); + _autoId = strtoul(get_autoId.c_str(),NULL,10); + + String logicType = root[BLINKER_CMD_SET][BLINKER_CMD_AUTO][BLINKER_CMD_MODE].as(); + BLINKER_LOG_ALL(BLINKER_F("_autoId: "), get_autoId, " ", String(_autoId)); + BLINKER_LOG_ALL(BLINKER_F("logicType: "), logicType); + + // if (logicType == BLINKER_CMD_STATE) + // { + // BLINKER_LOG_ALL(BLINKER_F("state!")); + + // String target_key = root[BLINKER_CMD_DATA][0][BLINKER_CMD_KEY]; + + // strcpy(_targetKey[0], target_key.c_str()); + + // _targetNum = 1; + + // _logicType = BLINKER_TYPE_STATE; + + // logic_type[0] = BLINKER_TYPE_STATE; + + // String target_state = root[BLINKER_CMD_DATA][0][BLINKER_CMD_VALUE]; + + // if (target_state == BLINKER_CMD_ON) + // { + // _targetState[0] = true; + // } + // else if (target_state == BLINKER_CMD_OFF) + // { + // _targetState[0] = false; + // } + + // _duration[0] = root[BLINKER_CMD_DATA][0][BLINKER_CMD_DURATION]; + // _duration[0] = 60 * _duration[0]; + + // BLINKER_LOG_ALL(BLINKER_F("_logicType: "), _logicType); + // BLINKER_LOG_ALL(BLINKER_F("_targetKey: "), _targetKey[0]); + // BLINKER_LOG_ALL(BLINKER_F("_targetState: "), _targetState[0]); + // BLINKER_LOG_ALL(BLINKER_F("_duration: "), _duration[0]); + // } + // else if (logicType == BLINKER_CMD_NUMBERIC) + // { + // BLINKER_LOG_ALL(BLINKER_F("numberic!")); + + // String target_key = root[BLINKER_CMD_DATA][0][BLINKER_CMD_KEY]; + + // strcpy(_targetKey[0], target_key.c_str()); + + // _targetNum = 1; + + // _logicType = BLINKER_TYPE_NUMERIC; + + // logic_type[0] = BLINKER_TYPE_NUMERIC; + + // String _type = root[BLINKER_CMD_DATA][0][BLINKER_CMD_TYPE]; + + // if (_type == BLINKER_CMD_LESS) + // { + // _compareType[0] = BLINKER_COMPARE_LESS; + // } + // else if (_type == BLINKER_CMD_EQUAL) + // { + // _compareType[0] = BLINKER_COMPARE_EQUAL; + // } + // else if (_type == BLINKER_CMD_GREATER) + // { + // _compareType[0] = BLINKER_COMPARE_GREATER; + // } + + // _targetData[0] = root[BLINKER_CMD_DATA][0][BLINKER_CMD_VALUE]; + // _duration[0] = root[BLINKER_CMD_DATA][0][BLINKER_CMD_DURATION]; + // _duration[0] = 60 * _duration[0]; + + // BLINKER_LOG_ALL(BLINKER_F("_logicType: "), _logicType); + // BLINKER_LOG_ALL(BLINKER_F("_type: "), _type, + // BLINKER_F(" _compareType: "), _compareType[0]); + // BLINKER_LOG_ALL(BLINKER_F("_targetKey: "), _targetKey[0], + // BLINKER_F(" _targetData: "), _targetData[0]); + // BLINKER_LOG_ALL(BLINKER_F("_duration: "), _duration[0]); + // } + // else + // if (logicType == BLINKER_CMD_OR || logicType == BLINKER_CMD_AND) + // { + if (logicType == BLINKER_CMD_OR) + { + BLINKER_LOG_ALL(BLINKER_F("or!")); + _logicType = BLINKER_TYPE_OR; + } + else if (logicType == BLINKER_CMD_AND) + { + BLINKER_LOG_ALL(BLINKER_F("and!")); + _logicType = BLINKER_TYPE_AND; + } + + String target_key = root[BLINKER_CMD_SET][BLINKER_CMD_AUTO][BLINKER_CMD_TRIGGER][0][BLINKER_CMD_SOURCE]; + String target_State = root[BLINKER_CMD_SET][BLINKER_CMD_AUTO][BLINKER_CMD_TRIGGER][0]["value"]; + String compare_type = root[BLINKER_CMD_SET][BLINKER_CMD_AUTO][BLINKER_CMD_TRIGGER][0][BLINKER_CMD_OPERATOR]; + String day_set = root[BLINKER_CMD_SET][BLINKER_CMD_AUTO]["time"][BLINKER_CMD_DAY]; + _start_time = root[BLINKER_CMD_SET][BLINKER_CMD_AUTO]["time"][BLINKER_CMD_RANGE][0].as(); + _end_time = root[BLINKER_CMD_SET][BLINKER_CMD_AUTO]["time"][BLINKER_CMD_RANGE][1].as(); + _duration = root[BLINKER_CMD_SET][BLINKER_CMD_AUTO][BLINKER_CMD_DATA][0][BLINKER_CMD_DURATION].as(); + + for (uint8_t day = 0; day < 7; day++) + { + if (day_set.substring(day, day+1) == "1") + { + _day |= (0x01 << day); + + BLINKER_LOG_ALL(BLINKER_F("day: "), day, BLINKER_F(" _day: "), _day); + } + } + + BLINKER_LOG_ALL(BLINKER_F("target_key: "), target_key); + BLINKER_LOG_ALL(BLINKER_F("target_State: "), target_State); + BLINKER_LOG_ALL(BLINKER_F("compare_type: "), compare_type); + BLINKER_LOG_ALL(BLINKER_F("day_set: "), day_set); + BLINKER_LOG_ALL(BLINKER_F("_start_time: "), _start_time); + BLINKER_LOG_ALL(BLINKER_F("_end_time: "), _end_time); + + strcpy(_targetKey, target_key.c_str()); + if (compare_type == BLINKER_CMD_LESS) + { + _compareType = BLINKER_COMPARE_LESS; + } + else if (compare_type == BLINKER_CMD_EQUAL) + { + _compareType = BLINKER_COMPARE_EQUAL; + } + else if (compare_type == BLINKER_CMD_GREATER) + { + _compareType = BLINKER_COMPARE_GREATER; + } + + if (target_State == BLINKER_CMD_ON) + { + _targetState = 1; + } + else if (target_State == BLINKER_CMD_OFF) + { + _targetState = 0; + } + else { + _targetState = target_State.toFloat(); + } + + // _targetNum = 2; + + // for (uint8_t t_num = 0; t_num < _targetNum; t_num++) + // { + // String target_key = root[BLINKER_CMD_DATA][t_num][BLINKER_CMD_KEY]; + + // String compare_type = root[BLINKER_CMD_DATA][t_num][BLINKER_CMD_TYPE]; + + // if (compare_type.length()) + // { + // BLINKER_LOG_ALL(BLINKER_F("or/and numberic!")); + + // logic_type[t_num] = BLINKER_TYPE_NUMERIC; + + // strcpy(_targetKey[t_num], target_key.c_str()); + + // if (compare_type == BLINKER_CMD_LESS) + // { + // _compareType[t_num] = BLINKER_COMPARE_LESS; + // } + // else if (compare_type == BLINKER_CMD_EQUAL) + // { + // _compareType[t_num] = BLINKER_COMPARE_EQUAL; + // } + // else if (compare_type == BLINKER_CMD_GREATER) + // { + // _compareType[t_num] = BLINKER_COMPARE_GREATER; + // } + + // _targetData[t_num] = root[BLINKER_CMD_DATA][t_num][BLINKER_CMD_VALUE]; + // _duration[t_num] = root[BLINKER_CMD_DATA][t_num][BLINKER_CMD_DURATION]; + // _duration[t_num] = 60 * _duration[t_num]; + + // BLINKER_LOG_ALL(BLINKER_F("_logicType: "), _logicType); + // BLINKER_LOG_ALL(BLINKER_F("_compareType: "), _compareType[t_num]); + // BLINKER_LOG_ALL(BLINKER_F("_targetKey: "), _targetKey[t_num], BLINKER_F(" _targetData: "), _targetData[t_num]); + // BLINKER_LOG_ALL(BLINKER_F("_duration: "), _duration[t_num]); + // } + // else + // { + // BLINKER_LOG_ALL(BLINKER_F("or/and state!")); + + // logic_type[t_num] = BLINKER_TYPE_STATE; + + // strcpy(_targetKey[t_num], target_key.c_str()); + + // String target_state = root[BLINKER_CMD_DATA][t_num][BLINKER_CMD_VALUE]; + + // if (target_state == BLINKER_CMD_ON) + // { + // _targetState[t_num] = true; + // } + // else if (target_state == BLINKER_CMD_OFF) + // { + // _targetState[t_num] = false; + // } + + // _duration[t_num] = root[BLINKER_CMD_DATA][t_num][BLINKER_CMD_DURATION]; + // _duration[t_num] = 60 * _duration[t_num]; + + // BLINKER_LOG_ALL(BLINKER_F("_logicType: "), _logicType); + // BLINKER_LOG_ALL(BLINKER_F("_targetKey: "), _targetKey[t_num]); + // BLINKER_LOG_ALL(BLINKER_F("_targetState: "), _targetState[t_num]); + // BLINKER_LOG_ALL(BLINKER_F("_duration: "), _duration[t_num]); + // } + // } + // } + + // int32_t timeValue = root[BLINKER_CMD_SET][BLINKER_CMD_AUTO] + // [BLINKER_CMD_RANGE][0]; + + // if (timeValue) + // { + // _time1[0] = root[BLINKER_CMD_SET][BLINKER_CMD_AUTO] + // [BLINKER_CMD_RANGE][0]; + // _time1[0] = 60 * _time1[0]; + // _time2[0] = root[BLINKER_CMD_SET][BLINKER_CMD_AUTO] + // [BLINKER_CMD_RANGE][1]; + // _time2[0] = 60 * _time2[0]; + // } + // else + // { + // _time1[0] = 0; + // _time2[0] = 24 * 60 * 60; + // } + + // BLINKER_LOG_ALL(BLINKER_F("_time1: "), _time1[0], \ + // BLINKER_F(" _time2: "), _time2[0]); + + serialization(); +} + +void BlinkerAUTO::deserialization() +{ + uint8_t checkData; + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_CHECK, checkData); + + if (checkData != BLINKER_CHECK_DATA) + { + _haveAuto = false; + _autoState = false; + EEPROM.commit(); + EEPROM.end(); + return; + } + + uint64_t auto_data; + + EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + a_num * BLINKER_ONE_AUTO_DATA_SIZE + + BLINKER_EEP_ADDR_AUTODATA, auto_data); + + // EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_SOURCE, _targetKey); + + // EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_VALUE, _targetState); + + // EEPROM.commit(); + // EEPROM.end(); + + _haveAuto = auto_data >> (11 + 11 + 12 + 7 + 2 + 1 + 1) & 0x01; + _autoState = auto_data >> (11 + 11 + 12 + 7 + 2 + 1) & 0x01; + _logicType = auto_data >> (11 + 11 + 12 + 7 + 2) & 0x01; + _compareType = auto_data >> (11 + 11 + 12 + 7) & 0x03; + + BLINKER_LOG_ALL(BLINKER_F("_haveAuto: "), _haveAuto); + BLINKER_LOG_ALL(BLINKER_F("_autoState: "), _autoState); + BLINKER_LOG_ALL(BLINKER_F("_logicType: "), _logicType); + BLINKER_LOG_ALL(BLINKER_F("_compareType: "), _compareType); + + if (!_haveAuto) + { + EEPROM.commit(); + EEPROM.end(); + return; + } + + _day = auto_data >> (11 + 11 + 12) & 0x7F; + _duration = auto_data >> (11 + 11) & 0xFFF; + _start_time = auto_data >> (11) & 0x7FF; + _end_time = auto_data & 0x7FF; + + EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + a_num * BLINKER_ONE_AUTO_DATA_SIZE + + BLINKER_EEP_ADDR_AUTOID, _autoId); + + EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + a_num * BLINKER_ONE_AUTO_DATA_SIZE + + BLINKER_EEP_ADDR_SOURCE, _targetKey); + + EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + a_num * BLINKER_ONE_AUTO_DATA_SIZE + + BLINKER_EEP_ADDR_VALUE, _targetState); + + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("===============================================")); + BLINKER_LOG_ALL(BLINKER_F("_autoId: "), String(_autoId)); + BLINKER_LOG_ALL(BLINKER_F("_day: "), _day); + BLINKER_LOG_ALL(BLINKER_F("_duration: "), _duration); + BLINKER_LOG_ALL(BLINKER_F("_start_time: "), _start_time); + BLINKER_LOG_ALL(BLINKER_F("_end_time: "), _end_time); + BLINKER_LOG_ALL(BLINKER_F("_logicType: "), _logicType); + BLINKER_LOG_ALL(BLINKER_F("_compareType: "), _compareType); + BLINKER_LOG_ALL(BLINKER_F("_targetKey: "), _targetKey); + BLINKER_LOG_ALL(BLINKER_F("_targetState: "), _targetState); + BLINKER_LOG_ALL(BLINKER_F("===============================================")); + + // EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_AUTOID, _autoId); + // EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_TYPESTATE, _typeState); + + // _haveAuto = _typeState >> 7 & 0x01; + // _autoState = _typeState >> 6 & 0x01; + // _logicType = _typeState & 0x3F; + + // BLINKER_LOG_ALL(BLINKER_F("_typeState: "), _typeState); + // BLINKER_LOG_ALL(BLINKER_F("_haveAuto: "), _haveAuto); + + // if (!_haveAuto) + // { + // EEPROM.commit(); + // EEPROM.end(); + // return; + // } + + // if (_logicType == BLINKER_TYPE_STATE || _logicType == BLINKER_TYPE_NUMERIC) + // { + // _targetNum = 1; + // } + // else + // { + // _targetNum = 2; + // } + + // BLINKER_LOG_ALL(BLINKER_F("_targetNum: "), _targetNum); + + // EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_AUTO1, _autoData[0]); + + // logic_type[0] = _autoData[0] >> 30 & 0x03; + + // BLINKER_LOG_ALL(BLINKER_F("===============================================")); + // BLINKER_LOG_ALL(BLINKER_F("_autoId: "), _autoId); + + // switch (_logicType) + // { + // case BLINKER_TYPE_STATE : + // BLINKER_LOG_ALL(BLINKER_F("_logicType: state")); + // break; + // case BLINKER_TYPE_NUMERIC : + // BLINKER_LOG_ALL(BLINKER_F("_logicType: numberic")); + // break; + // case BLINKER_TYPE_OR : + // BLINKER_LOG_ALL(BLINKER_F("_logicType: or")); + // break; + // case BLINKER_TYPE_AND : + // BLINKER_LOG_ALL(BLINKER_F("_logicType: and")); + // break; + // default : + // break; + // } + + // EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_TARGETKEY1, _targetKey[0]); + + // if (logic_type[0] == BLINKER_TYPE_STATE) + // { + // _targetState[0] = _autoData[0] >> 28 & 0x03; + + // BLINKER_LOG_ALL(BLINKER_F("_targetKey: "), _targetKey[0]); + // BLINKER_LOG_ALL(BLINKER_F("_targetState: "), _targetState[0] ? "on" : "off"); + // } + // else + // { + // _compareType[0] = _autoData[0] >> 28 & 0x03; + // // EEPROM.get(BLINKER_EEP_ADDR_TARGETDATA, _targetData); + // EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_TARGETDATA1, _targetData[0]); + + // BLINKER_LOG_ALL(BLINKER_F("_compareType: "), _compareType[0] ? (_compareType[0] == BLINKER_COMPARE_GREATER ? "greater" : "equal") : "less"); + // BLINKER_LOG_ALL(BLINKER_F("_targetKey: "), _targetKey[0]); + // BLINKER_LOG_ALL(BLINKER_F("_targetData: "), _targetData[0]); + // } + + // _duration[0] = (_autoData[0] >> 22 & 0x3f) * 60; + // _time1[0] = (_autoData[0] >> 11 & 0x7ff) * 60; + // _time2[0] = (_autoData[0] & 0x7ff) * 60; + + // BLINKER_LOG_ALL(BLINKER_F("_duration: "), _duration[0]); + // BLINKER_LOG_ALL(BLINKER_F("_time1: "), _time1[0], \ + // BLINKER_F(" _time2: "), _time2[0]); + + // if (_targetNum == 2) + // { + // EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_AUTO2, _autoData[1]); + + // logic_type[1] = _autoData[1] >> 30 & 0x03; + + // EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_TARGETKEY2, _targetKey[1]); + + // if (logic_type[1] == BLINKER_TYPE_STATE) + // { + // _targetState[1] = _autoData[1] >> 28 & 0x03; + + // BLINKER_LOG_ALL(BLINKER_F("_targetKey: "), _targetKey[1]); + // BLINKER_LOG_ALL(BLINKER_F("_targetState: "), _targetState[1] ? "on" : "off"); + // } + // else + // { + // _compareType[1] = _autoData[1] >> 28 & 0x03; + // // EEPROM.get(BLINKER_EEP_ADDR_TARGETDATA, _targetData); + // EEPROM.get(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_TARGETDATA2, _targetData[1]); + + // BLINKER_LOG_ALL(BLINKER_F("_compareType: "), _compareType[1] ? (_compareType[1] == BLINKER_COMPARE_GREATER ? "greater" : "equal") : "less"); + // BLINKER_LOG_ALL(BLINKER_F("_targetKey: "), _targetKey[1]); + // BLINKER_LOG_ALL(BLINKER_F("_targetData: "), _targetData[1]); + // } + + // _duration[1] = (_autoData[1] >> 22 & 0x3f) * 60; + // _time1[1] = (_autoData[1] >> 11 & 0x7ff) * 60; + // _time2[1] = (_autoData[1] & 0x7ff) * 60; + + // BLINKER_LOG_ALL(BLINKER_F("_duration: "), _duration[1]); + // BLINKER_LOG_ALL(BLINKER_F("_time1: "), _time1[1], BLINKER_F(" _time2: "), _time2[1]); + // } + + // BLINKER_LOG_ALL(BLINKER_F("===============================================")); + + // EEPROM.commit(); + // EEPROM.end(); + // } +} + +void BlinkerAUTO::serialization() +{ + uint64_t auto_data; + + auto_data = _haveAuto & 0x01; + auto_data = auto_data << 1 | _autoState & 0x01; + auto_data = auto_data << 1 | _logicType & 0x01; + auto_data = auto_data << 2 | _compareType & 0x03; + auto_data = auto_data << 7 | _day & 0x7F; + auto_data = auto_data << 12 | _duration & 0xFFF; + auto_data = auto_data << 11 | _start_time & 0x7FF; + auto_data = auto_data << 11 | _end_time & 0x7FF; + + uint8_t checkData; + + EEPROM.begin(BLINKER_EEP_SIZE); + + EEPROM.get(BLINKER_EEP_ADDR_CHECK, checkData); + + if (checkData != BLINKER_CHECK_DATA) + { + EEPROM.put(BLINKER_EEP_ADDR_CHECK, BLINKER_CHECK_DATA); + } + + EEPROM.put(BLINKER_EEP_ADDR_AUTO_START + + a_num * BLINKER_ONE_AUTO_DATA_SIZE + + BLINKER_EEP_ADDR_AUTOID, _autoId); + + EEPROM.put(BLINKER_EEP_ADDR_AUTO_START + + a_num * BLINKER_ONE_AUTO_DATA_SIZE + + BLINKER_EEP_ADDR_AUTODATA, auto_data); + + EEPROM.put(BLINKER_EEP_ADDR_AUTO_START + + a_num * BLINKER_ONE_AUTO_DATA_SIZE + + BLINKER_EEP_ADDR_SOURCE, _targetKey); + + EEPROM.put(BLINKER_EEP_ADDR_AUTO_START + + a_num * BLINKER_ONE_AUTO_DATA_SIZE + + BLINKER_EEP_ADDR_VALUE, _targetState); + + EEPROM.commit(); + EEPROM.end(); + + // uint8_t checkData; + + // _typeState = _haveAuto << 7 | _autoState << 6 | _logicType;// | _linkNum; + + // EEPROM.begin(BLINKER_EEP_SIZE); + + // EEPROM.get(BLINKER_EEP_ADDR_CHECK, checkData); + + // if (checkData != BLINKER_CHECK_DATA) + // { + // EEPROM.put(BLINKER_EEP_ADDR_CHECK, BLINKER_CHECK_DATA); + // } + + // EEPROM.put(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_AUTOID, _autoId); + // EEPROM.put(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_TYPESTATE, _typeState); + + // _autoData[0] = logic_type[0] << 30 ; + // if (logic_type[0] == BLINKER_TYPE_STATE) + // { + // _autoData[0] |= _targetState[0] << 28; + // } + // else + // { + // _autoData[0] |= _compareType[0] << 28; + // } + // _autoData[0] |= _duration[0] / 60 << 22 | _time1[0] / 60 << 11 | _time2[0] / 60; + + // EEPROM.put(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_AUTO1, _autoData[0]); + // EEPROM.put(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_TARGETKEY1, _targetKey[0]); + + // if (logic_type[0] == BLINKER_TYPE_NUMERIC) + // { + // EEPROM.put(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_TARGETDATA1, _targetData[0]); + // } + + // BLINKER_LOG_ALL(BLINKER_F("serialization _typeState: "), _typeState); + // BLINKER_LOG_ALL(BLINKER_F("serialization _autoData: "), _autoData[0]); + + // if (_targetNum == 2) + // { + // _autoData[1] = logic_type[1] << 30 ; + // if (logic_type[1] == BLINKER_TYPE_STATE) + // { + // _autoData[1] |= _targetState[1] << 28; + // } + // else + // { + // _autoData[1] |= _compareType[1] << 28; + // } + // _autoData[1] |= _duration[1] / 60 << 22 | _time1[1] / 60 << 11 | _time2[1] / 60; + + // EEPROM.put(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_AUTO2, _autoData[1]); + // EEPROM.put(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_TARGETKEY2, _targetKey[1]); + + // if (logic_type[1] == BLINKER_TYPE_NUMERIC) + // { + // EEPROM.put(BLINKER_EEP_ADDR_AUTO_START + + // a_num * BLINKER_ONE_AUTO_DATA_SIZE + + // BLINKER_EEP_ADDR_TARGETDATA2, _targetData[1]); + // } + // BLINKER_LOG_ALL(BLINKER_F("serialization _autoData: "), _autoData[1]); + // } + + // EEPROM.commit(); + // EEPROM.end(); +} + +void BlinkerAUTO::fresh() +{ + // for (uint8_t _num = 0; _num < _targetNum; _num++) + // { + // if (isRecord[_num]) { + // _isTrigged[_num] = true; + // } + // } + // _trigged = false; + + if (isRecord) _isTrigged = true; + + _trigged = false; +} + +void BlinkerAUTO::triggerCheck(const String & state) +{ + if (!isRecord) + { + isRecord = true; + _treTime = millis(); + } + + switch (_logicType) + { + case BLINKER_TYPE_OR : + BLINKER_LOG_ALL(("_logicType: or")); + // state = BLINKER_F("or ") + state; + break; + case BLINKER_TYPE_AND : + BLINKER_LOG_ALL(("_logicType: and")); + // state = BLINKER_F("and ") + state; + break; + default : + break; + } + + if ((millis() - _treTime) / 1000 >= _duration) + { + if (_logicType != BLINKER_TYPE_AND) + { + BLINKER_LOG_ALL(state, BLINKER_F(" trigged")); + _trigged = true; + } + else + { + _isTrigged = true; + if (_isTrigged) + { + BLINKER_LOG_ALL(state, BLINKER_F(" trigged")); + _trigged = true; + } + } + } + + // if (!isRecord[num]) + // { + // isRecord[num] = true; + // _treTime[num] = millis(); + // } + + // switch (_logicType) + // { + // case BLINKER_TYPE_STATE : + // BLINKER_LOG_ALL(("_logicType: state")); + // // state = BLINKER_F("state ") + state; + // break; + // case BLINKER_TYPE_NUMERIC : + // BLINKER_LOG_ALL(("_logicType: numberic")); + // // state = BLINKER_F("numberic ") + state; + // break; + // case BLINKER_TYPE_OR : + // BLINKER_LOG_ALL(("_logicType: or")); + // // state = BLINKER_F("or ") + state; + // break; + // case BLINKER_TYPE_AND : + // BLINKER_LOG_ALL(("_logicType: and")); + // // state = BLINKER_F("and ") + state; + // break; + // default : + // break; + // } + + // if ((millis() - _treTime[num]) / 1000 >= _duration[num]) + // { + // if (_logicType != BLINKER_TYPE_AND) + // { + // BLINKER_LOG_ALL(state, BLINKER_F(" trigged")); + // _trigged = true; + // } + // else + // { + // _isTrigged[num] = true; + // if (_isTrigged[0] && _isTrigged[1]) + // { + // BLINKER_LOG_ALL(state, BLINKER_F(" trigged")); + // _trigged = true; + // } + // } + // } +} + +#endif + +#endif diff --git a/blinker-library/src/Blinker/BlinkerAutoGateway.h b/blinker-library/src/Blinker/BlinkerAutoGateway.h new file mode 100644 index 0000000..e69de29 diff --git a/blinker-library/src/Blinker/BlinkerAutoSubdevice.h b/blinker-library/src/Blinker/BlinkerAutoSubdevice.h new file mode 100644 index 0000000..9aa3188 --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerAutoSubdevice.h @@ -0,0 +1,65 @@ +#ifndef BLINKER_AUTO_SUBDEVICE_H +#define BLINKER_AUTO_SUBDEVICE_H + +#if defined(BLINKER_WIFI_SUBDEVICE) + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include + +// #include "Blinker/BlinkerAuto.h" +#include "Blinker/BlinkerConfig.h" +#include "Blinker/BlinkerDebug.h" +#include "Blinker/BlinkerUtility.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "modules/ArduinoJson/ArduinoJson.h" +#endif + +class BlinkerAutoSubdevice +{ + private : + uint8_t a_num; + + // { + // "auto":{ + // "ena":1,//_autoState + // "id":123456,//_autoId + // "logic":"numberic",//_logicType + // "data": + // [ + // { + // "key":"humi", + // "value":40, + // "type":"<",//_targetState|_compareType + // "dur":10 + // } + // ], + // "range":[540, 1260], + // } + // } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + // | | | | | | _time1 0-1440min 11 | _time2 0-1440min 11 + // | | | | | _duration 0-60min 6 + // | | | | _targetState|_compareType on/off|less/equal/greater 2 + // | | | _targetState|_compareType on/off|less/equal/greater + // | + // | logic_type state/numberic 2 + // autoData + + // | _linkNum + // - - - - - - - - + // | | |_logicType state/numberic/and/or 2 + // | | _autoState true/false 1 + // | _haveAuto + // | + // typestate +}; + +#endif + +#endif diff --git a/blinker-library/src/Blinker/BlinkerConfig.h b/blinker-library/src/Blinker/BlinkerConfig.h new file mode 100644 index 0000000..a0b920e --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerConfig.h @@ -0,0 +1,2133 @@ +#ifndef BlinkerConfig_H +#define BlinkerConfig_H + +// #include "Blinker/BlinkerDebug.h" +// #include "Blinker/BlinkerUtility.h" +#include "../Server/BlinkerServer.h" + +#define BLINKER_VERSION "0.3.80210803" + +#define BLINKER_CONNECT_TIMEOUT_MS 10000UL + +#define BLINKER_STREAM_TIMEOUT 100 + +#define BLINKER_NTP_TIMEOUT 1000UL + +#define BLINKER_GPS_MSG_LIMIT 30000UL + +#define BLINKER_PRINT_MSG_LIMIT 20 + +#define BLINKER_MQTT_MSG_LIMIT 1000UL + +#define BLINKER_PRO_MSG_LIMIT 200UL + +#define BLINKER_MQTT_CONNECT_TIMESLOT 5000UL + +#define BLINKER_BRIDGE_MSG_LIMIT 10000UL + +#define BLINKER_LINK_MSG_LIMIT 10000UL + +#define BLINKER_MQTT_KEEPALIVE 30000UL + +#define BLINKER_SMS_MSG_LIMIT 60000UL + +#define BLINKER_PUSH_MSG_LIMIT 60000UL + +#define BLINKER_WECHAT_MSG_LIMIT 60000UL + +#define BLINKER_WEATHER_MSG_LIMIT 60000UL + +#define BLINKER_AQI_MSG_LIMIT 60000UL + +#define BLINKER_LOG_MSG_LIMIT 60000UL + +#define BLINKER_COD_MSG_LIMIT 60000UL + +#define BLINKER_CONFIG_UPDATE_LIMIT 10000UL + +#define BLINKER_CONFIG_GET_LIMIT 10000UL + +#define BLINKER_WIFI_AUTO_INIT_TIMEOUT 20000UL + +#define BLINKER_AT_MSG_TIMEOUT 1000UL + +#define BLINKER_SERVER_CONNECT_LIMIT 3 + +#if defined(BLINKER_DATA_HOUR_UPDATE) + #define BLINKER_DATA_FREQ_TIME 3600UL +#else + #define BLINKER_DATA_FREQ_TIME 60 +#endif + +#define BLINKER_DEVICE_HEARTBEAT_TIME 600 + +#define BLINKER_MDNS_SERVICE_BLINKER "blinker" + +#define BLINKER_ERROR 0x00 + +#define BLINKER_SUCCESS 0x01 + +#define BLINKER_MSG_FROM_MQTT 0 + +#define BLINKER_MSG_FROM_WS 1 + +#define BLINKER_INT_DATA 0 + +#define BLINKER_UINT_DATA 1 + +#define BLINKER_FLOAT_DATA 2 + +// #if defined(BLINKER_MQTT) +// #define BLINKER_MSG_AUTOFORMAT_TIMEOUT 1000 +// #else + #define BLINKER_MSG_AUTOFORMAT_TIMEOUT 100 +// #endif + +#define BLINKER_SMS_MAX_SEND_SIZE 128 + +#if defined(BLINKER_BUTTON_LONGPRESS_POWERDOWN) + #define BLINKER_PRESSTIME_POWERDOWN 2000UL + + #define BLINKER_PRESSTIME_RESET 10000UL +#endif + +#if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_WIFI_SUBDEVICE) || \ + defined(BLINKE_HTTP) + #define BLINKER_MAX_WIDGET_SIZE 16 +#else + #define BLINKER_MAX_WIDGET_SIZE 6 +#endif + +#define BLINKER_OBJECT_NOT_AVAIL -1 + +#ifndef BLINKER_MAX_READ_SIZE + #if defined(ESP8266) || defined(ESP32) + #define BLINKER_MAX_READ_SIZE 1024 + #else + // #if defined(BLINKER_MQTT_AT) + // #define BLINKER_MAX_READ_SIZE 256 + // #else + #define BLINKER_MAX_READ_SIZE 128 + // #endif + #endif +#endif + +#ifndef BLINKER_MAX_SEND_SIZE + #if defined(ESP8266) || defined(ESP32) + #if defined(BLINKER_MQTT) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKE_HTTP) + #define BLINKER_MAX_SEND_SIZE 1024 + #else + #define BLINKER_MAX_SEND_SIZE 512 + #endif + #else + #if defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + #define BLINKER_MAX_SEND_SIZE 512 + #else + #define BLINKER_MAX_SEND_SIZE 128 + #endif + #endif +#endif + +#ifndef BLINKER_MAX_SEND_BUFFER_SIZE + #if defined(ESP8266) || defined(ESP32) + #if defined(BLINKER_MQTT) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKE_HTTP) + #define BLINKER_MAX_SEND_BUFFER_SIZE BLINKER_MAX_SEND_SIZE - 128 + #else + #define BLINKER_MAX_SEND_BUFFER_SIZE BLINKER_MAX_SEND_SIZE + #endif + #else + #if defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + #define BLINKER_MAX_SEND_BUFFER_SIZE 512 + #else + #define BLINKER_MAX_SEND_BUFFER_SIZE 128 + #endif + #endif +#endif + +#define BLINKER_AUTHKEY_SIZE 14 + +#if defined(ESP8266) || defined(ESP32) + #define BLINKER_LOGO_3D +#else + #define BLINKER_NO_LOGO +#endif + +#define BLINKER_MAX_SUMMARY_DATA_SIZE 20 + +// #define BLINKER_DEBUG + +#define BLINKER_CMD_ON "on" + +#define BLINKER_CMD_OFF "off" + +#define BLINKER_CMD_TRUE "true" + +#define BLINKER_CMD_FALSE "false" + +#define BLINKER_CMD_JOYSTICK "joy" + +#define BLINKER_CMD_GYRO "gyro" + +#define BLINKER_CMD_AHRS "ahrs" + +#define BLINKER_CMD_GPS "gps" + +#define BLINKER_CMD_RGB "rgb" + +#define BLINKER_CMD_VIBRATE "vibrate" + +#define BLINKER_CMD_BUTTON_TAP "tap" + +#define BLINKER_CMD_BUTTON_PRESSED "press" + +#define BLINKER_CMD_BUTTON_RELEASED "pressup" + +#define BLINKER_CMD_BUTTON_PRESS "press" + +#define BLINKER_CMD_BUTTON_PRESSUP "pressup" + +#define BLINKER_CMD_NEWLINE "\n" + +#define BLINKER_CMD_INTERSPACE " " + +#define BLINKER_CMD_DATA "data" + +#define BLINKER_CMD_FREQ "freq" + +#define BLINKER_CMD_GET "get" + +#define BLINKER_CMD_SET "set" + +#define BLINKER_CMD_STATE "state" + +#define BLINKER_CMD_ONLINE "online" + +#define BLINKER_CMD_CONNECTED "connected" + +#define BLINKER_CMD_VERSION "version" + +#define BLINKER_CMD_NOTICE "notice" + +#define BLINKER_CMD_BUILTIN_SWITCH "switch" + +#define BLINKER_CMD_FROMDEVICE "fromDevice" + +#define BLINKER_CMD_NOTFOUND "device not found" + +#define BLINKER_CMD_COMMAND "cmd" + +#define BLINKER_CMD_EVENT "event" + +#define BLINKER_CMD_AUTO "auto" + +#define BLINKER_CMD_AUTOID "autoId" + +#define BLINKER_CMD_ID "id" + +#define BLINKER_CMD_AUTODATA "autoData" + +#define BLINKER_CMD_DELETID "deletId" + +#define BLINKER_CMD_LOGIC "logic" + +#define BLINKER_CMD_LOGICDATA "logicData" + +#define BLINKER_CMD_LOGICTYPE "logicType" + +#define BLINKER_CMD_LESS "<"//"less" + +#define BLINKER_CMD_EQUAL "="//"equal" + +#define BLINKER_CMD_GREATER ">"//"greater" + +#define BLINKER_CMD_NUMBERIC "numberic" + +#define BLINKER_CMD_OR "or" + +#define BLINKER_CMD_AND "and" + +#define BLINKER_CMD_COMPARETYPE "compareType" + +#define BLINKER_CMD_TRIGGER "triggers" + +#define BLINKER_CMD_SOURCE "source" + +#define BLINKER_CMD_OPERATOR "operator" + +#define BLINKER_CMD_DURATION "duration" + +#define BLINKER_CMD_TARGETKEY "targetKey" + +#define BLINKER_CMD_TARGETSTATE "targetState" + +#define BLINKER_CMD_TARGETDATA "targetData" + +#define BLINKER_CMD_TIMESLOT "timeSlot" + +#define BLINKER_CMD_RANGE "range" + +#define BLINKER_CMD_LINKDEVICE "linkDevice" + +#define BLINKER_CMD_LINKTYPE "linkType" + +#define BLINKER_CMD_LINKDATA "linkData" + +#define BLINKER_CMD_TRIGGEDDATA "triggedData" + +#define BLINKER_CMD_TYPE "type" + +#define BLINKER_CMD_TIMER "timer" + +#define BLINKER_CMD_RUN "run" + +#define BLINKER_CMD_ENABLE "ena" + +#define BLINKER_CMD_COUNTDOWN "countdown" + +#define BLINKER_CMD_COUNTDOWNDATA "countdownData" + +#define BLINKER_CMD_TOTALTIME "ttim" + +#define BLINKER_CMD_RUNTIME "rtim" + +#define BLINKER_CMD_ACTION "act" + +#define BLINKER_CMD_ACTION1 "act1" + +#define BLINKER_CMD_ACTION2 "act2" + +#define BLINKER_CMD_LOOP "loop" + +#define BLINKER_CMD_LOOPDATA "loopData" + +#define BLINKER_CMD_TIME "tim" + +#define BLINKER_CMD_TIME_ALL "time" + +#define BLINKER_CMD_TIMES "tis" + +#define BLINKER_CMD_TRIGGED "tri" + +#define BLINKER_CMD_TIME1 "dur1" + +#define BLINKER_CMD_TIME2 "dur2" + +#define BLINKER_CMD_TIMING "timing" + +#define BLINKER_CMD_TIMINGDATA "timingData" + +#define BLINKER_CMD_DAY "day" + +#define BLINKER_CMD_TASK "task" + +#define BLINKER_CMD_DELETETASK "dlt" + +#define BLINKER_CMD_DELETE "dlt" + +#define BLINKER_CMD_DETAIL "detail" + +#define BLINKER_CMD_OK "OK" + +#define BLINKER_CMD_ERROR "ERROR" + +#define BLINKER_CMD_MESSAGE "message" + +#define BLINKER_CMD_DEVICENAME "deviceName" + +#define BLINKER_CMD_AUTHKEY "authKey" + +#define BLINKER_CMD_IOTID "iotId" + +#define BLINKER_CMD_IOTTOKEN "iotToken" + +#define BLINKER_CMD_PRODUCTKEY "productKey" + +#define BLINKER_CMD_BROKER "broker" + +#define BLINKER_CMD_UUID "uuid" + +#define BLINKER_CMD_KEY "key" + +#define BLINKER_CMD_SMS "sms" + +#define BLINKER_CMD_PUSH "push" + +#define BLINKER_CMD_WECHAT "wechat" + +#define BLINKER_CMD_WEATHER "weather" + +#define BLINKER_CMD_AQI "aqi" + +#define BLINKER_CMD_CONFIG "config" + +#define BLINKER_CMD_DEFAULT "default" + +#define BLINKER_CMD_SWITCH "swi" + +#define BLINKER_CMD_VALUE "val" + +#define BLINKER_CMD_ICON "ico" + +#define BLINKER_CMD_COLOR "clr" + +#define BLINKER_CMD_COLOR_ "col" + +#define BLINKER_CMD_TITLE "tit" + +#define BLINKER_CMD_CONTENT "con" + +#define BLINKER_CMD_TEXT "tex" + +#define BLINKER_CMD_TEXT1 "tex1" + +#define BLINKER_CMD_TEXTCOLOR "tco" + +#define BLINKER_CMD_UNIT "uni" + +#define BLINKER_CMD_SUMMARY "sum" + +#define BLINKER_CMD_POWERSTATE "pState" + +#define BLINKER_CMD_POWERSTATE1 "pstate" + +#define BLINKER_CMD_NUM "num" + +#define BLINKER_CMD_BRIGHTNESS "bright" + +#define BLINKER_CMD_UPBRIGHTNESS "upBright" + +#define BLINKER_CMD_DOWNBRIGHTNESS "downBright" + +#define BLINKER_CMD_COLORTEMP "colTemp" + +#define BLINKER_CMD_UPCOLORTEMP "upColTemp" + +#define BLINKER_CMD_DOWNCOLORTEMP "downColTemp" + +#define BLINKER_CMD_TEMP "temp" + +#define BLINKER_CMD_HUMI "humi" + +#define BLINKER_CMD_PM25 "pm25" + +#define BLINKER_CMD_PM10 "pm10" + +#define BLINKER_CMD_CO2 "co2" + +#define BLINKER_CMD_MAX "max" + +#define BLINKER_CMD_MIN "min" + +#define BLINKER_CMD_MODE "mode" + +#define BLINKER_CMD_CANCELMODE "cMode" + +#define BLINKER_CMD_READING "reading" + +#define BLINKER_CMD_MOVIE "movie" + +#define BLINKER_CMD_SLEEP "sleep" + +#define BLINKER_CMD_HOLIDAY "holiday" + +#define BLINKER_CMD_MUSIC "music" + +#define BLINKER_CMD_COMMON "common" + +#define BLINKER_CMD_LEVEL "level" + +#define BLINKER_CMD_LEVEL_UP "upLevel" + +#define BLINKER_CMD_LEVEL_DW "downLevel" + +#define BLINKER_CMD_TEMP_UP "upTemp" + +#define BLINKER_CMD_TEMP_DW "downTemp" + +#define BLINKER_CMD_HSTATE "hsState" + +#define BLINKER_CMD_VSTATE "vsState" + +#define BLINKER_CMD_ECO "eco" + +#define BLINKER_CMD_ANION "anion" + +#define BLINKER_CMD_HEATER "heater" + +#define BLINKER_CMD_DRYER "dryer" + +#define BLINKER_CMD_SOFT "soft" + +#define BLINKER_CMD_UV "uv" + +#define BLINKER_CMD_UNSB "unsb" + +#define BLINKER_CMD_ALIGENIE_READING "reading" + +#define BLINKER_CMD_ALIGENIE_MOVIE "movie" + +#define BLINKER_CMD_ALIGENIE_SLEEP "sleep" + +#define BLINKER_CMD_ALIGENIE_HOLIDAY "holiday" + +#define BLINKER_CMD_ALIGENIE_MUSIC "music" + +#define BLINKER_CMD_ALIGENIE_COMMON "common" + +#define BLINKER_CMD_DUEROS_READING "READING" + +#define BLINKER_CMD_DUEROS_SLEEP "SLEEP" + +#define BLINKER_CMD_DUEROS_ALARM "ALARM" + +#define BLINKER_CMD_DUEROS_NIGHT_LIGHT "NIGHT_LIGHT" + +#define BLINKER_CMD_DUEROS_ROMANTIC "ROMANTIC" + +#define BLINKER_CMD_DUEROS_SUNDOWN "SUNDOWN" + +#define BLINKER_CMD_DUEROS_SUNRISE "SUNRISE" + +#define BLINKER_CMD_DUEROS_RELAX "RELAX" + +#define BLINKER_CMD_DUEROS_LIGHTING "LIGHTING" + +#define BLINKER_CMD_DUEROS_SUN "SUN" + +#define BLINKER_CMD_DUEROS_STAR "STAR" + +#define BLINKER_CMD_DUEROS_ENERGY_SAVING "ENERGY_SAVING" + +#define BLINKER_CMD_DUEROS_MOON "MOON" + +#define BLINKER_CMD_DUEROS_JUDI "JUDI" + +#define BLINKER_CMD_MIOT_DAY 0 + +#define BLINKER_CMD_MIOT_NIGHT 1 + +#define BLINKER_CMD_MIOT_COLOR 2 + +#define BLINKER_CMD_MIOT_WARMTH 3 + +#define BLINKER_CMD_MIOT_TV 4 + +#define BLINKER_CMD_MIOT_READING 5 + +#define BLINKER_CMD_MIOT_COMPUTER 6 + +#define BLINKER_CMD_UPGRADE "upgrade" + +#define BLINKER_CMD_SHARE "share" + +#define BLINKER_CMD_AUTO_UPDATE_KEY "upKey" + +#define BLINKER_CMD_CANCEL_UPDATE_KEY "cKey" + +#define BLINKER_CMD_ALIGENIE "AliGenie" + +#define BLINKER_CMD_DUEROS "DuerOS" + +#define BLINKER_CMD_MIOT "MIOT" + +#define BLINKER_CMD_SERVERCLIENT "serverClient" + +#define BLINKER_CMD_HELLO "hello" + +// #define BLINKER_CMD_WHOIS "whois" + +#define BLINKER_CMD_AT "AT" + +#define BLINKER_CMD_GATE "gate" + +#define BLINKER_CMD_CONTROL "ctrl" + +#define BLINKER_CMD_DEVICEINFO "dInf" + +#define BLINKER_CMD_NEW "{\"hello\":\"new\"}" + +#define BLINKER_CMD_WHOIS "{\"hello\":\"whois\"}" + +#define BLINKER_MESH_CHECK_FREQ 60000UL + +#define BLINKER_CMD_MODE_READING_NUMBER 0 + +#define BLINKER_CMD_MODE_MOVIE_NUMBER 1 + +#define BLINKER_CMD_SLEEP_NUMBER 2 + +#define BLINKER_CMD_HOLIDAY_NUMBER 3 + +#define BLINKER_CMD_MUSIC_NUMBER 4 + +#define BLINKER_CMD_COMMON_NUMBER 5 + +#define BLINKER_CMD_QUERY_ALL_NUMBER 0 + +#define BLINKER_CMD_QUERY_POWERSTATE_NUMBER 1 + +#define BLINKER_CMD_QUERY_COLOR_NUMBER 2 + +#define BLINKER_CMD_QUERY_MODE_NUMBER 3 + +#define BLINKER_CMD_QUERY_COLORTEMP_NUMBER 4 + +#define BLINKER_CMD_QUERY_BRIGHTNESS_NUMBER 5 + +#define BLINKER_CMD_QUERY_TEMP_NUMBER 6 + +#define BLINKER_CMD_QUERY_HUMI_NUMBER 7 + +#define BLINKER_CMD_QUERY_PM25_NUMBER 8 + +#define BLINKER_CMD_QUERY_PM10_NUMBER 9 + +#define BLINKER_CMD_QUERY_CO2_NUMBER 10 + +#define BLINKER_CMD_QUERY_AQI_NUMBER 11 + +#define BLINKER_CMD_QUERY_TIME_NUMBER 12 + +#define BLINKER_JOYSTICK_VALUE_DEFAULT 128 + +#define BLINKER_ONE_HOUR_TIME 3600UL + +#define BLINKER_ONE_DAY_TIME 86400UL + +#define BLINKER_CMD_TAB_0 16 // 0x10000 + +#define BLINKER_CMD_TAB_1 8 // 0x01000 + +#define BLINKER_CMD_TAB_2 4 // 0x00100 + +#define BLINKER_CMD_TAB_3 2 // 0x00010 + +#define BLINKER_CMD_TAB_4 1 // 0x00001 + +#define BLINKER_MAX_SUB_DEVICE_NUM 36 + +// #define BLINKER_NTP_SERVER_1 "ntp1.aliyun.com" + +// #define BLINKER_NTP_SERVER_2 "210.72.145.44" + +// #define BLINKER_NTP_SERVER_3 "time.pool.aliyun.com" + +#ifndef BLINKER_MAX_BRIDGE_SIZE + #if defined(BLINKER_MQTT) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKE_HTTP) + #define BLINKER_MAX_BRIDGE_SIZE 4 + #elif defined(BLINKER_PRO) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_WIFI_SUBDEVICE) + #define BLINKER_MAX_BRIDGE_SIZE 16 + #endif +#endif + +#define BLINKER_MAX_BLINKER_DATA_SIZE 8 + +#define BLINKER_MAX_DATA_COUNT 4 + +#define BLINKER_DATA_UPDATE_COUNT 2 + +#if defined(BLINKER_ESP_AT) + + #define BLINKER_ESP_AT_VERSION "0.1.0" + + #define BLINKER_UART_PARAM_NUM 4 + + #define BLINKER_COMWLAN_PARAM_NUM 4 + + #define BLINKER_SMCFG_PARAM_NUM 2 + + #define BLINKER_APCFG_PARAM_NUM 2 + + #define BLINKER_IOSETCFG_PARAM_NUM 3 + + #define BLINKER_IOGETCFG_PARAM_NUM 1 + + #define BLINKER_GPIOWRITE_PARAM_NUM 2 + + #define BLINKER_GPIOREAD_PARAM_NUM 1 + + #define BLINKER_IO_INPUT_NUM 0 + + #define BLINKER_IO_OUTPUT_NUM 1 + + #define BLINKER_IO_DEFAULT_NUM 2 + + #define BLINKER_ALIGENIE_CFG_NUM 0 + + #define BLINKER_ALIGENIE_PARAM_NUM 1 + + #define BLINKER_DUEROS_CFG_NUM 0 + + #define BLINKER_DUEROS_PARAM_NUM 1 + + #define BLINKER_TIMEZONE_CFG_NUM 0 + + #define BLINKER_TIMEZONE_PARAM_NUM 1 + + #if defined(ESP8266) + + #define BLINKER_MAX_PIN_NUM 17 + + #elif defined(ESP32) + + #define BLINKER_MAX_PIN_NUM 40 + + #endif + + #define BLINKER_CMD_RST "RST" + + #define BLINKER_CMD_GMR "GMR" + + #define BLINKER_CMD_UART_CUR "UART_CUR" + + #define BLINKER_CMD_UART_DEF "UART_DEF" + + #define BLINKER_CMD_RAM "SYSRAM" + + #define BLINKER_CMD_ADC "SYSADC" + + #define BLINKER_CMD_IOSETCFG "SYSIOSETCFG" + + #define BLINKER_CMD_IOGETCFG "SYSIOGETCFG" + + #define BLINKER_CMD_GPIOWRITE "SYSGPIOWRITE" + + #define BLINKER_CMD_GPIOWREAD "SYSGPIOREAD" + + #define BLINKER_CMD_BLINKER_MQTT "BLINKER_WIFI" + + #define BLINKER_CMD_BLINKER_ALIGENIE "BLINKER_ALIGENIE" + + #define BLINKER_CMD_BLINKER_DUEROS "BLINKER_DUEROS" + + #define BLINKER_CMD_BLINKER_MIOT "BLINKER_MIOT" + + #define BLINKER_CMD_TIMEZONE "TIMEZONE" + + #define BLINKER_CMD_TIME_AT "TIME" + + #define BLINKER_CMD_SECOND "SECOND" + + #define BLINKER_CMD_MINUTE "MINUTE" + + #define BLINKER_CMD_HOUR "HOUR" + + #define BLINKER_CMD_WDAY "WDAY" + + #define BLINKER_CMD_MDAY "MDAY" + + #define BLINKER_CMD_YDAY "YDAY" + + #define BLINKER_CMD_MONTH "MONTH" + + #define BLINKER_CMD_YEAR "YEAR" + + #define BLINKER_CMD_WEATHER_AT "WEATHER" + + #define BLINKER_CMD_WEATHER_FORECAST_AT "WEATHER_FORECAST" + + #define BLINKER_CMD_AQI_AT "AQI" + + #define BLINKER_CMD_NOTICE_AT "NOTIFY" + + #define BLINKER_CMD_SMS_AT "SMS" + + #define BLINKER_CMD_SMARTCONFIG "ESPTOUCH" + + #define BLINKER_CMD_APCONFIG "APCONFIG" + + #define BLINKER_CMD_COMCONFIG "COMCONFIG" + + #define BLINKER_SERIAL_DEFAULT 9600 << 8 | 8 << 4 | 1 << 2 | 0 + + #define BLINKER_SERIAL_5N1 5 << 4 | 1 << 2 | 0 + + #define BLINKER_SERIAL_6N1 6 << 4 | 1 << 2 | 0 + + #define BLINKER_SERIAL_7N1 7 << 4 | 1 << 2 | 0 + + #define BLINKER_SERIAL_8N1 8 << 4 | 1 << 2 | 0 + + #define BLINKER_SERIAL_5N2 5 << 4 | 2 << 2 | 0 + + #define BLINKER_SERIAL_6N2 6 << 4 | 2 << 2 | 0 + + #define BLINKER_SERIAL_7N2 7 << 4 | 2 << 2 | 0 + + #define BLINKER_SERIAL_8N2 8 << 4 | 2 << 2 | 0 + + #define BLINKER_SERIAL_5E1 5 << 4 | 1 << 2 | 2 + + #define BLINKER_SERIAL_6E1 6 << 4 | 1 << 2 | 2 + + #define BLINKER_SERIAL_7E1 7 << 4 | 1 << 2 | 2 + + #define BLINKER_SERIAL_8E1 8 << 4 | 1 << 2 | 2 + + #define BLINKER_SERIAL_5E2 5 << 4 | 2 << 2 | 2 + + #define BLINKER_SERIAL_6E2 6 << 4 | 2 << 2 | 2 + + #define BLINKER_SERIAL_7E2 7 << 4 | 2 << 2 | 2 + + #define BLINKER_SERIAL_8E2 8 << 4 | 2 << 2 | 2 + + #define BLINKER_SERIAL_5O1 5 << 4 | 1 << 2 | 1 + + #define BLINKER_SERIAL_6O1 6 << 4 | 1 << 2 | 1 + + #define BLINKER_SERIAL_7O1 7 << 4 | 1 << 2 | 1 + + #define BLINKER_SERIAL_8O1 8 << 4 | 1 << 2 | 1 + + #define BLINKER_SERIAL_5O2 5 << 4 | 2 << 2 | 1 + + #define BLINKER_SERIAL_6O2 6 << 4 | 2 << 2 | 1 + + #define BLINKER_SERIAL_7O2 7 << 4 | 2 << 2 | 1 + + #define BLINKER_SERIAL_8O2 8 << 4 | 2 << 2 | 1 + + // #define BLINKER_EEP_ADDR_SERIALCFG 2432 + + // #define BLINKER_SERIALCFG_SIZE 4 + +#endif + +#if defined(BLINKER_MQTT_AT) + + #define BLINKER_MQTT_HOST_SIZE 50 + + #define BLINKER_MQTT_ID_SIZE 110 + + #define BLINKER_MQTT_NAME_SIZE 80 + + #define BLINKER_MQTT_KEY_SIZE 50 + + #define BLINKER_MQTT_PINFO_SIZE 12 + + #define BLINKER_MQTT_UUID_SIZE 40 + + #define BLINKER_MQTT_DEVICEID_SIZE 26 + + #define BLINKER_MQTT_DEVICENAME_SIZE 14 + +#endif + +#define BLINKER_CMD_COMCONFIG_NUM 0 + +#define BLINKER_CMD_SMARTCONFIG_NUM 1 + +#define BLINKER_CMD_APCONFIG_NUM 2 + +#if defined(BLINKER_NBIOT_WH) +/* + +>[Success][17:20:49:705] +COM14 (9600,None,_8,_1,148) Opend +>[Tx ->][17:21:06:364][Asc] +AT+CGATT? + +>[Rx <-][17:21:06:548][Asc] + ++CGATT:1 + +OK + +>[Success][17:21:06:565] +Success--[AT+CGATT?] +>[Tx ->][17:21:06:565][Asc] +AT+MIPLCREATE + +>[Rx <-][17:21:06:776][Asc] + ++CIS ERROR:602 + +>[Warn][17:21:06:781] +Fail--[AT+MIPLCREATE] +>[Tx ->][17:21:10:595][Asc] +AT+MIPLDELETE=0 + +>[Rx <-][17:21:11:015][Asc] + ++MIPLEVENT:0,15 + +>[Rx <-][17:21:11:291][Asc] + +OK + +>[Success][17:21:11:315] +Success--[AT+MIPLDELETE=0] +>[Tx ->][17:21:16:320][Asc] +AT+CGATT? + +>[Rx <-][17:21:16:513][Asc] + ++CGATT:1 + +OK + +>[Success][17:21:16:533] +Success--[AT+CGATT?] +>[Tx ->][17:21:16:533][Asc] +AT+MIPLCREATE + +>[Rx <-][17:21:16:760][Asc] + ++MIPLCREATE:0 + +OK + +>[Success][17:21:16:781] +Success--[AT+MIPLCREATE] +>[Tx ->][17:21:16:797][Asc] +AT+MIPLADDOBJ=0,3306,1,1,5,0 + +>[Rx <-][17:21:17:015][Asc] + +OK + +>[Success][17:21:17:048] +Success--[AT+MIPLADDOBJ=0,3306,1,1,5,0] +>[Tx ->][17:21:17:055][Asc] +AT+MIPLADDOBJ=0,3303,1,1,6,1 + +>[Rx <-][17:21:17:260][Asc] + +OK + +>[Success][17:21:17:294] +Success--[AT+MIPLADDOBJ=0,3303,1,1,6,1] +>[Tx ->][17:21:17:301][Asc] +AT+MIPLOPEN=0,3000 + +>[Rx <-][17:21:17:490][Asc] + +OK + +>[Success][17:21:17:526] +Success--[AT+MIPLOPEN=0,3000] +>[Rx <-][17:21:18:016][Asc] + ++MIPLEVENT:0,1 + +>[Rx <-][17:21:21:031][Asc] + ++MIPLEVENT:0,2 + ++MIPLEVENT:0,4 + +>[Rx <-][17:21:24:595][Asc] + ++MIPLEVENT:0,6 + ++MIPLOBSERVE:0,88436,1,3303,0,-1 + +>[Tx ->][17:21:25:548][Asc] +AT+MIPLOBSERVERSP=0,88436,1 + +>[Rx <-][17:21:25:752][Asc] + +OK + +>[Success][17:21:25:796] +Success--[AT+MIPLOBSERVERSP=0,88436,1] +>[Tx ->][17:21:26:922][Asc] +AT+MIPLNOTIFY=0,88436,3303,0,5700,4,2,13,1,0 + +>[Rx <-][17:21:27:158][Asc] + +OK + +>[Success][17:21:27:189] +Success--[AT+MIPLNOTIFY=0,88436,3303,0,5700,4,2,13,1,0] +>[Tx ->][17:21:28:339][Asc] +AT+MIPLNOTIFY=0,88436,3303,0,5701,1,3,"cel",0,0 + +>[Rx <-][17:21:28:564][Asc] + +OK + +>[Success][17:21:28:595] +Success--[AT+MIPLNOTIFY=0,88436,3303,0,5701,1,3,"cel",0,0] +>[Rx <-][17:21:29:476][Asc] + ++MIPLOBSERVE:0,153973,1,3306,0,-1 + +>[Tx ->][17:21:29:611][Asc] +AT+MIPLOBSERVERSP=0,153973,1 + +>[Rx <-][17:21:29:828][Asc] + +OK + +>[Success][17:21:29:875] +Success--[AT+MIPLOBSERVERSP=0,153973,1] +>[Rx <-][17:21:30:796][Asc] + ++MIPLDISCOVER:0,22902,3303 + +>[Success][17:21:30:843] +Success--[AT+MIPLNOTIFY=0,153973,3306,0,5850,5,1,0,1,0] +>[Tx ->][17:21:32:048][Asc] +AT+MIPLNOTIFY=0,153973,3306,0,5851,3,2,76,0,0 + +>[Rx <-][17:21:32:356][Asc] + +OK + +>[Success][17:21:32:411] +Success--[AT+MIPLNOTIFY=0,153973,3306,0,5851,3,2,76,0,0] +>[Tx ->][17:21:32:418][Asc] +AT+MIPLDISCOVERRSP=0,22902,1,34,"5700;5701;5601;5602;5603;5604;5605" + +>[Tx ->][17:21:32:564][Asc] +AT+MIPLNOTIFY=0,153973,3306,0,5850,5,1,0,1,0 + +>[Success][17:21:32:564] +Success--[AT+MIPLNOTIFY=0,153973,3306,0,5850,5,1,0,1,0] +>[Rx <-][17:21:32:797][Asc] + +OK + +OK + +>[Success][17:21:32:906] +Success--[AT+MIPLDISCOVERRSP=0,22902,1,34,"5700;5701;5601;5602;5603;5604;5605"] +>[Rx <-][17:21:33:548][Asc] + ++MIPLDISCOVER:0,22903,3306 + +>[Tx ->][17:21:33:922][Asc] +AT+MIPLDISCOVERRSP=0,22903,1,24,"5850;5851;5852;5853;5750" + +>[Rx <-][17:21:34:174][Asc] + +OK + +>[Success][17:21:34:238] +Success--[AT+MIPLDISCOVERRSP=0,22903,1,24,"5850;5851;5852;5853;5750"] + +*/ + + // http://www.mokuai.cn/Down/WH-NB73_al_onenet_V1.0.0.pdf + // http://www.mokuai.cn/Down/WH-NB73_at_V2.2.1.pdf + // http://www.openmobilealliance.org/wp/OMNA/LwM2M/LwM2MRegistry.html + #define BLINKER_NB_STREAM_TIMEOUT 60000UL + + #define BLINKER_NB_LIFTIME 1800UL + + #define BLINKER_CMD_NB_NB73 "[WH-NB73]" + + #define BLINKER_CMD_NB_RESET "AT+NRB" + + #define BLINKER_CMD_NB_CGATT "AT+CGATT?" + + #define BLINKER_CMD_CGATT "CGATT" + // Waiting module attachment network + #define BLINKER_CMD_NB_CGATT_SUCCESSED "+CGATT:1" + + #define BLINKER_CMD_NB_CGATT_FAILED "+CGATT:0" + + #define BLINKER_CMD_NB_MIPLCREATE "AT+MIPLCREATE" + // Create communication kite + #define BLINKER_CMD_MIPLCREATE "MIPLCREATE" + + #define BLINKER_CMD_NB_CREATE_SUCCESSED "+MIPLCREATE:0" + + #define BLINKER_CMD_NB_MIPLDELETE "AT+MIPLDELETE" + + #define BLINKER_CMD_NB_MIPLADDOBJ "AT+MIPLADDOBJ" + // Add object + // AT+MIPLADDOBJ = , 0 通信套件编号 + // , 3303 IPSO 对象ID + // , 1 实例个数 + // , 1 实例位图 + // , 6 属性个数 + // 1 操作个数 + // AT+MIPLADDOBJ=0,3306,1,1,5,0 + // AT+MIPLADDOBJ=0,3303,1,1,6,1 + // 建议使用 Generic Sensor 3300 + #define BLINKER_CMD_NB_MIPLDELOBJ "AT+MIPLDELOBJ" + // AT+MIPLDELOBJ=, + // AT+MIPLDELOBJ=0,3303 + #define BLINKER_CMD_NB_MIPLOPEN "AT+MIPLOPEN" + // AT+MIPLOPEN=,[,] + // AT+MIPLOPEN=0,1200 + // lifetime 是设备连接服务器的一个参数,单位为秒,默认为 86400 秒,lifetime 到期 + // 后,平台就会把设备踢下线,此时设备无法上报数据,只能重新注册。设备必须 + // lifetime 未过期时通过发送 AT+MILPUPDATE 命令更新 lifetime 以保证设备在线。 + // 取值范围(15~‭268435455) + #define BLINKER_CMD_NB_MIPLUPDATE "AT+MIPLUPDATE" + // AT+MIPLUPDATE=,, + // AT+MIPLUPDATE=0,86400,0 + #define BLINKER_CMD_NB_MIPLCLOSE "AT+MIPLCLOSE" + // AT+MIPLCLOSE= + // AT+MIPLCLOSE=0 + #define BLINKER_CMD_MIPLEVENT "MIPLEVENT" + // +MIPLEVENT:, + // +MIPLEVENT:0,11 + + // 1 BOOTSTRAP_START + // 2 BOOTSTRAP_SUCCESS + // 3 BOOTSTRAP_FAILED + // 4 CONNECT_SUCCESS + // 5 CONNECT_FAILED + // 6 REG_SUCCESS + // 7 REG_FAILED + // 8 REG_TIMEOUT + // 9 LIFETIME_TIMEOUT + // 10 STATUS_HALT + // 11 UPDATE_SUCCESS + // 12 UPDATE_FAILED + // 13 UPDATE_TIMEOUT + // 14 UPDATE_NEED + // 20 RESPONSE_FAILED + // 21 RESPONSE_SUCCESS + // 25 NOTIFY_FAILED + // 26 NOTIFY_SUCCESS + #define BLINKER_CMD_NB_EVENT_1 "+MIPLEVENT:0,1" + + #define BLINKER_CMD_NB_EVENT_2 "+MIPLEVENT:0,2" + + #define BLINKER_CMD_NB_EVENT_4 "+MIPLEVENT:0,4" + + #define BLINKER_CMD_NB_EVENT_6 "+MIPLEVENT:0,6" + + #define BLINKER_CMD_NB_DISCOVEREQ "+MIPLDISCOVER" + // Resource discovery + // +MIPLDISCOVER:,, + // 3 + // +MIPLREAD:0,888888,3303 + + // 3341 Addressable Text Display + // This IPSO object is used to send text to a text-only or text mode graphics display. + #define BLINKER_CMD_NB_DISCOVERESP "AT+MIPLDISCOVERRSP" + // AT+MIPLDISCOVERRSP= , 0 + // , %d + // , 1 + // 1 2.05 Content + // 11 4.00 Bad Request + // 12 4.01 Unauthorized + // 13 4.04 Not Found + // 14 4.05 Method Not Allowed + // 15 4.06 Not Acceptable + // , 19 + // "5850;5851;5852;5853" + // AT+MIPLDISCOVERRSP=0,%d,1,19,"5850;5851;5852;5853" + + // 5527 Text RW String + #define BLINKER_CMD_MIPLOBSERVE "MIPLOBSERVE" + + #define BLINKER_CMD_NB_OBSERVEREQ "+MIPLOBSERVE" + // Resource observation + // +MIPLOBSERVE:,,,,[,] + // 6 + // +MIPLREAD:0,888888,1,3303,1,5700 + #define BLINKER_CMD_NB_OBSERVERSP "AT+MIPLOBSERVERSP" + // AT+MIPLOBSERVERSP=,, + // 1 2.05 Content + // 11 4.00 Bad Request + // 12 4.01 Unauthorized + // 13 4.04 Not Found + // 14 4.05 Method Not Allowed + // 15 4.06 Not Acceptable + // AT+MIPLOBSERVERSP=0,88888,1 + #define BLINKER_CMD_NB_MIPLNOTIFY "AT+MIPLNOTIFY" + // AT+MIPLNOTIFY = , 0 + // , %d + // , 3303 + // , 0 + // , 5700 + // , 4 + // 1-char 2-hex 3-int 4-float 5-bool + // , 3 + // , 2.1 + // , 1 + // [, 0 + // ] + // AT+MIPLNOTIFY=0,%d,3303,0,5700,4,3,2.1,1,0 + #define BLINKER_CMD_NB_UPDATE "AT+MIPLUPDATE" + // AT+MIPLUPDATE=,, + // AT+MIPLUPDATE=0,0,0 + #define BLINKER_CMD_NB_LEVEL "AT+MIPLVER" + + #define BLINKER_CMD_NB_WRITEREQ "+MIPLWRITE" + // +MIPLWRITE: , + // , + // , + // , + // , + // , + // 1-char 2-hex 3-int 4-float 5-bool + // , + // , + // , + // + // 10 + // +MIPLWRITE:0,51130,3306,0,0,2,2,01,0,0 + #define BLINKER_CMD_NB_WRITERSP "AT+MIPLWRITERSP" + // AT+MIPLWRITERSP=,, + // 2 2.04 Changed + // 11 4.00 Bad Request + // 12 4.01 Unauthorized + // 13 4.04 Not Found + // 14 4.05 Method Not Allowed + // 16 2.31 Continue + // 17 4.08 Request Entity Incomplete + // 18 4.13 Request entity too large + // 19 4.15 Unsupported content format + // 3 + // AT+MIPLWRITERSP=0,88888,2 + #define BLINKER_CMD_NB_READREQ "+MIPLREAD" + // +MIPLREAD:,,,, + // 5 + // +MIPLREAD:0,888888,3303,1,5700 + #define BLINKER_CMD_NB_READRSP "AT+MIPLREADRSP" + // AT+MIPLREADRSP= , 0 + // , 86635 + // [, 1 + // 1 2.05 Content + // 11 4.00 BadRequest + // 12 4.01 Unauthorized + // 13 4.04 NotFound + // 14 4.05 MethodNotAllowed + // 15 4.06 NotAcceptable + // , 3303 + // , 1 + // , 5700 + // , 4 + // , 2 + // , 20 + // , 1 + // ] 0 + // 11 + // AT+MIPLREADRSP=0,86635,1,3303,1,5700,4,2,20,1,0 + #define BLINKER_CMD_NB_EXECUTEREQ "+MIPLEXECUTE" + // +MIPLEXECUTE:,,,,,[,,] + // 7 + // +MIPLEXECUTE:0,51131,3303,0, 5605,5,reset + #define BLINKER_CMD_NB_EXECUTERSP "AT+MIPLEXECUTERSP" + // AT+MIPLEXECUTERSP=,, + // 2 2.04 Changed + // 11 4.00 Bad Request + // 12 4.01 Unauthorized + // 13 4.04 Not Found + // 14 4.05 Method Not Allowed + // AT+MIPLEXECUTERSP=0,88888,2 + #define BLINKER_CMD_NB_PARAMETERREQ "+MIPLPARAMETER" + // +MIPLPARAMETER:,,,,,, + // 7 + // +MIPLPARAMETER:0,88688,3203,1,5603,39,“pmin=1.8;pmax=5.0;gt=3.6;lt=3.0;stp=0.1” + #define BLINKER_CMD_NB_PARAMETERRSP "AT+MIPLPARAMETERSP" + // AT+MIPLPARAMETERRSP=,, + // 1 2.04 Changed + // 11 4.00 Bad Request + // 12 4.01 Unauthorized + // 13 4.04 Not Found + // 14 4.05 Method Not Allowed + // AT+MIPLPARAMETERRSP=0,888888,1 + + + // Digital Input 3200 + // Digital Output 3201 + // Analogue Input 3202 + // Analogue Output 3203 + // Generic Sensor 3300 + // Illuminance Sensor 3301 + // Presence sensor 3302 + // Temperature Sensor 3303 + // Humidity Sensor 3304 + // Power Measurement 3305 + // Actuation 3306 + // Set Point 3308 + // Load Control 3310 + // Light Control 3311 + // Power Control 3312 + // Accelerometer 3313 + // Magnetometer 3314 + // Barometer 3315 + // Voltage 3316 + // Current 3317 + // Frequency 3318 + // Depth 3319 + // Percentage 3320 + // Altitude 3321 + // Load 3322 + // Pressure 3323 + // Loudness 3324 + // Concentration 3325 + // Acidity 3326 + // Conductivity 3327 + // Power 3328 + // Power Factor 3329 + // Distance 3330 + // Energy 3331 + // Direction 3332 + // Time 3333 + // Gyrometer 3334 + // Color 3335 + // GPS Location 3336 + // Positioner 3337 + // Buzzer 3338 + // Audio Clip 3339 + // Timer 3340 + // Addressable Text Display 3341 + // On/Off Switch 3342 + // Dimmer 3343 + // Up/Down Control 3344 + // Multiple Axis Joystick 3345 + // Rate 3346 + // Push Button 3347 + // Multi-state Selector 3348 + // Bitmap 3349 + // Stopwatch 3350 + + // Digital Input State 5500 R Boolean + // Digital Input Counter 5501 R Integer + // Digital Input Polarity 5502 R,W Boolean + // Digital Input Debounce 5503 R,W Integer + // Digital Input Edge Selection 5504 R,W Integer + // Digital Input Counter Reset 5505 E + // Current Time 5506 R,W Time + // Fractional Time 5507 R,W Float + // Min X Value 5508 R Float + // Max X Value 5509 R Float + // Min Y Value 5510 R Float + // Max Y Value 5511 R Float + // Min Z Value 5512 R Float + // Max Z Value 5513 R Float + // Latitude 5514 R String + // Longitude 5515 R String + // Uncertainty 5516 R String + // Velocity 5517 R Opaque + // Timestamp 5518 R Time + // Min Limit 5519 R Float + // Max Limit 5520 R Float + // Delay Duration 5521 R,W Float + // Clip 5522 R,W Opaque + // Trigger 5523 E + // Duration 5524 R,W Float + // Minimum Off-time 5525 R,W Float + // Mode 5526 R,W Integer + // Text 5527 R,W String + // X Coordinate 5528 R,W Integer + // Y Coordinate 5529 R,W Integer + // Clear Display 5530 E + // Contrast 5531 R,W Float + // Increase Input State 5532 R Boolean + // Decrease Input State 5533 R Boolean + // Counter 5534 R,W Integer + // Current Position 5536 R,W Float + // Transition Time 5537 R,W Float + // Remaining Time 5538 R Float + // Up Counter 5541 R,W Integer + // Down Counter 5542 R,W Integer + // Digital State 5543 R Boolean + // Cumulative Time 5544 R,W Float + // Max X Coordinate 5545 R Integer + // Max Y Coordinate 5546 R Integer + // Multi-state Input 5547 R Integer + // Level 5548 R,W Float + // Digital Output State 5550 R,W Boolean + // Digital Output Polarity 5551 R,W Boolean + // Analog Input State 5600 R Float + // Min Measured Value 5601 R Float + // Max Measured Value 5602 R Float + // Min Range Value 5603 R Float + // Max Range Value 5604 R Float + // Reset Min and Max Measured Values 5605 E + // Analog Output Current Value 5650 R,W Float + // Sensor Value 5700 R Float + // Sensor Units 5701 R String + // X Value 5702 R Float + // Y Value 5703 R Float + // Z Value 5704 R Float + // Compass Direction 5705 R Float + // Colour 5706 R,W String + // Application Type 5750 R,W String + // Sensor Type 5751 R String + // Instantaneous active power 5800 R Float + // Min Measured active power 5801 R Float + // Max Measured active power 5802 R Float + // Min Range active power 5803 R Float + // Max Range active power 5804 R Float + // Cumulative active power 5805 R Float + // Active Power Calibration 5806 W Float + // Instantaneous reactive power 5810 R Float + // Min Measured reactive power 5811 R Float + // Max Measured reactive power 5812 R Float + // Min Range reactive power 5813 R Float + // Max Range reactive power 5814 R Float + // Cumulative reactive power 5815 R Float + // Reactive Power Calibration 5816 W Float + // Power Factor 5820 R Float + // Current Calibration 5821 R,W Float + // Reset Cumulative energy 5822 E + // Event Identifier 5823 R,W String + // Start Time 5824 R,W Float + // Duration In Min 5825 R,W Float + // Criticality Level 5826 R,W Integer + // Avg Load Adj Pct 5827 R,W String + // Duty Cycle 5828 R,W Integer + // On/Off 5850 R,W Boolean + // Dimmer 5851 R,W Integer + // On Time 5852 R,W Integer + // Muti-state Output 5853 R,W String + // Off Time 5854 R,W Integer + // Set Point Value 5900 R,W Float + // Busy to Clear delay 5903 R,W Integer + // Clear to Busy delay 5904 R,W Integer + // Bitmap Input 5910 R Integer + // Bitmap Input Reset 5911 E + // Element Description 5912 R,W String + // UUID 5913 R,W String +#endif + +#if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_PRO) || defined(BLINKER_AT_MQTT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_LOWPOWER_AIR202) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + #define BLINKER_CMD_SMS_NUMBER 1 + + #define BLINKER_CMD_PUSH_NUMBER 2 + + #define BLINKER_CMD_WECHAT_NUMBER 3 + + #define BLINKER_CMD_WEATHER_NUMBER 4 + + #define BLINKER_CMD_AQI_NUMBER 5 + + #define BLINKER_CMD_BRIDGE_NUMBER 6 + + #define BLINKER_CMD_CONFIG_UPDATE_NUMBER 7 + + #define BLINKER_CMD_CONFIG_GET_NUMBER 8 + + #define BLINKER_CMD_CONFIG_DELETE_NUMBER 9 + + #define BLINKER_CMD_DATA_STORAGE_NUMBER 10 + + #define BLINKER_CMD_DATA_GET_NUMBER 11 + + #define BLINKER_CMD_DATA_DELETE_NUMBER 12 + + #define BLINKER_CMD_AUTO_PULL_NUMBER 13 + + #define BLINKER_CMD_OTA_NUMBER 14 + + #define BLINKER_CMD_OTA_STATUS_NUMBER 15 + + #define BLINKER_CMD_FRESH_SHARERS_NUMBER 16 + + #define BLINKER_CMD_LOWPOWER_FREQ_GET_NUM 17 + + #define BLINKER_CMD_LOWPOWER_FREQ_UP_NUMBER 18 + + #define BLINKER_CMD_LOWPOWER_DATA_GET_NUM 19 + + #define BLINKER_CMD_LOWPOWER_DATA_UP_NUMBER 20 + + #define BLINKER_CMD_EVENT_DATA_NUMBER 21 + + #define BLINKER_CMD_GPS_DATA_NUMBER 22 + + #define BLINKER_CMD_DEVICE_HEARTBEAT_NUMBER 23 + + #define BLINKER_CMD_EVENT_WARNING_NUMBER 24 + + #define BLINKER_CMD_EVENT_ERROR_NUMBER 25 + + #define BLINKER_CMD_EVENT_MSG_NUMBER 26 + + #define BLINKER_CMD_WEATHER_FORECAST_NUMBER 27 + + #define BLINKER_CMD_TIME_SLOT_DATA_NUMBER 28 + + #define BLINKER_CMD_TEXT_DATA_NUMBER 29 + + #define BLINKER_CMD_JSON_DATA_NUMBER 30 + + #define BLINKER_CMD_LOG_NUMBER 31 + + #define BLINKER_CMD_COD_NUMBER 32 + + #define BLINKER_CMD_JSON_DATA_GET_NUMBER 33 + + #define BLINKER_CMD_DEFAULT_NUMBER 0 + +#endif + +#if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_LOWPOWER_AIR202) || defined(BLINKER_WIFI_SUBDEVICE) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) || defined(BLINKE_HTTP) + #define BLINKER_MQTT_BORKER_ALIYUN "aliyun" + + #define BLINKER_MQTT_ALIYUN_HOST "public.iot-as-mqtt.cn-shanghai.aliyuncs.com" + + #define BLINKER_MQTT_ALIYUN_PORT 1883 + + #define BLINKER_MQTT_BORKER_QCLOUD "qcloud" + + #define BLINKER_MQTT_QCLOUD_HOST "iotcloud-mqtt.gz.tencentdevices.com" + + #define BLINKER_MQTT_QCLOUD_PORT 8883 + + #define BLINKER_MQTT_BORKER_ONENET "onenet" + + #define BLINKER_MQTT_ONENET_HOST "mqtt.heclouds.com" + + #define BLINKER_MQTT_ONENET_PORT 6002 + + #define BLINKER_MQTT_BORKER_BLINKER "blinker" + + #define BLINKER_MQTT_BLINKER_HOST "broker.clz.me" + + #define BLINKER_MQTT_BLINKER_PORT 21303 + + #define BLINKER_MQTT_PING_TIMEOUT 30000UL + + #define BLINKER_MQTT_HOST_SIZE 50 + + #define BLINKER_MQTT_ID_SIZE 110 + + #define BLINKER_MQTT_NAME_SIZE 80 + + #define BLINKER_MQTT_KEY_SIZE 50 + + #define BLINKER_MQTT_PINFO_SIZE 12 + + #define BLINKER_MQTT_UUID_SIZE 40 + + #define BLINKER_MQTT_DEVICEID_SIZE 26 + + #define BLINKER_MQTT_DEVICENAME_SIZE 14 + + #define BLINKER_MQTT_USER_UUID_SIZE 24 + + #define BLINKER_MQTT_MAX_SHARERS_NUM 9 + + #define BLINKER_MQTT_FROM_AUTHER BLINKER_MQTT_MAX_SHARERS_NUM + + #define BLINKER_MQTT_FORM_SERVER BLINKER_MQTT_MAX_SHARERS_NUM + 1 + +#endif + +#if defined(ESP8266) || defined(ESP32) + + #define BLINKER_TIMING_TIMER_SIZE 10 + + // #define BLINKER_TYPE_STATE 0 + + // #define BLINKER_TYPE_NUMERIC 1 + + #define BLINKER_TYPE_OR 0 + + #define BLINKER_TYPE_AND 1 + + #define BLINKER_COMPARE_LESS 0 + + #define BLINKER_COMPARE_EQUAL 1 + + #define BLINKER_COMPARE_GREATER 2 + + #define BLINKER_CHECK_DATA 170 + + #define BLINKER_EEP_SIZE 4096 + + #define BLINKER_EEP_ADDR_CHECK 0 + + #define BLINKER_CHECK_SIZE 1 + + #define BLINKER_EEP_ADDR_AUTONUM (BLINKER_EEP_ADDR_CHECK + BLINKER_CHECK_SIZE) + + #define BLINKER_AUTONUM_SIZE 1 + + #define BLINKER_EEP_ADDR_AUTO_START (BLINKER_EEP_ADDR_AUTONUM + BLINKER_AUTONUM_SIZE) + + //////////////////////////////////////////////////////////////////////////////////////// + + #define BLINKER_EEP_ADDR_AUTOID 0 + + #define BLINKER_AUTOID_SIZE 4 + + #define BLINKER_EEP_ADDR_AUTODATA (BLINKER_EEP_ADDR_AUTOID + BLINKER_AUTOID_SIZE) + + #define BLINKER_AUTODATA_SIZE 6 + + #define BLINKER_EEP_ADDR_SOURCE (BLINKER_EEP_ADDR_AUTODATA + BLINKER_AUTODATA_SIZE) + + #define BLINKER_SOURCE_SIZE 12 + + #define BLINKER_EEP_ADDR_VALUE (BLINKER_EEP_ADDR_SOURCE + BLINKER_SOURCE_SIZE) + + #define BLINKER_VALUE_SIZE 4 + + #define BLINKER_ONE_AUTO_DATA_SIZE (BLINKER_AUTOID_SIZE + BLINKER_AUTODATA_SIZE + BLINKER_SOURCE_SIZE + BLINKER_VALUE_SIZE) + + // #define BLINKER_EEP_ADDR_TYPESTATE (BLINKER_EEP_ADDR_AUTOID + BLINKER_AUTOID_SIZE) + + // #define BLINKER_TYPESTATE_SIZE 1 + + // #define BLINKER_EEP_ADDR_AUTO1 (BLINKER_EEP_ADDR_TYPESTATE + BLINKER_TYPESTATE_SIZE) + + // #define BLINKER_AUTODATA_SIZE 4 + + // #define BLINKER_EEP_ADDR_TARGETKEY1 (BLINKER_EEP_ADDR_AUTO1 + BLINKER_AUTODATA_SIZE) + + // #define BLINKER_TARGETKEY_SIZE 12 + + // #define BLINKER_EEP_ADDR_TARGETDATA1 (BLINKER_EEP_ADDR_TARGETKEY1 + BLINKER_TARGETKEY_SIZE) + + // #define BLINKER_TARGETDATA_SIZE 4 + + // #define BLINKER_EEP_ADDR_AUTO2 (BLINKER_EEP_ADDR_TARGETDATA1 + BLINKER_TARGETDATA_SIZE) + + // #define BLINKER_AUTODATA_SIZE 4 + + // #define BLINKER_EEP_ADDR_TARGETKEY2 (BLINKER_EEP_ADDR_AUTO2 + BLINKER_AUTODATA_SIZE) + + // #define BLINKER_TARGETKEY_SIZE 12 + + // #define BLINKER_EEP_ADDR_TARGETDATA2 (BLINKER_EEP_ADDR_TARGETKEY2 + BLINKER_TARGETKEY_SIZE) + + // #define BLINKER_TARGETDATA_SIZE 4 + + // // // #define BLINKER_TARGET_DATA_SIZE (BLINKER_AUTOID_SIZE + BLINKER_AUTODATA_SIZE + BLINKER_TARGETKEY_SIZE + BLINKER_TARGETDATA_SIZE) + + // // #define BLINKER_EEP_ADDR_LINKDEVICE1 (BLINKER_EEP_ADDR_TARGETDATA2 + BLINKER_TARGETDATA_SIZE) + + // // #define BLINKER_LINKDEVICE_SIZE 26 + + // // #define BLINKER_EEP_ADDR_LINKTYPE1 (BLINKER_EEP_ADDR_LINKDEVICE1 + BLINKER_LINKDEVICE_SIZE) + + // // #define BLINKER_LINKTYPE_SIZE 18 + + // // #define BLINKER_EEP_ADDR_LINKDATA1 (BLINKER_EEP_ADDR_LINKTYPE1 + BLINKER_LINKTYPE_SIZE) + + // // #define BLINKER_LINKDATA_SIZE 212 + + // // #define BLINKER_EEP_ADDR_LINKDEVICE2 (BLINKER_EEP_ADDR_LINKDATA1 + BLINKER_LINKDATA_SIZE) + + // // #define BLINKER_LINKDEVICE_SIZE 26 + + // // #define BLINKER_EEP_ADDR_LINKTYPE2 (BLINKER_EEP_ADDR_LINKDEVICE2 + BLINKER_LINKDEVICE_SIZE) + + // // #define BLINKER_LINKTYPE_SIZE 18 + + // // #define BLINKER_EEP_ADDR_LINKDATA2 (BLINKER_EEP_ADDR_LINKTYPE2 + BLINKER_LINKTYPE_SIZE) + + // // #define BLINKER_LINKDATA_SIZE 212 + + // #define BLINKER_ONE_AUTO_DATA_SIZE (BLINKER_AUTOID_SIZE + BLINKER_TYPESTATE_SIZE + \ + // (BLINKER_AUTODATA_SIZE + BLINKER_TARGETKEY_SIZE + \ + // BLINKER_TARGETDATA_SIZE) * 2)// + BLINKER_LINKDEVICE_SIZE + BLINKER_LINKTYPE_SIZE + BLINKER_LINKDATA_SIZE) * 2) + + // #define BLINKER_EEP_ADDR_AUTONUM_SUB (BLINKER_EEP_ADDR_OTA_CHECK + BLINKER_OTA_CHECK_SIZE) + + // #define BLINKER_AUTONUM_SUB_SIZE 1 + + // #define BLINKER_EEP_ADDR_AUTO_START_SUB (BLINKER_EEP_ADDR_AUTONUM_SUB + BLINKER_AUTONUM_SUB_SIZE) + + // //////////////////////////////////////////////////////////////////////////////////////// + + // #define BLINKER_EEP_ADDR_AUTOID_SUB 0 + + // #define BLINKER_AUTOID_SUB_SIZE 4 + +#endif + +#if defined(BLINKER_PRO) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_LOWPOWER_AIR202) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_WIFI_SUBDEVICE) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) || defined(BLINKER_WIFI) || \ + defined(BLINKER_MQTT) + + #ifndef BLINKER_BUTTON_PIN + #define BLINKER_BUTTON_PIN 2 + #endif + + #define BLINKER_CMD_REGISTER "register" + + #define BLINKER_DIY_DEVICE "DiyArduino" + + #define BLINKER_AIR_STATION "AirStation" + + #define BLINKER_AIR_DETECTOR "OwnAirdetector" + + #define BLINKER_SMART_PLUGIN "OwnPlug" + + #define BLINKER_SMART_LAMP "OwnLight" + + #ifndef BLINKER_PRO_VERSION + #define BLINKER_PRO_VERSION "1.0.0" + #endif + + // #define BLINKER_OTA_VERSION_CODE B00000001 + + // #define BLINKER_OTA_RUN B00000111 + + // #define BLINKER_OTA_START B01010011 + + // #define BLINKER_OTA_CLEAR B00000001 + + #define BLINKER_CHECK_AUTH_TIME 120000UL + + #define BLINKER_AUTH_CHECK_DATA 0x55 + + #define BLINKER_EEP_ADDR_SSID 1280 + + #define BLINKER_SSID_SIZE 32 + + #define BLINKER_EEP_ADDR_PSWD (BLINKER_EEP_ADDR_SSID + BLINKER_SSID_SIZE) + + #define BLINKER_PSWD_SIZE 32 + + #define BLINKER_EEP_ADDR_WLAN_CHECK (BLINKER_EEP_ADDR_PSWD + BLINKER_PSWD_SIZE) + + #define BLINKER_WLAN_CHECK_SIZE 3 + + #define BLINKER_EEP_ADDR_AUUID (BLINKER_EEP_ADDR_WLAN_CHECK + BLINKER_WLAN_CHECK_SIZE) + + #define BLINKER_AUUID_SIZE 34 + + #define BLINKER_EEP_ADDR_AUTH_CHECK (BLINKER_EEP_ADDR_AUUID + BLINKER_AUUID_SIZE) + + #define BLINKER_AUTH_CHECK_SIZE 1 + + #define BLINKER_EEP_ADDR_POWER_ON_COUNT (BLINKER_EEP_ADDR_AUTH_CHECK + BLINKER_AUTH_CHECK_SIZE) + + #define BLINKER_POWER_ON_COUNT_SIZE 1 + + #define BLINKER_PRO_DATA_SIZE (BLINKER_SSID_SIZE + BLINKER_PSWD_SIZE + BLINKER_WLAN_CHECK_SIZE + BLINKER_AUUID_SIZE + BLINKER_AUTH_CHECK_SIZE + BLINKER_POWER_ON_COUNT_SIZE) + + #define BLINKER_PRO_HELLO "{\"message\":\"Registration successful\"}" + + // #define BLINKER_EEP_ADDR_OTA_INFO (BLINKER_EEP_ADDR_AUTH_CHECK + BLINKER_AUTH_CHECK_SIZE) + + // #define BLINKER_OTA_INFO_SIZE 4 + + // #define BLINKER_EEP_ADDR_OTA_CHECK (BLINKER_EEP_ADDR_OTA_INFO + BLINKER_OTA_INFO_SIZE) + + // #define BLINKER_OTA_CHECK_SIZE 1 +#endif + +#ifndef BLINKER_OTA_VERSION_CODE + + #define BLINKER_OTA_VERSION_CODE "0.1.0" + +#endif + +#if defined(BLINKER_WIFI) || defined(BLINKER_MQTT) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_SUBDEVICE) || \ + defined(BLINKE_HTTP) + + // #ifndef BLINKER_OTA_VERSION_CODE + + // #define BLINKER_OTA_VERSION_CODE "0.1.0" + + // #endif + + #define BLINKER_OTA_RUN 1 + + #define BLINKER_OTA_START 2 + + #define BLINKER_OTA_CLEAR 0 + + #define BLINKER_EEP_ADDR_OTA_INFO 2436 + + #define BLINKER_OTA_INFO_SIZE 11 + + #define BLINKER_EEP_ADDR_OTA_CHECK (BLINKER_EEP_ADDR_OTA_INFO + BLINKER_OTA_INFO_SIZE) + + #define BLINKER_OTA_CHECK_SIZE 1 + +#endif + +#if defined(ESP8266) || defined(ESP32) + + #define BLINKER_ACTION_SIZE 30 + + #define BLINKER_ACTION_NUM 2 + + #define BLINKER_EEP_ADDR_TIMER 1536 + + #define BLINKER_EEP_ADDR_TIMER_COUNTDOWN BLINKER_EEP_ADDR_TIMER + + #define BLINKER_TIMER_COUNTDOWN_SIZE 4 + + #define BLINKER_EEP_ADDR_TIMER_COUNTDOWN_ACTION (BLINKER_EEP_ADDR_TIMER_COUNTDOWN + BLINKER_TIMER_COUNTDOWN_SIZE) + + #define BLINKER_TIMER_COUNTDOWN_ACTION_SIZE (BLINKER_ACTION_SIZE * BLINKER_ACTION_NUM) + + #define BLINKER_EEP_ADDR_TIMER_LOOP (BLINKER_EEP_ADDR_TIMER_COUNTDOWN_ACTION + BLINKER_TIMER_COUNTDOWN_ACTION_SIZE) + + #define BLINKER_TIMER_LOOP_SIZE 4 + + #define BLINKER_EEP_ADDR_TIMER_LOOP_TRI (BLINKER_EEP_ADDR_TIMER_LOOP + BLINKER_TIMER_LOOP_SIZE) + + #define BLINKER_TIMER_LOOP_TRI_SIZE 1 + + #define BLINKER_EEP_ADDR_TIMER_LOOP_ACTION1 (BLINKER_EEP_ADDR_TIMER_LOOP_TRI + BLINKER_TIMER_LOOP_TRI_SIZE) + + #define BLINKER_TIMER_LOOP_ACTION1_SIZE (BLINKER_ACTION_SIZE * BLINKER_ACTION_NUM) + + #define BLINKER_EEP_ADDR_TIMER_LOOP_ACTION2 (BLINKER_EEP_ADDR_TIMER_LOOP_ACTION1 + BLINKER_TIMER_LOOP_ACTION1_SIZE) + + #define BLINKER_TIMER_LOOP_ACTION2_SIZE (BLINKER_ACTION_SIZE * BLINKER_ACTION_NUM) + + #define BLINKER_EEP_ADDR_TIMER_TIMING_COUNT (BLINKER_EEP_ADDR_TIMER_LOOP_ACTION2 + BLINKER_TIMER_LOOP_ACTION2_SIZE) + + #define BLINKER_TIMER_TIMING_COUNT_SIZE 1 + + #define BLINKER_EEP_ADDR_TIMER_TIMING (BLINKER_EEP_ADDR_TIMER_TIMING_COUNT + BLINKER_TIMER_TIMING_COUNT_SIZE) + + #define BLINKER_TIMER_TIMING_SIZE 4 + + #define BLINKER_TIMER_TIMING_ACTION_SIZE (BLINKER_ACTION_SIZE * BLINKER_ACTION_NUM) + + #define BLINKER_ONE_TIMER_TIMING_SIZE (BLINKER_TIMER_TIMING_SIZE + BLINKER_TIMER_TIMING_ACTION_SIZE) + + #define BLINKER_EEP_ADDR_TIMER_ERASE 2430 + + #define BLINKER_TIMER_ERASE_SIZE 1 + + #define BLINKER_EEP_ADDR_TIMER_END (BLINKER_EEP_ADDR_TIMER_ERASE + BLINKER_TIMER_ERASE_SIZE) + + // 2 60 | 4 120 | 1 4 60 x 10 + 2 + 1 + // 793 896 + + + + #define BLINKER_EVENT_MSG_SMS 0 + + #define BLINKER_EVENT_MSG_PUSH 1 + + #define BLINKER_EVENT_KEY_SIZE 15 + + #define BLINKER_EVENT_NUM_SIZE 2 + + #define BLINKER_EEP_ADDR_EVENT (BLINKER_EEP_ADDR_TIMER_END + BLINKER_TIMER_ERASE_SIZE) + + #define BLINKER_EEP_ADDR_EVENTDATA BLINKER_EEP_ADDR_EVENT + + #define BLINKER_EVENTDATA_SIZE 1 + + // #define BLINKER_EEP_ADDR_EVENT_DATA1 (BLINKER_EEP_ADDR_EVENTDATA + BLINKER_EVENTDATA_SIZE) + + // #define BLINKER_EVENT_DATA1_SIZE 2 + + #define BLINKER_EEP_ADDR_EVENT_DATA (BLINKER_EEP_ADDR_EVENTDATA + BLINKER_EVENTDATA_SIZE) + + #define BLINKER_EVENT_DATA_SIZE 4 + + #define BLINKER_EEP_ADDR_EVENT_KEY1 (BLINKER_EEP_ADDR_EVENT_DATA + BLINKER_EVENT_DATA_SIZE) + + #define BLINKER_EVENT_KEY1_SIZE BLINKER_EVENT_KEY_SIZE + + // #define BLINKER_EEP_ADDR_EVENT_DATA2 (BLINKER_EEP_ADDR_EVENT_KEY1 + BLINKER_EVENT_KEY1_SIZE) + + #define BLINKER_EEP_ADDR_EVENT_KEY2 (BLINKER_EEP_ADDR_EVENT_KEY1 + BLINKER_EVENT_KEY1_SIZE) + + #define BLINKER_EVENT_KEY2_SIZE BLINKER_EVENT_KEY_SIZE + + #define BLINKER_EEP_ADDR_EVENT_MSG (BLINKER_EEP_ADDR_EVENT_KEY2 + BLINKER_EVENT_KEY2_SIZE) + + #define BLINKER_EVENT_MSG_SIZE 20 + + #define BLINKER_EEP_ADDR_EVENT_ERASE (BLINKER_EEP_ADDR_EVENT_MSG + BLINKER_EVENT_MSG_SIZE) + + #define BLINKER_EVENT_ERASE_SIZE 1 + + #define BLINKER_EEP_ADDR_EVENT_END (BLINKER_EEP_ADDR_EVENT_ERASE + BLINKER_EVENT_ERASE_SIZE) + + // 56 + + #define BLINKER_EEP_ADDR_SERIALCFG 2432 + + #define BLINKER_SERIALCFG_SIZE 4 + +#endif + +#if defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_LOWPOWER_AIR202) + + // http://www.openluat.com/Product/file/rda8955/AirM2M%20%E6%97%A0%E7%BA%BF%E6%A8%A1%E5%9D%97AT%E5%91%BD%E4%BB%A4%E6%89%8B%E5%86%8CV3.90.pdf + // http://www.openluat.com/Product/file/rda8955/%E8%BF%9E%E6%8E%A5%E9%98%BF%E9%87%8C%E4%BA%91AT%E6%B5%81%E7%A8%8B%E8%AF%B4%E6%98%8E%EF%BC%88%E4%B8%80%E6%9C%BA%E4%B8%80%E5%AF%86%E8%AE%A4%E8%AF%81%E6%96%B9%E6%A1%88%EF%BC%8CAT_S_TTS%E5%92%8CAT_S%E7%89%88%E6%9C%AC%E4%B8%8D%E6%94%AF%E6%8C%81%EF%BC%8CAT_S_SSL%E5%92%8CAT_S_NOTTS%E7%89%88%E6%9C%AC%E6%94%AF%E6%8C%81%EF%BC%89.pdf + + #define BLINKER_CMD_AT "AT" + + #define BLINKER_CMD_CGMMR_REQ "AT+CGMR" + + #define BLINKER_CMD_CGMMR_RESP "AirM2M_V5595_AT_S_SSL" + + #define BLINKER_CMD_CGATT "CGATT" + + #define BLINKER_CMD_CGQTT_REQ "AT+CGATT?" + + #define BLINEKR_CMD_SAPBR_REQ "AT+SAPBR" + // AT+SAPBR=,[,,] + + #define BLINKER_CMD_MCONFIG_REQ "AT+MCONFIG" + + #define BLINKER_CMD_SSLMIPSTART "AT+SSLMIPSTART" + + #define BLINKER_CMD_MCONNECT_REQ "AT+MCONNECT" + + #define BLINKER_CMD_CONNECT_OK "CONNECT OK" + + #define BLINKER_CMD_CONNACK_OK "CONNACK OK" + + #define BLINKER_CMD_CONNACK "CONNACK" + + #define BLINKER_CMD_MSUB_REQ "AT+MSUB" + + #define BLINKER_CMD_SUBACK "SUBACK" + + #define BLINKER_CMD_MQTTTMSGSET_REQ "AT+MQTTMSGSET" + + #define BLINKER_CMD_MPUB_REQ "AT+MPUB" + + #define BLINKER_CMD_MSUB "MSUB" + + #define BLINKER_CMD_PUBACK "PBACK" + + #define BLINKER_CMD_MQTTSTATU_REQ "AT+MQTTSTATU" + + #define BLINKER_CMD_MQTTSTATUS "MQTTSTATU " + + #define BLINKER_CMD_MIPCLOSE_REQ "AT+MIPCLOSE" + + #define BLINKER_CMD_CIPSHUT_REQ "AT+CIPSHUT" + + #define BLINKER_CMD_CSTT_REQ "AT+CSTT" + + #define BLINKER_CMD_CMNET "CMNET" + + #define BLINKER_CMD_CIICR_REQ "AT+CIICR" + + #define BLINKER_CMD_HTTPINIT_REQ "AT+HTTPINIT" + + #define BLINKER_CMD_HTTPPARA_REQ "AT+HTTPPARA" + + #define BLINKER_CMD_HTTPACTION_REQ "AT+HTTPACTION" + + #define BLINKER_CMD_HTTPACTION "HTTPACTION" + + #define BLINKER_CMD_HTTPREAD_REQ "AT+HTTPREAD" + + #define BLINKER_CMD_HTTPREAD "HTTPREAD" + + #define BLINKER_CMD_HTTPERM_REQ "AT+HTTPTERM" + + #define BLINKER_CMD_HTTPDATA_REQ "AT+HTTPDATA" + + #define BLINKER_CMD_DOWNLOAD "DOWNLOAD" + + #define BLINEKR_CMD_CGSN_REQ "AT+CGSN" + + #define BLINKER_CMD_ICCID_REQ "AT+ICCID" + + #define BLINKER_CMD_ICCID "ICCID" + + #define BLINEKR_CMD_CGSN "CGSN" + + #define BLINKER_CMD_MDISCONNECT_REQ "AT+MDISCONNECT" + + #define BLINKER_CMD_AMGSMLOC_REQ "AT+AMGSMLOC" + + #define BLINKER_CMD_AMGSMLOC "AMGSMLOC" + + #define BLINKER_CMD_CNTP_REQ "AT+CNTP" + + #define BLINKER_CMD_CNTP "CNTP" + + #define BLINKER_CMD_CCLK_REQ "AT+CCLK?" + + #define BLINKER_CMD_CCLK "CCLK" + +#endif + +#if defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + // http://www.simcom.com/upload/file/1547183713.pdf HTTP + // http://www.simcom.com/upload/file/1547183663.pdf MQTT + // http://www.simcom.com/upload/file/1547177595.pdf AT + + #define BLINKER_CMD_AT "AT" + + #define BLINKER_CMD_CPIN_REQ "AT+CPIN?" + + #define BLINKER_CMD_CPIN "CPIN" + + #define BLINKER_CMD_READY "READY" + + #define BLINKER_CMD_CSQ_REQ "AT+CSQ" + + #define BLINKER_CMD_CSQ "CSQ" + + #define BLINKER_CMD_CGREG_REQ "AT+CGREG?" + + #define BLINKER_CMD_CGREG "CGREG" + + #define BLINKER_CMD_CGACT_REQ "AT+CGACT?" + + #define BLINKER_CMD_CGACT "CGACT" + + #define BLINEKR_CMD_GSN_REQ "AT+GSN" + + #define BLINKER_CMD_COPS_REQ "AT+COPS?" + + #define BLINKER_CMD_COPS "COPS" + + #define BLINKER_CMD_CGCONTRDP_REQ "AT+CGCONTRDP" + + #define BLINKER_CMD_CGCONTRDP "CGCONTRDP" + + #define BLINKER_CMD_GSN_REQ "AT+GSN" + + #define BLINKER_CMD_CCID_REQ "AT+CCID" + + #define BLINKER_CMD_CSNTPSTART_REQ "AT+CSNTPSTART" + + #define BLINKER_CMD_CSNTPSTOP_REQ "AT+CSNTPSTOP" + + #define BLINKER_CMD_CSNTP "CSNTP" + + #define BLINKER_CMD_CHTTPCREATE_REQ "AT+CHTTPCREATE" + + #define BLINKER_CMD_CHTTPCREATE "CHTTPCREATE" + + #define BLINEKR_CMD_CHTTPCON_REQ "AT+CHTTPCON" + + #define BLINKER_CMD_CHTTPSEND_REQ "AT+CHTTPSEND" + + #define BLINKER_CMD_CHTTPNMIH "CHTTPNMIH" + + #define BLINKER_CMD_CHTTPNMIC "CHTTPNMIC" + + #define BLINKER_CMD_CHTTPDISCON_REQ "AT+CHTTPDISCON" + + #define BLINKER_CMD_CHTTPDESTROY_REQ "AT+CHTTPDESTROY" + + #define BLINKER_CMD_CMQNEW_REQ "AT+CMQNEW" + + #define BLINKER_CMD_CMQNEW "CMQNEW" + + #define BLINKER_CMD_CMQCON_REQ "AT+CMQCON" + + #define BLINKER_CMD_CMQCON "CMQCON" + + #define BLINKER_CMD_CMQSUB_REQ "AT+CMQSUB" + + #define BLINKER_CMD_CMQPUB_REQ "AT+CMQPUB" + + #define BLINKER_CMD_CMQPUB "CMQPUB" + + #define BLINKER_CMD_CMQDISCON_RESQ "AT+CMQDISCON" + + #define BLINKER_CMD_CMQDISCON "CMQDISCON" + + #define BLINKER_CMD_CRESET_RESQ "AT+CRESET" + + // AT+CMQNEW="public.iot-as-mqtt.cn-shanghai.aliyuncs.com","1883",12000,1024 + // +CMQNEW: 0 + // OK + // AT+CMQCON=0,3,"278669B20M25B642205N3CXP",600,0,0,"SFETga2UxKxN8jiqnNQg00105d5400","0ceed0bac52d4968b298e004be3dd496" + // OK + // AT+CMQSUB=0,"/JgCGbHlndgz/278669B20M25B642205N3CXP/r",0 + // OK + // +CMQPUB: 0,"/JgCGbHlndgz/278669B20M25B642205N3CXP/r",0,0,0,6,"313233" + +// #endif + +// #if defined(BLINKER_NBIOT_SIM7000) + + // #define BLINKER_CMD_AT "AT" + + #define BLINKER_CMD_SHCONF_REQ "AT+SHCONF" + + #define BLINKER_CMD_SHCONN_REQ "AT+SHCONN" + + #define BLINKER_CMD_SHSTATE_REQ "AT+SHSTATE" + + #define BLINKER_CMD_SHSTATE "SHSTATE" + + #define BLINKER_CMD_SHCHEAD_REQ "AT+SHCHEAD" + + #define BLINKER_CMD_SHAHEAD_REQ "AT+SHAHEAD" + + #define BLINKER_CMD_SHBOD_REQ "AT+SHBOD" + + #define BLINKER_CMD_SHREQ_REQ "AT+SHREQ" + + #define BLINKER_CMD_SHREQ "SHREQ" + + #define BLINKER_CMD_SHREAD_REQ "AT+SHREAD" + + #define BLINKER_CMD_SHREAD "SHREAD" + + #define BLINKER_CMD_SHBOD "SHBOD" + + #define BLINKER_CMD_SHDISC_REQ "AT+SHDISC" + + #define BLINKER_CMD_SMCONF_REQ "AT+SMCONF" + + #define BLINKER_CMD_SMCONN_REQ "AT+SMCONN" + + #define BLINKER_CMD_SMSUB_REQ "AT+SMSUB" + + #define BLINKER_CMD_SMUNSUB_REQ "AT+SMUNSUB" + + #define BLINKER_CMD_SMSUB "SMSUB" + + #define BLINKER_CMD_SMPUB_REQ "AT+SMPUB" + + #define BLINKER_CMD_SMDISC_REQ "AT+SMDISC" + + #define BLINKER_CMD_SMSTATE_REQ "AT+SMSTATE" + + #define BLINKER_CMD_SMSTATE "SMSTATE" + + #define BLINKER_CMD_CNTP_REQ "AT+CNTP" + + #define BLINKER_CMD_CNTP "CNTP" + + #define BLINKER_CMD_CNACT_REQ "AT+CNACT" + +#endif + +#endif diff --git a/blinker-library/src/Blinker/BlinkerDataTicker.h b/blinker-library/src/Blinker/BlinkerDataTicker.h new file mode 100644 index 0000000..0202291 --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerDataTicker.h @@ -0,0 +1,35 @@ +// #ifndef BlinkerDataTicker_H +// #define BlinkerDataTicker_H + +// #if defined(ESP8266) || defined(ESP32) + +// #include "Blinker/BlinkerConfig.h" +// #include "Blinker/BlinkerDebug.h" +// #include "Blinker/BlinkerTimer.h" + +// #include + +// Ticker dataTicker; + +// bool _dataTrigged = false; +// uint32_t _data_time = 60; + +// void dataInit(uint8_t mins, uint8_t seconds, uint32_t tickers = 60) +// { +// _data_time = tickers; + +// if (_data_time == 60) +// { +// uint32_t tTime = _data_time - seconds; +// dataTicker. +// } +// } + +// void dataHandle() +// { +// _dataTrigged = true; +// } + +// #endif + +// #endif diff --git a/blinker-library/src/Blinker/BlinkerDebug.cpp b/blinker-library/src/Blinker/BlinkerDebug.cpp new file mode 100644 index 0000000..4810b4d --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerDebug.cpp @@ -0,0 +1,129 @@ +#include "Blinker/BlinkerDebug.h" + +#include +#ifdef ESP8266 + extern "C" { + #include + #include + #include + } + #include +#else + #include +#endif + +#if defined(ARDUINO) + #if (defined(__AVR__)) + #include + #elif defined(ESP8266) || defined(ESP32) + #include + #endif +#endif + +uint32_t BLINKER_FreeHeap() +{ +#if defined(ARDUINO) + #if defined(ESP8266) || defined(ESP32) + return ESP.getFreeHeap(); +// #elif defined(ARDUINO) && defined(ESP32) +// return ESP.getFreeHeap(); + #elif defined(__AVR__) + extern int __heap_start, *__brkval; + int v; + return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); + #else + return 0; + #endif +#else + return 0; +#endif +} + +BlinkerDebug BLINKER_DEBUG; + +void BlinkerDebug::stream(Stream& s, blinker_debug_level_t level) +{ + isInit = true; + debugger = &s; + debug_level = level; +} + +void BlinkerDebug::time() +{ + if (debug_level != _debug_none) + { + debugger->print(BLINKER_DEBUG_F("[")); + debugger->print(millis()); + debugger->print(BLINKER_DEBUG_F("] ")); + } + return; +} + +// uint32_t BlinkerDebug::BLINKER_FreeHeap() +// { +// #if defined(ARDUINO) +// #if defined(ESP8266) || defined(ESP32) +// return ESP.getFreeHeap(); +// // #elif defined(ARDUINO) && defined(ESP32) +// // return ESP.getFreeHeap(); +// #elif defined(__AVR__) +// extern int __heap_start, *__brkval; +// int v; +// return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); +// #else +// return 0; +// #endif +// #else +// return 0; +// #endif +// } + +void BlinkerDebug::freeheap() +{ + if (debug_level != _debug_none) + { + // time(); + // debugger->print(BLINKER_DEBUG_F("Freeheap: ")); + debugger->println(BLINKER_FreeHeap()); + } + return; +} + +void BLINKER_LOG_TIME() +{ + if (BLINKER_DEBUG.isDebug()) + { + BLINKER_DEBUG.print(BLINKER_DEBUG_F("[")); + BLINKER_DEBUG.print(millis()); + BLINKER_DEBUG.print(BLINKER_DEBUG_F("] ")); + } + return; +} + +void BLINKER_LOG_FreeHeap() +{ + if (BLINKER_DEBUG.isDebug()) + { + BLINKER_LOG_TIME(); + BLINKER_DEBUG.print(BLINKER_DEBUG_F("Freeheap: ")); + BLINKER_DEBUG.freeheap(); + } + return; +} + +void BLINKER_LOG_FreeHeap_ALL() +{ + if (BLINKER_DEBUG.isDebugAll()) + { + BLINKER_LOG_TIME(); + BLINKER_DEBUG.print(BLINKER_DEBUG_F("Freeheap: ")); + BLINKER_DEBUG.freeheap(); + } + return; +} + +void BLINKER_LOG_T() +{ + if (BLINKER_DEBUG.isDebug()) BLINKER_DEBUG.println(); + return; +} diff --git a/blinker-library/src/Blinker/BlinkerDebug.h b/blinker-library/src/Blinker/BlinkerDebug.h new file mode 100644 index 0000000..ede8c2e --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerDebug.h @@ -0,0 +1,118 @@ +#ifndef BLINKER_DEBUG_H +#define BLINKER_DEBUG_H + +#if defined(ARDUINO) + #if ARDUINO >= 100 + #include + #else + #include + #endif +#endif + +#define BLINKER_DEBUG_F(s) F(s) +#define BLINKER_F(s) F(s) + +uint32_t BLINKER_FreeHeap(); + +class BlinkerDebug +{ + enum blinker_debug_level_t + { + _debug_none, + _debug_default, + _debug_all + }; + + public : + BlinkerDebug() + : isInit(false) + , debug_level(_debug_none) + {} + + // BlinkerDebug(Stream& s, blinker_debug_level_t level = _debug_default) + // : debugger(&s) + // , debug_level(level) + // {} + + void stream(Stream& s, blinker_debug_level_t level = _debug_default); + void debugAll() { debug_level = _debug_all; } + + void time(); + void freeheap(); + + bool isDebug() { return isInit ? debug_level != _debug_none : false; } + bool isDebugAll() { return isInit ? debug_level == _debug_all : false;} + + template + void print(T arg) { debugger->print(arg); } + + template + void println(T arg) { debugger->println(arg); } + void println() { debugger->println(); } + + private : + bool isInit; + Stream* debugger; + blinker_debug_level_t debug_level; + + // uint32_t BLINKER_FreeHeap(); +}; + +extern BlinkerDebug BLINKER_DEBUG; + +void BLINKER_LOG_TIME(); +void BLINKER_LOG_FreeHeap(); +void BLINKER_LOG_FreeHeap_ALL(); +extern void BLINKER_LOG_T(); + +/* BLINKER_LOG_T递归模板 */ +template +void BLINKER_LOG_T(T arg,Ts... args) +{ + if (BLINKER_DEBUG.isDebug()) + { + BLINKER_DEBUG.print(arg); + BLINKER_LOG_T(args...); + } + return; +} +/* BLINKER_LOG可变参数模板 */ +template +void BLINKER_LOG(Ts... args) +{ + BLINKER_LOG_TIME(); + BLINKER_LOG_T(args...); + return; +} +/* BLINKER_ERR_LOG可变参数模板 */ +template +void BLINKER_ERR_LOG(Ts... args) +{ + if (BLINKER_DEBUG.isDebug()) + { + BLINKER_LOG_TIME(); + BLINKER_DEBUG.print(BLINKER_DEBUG_F("ERROR: ")); + BLINKER_LOG_T(args...); + } + return; +} + +template +void BLINKER_LOG_ALL(Ts... args) +{ + if (BLINKER_DEBUG.isDebugAll()) + { + BLINKER_LOG_TIME(); + BLINKER_LOG_T(args...); + } + return; +} + +template +void BLINKER_ERR_LOG_ALL(Ts... args) +{ + if (BLINKER_DEBUG.isDebugAll()) { BLINKER_ERR_LOG(args...); } + return; +} + +#endif diff --git a/blinker-library/src/Blinker/BlinkerMQTTATBase.h b/blinker-library/src/Blinker/BlinkerMQTTATBase.h new file mode 100644 index 0000000..3ac92e0 --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerMQTTATBase.h @@ -0,0 +1,451 @@ +#ifndef BLINKER_MQTT_AT_BASE_H +#define BLINKER_MQTT_AT_BASE_H + +#if defined(ESP8266) || defined(ESP32) + +#include "BlinkerDebug.h" +#include "BlinkerConfig.h" +#include "BlinkerUtility.h" + +// extern uint32_t serialSet; + +// #if defined(ESP8266) +// extern SerialConfig ss_cfg; +// #elif defined(ESP32) +// extern uint32_t ss_cfg; +// #endif + +// #if defined(ESP8266) +// extern SerialConfig serConfig(); +// #elif defined(ESP32) +// extern uint32_t serConfig(); +// #endif + +uint8_t parseMode(uint8_t _mode, uint8_t _pullState); + +enum blinker_at_state_t { + AT_NONE, + AT_TEST, + AT_QUERY, + AT_SETTING, + AT_ACTION +}; + +enum blinker_at_status_t { + BL_BEGIN, + BL_INITED + // , + // BL_SUC, + // MQTT_WIFI_PSWD +}; + +enum blinker_at_serial_t { + SER_BAUD, + SER_DBIT, + SER_SBIT, + SER_PRIT +}; + +enum blinker_at_mqtt_t { + MQTT_CONFIG_MODE, + MQTT_AUTH_KEY, + MQTT_WIFI_SSID, + MQTT_WIFI_PSWD +}; + +enum blinker_at_aligenie_t { + ALI_NONE, + ALI_LIGHT, + ALI_OUTLET, + ALI_SENSOR +}; + +enum blinker_at_dueros_t { + DUER_NONE, + DUER_LIGHT, + DUER_OUTLET, + DUER_SENSOR +}; + +uint32_t serialSet = BLINKER_SERIAL_DEFAULT; + +#if defined(ESP8266) +SerialConfig ss_cfg; +#elif defined(ESP32) +uint32_t ss_cfg; +#endif + +#if defined(ESP8266) +SerialConfig serConfig() +#elif defined(ESP32) +uint32_t serConfig() +#endif +{ + uint8_t _bitSet = serialSet & 0xFF; + + switch (_bitSet) + { + case BLINKER_SERIAL_5N1 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_5N1")); + return SERIAL_5N1; + case BLINKER_SERIAL_6N1 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_6N1")); + return SERIAL_6N1; + case BLINKER_SERIAL_7N1 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_7N1")); + return SERIAL_7N1; + case BLINKER_SERIAL_8N1 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_8N1")); + return SERIAL_8N1; + case BLINKER_SERIAL_5N2 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_5N2")); + return SERIAL_5N2; + case BLINKER_SERIAL_6N2 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_6N2")); + return SERIAL_6N2; + case BLINKER_SERIAL_7N2 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_7N2")); + return SERIAL_7N2; + case BLINKER_SERIAL_8N2 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_8N2")); + return SERIAL_8N2; + case BLINKER_SERIAL_5E1 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_5E1")); + return SERIAL_5E1; + case BLINKER_SERIAL_6E1 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_6E1")); + return SERIAL_6E1; + case BLINKER_SERIAL_7E1 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_7E1")); + return SERIAL_7E1; + case BLINKER_SERIAL_8E1 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_8E1")); + return SERIAL_8E1; + case BLINKER_SERIAL_5E2 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_5E2")); + return SERIAL_5E2; + case BLINKER_SERIAL_6E2 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_6E2")); + return SERIAL_6E2; + case BLINKER_SERIAL_7E2 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_7E2")); + return SERIAL_7E2; + case BLINKER_SERIAL_8E2 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_8E2")); + return SERIAL_8E2; + case BLINKER_SERIAL_5O1 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_5O1")); + return SERIAL_5O1; + case BLINKER_SERIAL_6O1 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_6O1")); + return SERIAL_6O1; + case BLINKER_SERIAL_7O1 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_7O1")); + return SERIAL_7O1; + case BLINKER_SERIAL_8O1 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_8O1")); + return SERIAL_8O1; + case BLINKER_SERIAL_5O2 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_5O2")); + return SERIAL_5O2; + case BLINKER_SERIAL_6O2 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_6O2")); + return SERIAL_6O2; + case BLINKER_SERIAL_7O2 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_7O2")); + return SERIAL_7O2; + case BLINKER_SERIAL_8O2 : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_8O2")); + return SERIAL_8O2; + default : + BLINKER_LOG_ALL(BLINKER_F("SerialConfig SERIAL_8N1")); + return SERIAL_8N1; + } +} + +uint8_t parseMode(uint8_t _mode, uint8_t _pullState) +{ + uint8_t _modes = _mode << 4 | _pullState; + + switch(_modes) + { + case 0 << 4 | 0 : + return INPUT; + case 1 << 4 | 0 : + return OUTPUT; + case 0 << 4 | 1 : + return INPUT_PULLUP; + case 0 << 4 | 2 : +#if defined(ESP8266) + return INPUT_PULLDOWN_16; +#elif defined(ESP32) + return INPUT_PULLDOWN; +#endif + default : + return INPUT; + } +} + +class BlinkerSlaverAT +{ + public : + BlinkerSlaverAT() {} + + void update(const String & data) { + // _data = data; + // BLINKER_LOG(BLINKER_F("update data: "), data); + // _isAT = serialize(data); + serialize(data); + + BLINKER_LOG(BLINKER_F("serialize _set: "), _set); + // return _isAT; + } + + blinker_at_state_t state() { return _set; } + + String cmd() { return _atCmd; } + + uint8_t paramNum() { return _paramNum; } + + String getParam(uint8_t num) { + if (num >= _paramNum) return ""; + else return _param[num]; + } + + private : + // bool _isAT; + blinker_at_state_t _set; + uint8_t _paramNum; + // String _data; + String _atCmd; + String _param[6]; + + void serialize(const String & _data) { + BLINKER_LOG_ALL(BLINKER_F("serialize _data: "), _data); + + _paramNum = 0; + // _isAT = false; + _set = AT_NONE; + int addr_start = 0;//_data.indexOf("+"); + int addr_end = 0; + + String startCmd = _data.substring(0, 2); + BLINKER_LOG_ALL(BLINKER_F("startCmd: "), startCmd); + + // startCmd = _data.substring(0, 3); + // BLINKER_LOG(BLINKER_F("startCmd: "), startCmd); + + BLINKER_LOG_ALL(BLINKER_F("startCmd len: "), _data.length()); + + // BLINKER_LOG(BLINKER_F("serialize addr_start: "), addr_start); + // BLINKER_LOG(BLINKER_F("serialize addr_end: "), addr_end); + + // if ((addr_start != -1) && STRING_contains_string(_data, ":")) + if (startCmd == BLINKER_CMD_AT) + { + // _isAT = true; + + // if (_data.length() == 3) { + // _set = AT_ACTION; + // return true; + // } + + addr_start = 3; + // int addr_end1 = _data.indexOf("="); + // int addr_end2 = _data.indexOf("?"); + // int addr_end3 = _data.indexOf("\n"); + + // check "=" + addr_end = _data.indexOf("="); + BLINKER_LOG_ALL(BLINKER_F("serialize addr_end: "), addr_end); + if (addr_end != -1) + { + _set = AT_SETTING; + + _atCmd = _data.substring(addr_start, addr_end); + BLINKER_LOG_ALL(BLINKER_F("serialize _atCmd: "), _atCmd); + } + else + { + addr_end = _data.indexOf("?"); + BLINKER_LOG_ALL(BLINKER_F("serialize addr_end: "), addr_end); + if (addr_end != -1) + { + _set = AT_QUERY; + + _atCmd = _data.substring(addr_start, addr_end); + BLINKER_LOG_ALL(BLINKER_F("serialize _atCmd: "), _atCmd); + return; + } + else + { + addr_end = _data.indexOf("\r"); + BLINKER_LOG_ALL(BLINKER_F("serialize addr_end: "), addr_end); + if (addr_end != -1) + { + _set = AT_ACTION; + + if (addr_end == (addr_start-1)) { + _atCmd = startCmd; + BLINKER_LOG_ALL(BLINKER_F("serialize _atCmd: "), _atCmd); + return; + } + + _atCmd = _data.substring(addr_start, addr_end); + BLINKER_LOG_ALL(BLINKER_F("serialize _atCmd: "), _atCmd); + return; + } + else if (_data.length() == startCmd.length()) + { + _set = AT_ACTION; + + // if (addr_end == -1) { + _atCmd = startCmd; + BLINKER_LOG_ALL(BLINKER_F("serialize _atCmd: "), _atCmd); + return; + // } + + // _atCmd = _data.substring(addr_start, addr_end); + // BLINKER_LOG_ALL(BLINKER_F("serialize _atCmd: "), _atCmd); + // return; + } + else + { + _set = AT_ACTION; + + _atCmd = _data.substring(3, _data.length()); + BLINKER_LOG_ALL(BLINKER_F("serialize _atCmd: "), _atCmd); + return; + } + } + } + + // BLINKER_LOG(BLINKER_F("serialize _data: "), _data); + + String serData; + uint16_t dataLen; + if (_data.indexOf("\r") != -1) dataLen = _data.length() - 1; + else dataLen = _data.length(); + + addr_start = 0; + + for (_paramNum = 0; _paramNum < 11; _paramNum++) { + // if (addr_end != -1) + // { + addr_start += addr_end; + addr_start += 1; + // } + // else + // { + // addr_start = 3; + // } + + serData = _data.substring(addr_start, dataLen); + + addr_end = serData.indexOf(","); + + BLINKER_LOG_ALL(BLINKER_F("serialize serData: "), serData); + BLINKER_LOG_ALL(BLINKER_F("serialize addr_start: "), addr_start); + BLINKER_LOG_ALL(BLINKER_F("serialize addr_end: "), addr_end); + + if (addr_end == -1) { + if (addr_start >= dataLen) return; + + addr_end = serData.indexOf(" "); + + if (addr_end != -1) { + _param[_paramNum] = serData.substring(0, addr_end); + + if (_param[_paramNum] == "?" && _paramNum == 0) { + _set = AT_TEST; + } + BLINKER_LOG_ALL(BLINKER_F("_param0["), _paramNum, \ + BLINKER_F("]: "), _param[_paramNum]); + // BLINKER_LOG_ALL(BLINKER_F("_set: "), _set); + _paramNum++; + return; + } + + _param[_paramNum] = serData; + + if (_param[_paramNum] == "?" && _paramNum == 0) { + _set = AT_TEST; + } + BLINKER_LOG_ALL(BLINKER_F("_param1["), _paramNum, \ + BLINKER_F("]: "), _param[_paramNum]); + // BLINKER_LOG_ALL(BLINKER_F("_set: "), _set); + _paramNum++; + return; + } + else { + _param[_paramNum] = serData.substring(0, addr_end); + } + BLINKER_LOG_ALL(BLINKER_F("_param["), _paramNum, \ + BLINKER_F("]: "), _param[_paramNum]); + } + // return; + } + // else { + // // _isAT = false; + // return; + // } + } +}; + +enum atPin_t { + PIN_SET, + PIN_MODE, + PIN_PULLSTATE +}; + +enum atIO_t { + IO_PIN, + IO_LVL +}; + +class PinData +{ + public : + PinData(uint8_t _pin, uint8_t _mode, uint8_t _pullState) + { + // pin_num = _pin; + // pin_mode = _mode; + // pin_pull = _pullState; + _pinDatas = _pin << 8 | _mode << 4 | _pullState; + + pinMode(_pin, parseMode(_mode, _pullState)); + } + + uint8_t getPin() { return (_pinDatas >> 8 & 0xFF); } + uint8_t getMode() { return (_pinDatas >> 4 & 0x0F); } + uint8_t getPull() { return (_pinDatas & 0x0F); } + + String data() { + String _data = STRING_format(_pinDatas >> 8 & 0xFF) + "," + \ + STRING_format(_pinDatas >> 4 & 0x0F) + "," + \ + STRING_format(_pinDatas & 0x0F); + + return _data; + } + + bool checkPin(uint8_t _pin) { return (_pinDatas >> 8 & 0xFF) == _pin; } + + void fresh(uint8_t _mode, uint8_t _pullState) + { + _pinDatas = (_pinDatas >> 8 & 0xFF) << 8 | _mode << 4 | _pullState; + + pinMode((_pinDatas >> 8 & 0xFF) << 8, parseMode(_mode, _pullState)); + } + + private : + uint16_t _pinDatas; + // uint8_t pin_num; + // atPinMode_t pin_mode; + // atPull_t pin_pull; +}; +// static class BlinkerSlaverAT * _slaverAT; +// static class PinData * _pinData[BLINKER_MAX_PIN_NUM]; + +#endif + +#endif diff --git a/blinker-library/src/Blinker/BlinkerProtocol.h b/blinker-library/src/Blinker/BlinkerProtocol.h new file mode 100644 index 0000000..932f487 --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerProtocol.h @@ -0,0 +1,637 @@ +#ifndef BLINKER_PROTOCOL_H +#define BLINKER_PROTOCOL_H + +#include "BlinkerConfig.h" +#include "BlinkerDebug.h" +#include "BlinkerStream.h" +#include "BlinkerUtility.h" + +enum _blinker_state_t +{ + CONNECTING, + CONNECTED, + DISCONNECTED +}; + +class BlinkerProtocol +{ + public : + BlinkerProtocol() + : state(CONNECTING) + , isInit(false) + , isFresh(false) + , isAvail(false) + , availState(false) + , canParse(false) + {} + + void transport(BlinkerStream & bStream) { conn = &bStream; isInit = true; } + + // #if defined(BLINKER_LOWPOWER_AIR202) + // void print(const String & data); + // void print(const String & key, const String & data); + // char * deviceName() { if (isInit) return conn->deviceName(); else return ""; } + // char * authKey() { if (isInit) return conn->authKey(); else return ""; } + // int init() { return isInit ? conn->init() : false; } + // void begin(const char* _key, const char* _type, String _imei) + // { conn->begin(_key, _type, _imei); } + // int deviceRegister(){ return conn->deviceRegister(); } + // #else + int connect() { return isInit ? conn->connect() : false; } + int connected() + { + if (isInit) + { + // if (conn->connected()) + // { + // state == CONNECTED; + // return true; + // } + // else + // { + // state = DISCONNECTED; + // return false; + // } + return conn->connected(); + } + else + { + state = DISCONNECTED; + return false; + } + } + void disconnect() { if (isInit) { conn->disconnect(); state = DISCONNECTED; } } + // bool available() { if (availState) {availState = false; return true;} else return false; } + void flush(); + void checkState(bool state = true) { isCheck = state; } + void print(const String & data); + void print(const String & key, const String & data); + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_MQTT_AT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_SUBDEVICE) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) || defined(BLINKE_HTTP) + int aliPrint(const String & data) { return isInit ? conn->aliPrint(data) : false; } + int duerPrint(const String & data, bool report = false) { return isInit ? conn->duerPrint(data, report) : false; } + #if !defined(BLINKER_GPRS_AIR202) && !defined(BLINKER_NBIOT_SIM7020) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7020) && !defined(BLINKER_NBIOT_SIM7000) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7000) + int miPrint(const String & data) { return isInit ? conn->miPrint(data) : false; } + #endif + // void ping() { if (isInit) conn->ping(); } + #if !defined(BLINKER_MQTT_AT) + int bPrint(char * name, const String & data) { return isInit ? conn->bPrint(name, data) : false; } + int autoPrint(unsigned long id) { return isInit ? conn->autoPrint(id) : false; } + void sharers(const String & data) { if (isInit) conn->sharers(data); } + int needFreshShare() { if (isInit) return conn->needFreshShare(); else return false; } + #endif + #endif + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + int toServer(char * data) { return isInit ? conn->toServer(data) : false; } + char * deviceName() { if (isInit) return conn->deviceName(); else return ""; } + char * authKey() { if (isInit) return conn->authKey(); else return ""; } + char * token() { if (isInit) return conn->token(); else return ""; } + int init() { return isInit ? conn->init() : false; } + int mConnected() { return isInit ? conn->mConnected() : false; } + void freshAlive() { if (isInit) conn->freshAlive(); } + #endif + + #if defined(BLINKER_LOWPOWER_AIR202) + char * deviceName() { if (isInit) return conn->deviceName(); else return ""; } + char * authKey() { if (isInit) return conn->authKey(); else return ""; } + char * token() { if (isInit) return conn->token(); else return ""; } + int init() { return isInit ? conn->init() : false; } + void begin(const char* _key, const char* _type, String _imei) { conn->begin(_key, _type, _imei); } + int deviceRegister(){ return conn->deviceRegister(); } + #endif + + #if defined(BLINKER_PRO) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_WIFI_SUBDEVICE) + int deviceRegister(){ return conn->deviceRegister(); } + int authCheck() { return conn->authCheck(); } + #if defined(BLINKER_PRO) + void begin(const char* _deviceType) { conn->begin(_deviceType); } + #elif defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_WIFI_SUBDEVICE) + void begin(const char* _key, const char* _type) { conn->begin(_key, _type); } + #endif + #elif defined(BLINKER_GPRS_AIR202) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) + int deviceRegister(){ return conn->deviceRegister(); } + + #if defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + void begin(const char* _authKey, const char* _deviceType, String _imei) + { conn->begin(_authKey, _deviceType, _imei); } + #else + void begin(const char* _deviceType, String _imei) + { conn->begin(_deviceType, _imei); } + #endif + + #if defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) + int authCheck() { return conn->authCheck(); } + #endif + #endif + + // #if defined(BLINKER_WIFI_SUBDEVICE) + // void attachSubAvailable(blinker_callback_return_int_t func) + // { if (isInit) conn->attachAvailable(func); } + + // void attachSubRead(blinker_callback_return_string_t func) + // { if (isInit) conn->attachRead(func); } + + // void attachSubPrint(blinker_callback_with_string_arg_t func) + // { if (isInit) conn->attachPrint(func); } + + // void attachSubBegin(blinker_callback_t func) + // { if (isInit) conn->attachBegin(func); } + + // void attachSubConnect(blinker_callback_return_int_t func) + // { if (isInit) conn->attachConnect(func); } + + // void attachSubConnected(blinker_callback_return_int_t func) + // { if (isInit) conn->attachConnected(func); } + + // void attachSubDisconnect(blinker_callback_t func) + // { if (isInit) conn->attachDisconnect(func); } + // #endif + + #if defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_WIFI_SUBDEVICE) + void meshCheck() { conn->meshCheck(); } + #if !defined(BLINKER_WIFI_SUBDEVICE) + void setTimezone(float tz) { conn->setTimezone(tz); } + #endif + #if defined(BLINKER_WIFI_SUBDEVICE) + int subPrint(const String & data) { return conn->subPrint(data); } + int meshAvail() { return conn->meshAvail(); } + char * meshLastRead() { return conn->meshLastRead(); } + void meshFlush() { conn->meshFlush(); } + #endif + #endif + + #if defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) + void smartConfigType() { conn->setSmartConfig(); } + void apConfigType() { conn->setApConfig(); } + bool checkIsSmartConfig() { return conn->checkSmartConfig(); } + #endif + + #if defined(BLINKER_HTTP) + void subscribe() { conn->subscribe(); } + #endif + // #endif + private : + + protected : + BlinkerStream *conn; + _blinker_state_t state; + bool isInit; + bool isFresh; + bool isAvail; + bool availState; + bool canParse; + bool autoFormat = false; + bool isCheck = true; + uint32_t autoFormatFreshTime; + char* _sendBuf; + blinker_callback_with_string_arg_t _availableFunc = NULL; + + // #if defined(BLINKER_LOWPOWER_AIR202) + // void checkFormat(); + // void autoFormatData(const String & key, const String & jsonValue); + // #else + int checkAvail(); + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKE_HTTP) + bool checkAliAvail() { return conn->aligenieAvail(); } + bool checkDuerAvail() { return conn->duerAvail(); } + #if !defined(BLINKER_GPRS_AIR202) && !defined(BLINKER_NBIOT_SIM7020) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7020) && !defined(BLINKER_NBIOT_SIM7000) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7000) + bool checkMIOTAvail() { return conn->miAvail(); } + #endif + #endif + + #if defined(BLINKER_AT_MQTT) + void begin(const char* auth) { return conn->begin(auth); } + int serialAvailable() { return conn->serialAvailable(); } + int serialPrint(const String & s1, const String & s2, bool needCheck = true) + { return conn->serialPrint(s1, s2, needCheck); } + int serialPrint(const String & s, bool needCheck = true) + { return conn->serialPrint(s, needCheck); } + int mqttPrint(const String & data) + { return conn->mqttPrint(data); } + char * serialLastRead() { return conn->serialLastRead(); } + void aligenieType(blinker_at_aligenie_t _type) + { conn->aligenieType(_type); } + void duerType(blinker_at_dueros_t _type) + { conn->duerType(_type); } + char * deviceId() { return conn->deviceId(); } + char * uuid() { return conn->uuid(); } + void softAPinit() { conn->softAPinit(); } + void smartconfig() { conn->smartconfig(); } + int autoInit() { return conn->autoInit(); } + void connectWiFi(String _ssid, String _pswd) { return conn->connectWiFi(_ssid, _pswd); } + void connectWiFi(const char* _ssid, const char* _pswd) { return conn->connectWiFi(_ssid, _pswd); } + #endif + void checkFormat(); + void checkAutoFormat(); + char* dataParse() { if (canParse) return conn->lastRead(); else return ""; } + char* lastRead() { return conn->lastRead(); } + void isParsed() { BLINKER_LOG_ALL(BLINKER_F("isParsed")); flush(); } + int parseState() { return canParse; } + int printNow(); + void _timerPrint(const String & n); + int _print(char * n, bool needCheckLength = true); + + void autoFormatData(const String & key, const String & jsonValue); + // #endif +}; + +// #if !defined(BLINKER_LOWPOWER_AIR202) +void BlinkerProtocol::flush() +{ + if (isInit && isAvail) conn->flush(); + isAvail = false; + isFresh = false; + availState = false; + canParse = false; +} + +int BlinkerProtocol::checkAvail() +{ + if (!isInit) return false; + + flush(); + + if (connected()) + { + isAvail = conn->available(); + + if (isAvail) + { + BLINKER_LOG_ALL(BLINKER_F("checkAvail: "), isAvail); + + isFresh = true; + canParse = true; + availState = true; + } + } + + return isAvail; +} + +void BlinkerProtocol::checkAutoFormat() +{ + if (autoFormat) + { + if ((millis() - autoFormatFreshTime) >= BLINKER_MSG_AUTOFORMAT_TIMEOUT) + { + if (strlen(_sendBuf)) + { + // #if !defined(BLINKER_LOWPOWER_AIR202) + #if defined(BLINKER_ARDUINOJSON) + _print(_sendBuf); + #else + strcat(_sendBuf, "}"); + _print(_sendBuf); + #endif + // #endif + } + free(_sendBuf); + autoFormat = false; + BLINKER_LOG_FreeHeap_ALL(); + } + } +} + +int BlinkerProtocol::printNow() +{ + if (strlen(_sendBuf) && autoFormat) + { + int8_t print_state = BLINKER_ERROR; + #if defined(BLINKER_ARDUINOJSON) + if (_print(_sendBuf)) print_state = BLINKER_SUCCESS; + #else + strcat(_sendBuf, "}"); + if (_print(_sendBuf)) print_state = BLINKER_SUCCESS; + #endif + + free(_sendBuf); + autoFormat = false; + BLINKER_LOG_FreeHeap_ALL(); + + return print_state; + } + + return BLINKER_ERROR; +} + +void BlinkerProtocol::_timerPrint(const String & n) +{ + BLINKER_LOG_ALL(BLINKER_F("print: "), n); + + if (n.length() <= BLINKER_MAX_SEND_SIZE) + { + checkFormat(); + checkState(false); + strcpy(_sendBuf, n.c_str()); + } + else + { + BLINKER_ERR_LOG(BLINKER_F("SEND DATA BYTES MAX THAN LIMIT!")); + } +} + +int BlinkerProtocol::_print(char * n, bool needCheckLength) +{ + BLINKER_LOG_ALL(BLINKER_F("print: "), n); + + if (strlen(n) <= BLINKER_MAX_SEND_SIZE || \ + !needCheckLength) + { + // BLINKER_LOG_FreeHeap_ALL(); + BLINKER_LOG_ALL(BLINKER_F("Proto print...")); + BLINKER_LOG_FreeHeap_ALL(); + conn->print(n, isCheck); + if (!isCheck) isCheck = true; + + return true; + } + else { + BLINKER_ERR_LOG(BLINKER_F("SEND DATA BYTES MAX THAN LIMIT!")); + + return false; + } +} + +void BlinkerProtocol::print(const String & data) +{ + #if !defined(BLINKER_LOWPOWER_AIR202) + checkFormat(); + strcpy(_sendBuf, data.c_str()); + _print(_sendBuf); + free(_sendBuf); + autoFormat = false; + BLINKER_LOG_FreeHeap_ALL(); + #endif +} + +void BlinkerProtocol::print(const String & key, const String & data) +{ + checkFormat(); + autoFormatData(key, data); + if ((millis() - autoFormatFreshTime) >= BLINKER_MSG_AUTOFORMAT_TIMEOUT) + { + autoFormatFreshTime = millis(); + } +} + +void BlinkerProtocol::checkFormat() +{ + if (!autoFormat) + { + autoFormat = true; + _sendBuf = (char*)malloc(BLINKER_MAX_SEND_SIZE*sizeof(char)); + memset(_sendBuf, '\0', BLINKER_MAX_SEND_SIZE); + } +} + +void BlinkerProtocol::autoFormatData(const String & key, const String & jsonValue) +{ + #if defined(BLINKER_ARDUINOJSON) + BLINKER_LOG_ALL(BLINKER_F("autoFormatData key: "), key, \ + BLINKER_F(", json: "), jsonValue); + + String _data; + + if (STRING_contains_string(STRING_format(_sendBuf), key)) + { + + // DynamicJsonBuffer jsonSendBuffer; + DynamicJsonDocument jsonBuffer(1024); + + if (strlen(_sendBuf)) { + BLINKER_LOG_ALL(BLINKER_F("add")); + + // JsonObject& root = jsonSendBuffer.parseObject(STRING_format(_sendBuf)); + deserializeJson(jsonBuffer, STRING_format(_sendBuf)); + JsonObject root = jsonBuffer.as(); + + if (root.containsKey(key)) { + root.remove(key); + } + // root.printTo(_data); + serializeJson(root, _data); + + _data = _data.substring(0, _data.length() - 1); + + if (_data.length() > 4 ) _data += BLINKER_F(","); + _data += jsonValue; + _data += BLINKER_F("}"); + } + else { + BLINKER_LOG_ALL(BLINKER_F("new")); + + _data = BLINKER_F("{"); + _data += jsonValue; + _data += BLINKER_F("}"); + } + } + else { + _data = STRING_format(_sendBuf); + + if (_data.length()) + { + BLINKER_LOG_ALL(BLINKER_F("add.")); + + _data = _data.substring(0, _data.length() - 1); + + _data += BLINKER_F(","); + _data += jsonValue; + _data += BLINKER_F("}"); + } + else { + BLINKER_LOG_ALL(BLINKER_F("new.")); + + _data = BLINKER_F("{"); + _data += jsonValue; + _data += BLINKER_F("}"); + } + } + + if (_data.length() > BLINKER_MAX_SEND_BUFFER_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("FORMAT DATA SIZE IS MAX THAN LIMIT: "), BLINKER_MAX_SEND_BUFFER_SIZE); + return; + } + + strcpy(_sendBuf, _data.c_str()); + #else + String data; + + BLINKER_LOG_ALL(BLINKER_F("autoFormatData data: "), jsonValue); + BLINKER_LOG_ALL(BLINKER_F("strlen(_sendBuf): "), strlen(_sendBuf)); + BLINKER_LOG_ALL(BLINKER_F("data.length(): "), jsonValue.length()); + + if ((strlen(_sendBuf) + jsonValue.length()) >= BLINKER_MAX_SEND_BUFFER_SIZE) + { + BLINKER_ERR_LOG(BLINKER_F("FORMAT DATA SIZE IS MAX THAN LIMIT")); + return; + } + + if (strlen(_sendBuf) > 0) { + data = "," + jsonValue; + strcat(_sendBuf, data.c_str()); + } + else { + data = "{" + jsonValue; + strcpy(_sendBuf, data.c_str()); + } + #endif +} + +// #elif defined(BLINKER_LOWPOWER_AIR202) + +// void BlinkerProtocol::print(const String & data) +// { +// #if !defined(BLINKER_LOWPOWER_AIR202) +// checkFormat(); +// strcpy(_sendBuf, data.c_str()); +// _print(_sendBuf); +// free(_sendBuf); +// autoFormat = false; +// BLINKER_LOG_FreeHeap_ALL(); +// #endif +// } + +// void BlinkerProtocol::print(const String & key, const String & data) +// { +// checkFormat(); +// autoFormatData(key, data); +// if ((millis() - autoFormatFreshTime) >= BLINKER_MSG_AUTOFORMAT_TIMEOUT) +// { +// autoFormatFreshTime = millis(); +// } +// } + +// void BlinkerProtocol::checkFormat() +// { +// if (!autoFormat) +// { +// autoFormat = true; +// _sendBuf = (char*)malloc(BLINKER_MAX_SEND_SIZE*sizeof(char)); +// memset(_sendBuf, '\0', BLINKER_MAX_SEND_SIZE); +// } +// } + +// void BlinkerProtocol::autoFormatData(const String & key, const String & jsonValue) +// { +// #if defined(BLINKER_ARDUINOJSON) +// BLINKER_LOG_ALL(BLINKER_F("autoFormatData key: "), key, +// BLINKER_F(", json: "), jsonValue); + +// String _data; + +// if (STRING_contains_string(STRING_format(_sendBuf), key)) +// { + +// DynamicJsonBuffer jsonSendBuffer; + +// if (strlen(_sendBuf)) { +// BLINKER_LOG_ALL(BLINKER_F("add")); + +// JsonObject& root = jsonSendBuffer.parseObject(STRING_format(_sendBuf)); + +// if (root.containsKey(key)) { +// root.remove(key); +// } +// root.printTo(_data); + +// _data = _data.substring(0, _data.length() - 1); + +// if (_data.length() > 4 ) _data += BLINKER_F(","); +// _data += jsonValue; +// _data += BLINKER_F("}"); +// } +// else { +// BLINKER_LOG_ALL(BLINKER_F("new")); + +// _data = BLINKER_F("{"); +// _data += jsonValue; +// _data += BLINKER_F("}"); +// } +// } +// else { +// _data = STRING_format(_sendBuf); + +// if (_data.length()) +// { +// BLINKER_LOG_ALL(BLINKER_F("add.")); + +// _data = _data.substring(0, _data.length() - 1); + +// _data += BLINKER_F(","); +// _data += jsonValue; +// _data += BLINKER_F("}"); +// } +// else { +// BLINKER_LOG_ALL(BLINKER_F("new.")); + +// _data = BLINKER_F("{"); +// _data += jsonValue; +// _data += BLINKER_F("}"); +// } +// } + +// if (_data.length() > BLINKER_MAX_SEND_BUFFER_SIZE) +// { +// BLINKER_ERR_LOG(BLINKER_F("FORMAT DATA SIZE IS MAX THAN LIMIT: "), BLINKER_MAX_SEND_BUFFER_SIZE); +// return; +// } + +// strcpy(_sendBuf, _data.c_str()); +// #else +// String data; + +// BLINKER_LOG_ALL(BLINKER_F("autoFormatData data: "), jsonValue); +// BLINKER_LOG_ALL(BLINKER_F("strlen(_sendBuf): "), strlen(_sendBuf)); +// BLINKER_LOG_ALL(BLINKER_F("data.length(): "), jsonValue.length()); + +// if ((strlen(_sendBuf) + jsonValue.length()) >= BLINKER_MAX_SEND_BUFFER_SIZE) +// { +// BLINKER_ERR_LOG(BLINKER_F("FORMAT DATA SIZE IS MAX THAN LIMIT")); +// return; +// } + +// if (strlen(_sendBuf) > 0) { +// data = "," + jsonValue; +// strcat(_sendBuf, data.c_str()); +// } +// else { +// data = "{" + jsonValue; +// strcpy(_sendBuf, data.c_str()); +// } +// #endif +// } +// #endif + +#endif diff --git a/blinker-library/src/Blinker/BlinkerStream.h b/blinker-library/src/Blinker/BlinkerStream.h new file mode 100644 index 0000000..7cedbd3 --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerStream.h @@ -0,0 +1,178 @@ +#ifndef BLINKER_STREAM_H +#define BLINKER_STREAM_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +// #if defined(BLINKER_AT_MQTT) +// #include "Blinker/BlinkerMQTTATBase.h" +// #endif + +#include "BlinkerUtility.h" + +class BlinkerStream +{ + public : + // #if defined(BLINKER_LOWPOWER_AIR202) + // virtual void begin(const char* _key, const char* _deviceType, String _imei) = 0; + // virtual char * deviceName() = 0; + // virtual char * authKey() = 0; + // virtual int init() = 0; + // virtual int deviceRegister() = 0; + // #else + virtual int available() = 0; + virtual char * lastRead() = 0; + virtual void flush() = 0; + // virtual int print(const String & s, bool needCheck = true) = 0; + virtual int print(char * data, bool needCheck = true) = 0; + virtual int connect() = 0; + virtual int connected() = 0; + virtual void disconnect() = 0; + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_MQTT_AT) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_SUBDEVICE) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) || defined(BLINKE_HTTP) + virtual int aliPrint(const String & data) = 0; + virtual int duerPrint(const String & data, bool report = false) = 0; + #if !defined(BLINKER_GPRS_AIR202) && !defined(BLINKER_NBIOT_SIM7020) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7020) && !defined(BLINKER_NBIOT_SIM7000) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7000) + virtual int miPrint(const String & data) = 0; + #endif + // virtual void ping() = 0; + #if !defined(BLINKER_MQTT_AT) + virtual int bPrint(char * name, const String & data) = 0; + virtual int autoPrint(unsigned long id) = 0; + virtual void sharers(const String & data); + virtual int aligenieAvail() = 0; + virtual int duerAvail() = 0; + #if !defined(BLINKER_GPRS_AIR202) && !defined(BLINKER_NBIOT_SIM7020) && \ + !defined(BLINKER_PRO_SIM7020) && !defined(BLINKER_PRO_AIR202) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7020) && !defined(BLINKER_NBIOT_SIM7000) && \ + !defined(BLINKER_QRCODE_NBIOT_SIM7000) + virtual int miAvail() = 0; + #endif + virtual int needFreshShare() = 0; + #endif + #endif + + #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_GPRS_AIR202) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) || \ + defined(BLINKE_HTTP) + virtual int toServer(char * data) = 0; + virtual char * deviceName() = 0; + virtual char * authKey() = 0; + virtual char * token() = 0; + virtual int init() = 0; + virtual int mConnected() = 0; + virtual void freshAlive() = 0; + #endif + + #if defined(BLINKER_LOWPOWER_AIR202) + virtual char * deviceName() = 0; + virtual char * authKey() = 0; + virtual int init() = 0; + virtual void begin(const char* _key, const char* _type, String _imei) = 0; + virtual int deviceRegister() = 0; + #endif + + // #if defined(BLINKER_MQTT) || defined(BLINKER_PRO) + // virtual int aligenieAvail() = 0; + // virtual int duerAvail() = 0; + #if defined(BLINKER_AT_MQTT) + virtual void begin(const char* auth) = 0; + // virtual void begin() = 0; + virtual int serialAvailable() = 0; + virtual int serialPrint(const String & s1, const String & s2, bool needCheck = true) = 0; + virtual int serialPrint(const String & s, bool needCheck = true) = 0; + virtual int mqttPrint(const String & data); + virtual char * serialLastRead() = 0; + virtual void aligenieType(int _type) = 0; + virtual void duerType(int _type) = 0; + virtual char * deviceId() = 0; + virtual char * uuid() = 0; + virtual void softAPinit() = 0; + virtual void smartconfig() = 0; + virtual int autoInit() = 0; + virtual void connectWiFi(String _ssid, String _pswd) = 0; + virtual void connectWiFi(const char* _ssid, const char* _pswd) = 0; + #endif + + #if defined(BLINKER_PRO) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_WIFI_SUBDEVICE) + virtual int deviceRegister() = 0; + virtual int authCheck() = 0; + #if defined(BLINKER_PRO) + virtual void begin(const char* _deviceType) = 0; + #elif defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_WIFI_SUBDEVICE) + virtual void begin(const char* auth, const char* type) = 0; + #endif + #elif defined(BLINKER_GPRS_AIR202) || defined(BLINKER_NBIOT_SIM7020) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_NBIOT_SIM7000) || \ + defined(BLINKER_QRCODE_NBIOT_SIM7000) + virtual int deviceRegister() = 0; + + #if defined(BLINKER_QRCODE_NBIOT_SIM7020) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + virtual void begin(const char* _auth, const char* _type, String _imei) = 0; + #else + virtual void begin(const char* _type, String _imei) = 0; + #endif + + #if defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) + virtual int authCheck() = 0; + #endif + #endif + + #if defined(BLINKER_WIFI_GATEWAY) || defined(BLINKER_WIFI_SUBDEVICE) + virtual void meshCheck() = 0; + #if !defined(BLINKER_WIFI_SUBDEVICE) + virtual void setTimezone(float tz) = 0; + #endif + #if defined(BLINKER_WIFI_SUBDEVICE) + virtual int subPrint(const String & data) = 0; + virtual int meshAvail() = 0; + virtual char * meshLastRead() = 0; + virtual void meshFlush() = 0; + #endif + #endif + + #if defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) + virtual void setSmartConfig() = 0; + virtual void setApConfig() = 0; + virtual bool checkSmartConfig() = 0; + #endif + + #if defined(BLINKER_HTTP) + virtual void subscribe() = 0; + #endif + + // #if defined(BLINKER_WIFI_SUBDEVICE) + // virtual void attachAvailable(blinker_callback_return_int_t func) = 0; + // virtual void attachRead(blinker_callback_return_string_t func) = 0; + // virtual void attachPrint(blinker_callback_with_string_arg_t func) = 0; + // virtual void attachBegin(blinker_callback_t func) = 0; + // virtual void attachConnect(blinker_callback_return_int_t func) = 0; + // virtual void attachConnected(blinker_callback_return_int_t func) = 0; + // virtual void attachDisconnect(blinker_callback_t func) = 0; + // #endif + // #endif +}; + +#endif diff --git a/blinker-library/src/Blinker/BlinkerTimer.cpp b/blinker-library/src/Blinker/BlinkerTimer.cpp new file mode 100644 index 0000000..9e3508d --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerTimer.cpp @@ -0,0 +1,143 @@ +#if defined(ESP8266) || defined(ESP32) + +#include "BlinkerConfig.h" +#include "BlinkerDebug.h" +#include "BlinkerTimer.h" + +Ticker cdTicker; +Ticker lpTicker; +Ticker tmTicker; + +bool _cdRunState = false; +bool _lpRunState = false; +bool _tmRunState = false; +bool _cdState = false; +bool _lpState = false; +bool _tmState = false; +bool _lpRun1 = true; +bool _tmRun1 = true; +bool _tmDay = false; +bool _cdTrigged = false; +bool _lpTrigged = false; +bool _tmTrigged = false; +bool _isTimingLoop = false; + +uint8_t _lpTimes; +uint8_t _lpTrigged_times; + +uint32_t _cdTime1; +uint32_t _cdTime2; +uint32_t _cdStart; +uint32_t _cdData; +// bool _cdStop = true; + +uint32_t _lpTime1; +uint32_t _lpTime1_start; +uint32_t _lpTime2; +uint32_t _lpTime2_start; +uint32_t _lpData; +bool _lpStop = true; + +uint32_t _tmTime1; +uint32_t _tmTime2; +uint32_t _tmTime; +uint8_t _timingDay = 0; +uint8_t taskCount = 0; +uint8_t triggedTask = 0; + +void disableTimer() { + _cdRunState = false; + cdTicker.detach(); + _lpRunState = false; + lpTicker.detach(); + _tmRunState = false; + tmTicker.detach(); +} + +void _cd_callback() +{ + uint32_t cd_during = millis() -_cdStart; + uint32_t cd_remain = _cdTime1 * 60 - cd_during / 1000; + + if (_cdTime1 * 60 > BLINKER_ONE_HOUR_TIME) { + if (cd_remain > 0) { + if (cd_remain > BLINKER_ONE_HOUR_TIME) cd_remain = BLINKER_ONE_HOUR_TIME; + + cdTicker.once(cd_remain, _cd_callback); + + return; + } + } + // _cdState = false; + _cdTrigged = true; + + BLINKER_LOG_ALL(BLINKER_F("countdown trigged!")); +} + +void _lp_callback() +{ + if (_lpRun1) { + uint32_t lp_1_during = millis() -_lpTime1_start; + uint32_t lp_1_remain = _lpTime1 * 60 - lp_1_during / 1000; + + if (_lpTime1 * 60 > BLINKER_ONE_HOUR_TIME) { + if (lp_1_remain > 0) { + if (lp_1_remain > BLINKER_ONE_HOUR_TIME) lp_1_remain = BLINKER_ONE_HOUR_TIME; + + lpTicker.once(lp_1_remain, _lp_callback); + + return; + } + } + } + else { + uint32_t lp_2_during = millis() -_lpTime2_start; + uint32_t lp_2_remain = _lpTime2 * 60 - lp_2_during / 1000; + + if (_lpTime2 * 60 > BLINKER_ONE_HOUR_TIME) { + if (lp_2_remain > 0) { + if (lp_2_remain > BLINKER_ONE_HOUR_TIME) lp_2_remain = BLINKER_ONE_HOUR_TIME; + + lpTicker.once(lp_2_remain, _lp_callback); + + return; + } + } + } + + + _lpRun1 = !_lpRun1; + if (_lpRun1) { + _lpTrigged_times++; + + if (_lpTimes) { + if (_lpTimes == _lpTrigged_times && _lpTimes != 0) { + lpTicker.detach(); + _lpStop = true; + } + else { + lpTicker.once(_lpTime1 * 60, _lp_callback); + } + } + else { + lpTicker.once(_lpTime1 * 60, _lp_callback); + } + } + else { + lpTicker.once(_lpTime2 * 60, _lp_callback); + } + _lpTrigged = true; + + BLINKER_LOG_ALL(BLINKER_F("loop trigged!")); +} + +void timingHandle(uint8_t cbackData) +{ + uint8_t task = cbackData; + + _tmTrigged = true; + + triggedTask = task; +} + +#endif diff --git a/blinker-library/src/Blinker/BlinkerTimer.h b/blinker-library/src/Blinker/BlinkerTimer.h new file mode 100644 index 0000000..cc09ac2 --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerTimer.h @@ -0,0 +1,57 @@ +#ifndef BLINKER_TIMER_H +#define BLINKER_TIMER_H + +#if defined(ESP8266) || defined(ESP32) + +#include +#include + +extern Ticker cdTicker; +extern Ticker lpTicker; +extern Ticker tmTicker; + +extern bool _cdRunState; +extern bool _lpRunState; +extern bool _tmRunState; +extern bool _cdState; +extern bool _lpState; +extern bool _tmState; +extern bool _lpRun1; +extern bool _tmRun1; +extern bool _tmDay; +extern bool _cdTrigged; +extern bool _lpTrigged; +extern bool _tmTrigged; +extern bool _isTimingLoop; + +extern uint8_t _lpTimes; +extern uint8_t _lpTrigged_times; + +extern uint32_t _cdTime1; +extern uint32_t _cdTime2; +extern uint32_t _cdStart; +extern uint32_t _cdData; +// bool _cdStop = true; + +extern uint32_t _lpTime1; +extern uint32_t _lpTime1_start; +extern uint32_t _lpTime2; +extern uint32_t _lpTime2_start; +extern uint32_t _lpData; +extern bool _lpStop; + +extern uint32_t _tmTime1; +extern uint32_t _tmTime2; +extern uint32_t _tmTime; +extern uint8_t _timingDay; +extern uint8_t taskCount; +extern uint8_t triggedTask; + +void disableTimer(); +void _cd_callback(); +void _lp_callback(); +void timingHandle(uint8_t cbackData); + +#endif + +#endif diff --git a/blinker-library/src/Blinker/BlinkerUtility.cpp b/blinker-library/src/Blinker/BlinkerUtility.cpp new file mode 100644 index 0000000..d8c6040 --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerUtility.cpp @@ -0,0 +1,279 @@ +#include "BlinkerUtility.h" + +#if defined(ESP8266) +extern "C" { + #include +} + +String macDeviceName() +{ + uint8_t mac[6]; + char macStr[13] = { 0 }; + #define STATION_IF 0x00 + wifi_get_macaddr(STATION_IF, mac); + + sprintf(macStr, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + String macStr_l = STRING_format(macStr); + //macStr_l.toLowerCase(); + //BLINKER_LOG("MACADDR: ", macStr_l); + return macStr_l; +} +#elif defined(ESP32) +#include "esp_wifi.h" + +String macDeviceName() +{ + uint8_t mac[6]; + char macStr[13] = { 0 }; + // #define WIFI_IF_STA 0x00 + esp_wifi_get_mac(WIFI_IF_STA, mac); + + sprintf(macStr, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + String macStr_l = STRING_format(macStr); + //macStr_l.toLowerCase(); + //BLINKER_LOG("MACADDR: ", macStr_l); + return macStr_l; +} +#endif + + +// String deviceLocalIP() +// { +// uint8_t mac[4]; +// char macStr[13] = { 0 }; +// ips = WiFi.localIP(); + +// sprintf(macStr, "%d.%d.%d.%d", ips[0], ips[1], ips[2], ips[3]); +// String macStr_l = STRING_format(macStr); +// //macStr_l.toLowerCase(); +// //BLINKER_LOG("MACADDR: ", macStr_l); +// return macStr_l; +// } + +String STRING_find_string(const String & src, const String & targetStart, const String & targetEnd, uint8_t skipNum) { + int addr_start = src.indexOf(targetStart); + int addr_end; + if (targetEnd.length()) { + addr_end = src.indexOf(targetEnd, addr_start + targetStart.length() + skipNum); + } + else { + addr_end = src.length(); + } + + if (addr_start == -1 || addr_end == -1) { + return ""; + } + else { + return src.substring(addr_start + targetStart.length() + skipNum, addr_end); + } +} + +bool STRING_contains_string(const String & src, const String & key) +{ + int addr_start = src.indexOf(key); + uint8_t keyLen = key.length(); + + return key == src.substring(addr_start, addr_start + keyLen); +} + +bool STRING_find_string_value(const String & src, String & dst, const String & key) +{ + int addr_start = src.indexOf(key); + uint8_t keyLen = key.length(); + // BLINKER_LOG("addr_start: ", addr_start); + // BLINKER_LOG("keyLen: ", keyLen); + + int addr_end = src.indexOf(STRING_VALUE_END, addr_start + keyLen + STRING_VALUE_SKIP); + // BLINKER_LOG("addr_end: ", addr_end); + if (addr_start == -1 || addr_end == -1) { + return false; + } + else { + dst = src.substring(addr_start + keyLen + STRING_VALUE_SKIP, addr_end); + // BLINKER_LOG("dst: ", dst); + return true; + } +} + +int32_t STRING_find_numberic_value(const String & src, const String & key) +{ + int addr_start = src.indexOf(key); + uint8_t keyLen = key.length(); + + if ( key != src.substring(addr_start, addr_start + keyLen)) { + return FIND_KEY_VALUE_FAILED; + } + + int addr_end1 = src.indexOf(NUMBERIC_VALUE_END_1, addr_start + keyLen + NUMBERIC_VALUE_SKIP); + int addr_end2 = src.indexOf(NUMBERIC_VALUE_END_2, addr_start + keyLen + NUMBERIC_VALUE_SKIP); + int addr_end = BlinkerMin(addr_end1, addr_end2); + + if (addr_end == -1) { + addr_end = BlinkerMax(addr_end1, addr_end2); + } + + if (addr_start == -1 || addr_end == -1) { + return FIND_KEY_VALUE_FAILED; + } + else { + String value = src.substring(addr_start + keyLen + NUMBERIC_VALUE_SKIP, addr_end); + return value.toInt(); + } +} + +float STRING_find_float_value(const String & src, const String & key) +{ + int addr_start = src.indexOf(key); + uint8_t keyLen = key.length(); + + if ( key != src.substring(addr_start, addr_start + keyLen)) { + return FIND_KEY_VALUE_FAILED; + } + + int addr_end1 = src.indexOf(NUMBERIC_VALUE_END_1, addr_start + keyLen + NUMBERIC_VALUE_SKIP); + int addr_end2 = src.indexOf(NUMBERIC_VALUE_END_2, addr_start + keyLen + NUMBERIC_VALUE_SKIP); + int addr_end = BlinkerMin(addr_end1, addr_end2); + + if (addr_end == -1) { + addr_end = BlinkerMax(addr_end1, addr_end2); + } + + if (addr_start == -1 || addr_end == -1) { + return (float)FIND_KEY_VALUE_FAILED; + } + else { + String value = src.substring(addr_start + keyLen + NUMBERIC_VALUE_SKIP, addr_end); + return value.toFloat(); + } +} + +int32_t STRING_find_array_numberic_value(const String & src, const String & key, uint8_t num) +{ + int addr_start = src.indexOf(key); + uint8_t keyLen = key.length(); + + if ( key != src.substring(addr_start, addr_start + keyLen) ) { + return FIND_KEY_VALUE_FAILED; + } + + addr_start = addr_start + keyLen + ARRAY_NUMBERIC_VALUE_SKIP_START; + + if (num > 0) { + int value_start1, value_start2, temp; + + for (uint8_t times = 0; times < num; ++times) { + value_start1 = src.indexOf(ARRAY_NUMBERIC_VALUE_END_1, addr_start); + value_start2 = src.indexOf(ARRAY_NUMBERIC_VALUE_END_2, addr_start); + temp = BlinkerMin(value_start1, value_start2); + + if(temp == -1) { + temp = BlinkerMax(value_start1, value_start2); + } + + addr_start = temp + ARRAY_NUMBERIC_VALUE_SKIP_IN; + } + } + + int addr_end1 = src.indexOf(ARRAY_NUMBERIC_VALUE_END_1, addr_start); + int addr_end2 = src.indexOf(ARRAY_NUMBERIC_VALUE_END_2, addr_start); + int addr_end = BlinkerMin(addr_end1, addr_end2); + + if (addr_end == -1) { + addr_end = BlinkerMax(addr_end1, addr_end2); + } + + if (addr_start == -1 || addr_end == -1) { + return FIND_KEY_VALUE_FAILED; + } + else { + String value = src.substring(addr_start, addr_end); + return value.toInt(); + } +} + +float STRING_find_array_float_value(const String & src, const String & key, uint8_t num) +{ + int addr_start = src.indexOf(key); + uint8_t keyLen = key.length(); + + if ( key != src.substring(addr_start, addr_start + keyLen)) { + return FIND_KEY_VALUE_FAILED; + } + + addr_start = addr_start + keyLen + ARRAY_NUMBERIC_VALUE_SKIP_START; + + if (num > 0) { + int value_start1, value_start2, temp; + for (uint8_t times = 0; times < num; ++times) { + value_start1 = src.indexOf(ARRAY_NUMBERIC_VALUE_END_1, addr_start); + value_start2 = src.indexOf(ARRAY_NUMBERIC_VALUE_END_2, addr_start); + temp = BlinkerMin(value_start1, value_start2); + + if(temp == -1) { + temp = BlinkerMax(value_start1, value_start2); + } + + addr_start = temp + ARRAY_NUMBERIC_VALUE_SKIP_IN; + } + } + + int addr_end1 = src.indexOf(ARRAY_NUMBERIC_VALUE_END_1, addr_start); + int addr_end2 = src.indexOf(ARRAY_NUMBERIC_VALUE_END_2, addr_start); + int addr_end = BlinkerMin(addr_end1, addr_end2); + + if (addr_end == -1) { + addr_end = BlinkerMax(addr_end1, addr_end2); + } + + if (addr_start == -1 || addr_end == -1) { + return (float)FIND_KEY_VALUE_FAILED; + } + else { + String value = src.substring(addr_start, addr_end); + return value.toFloat(); + } +} + +String STRING_find_array_string_value(const String & src, const String & key, uint8_t num) +{ + int addr_start = src.indexOf(key); + uint8_t keyLen = key.length(); + + if ( key != src.substring(addr_start, addr_start + keyLen) ) { + return ""; + } + + addr_start = addr_start + keyLen + ARRAY_NUMBERIC_VALUE_SKIP_START; + + if (num > 0) { + int value_start1, value_start2, temp; + + for (uint8_t times = 0; times < num; ++times) { + value_start1 = src.indexOf(ARRAY_NUMBERIC_VALUE_END_1, addr_start); + value_start2 = src.indexOf(ARRAY_NUMBERIC_VALUE_END_2, addr_start); + temp = BlinkerMin(value_start1, value_start2); + + if(temp == -1) { + temp = BlinkerMax(value_start1, value_start2); + } + + addr_start = temp + ARRAY_NUMBERIC_VALUE_SKIP_IN; + } + } + + int addr_end1 = src.indexOf(ARRAY_NUMBERIC_VALUE_END_1, addr_start); + int addr_end2 = src.indexOf(ARRAY_NUMBERIC_VALUE_END_2, addr_start); + int addr_end = BlinkerMin(addr_end1, addr_end2); + + if (addr_end == -1) { + addr_end = BlinkerMax(addr_end1, addr_end2); + } + + if (addr_start == -1 || addr_end == -1) { + return ""; + } + else { + String value = src.substring(addr_start, addr_end); + return value; + } +} \ No newline at end of file diff --git a/blinker-library/src/Blinker/BlinkerUtility.h b/blinker-library/src/Blinker/BlinkerUtility.h new file mode 100644 index 0000000..68e394b --- /dev/null +++ b/blinker-library/src/Blinker/BlinkerUtility.h @@ -0,0 +1,194 @@ +#ifndef BlinkerUtility_H +#define BlinkerUtility_H + +#if defined(ARDUINO) + #if ARDUINO >= 100 + #include + #else + #include + #endif +#endif + +#define NUMBERIC_VALUE_SKIP 2 +#define ARRAY_NUMBERIC_VALUE_SKIP_START 3 +#define ARRAY_NUMBERIC_VALUE_SKIP_IN 1 +#define STRING_VALUE_SKIP 3 +#define NUMBERIC_VALUE_END_1 "," +#define NUMBERIC_VALUE_END_2 "}" +#define ARRAY_NUMBERIC_VALUE_END_1 "," +#define ARRAY_NUMBERIC_VALUE_END_2 "]" +#define STRING_VALUE_END "\"" + +#define FIND_KEY_VALUE_FAILED -1000 + +#if defined(BLINKER_ARDUINOJSON) || defined(BLINKER_PRO) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) + #ifndef ARDUINOJSON_VERSION_MAJOR + #include "modules/ArduinoJson/ArduinoJson.h" + #endif +#endif + +extern "C" { + // typedef void (*callbackFunction)(void); + + typedef void (*blinker_callback_t)(void); + typedef void (*blinker_callback_with_arg_t)(void*); + // typedef void (*blinker_callback_with_char_arg_t)(char*); + typedef void (*blinker_callback_with_string_arg_t)(const String & data); + typedef void (*blinker_callback_with_string_uint8_arg_t)(const String & data, uint8_t num); + typedef void (*blinker_callback_with_string_string_arg_t)(const String & data, const String & state); + typedef void (*blinker_callback_with_uint8_arg_t)(uint8_t data); + typedef void (*blinker_callback_with_int32_arg_t)(int32_t data); + typedef void (*blinker_callback_with_int32_uint8_arg_t)(int32_t data, uint8_t num); + typedef void (*blinker_callback_with_rgb_arg_t)(uint8_t r_data, uint8_t g_data, uint8_t b_data, uint8_t bright_data); + typedef void (*blinker_callback_with_joy_arg_t)(uint8_t x_data, uint8_t y_data); + typedef void (*blinker_callback_with_table_arg_t)(uint8_t data); + typedef String (*blinker_callback_return_string_t)(void); + #if defined(BLINKER_PRO) || defined(BLINKER_PRO_SIM7020) || \ + defined(BLINKER_PRO_AIR202) || defined(BLINKER_MQTT_AUTO) || \ + defined(BLINKER_PRO_ESP) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_WIFI_SUBDEVICE) + typedef bool (*blinker_callback_with_json_arg_t)(const JsonObject & data); + #endif + typedef int (*blinker_callback_return_int_t)(void); + // typedef void (*callback_with_bool_arg_t)(bool state); +} + +// enum blinker_at_aligenie_t +// { +// ALI_NONE, +// ALI_LIGHT, +// ALI_OUTLET, +// ALI_SENSOR +// }; + +#if defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_AT_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_NBIOT_SIM7020) || defined(BLINKER_GPRS_AIR202) || \ + defined(BLINKER_PRO_SIM7020) || defined(BLINKER_PRO_AIR202) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKER_WIFI_SUBDEVICE) || defined(BLINKER_QRCODE_NBIOT_SIM7020) || \ + defined(BLINKER_NBIOT_SIM7000) || defined(BLINKER_QRCODE_NBIOT_SIM7000) + class BlinkerSharer + { + public : + BlinkerSharer(const String & _uuid) + { + name = (char*)malloc((_uuid.length()+1)*sizeof(char)); + strcpy(name, _uuid.c_str()); + } + + char * uuid() { return name; } + + private : + char * name; + }; + + #if defined(BLINKER_WIFI_GATEWAY) + class BlinkerMeshSub + { + public : + BlinkerMeshSub(uint32_t nodeId) + { + _id = nodeId; + _authState = false; + _new = true; + } + + bool isNew() { return _new; } + + void state(bool st) { _new = st; } + + void auth(const String & name, const String & key, + const String & type, uint16_t vas) + { + _new = false; + _name = (char*)malloc((name.length()+1)*sizeof(char)); + strcpy(_name, name.c_str()); + _key = (char*)malloc((key.length()+1)*sizeof(char)); + strcpy(_key, key.c_str()); + _type = (char*)malloc((type.length()+1)*sizeof(char)); + strcpy(_type, type.c_str()); + _vas = vas; + + BLINKER_LOG_ALL("auth msg, name: ", _name, + ", key: ", _key, + ", type: ", _type, + ", vas: ", _vas); + } + + void authData(const String & key, const String & name) + { + _auth = (char*)malloc((key.length()+1)*sizeof(char)); + strcpy(_auth, key.c_str()); + _dId = (char*)malloc((name.length()+1)*sizeof(char)); + strcpy(_dId, name.c_str()); + + BLINKER_LOG_ALL("register msg, authKey: ", _auth, + ", deviceId: ", _dId); + + _authState = true; + } + + void freshAuth(bool authState) { _authState = authState; } + + bool isAuth() { return _authState; } + + char *name() { return _name; } + + char *key() { return _key; } + + char *type() { return _type; } + + char *authKey() { return _auth; } + + String deviceName() { return _dId; } + + uint32_t id() { return _id; } + + private : + uint32_t _id; + bool _authState; + bool _new; + char *_name; + char *_key; + char *_type; + uint16_t _vas = 0; + char *_auth; + char *_dId; + }; + #endif +#endif + +template +String STRING_format(T p) { return String(p); } + +#if defined(ESP8266) || defined(ESP32) +String macDeviceName(); +// #elif defined(ESP32) +// String macDeviceName(); +#endif + +template +const T& BlinkerMin(const T& a, const T& b) { return (b < a) ? b : a; } + +template +const T& BlinkerMax(const T& a, const T& b) { return (b < a) ? a : b; } + +String STRING_find_string(const String & src, const String & targetStart, const String & targetEnd, uint8_t skipNum); + +bool STRING_contains_string(const String & src, const String & key); + +bool STRING_find_string_value(const String & src, String & dst, const String & key); + +int32_t STRING_find_numberic_value(const String & src, const String & key); + +float STRING_find_float_value(const String & src, const String & key); + +int32_t STRING_find_array_numberic_value(const String & src, const String & key, uint8_t num); + +float STRING_find_array_float_value(const String & src, const String & key, uint8_t num); + +String STRING_find_array_string_value(const String & src, const String & key, uint8_t num); + +#endif diff --git a/blinker-library/src/BlinkerAssistant.h b/blinker-library/src/BlinkerAssistant.h new file mode 100644 index 0000000..f2f911c --- /dev/null +++ b/blinker-library/src/BlinkerAssistant.h @@ -0,0 +1,530 @@ +#ifndef BLINKER_ASSISTANT_H +#define BLINKER_ASSISTANT_H + +#if defined(BLINKER_ALIGENIE_LIGHT) + #if defined(BLINKER_ALIGENIE_OUTLET) + #undef BLINKER_ALIGENIE_OUTLET + #endif + + #if defined(BLINKER_ALIGENIE_MULTI_OUTLET) + #undef BLINKER_ALIGENIE_MULTI_OUTLET + #endif + + #if defined(BLINKER_ALIGENIE_SWITCH) + #undef BLINKER_ALIGENIE_SWITCH + #endif + + #if defined(BLINKER_ALIGENIE_SENSOR) + #undef BLINKER_ALIGENIE_SENSOR + #endif + + #if defined(BLINKER_ALIGENIE_FAN) + #undef BLINKER_ALIGENIE_FAN + #endif + + #if defined(BLINKER_ALIGENIE_AIRCONDITION) + #undef BLINKER_ALIGENIE_AIRCONDITION + #endif + + #define BLINKER_ALIGENIE +#elif defined(BLINKER_ALIGENIE_OUTLET) + #if defined(BLINKER_ALIGENIE_MULTI_OUTLET) + #undef BLINKER_ALIGENIE_MULTI_OUTLET + #endif + + #if defined(BLINKER_ALIGENIE_LIGHT) + #undef BLINKER_ALIGENIE_LIGHT + #endif + + #if defined(BLINKER_ALIGENIE_SWITCH) + #undef BLINKER_ALIGENIE_SWITCH + #endif + + #if defined(BLINKER_ALIGENIE_SENSOR) + #undef BLINKER_ALIGENIE_SENSOR + #endif + + #if defined(BLINKER_ALIGENIE_FAN) + #undef BLINKER_ALIGENIE_FAN + #endif + + #if defined(BLINKER_ALIGENIE_AIRCONDITION) + #undef BLINKER_ALIGENIE_AIRCONDITION + #endif + + #define BLINKER_ALIGENIE +#elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + #if defined(BLINKER_ALIGENIE_OUTLET) + #undef BLINKER_ALIGENIE_OUTLET + #endif + + #if defined(BLINKER_ALIGENIE_LIGHT) + #undef BLINKER_ALIGENIE_LIGHT + #endif + + #if defined(BLINKER_ALIGENIE_SWITCH) + #undef BLINKER_ALIGENIE_SWITCH + #endif + + #if defined(BLINKER_ALIGENIE_SENSOR) + #undef BLINKER_ALIGENIE_SENSOR + #endif + + #if defined(BLINKER_ALIGENIE_FAN) + #undef BLINKER_ALIGENIE_FAN + #endif + + #if defined(BLINKER_ALIGENIE_AIRCONDITION) + #undef BLINKER_ALIGENIE_AIRCONDITION + #endif + + #define BLINKER_ALIGENIE +#elif defined(BLINKER_ALIGENIE_SWITCH) + #if defined(BLINKER_ALIGENIE_LIGHT) + #undef BLINKER_ALIGENIE_LIGHT + #endif + + #if defined(BLINKER_ALIGENIE_OUTLET) + #undef BLINKER_ALIGENIE_OUTLET + #endif + + #if defined(BLINKER_ALIGENIE_MULTI_OUTLET) + #undef BLINKER_ALIGENIE_MULTI_OUTLET + #endif + + #if defined(BLINKER_ALIGENIE_SENSOR) + #undef BLINKER_ALIGENIE_SENSOR + #endif + + #if defined(BLINKER_ALIGENIE_FAN) + #undef BLINKER_ALIGENIE_FAN + #endif + + #if defined(BLINKER_ALIGENIE_AIRCONDITION) + #undef BLINKER_ALIGENIE_AIRCONDITION + #endif + + #define BLINKER_ALIGENIE +#elif defined(BLINKER_ALIGENIE_SENSOR) + #if defined(BLINKER_ALIGENIE_LIGHT) + #undef BLINKER_ALIGENIE_LIGHT + #endif + + #if defined(BLINKER_ALIGENIE_OUTLET) + #undef BLINKER_ALIGENIE_OUTLET + #endif + + #if defined(BLINKER_ALIGENIE_MULTI_OUTLET) + #undef BLINKER_ALIGENIE_MULTI_OUTLET + #endif + + #if defined(BLINKER_ALIGENIE_SWITCH) + #undef BLINKER_ALIGENIE_SWITCH + #endif + + #if defined(BLINKER_ALIGENIE_FAN) + #undef BLINKER_ALIGENIE_FAN + #endif + + #if defined(BLINKER_ALIGENIE_AIRCONDITION) + #undef BLINKER_ALIGENIE_AIRCONDITION + #endif + + #define BLINKER_ALIGENIE +#elif defined(BLINKER_ALIGENIE_FAN) + #if defined(BLINKER_ALIGENIE_LIGHT) + #undef BLINKER_ALIGENIE_LIGHT + #endif + + #if defined(BLINKER_ALIGENIE_OUTLET) + #undef BLINKER_ALIGENIE_OUTLET + #endif + + #if defined(BLINKER_ALIGENIE_MULTI_OUTLET) + #undef BLINKER_ALIGENIE_MULTI_OUTLET + #endif + + #if defined(BLINKER_ALIGENIE_SWITCH) + #undef BLINKER_ALIGENIE_SWITCH + #endif + + #if defined(BLINKER_ALIGENIE_SENSOR) + #undef BLINKER_ALIGENIE_SENSOR + #endif + + #if defined(BLINKER_ALIGENIE_AIRCONDITION) + #undef BLINKER_ALIGENIE_AIRCONDITION + #endif + + #define BLINKER_ALIGENIE +#elif defined(BLINKER_ALIGENIE_AIRCONDITION) + #if defined(BLINKER_ALIGENIE_LIGHT) + #undef BLINKER_ALIGENIE_LIGHT + #endif + + #if defined(BLINKER_ALIGENIE_OUTLET) + #undef BLINKER_ALIGENIE_OUTLET + #endif + + #if defined(BLINKER_ALIGENIE_MULTI_OUTLET) + #undef BLINKER_ALIGENIE_MULTI_OUTLET + #endif + + #if defined(BLINKER_ALIGENIE_SWITCH) + #undef BLINKER_ALIGENIE_SWITCH + #endif + + #if defined(BLINKER_ALIGENIE_SENSOR) + #undef BLINKER_ALIGENIE_SENSOR + #endif + + #if defined(BLINKER_ALIGENIE_FAN) + #undef BLINKER_ALIGENIE_FAN + #endif + + #define BLINKER_ALIGENIE +#endif + +#if defined(BLINKER_DUEROS_LIGHT) + #if defined(BLINKER_DUEROS_OUTLET) + #undef BLINKER_DUEROS_OUTLET + #endif + + #if defined(BLINKER_DUEROS_MULTI_OUTLET) + #undef BLINKER_DUEROS_MULTI_OUTLET + #endif + + #if defined(BLINKER_DUEROS_SWITCH) + #undef BLINKER_DUEROS_SWITCH + #endif + + #if defined(BLINKER_DUEROS_SENSOR) + #undef BLINKER_DUEROS_SENSOR + #endif + + #if defined(BLINKER_DUEROS_FAN) + #undef BLINKER_DUEROS_FAN + #endif + + #if defined(BLINKER_DUEROS_AIRCONDITION) + #undef BLINKER_DUEROS_AIRCONDITION + #endif + + #define BLINKER_DUEROS +#elif defined(BLINKER_DUEROS_OUTLET) + #if defined(BLINKER_DUEROS_MULTI_OUTLET) + #undef BLINKER_DUEROS_MULTI_OUTLET + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + #undef BLINKER_DUEROS_LIGHT + #endif + + #if defined(BLINKER_DUEROS_SWITCH) + #undef BLINKER_DUEROS_SWITCH + #endif + + #if defined(BLINKER_DUEROS_SENSOR) + #undef BLINKER_DUEROS_SENSOR + #endif + + #if defined(BLINKER_DUEROS_FAN) + #undef BLINKER_DUEROS_FAN + #endif + + #if defined(BLINKER_DUEROS_AIRCONDITION) + #undef BLINKER_DUEROS_AIRCONDITION + #endif + + #define BLINKER_DUEROS +#elif defined(BLINKER_DUEROS_MULTI_OUTLET) + #if defined(BLINKER_DUEROS_OUTLET) + #undef BLINKER_DUEROS_OUTLET + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + #undef BLINKER_DUEROS_LIGHT + #endif + + #if defined(BLINKER_DUEROS_SWITCH) + #undef BLINKER_DUEROS_SWITCH + #endif + + #if defined(BLINKER_DUEROS_SENSOR) + #undef BLINKER_DUEROS_SENSOR + #endif + + #if defined(BLINKER_DUEROS_FAN) + #undef BLINKER_DUEROS_FAN + #endif + + #if defined(BLINKER_DUEROS_AIRCONDITION) + #undef BLINKER_DUEROS_AIRCONDITION + #endif + + #define BLINKER_DUEROS +#elif defined(BLINKER_DUEROS_SENSOR) + #if defined(BLINKER_DUEROS_LIGHT) + #undef BLINKER_DUEROS_LIGHT + #endif + + #if defined(BLINKER_DUEROS_SWITCH) + #undef BLINKER_DUEROS_SWITCH + #endif + + #if defined(BLINKER_DUEROS_OUTLET) + #undef BLINKER_DUEROS_OUTLET + #endif + + #if defined(BLINKER_DUEROS_MULTI_OUTLET) + #undef BLINKER_DUEROS_MULTI_OUTLET + #endif + + #if defined(BLINKER_DUEROS_FAN) + #undef BLINKER_DUEROS_FAN + #endif + + #if defined(BLINKER_DUEROS_AIRCONDITION) + #undef BLINKER_DUEROS_AIRCONDITION + #endif + + #define BLINKER_DUEROS +#elif defined(BLINKER_DUEROS_FAN) + #if defined(BLINKER_DUEROS_LIGHT) + #undef BLINKER_DUEROS_LIGHT + #endif + + #if defined(BLINKER_DUEROS_SWITCH) + #undef BLINKER_DUEROS_SWITCH + #endif + + #if defined(BLINKER_DUEROS_OUTLET) + #undef BLINKER_DUEROS_OUTLET + #endif + + #if defined(BLINKER_DUEROS_MULTI_OUTLET) + #undef BLINKER_DUEROS_MULTI_OUTLET + #endif + + #if defined(BLINKER_DUEROS_SENSOR) + #undef BLINKER_DUEROS_SENSOR + #endif + + #if defined(BLINKER_DUEROS_AIRCONDITION) + #undef BLINKER_DUEROS_AIRCONDITION + #endif + + #define BLINKER_DUEROS +#elif defined(BLINKER_DUEROS_AIRCONDITION) + #if defined(BLINKER_DUEROS_LIGHT) + #undef BLINKER_DUEROS_LIGHT + #endif + + #if defined(BLINKER_DUEROS_SWITCH) + #undef BLINKER_DUEROS_SWITCH + #endif + + #if defined(BLINKER_DUEROS_OUTLET) + #undef BLINKER_DUEROS_OUTLET + #endif + + #if defined(BLINKER_DUEROS_MULTI_OUTLET) + #undef BLINKER_DUEROS_MULTI_OUTLET + #endif + + #if defined(BLINKER_DUEROS_SENSOR) + #undef BLINKER_DUEROS_SENSOR + #endif + + #if defined(BLINKER_DUEROS_FAN) + #undef BLINKER_DUEROS_FAN + #endif + + #define BLINKER_DUEROS +#endif + +#if defined(BLINKER_MIOT_LIGHT) + #if defined(BLINKER_MIOT_OUTLET) + #undef BLINKER_MIOT_OUTLET + #endif + + #if defined(BLINKER_MIOT_MULTI_OUTLET) + #undef BLINKER_MIOT_MULTI_OUTLET + #endif + + #if defined(BLINKER_MIOT_SWITCH) + #undef BLINKER_MIOT_SWITCH + #endif + + #if defined(BLINKER_MIOT_SENSOR) + #undef BLINKER_MIOT_SENSOR + #endif + + #if defined(BLINKER_MIOT_FAN) + #undef BLINKER_MIOT_FAN + #endif + + #if defined(BLINKER_MIOT_AIRCONDITION) + #undef BLINKER_MIOT_AIRCONDITION + #endif + + #define BLINKER_MIOT +#elif defined(BLINKER_MIOT_OUTLET) + #if defined(BLINKER_MIOT_MULTI_OUTLET) + #undef BLINKER_MIOT_MULTI_OUTLET + #endif + + #if defined(BLINKER_MIOT_LIGHT) + #undef BLINKER_MIOT_LIGHT + #endif + + #if defined(BLINKER_MIOT_SWITCH) + #undef BLINKER_MIOT_SWITCH + #endif + + #if defined(BLINKER_MIOT_SENSOR) + #undef BLINKER_MIOT_SENSOR + #endif + + #if defined(BLINKER_MIOT_FAN) + #undef BLINKER_MIOT_FAN + #endif + + #if defined(BLINKER_MIOT_AIRCONDITION) + #undef BLINKER_MIOT_AIRCONDITION + #endif + + #define BLINKER_MIOT +#elif defined(BLINKER_MIOT_MULTI_OUTLET) + #if defined(BLINKER_MIOT_OUTLET) + #undef BLINKER_MIOT_OUTLET + #endif + + #if defined(BLINKER_MIOT_LIGHT) + #undef BLINKER_MIOT_LIGHT + #endif + + #if defined(BLINKER_MIOT_SWITCH) + #undef BLINKER_MIOT_SWITCH + #endif + + #if defined(BLINKER_MIOT_SENSOR) + #undef BLINKER_MIOT_SENSOR + #endif + + #if defined(BLINKER_MIOT_FAN) + #undef BLINKER_MIOT_FAN + #endif + + #if defined(BLINKER_MIOT_AIRCONDITION) + #undef BLINKER_MIOT_AIRCONDITION + #endif + + #define BLINKER_MIOT +#elif defined(BLINKER_MIOT_SWITCH) + #if defined(BLINKER_MIOT_LIGHT) + #undef BLINKER_MIOT_LIGHT + #endif + + #if defined(BLINKER_MIOT_OUTLET) + #undef BLINKER_MIOT_OUTLET + #endif + + #if defined(BLINKER_MIOT_MULTI_OUTLET) + #undef BLINKER_MIOT_MULTI_OUTLET + #endif + + #if defined(BLINKER_MIOT_SENSOR) + #undef BLINKER_MIOT_SENSOR + #endif + + #if defined(BLINKER_MIOT_FAN) + #undef BLINKER_MIOT_FAN + #endif + + #if defined(BLINKER_MIOT_AIRCONDITION) + #undef BLINKER_MIOT_AIRCONDITION + #endif + + #define BLINKER_MIOT +#elif defined(BLINKER_MIOT_SENSOR) + #if defined(BLINKER_MIOT_LIGHT) + #undef BLINKER_MIOT_LIGHT + #endif + + #if defined(BLINKER_MIOT_OUTLET) + #undef BLINKER_MIOT_OUTLET + #endif + + #if defined(BLINKER_MIOT_MULTI_OUTLET) + #undef BLINKER_MIOT_MULTI_OUTLET + #endif + + #if defined(BLINKER_MIOT_SWITCH) + #undef BLINKER_MIOT_SWITCH + #endif + + #if defined(BLINKER_MIOT_FAN) + #undef BLINKER_MIOT_FAN + #endif + + #if defined(BLINKER_MIOT_AIRCONDITION) + #undef BLINKER_MIOT_AIRCONDITION + #endif + + #define BLINKER_MIOT +#elif defined(BLINKER_MIOT_FAN) + #if defined(BLINKER_MIOT_LIGHT) + #undef BLINKER_MIOT_LIGHT + #endif + + #if defined(BLINKER_MIOT_OUTLET) + #undef BLINKER_MIOT_OUTLET + #endif + + #if defined(BLINKER_MIOT_MULTI_OUTLET) + #undef BLINKER_MIOT_MULTI_OUTLET + #endif + + #if defined(BLINKER_MIOT_SWITCH) + #undef BLINKER_MIOT_SWITCH + #endif + + #if defined(BLINKER_MIOT_SENSOR) + #undef BLINKER_MIOT_SENSOR + #endif + + #if defined(BLINKER_MIOT_AIRCONDITION) + #undef BLINKER_MIOT_AIRCONDITION + #endif + + #define BLINKER_MIOT +#elif defined(BLINKER_MIOT_AIRCONDITION) + #if defined(BLINKER_MIOT_LIGHT) + #undef BLINKER_MIOT_LIGHT + #endif + + #if defined(BLINKER_MIOT_OUTLET) + #undef BLINKER_MIOT_OUTLET + #endif + + #if defined(BLINKER_MIOT_MULTI_OUTLET) + #undef BLINKER_MIOT_MULTI_OUTLET + #endif + + #if defined(BLINKER_MIOT_SWITCH) + #undef BLINKER_MIOT_SWITCH + #endif + + #if defined(BLINKER_MIOT_SENSOR) + #undef BLINKER_MIOT_SENSOR + #endif + + #if defined(BLINKER_MIOT_FAN) + #undef BLINKER_MIOT_FAN + #endif + + #define BLINKER_MIOT +#endif + +#endif diff --git a/blinker-library/src/BlinkerESP32BLE.h b/blinker-library/src/BlinkerESP32BLE.h new file mode 100644 index 0000000..321d53a --- /dev/null +++ b/blinker-library/src/BlinkerESP32BLE.h @@ -0,0 +1,32 @@ +#ifndef BLINKER_ESP32_BLE_H +#define BLINKER_ESP32_BLE_H + +#if defined(ESP32) + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerBLE.h" +#include "Blinker/BlinkerApi.h" + +typedef BlinkerApi BApi; + +class BlinkerESP32BLE : public BlinkerApi +{ + public : + void begin() + { + BApi::begin(); + Transp.begin(); + transport(Transp); + BLINKER_LOG("ESP32_BLE initialized..."); + } + + private : + BlinkerBLE Transp; +}; + +#endif + +#endif diff --git a/blinker-library/src/BlinkerESPGateway.h b/blinker-library/src/BlinkerESPGateway.h new file mode 100644 index 0000000..dd0bbc5 --- /dev/null +++ b/blinker-library/src/BlinkerESPGateway.h @@ -0,0 +1,32 @@ +#ifndef BLINKER_ESP_GATEWAY_H +#define BLINKER_ESP_GATEWAY_H + +#if defined(ESP8266) || defined(ESP32) + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerGateway.h" +#include "Blinker/BlinkerApi.h" + +typedef BlinkerApi BApi; + +class BlinkerESPGateway : public BlinkerApi +{ + public : + void begin(const char* _key, const char* _type) + { + transport(Transp); + BApi::begin(_key, _type); + BApi::loadTimer(); + BLINKER_LOG(BLINKER_F("ESP_Gateway initialized...")); + } + + private : + BlinkerGateway Transp; +}; + +#endif + +#endif diff --git a/blinker-library/src/BlinkerESPHTTP.h b/blinker-library/src/BlinkerESPHTTP.h new file mode 100644 index 0000000..6fe0ffc --- /dev/null +++ b/blinker-library/src/BlinkerESPHTTP.h @@ -0,0 +1,65 @@ +#ifndef BLINKER_ESP_HTTP_H +#define BLINKER_ESP_HTTP_H + +#if defined(ESP8266) || defined(ESP32) + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerHTTP.h" +#include "Blinker/BlinkerApi.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "modules/ArduinoJson/ArduinoJson.h" +#endif + +#if defined(ESP8266) + #include + #include + // #include +#elif defined(ESP32) + #include + #include + // #include +#endif + +typedef BlinkerApi BApi; + +class BlinkerESPHTTP : public BlinkerApi +{ + public : + #if defined(BLINKER_ESP_SMARTCONFIG) || defined(BLINKER_APCONFIG) + void begin(const char* _auth) + { + BApi::begin(); + Transp.begin(_auth); + + transport(Transp); + + #if defined(BLINKER_ESP_SMARTCONFIG) + Transp.smartconfigBegin(); + #elif defined(BLINKER_APCONFIG) + Transp.apconfigBegin(); + #endif + } + #else + void begin( const char* _auth, + const char* _ssid, + const char* _pswd ) + { + BApi::begin(); + Transp.begin(_auth); + + transport(Transp); + + Transp.commonBegin(_ssid, _pswd); + } + #endif + + private : + BlinkerHTTP Transp; +}; + +#endif + +#endif diff --git a/blinker-library/src/BlinkerESPMQTT.h b/blinker-library/src/BlinkerESPMQTT.h new file mode 100644 index 0000000..e946919 --- /dev/null +++ b/blinker-library/src/BlinkerESPMQTT.h @@ -0,0 +1,603 @@ +#ifndef BLINKER_ESP_MQTT_H +#define BLINKER_ESP_MQTT_H + +#if defined(ESP8266) || defined(ESP32) + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#if defined(ESP8266) + #ifndef BLINKER_WITH_SSL + #define BLINKER_WITHOUT_SSL + #endif +#endif + +#include "Adapters/BlinkerMQTT.h" +#include "Blinker/BlinkerApi.h" +#ifndef ARDUINOJSON_VERSION_MAJOR +#include "modules/ArduinoJson/ArduinoJson.h" +#endif + +#if defined(ESP8266) + #include + #include + // #include +#elif defined(ESP32) + #include + #include + // #include +#endif + +typedef BlinkerApi BApi; + +class BlinkerESPMQTT : public BlinkerApi +{ + public : + #if defined(BLINKER_ESP_SMARTCONFIG) || defined(BLINKER_APCONFIG) + void begin(const char* _auth) + { + #if defined(BLINKER_ALIGENIE_LIGHT) + String _aliType = BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + String _aliType = BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + String _aliType = BLINKER_F("&aliType=multi_outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + String _aliType = BLINKER_F("&aliType=sensor"); + #elif defined(BLINKER_ALIGENIE_FAN) + String _aliType = BLINKER_F("&aliType=fan"); + #elif defined(BLINKER_ALIGENIE_AIRCONDITION) + String _aliType = BLINKER_F("&aliType=aircondition"); + #else + String _aliType = BLINKER_F(""); + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + String _duerType = BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + String _duerType = BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_MULTI_OUTLET) + String _duerType = BLINKER_F("&duerType=MULTI_SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + String _duerType = BLINKER_F("&duerType=AIR_MONITOR"); + #elif defined(BLINKER_DUEROS_FAN) + String _duerType = BLINKER_F("&duerType=FAN"); + #elif defined(BLINKER_DUEROS_AIRCONDITION) + String _duerType = BLINKER_F("&duerType=AIR_CONDITION"); + #else + String _duerType = BLINKER_F(""); + #endif + + #if defined(BLINKER_MIOT_LIGHT) + String _miType = BLINKER_F("&miType=light"); + #elif defined(BLINKER_MIOT_OUTLET) + String _miType = BLINKER_F("&miType=outlet"); + #elif defined(BLINKER_MIOT_MULTI_OUTLET) + String _miType = BLINKER_F("&miType=multi_outlet"); + #elif defined(BLINKER_MIOT_SENSOR) + String _miType = BLINKER_F("&miType=sensor"); + #elif defined(BLINKER_MIOT_FAN) + String _miType = BLINKER_F("&miType=fan"); + #elif defined(BLINKER_MIOT_AIRCONDITION) + String _miType = BLINKER_F("&miType=aircondition"); + #else + String _miType = BLINKER_F(""); + #endif + + BApi::begin(); + + Transp.aliType(_aliType); + Transp.duerType(_duerType); + Transp.miType(_miType); + Transp.begin(_auth); + + transport(Transp); + + #if defined(BLINKER_ESP_SMARTCONFIG) + Transp.smartconfigBegin(); + #elif defined(BLINKER_APCONFIG) + Transp.apconfigBegin(); + #endif + + BApi::loadTimer(); + + // #if defined(BLINKER_ESP_SMARTCONFIG) + // smartconfigBegin(_auth, _aliType, _duerType); + // #elif defined(BLINKER_APCONFIG) + // apconfigBegin(_auth, _aliType, _duerType); + // #endif + + // __auth = _auth; + + // #ifndef BLINKER_ESP_TASK + // beginMQTT(); + // #endif + } + #else + void begin( const char* _auth, + const char* _ssid, + const char* _pswd ) + { + #if defined(BLINKER_ALIGENIE_LIGHT) + String _aliType = BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + String _aliType = BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) + String _aliType = BLINKER_F("&aliType=multi_outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + String _aliType = BLINKER_F("&aliType=sensor"); + #elif defined(BLINKER_ALIGENIE_FAN) + String _aliType = BLINKER_F("&aliType=fan"); + #elif defined(BLINKER_ALIGENIE_AIRCONDITION) + String _aliType = BLINKER_F("&aliType=aircondition"); + #else + String _aliType = BLINKER_F(""); + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + String _duerType = BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + String _duerType = BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_MULTI_OUTLET) + String _duerType = BLINKER_F("&duerType=MULTI_SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + String _duerType = BLINKER_F("&duerType=AIR_MONITOR"); + #elif defined(BLINKER_DUEROS_FAN) + String _duerType = BLINKER_F("&duerType=FAN"); + #elif defined(BLINKER_DUEROS_AIRCONDITION) + String _duerType = BLINKER_F("&duerType=AIR_CONDITION"); + #else + String _duerType = BLINKER_F(""); + #endif + + #if defined(BLINKER_MIOT_LIGHT) + String _miType = BLINKER_F("&miType=light"); + #elif defined(BLINKER_MIOT_OUTLET) + String _miType = BLINKER_F("&miType=outlet"); + #elif defined(BLINKER_MIOT_MULTI_OUTLET) + String _miType = BLINKER_F("&miType=multi_outlet"); + #elif defined(BLINKER_MIOT_SENSOR) + String _miType = BLINKER_F("&miType=sensor"); + #elif defined(BLINKER_MIOT_FAN) + String _miType = BLINKER_F("&miType=fan"); + #elif defined(BLINKER_MIOT_AIRCONDITION) + String _miType = BLINKER_F("&miType=aircondition"); + #else + String _miType = BLINKER_F(""); + #endif + + BApi::begin(); + + Transp.aliType(_aliType); + Transp.duerType(_duerType); + Transp.miType(_miType); + Transp.begin(_auth); + + transport(Transp); + + #if defined(BLINKER_WIFI_MULTI) + Transp.multiBegin(_ssid, _pswd); + #else + Transp.commonBegin(_ssid, _pswd); + #endif + BApi::loadTimer(); + // __auth = _auth; + // __ssid = _ssid; + // __pswd = _pswd; + + // #ifndef BLINKER_ESP_TASK + // beginMQTT(); + // #endif + } + #endif + + #if defined(BLINKER_WIFI_MULTI) + void addAP( const char* _ssid, + const char* _pswd) + { + BLINKER_LOG(BLINKER_F("wifiMulti add "), _ssid); + wifiMulti.addAP(_ssid, _pswd); + } + + void existAP( const char* _ssid, + const char* _pswd) + { + BLINKER_LOG(BLINKER_F("wifiMulti existAP "), _ssid); + wifiMulti.existsAP(_ssid, _pswd); + } + + void cleanAPlist() + { + wifiMulti.cleanAPlist(); + } + #endif + // void beginMQTT() + // { + // #if defined(BLINKER_ALIGENIE_LIGHT) + // String _aliType = BLINKER_F("&aliType=light"); + // #elif defined(BLINKER_ALIGENIE_OUTLET) + // String _aliType = BLINKER_F("&aliType=outlet"); + // #elif defined(BLINKER_ALIGENIE_SENSOR) + // String _aliType = BLINKER_F("&aliType=sensor"); + // #else + // String _aliType = BLINKER_F(""); + // #endif + + // #if defined(BLINKER_DUEROS_LIGHT) + // String _duerType = BLINKER_F("&duerType=LIGHT"); + // #elif defined(BLINKER_DUEROS_OUTLET) + // String _duerType = BLINKER_F("&duerType=SOCKET"); + // #elif defined(BLINKER_DUEROS_SENSOR) + // String _duerType = BLINKER_F("&duerType=AIR_MONITOR"); + // #else + // String _duerType = BLINKER_F(""); + // #endif + + // #if defined(BLINKER_ESP_SMARTCONFIG) + // smartconfigBegin(__auth, _aliType, _duerType); + // #elif defined(BLINKER_APCONFIG) + // apconfigBegin(__auth, _aliType, _duerType); + // #else + // commonBegin(__auth, __ssid, __pswd, _aliType, _duerType); + // #endif + // } + + private : + // void commonBegin(const char* _auth, + // const char* _ssid, + // const char* _pswd, + // String & _alitype, + // String & _duertype); + // void smartconfigBegin(const char* _auth, String & _alitype, String & _duertype); + // void apconfigBegin(const char* _auth, String & _alitype, String & _duertype); + + // bool autoInit(); + // void smartconfig(); + // void softAPinit(); + // // void serverClient(); + // bool parseUrl(String data); + + // void connectWiFi(String _ssid, String _pswd); + // void connectWiFi(const char* _ssid, const char* _pswd); + + // const char* __auth; + // const char* __ssid; + // const char* __pswd; + + BlinkerMQTT Transp; +}; + +// void BlinkerESPMQTT::commonBegin(const char* _auth, +// const char* _ssid, +// const char* _pswd, +// String & _alitype, +// String & _duertype) +// { +// BApi::begin(); +// connectWiFi(_ssid, _pswd); +// // BApi::loadOTA(); +// Transp.aliType(_alitype); +// Transp.duerType(_duertype); +// Transp.begin(_auth); +// transport(Transp); +// BApi::loadTimer(); + +// #if defined(ESP8266) +// BLINKER_LOG(BLINKER_F("ESP8266_MQTT initialized...")); +// #elif defined(ESP32) +// BLINKER_LOG(BLINKER_F("ESP32_MQTT initialized...")); +// #endif +// } + +// void BlinkerESPMQTT::smartconfigBegin(const char* _auth, String & _alitype, +// String & _duertype) +// { +// BApi::begin(); +// if (!autoInit()) smartconfig(); +// // BApi::loadOTA(); +// Transp.aliType(_alitype); +// Transp.duerType(_duertype); +// Transp.begin(_auth); +// transport(Transp); +// BApi::loadTimer(); + +// #if defined(ESP8266) +// BLINKER_LOG(BLINKER_F("ESP8266_MQTT initialized...")); +// #elif defined(ESP32) +// BLINKER_LOG(BLINKER_F("ESP32_MQTT initialized...")); +// #endif +// } + +// void BlinkerESPMQTT::apconfigBegin(const char* _auth, String & _alitype, +// String & _duertype) +// { +// BApi::begin(); +// if (!autoInit()) +// { +// softAPinit(); +// // while(WiFi.status() != WL_CONNECTED) +// // { +// // serverClient(); +// // ::delay(10); +// // } +// } +// // BApi::loadOTA(); + +// Transp.aliType(_alitype); +// Transp.duerType(_duertype); +// Transp.begin(_auth); +// transport(Transp); +// BApi::loadTimer(); + +// #if defined(ESP8266) +// BLINKER_LOG(BLINKER_F("ESP8266_MQTT initialized...")); +// #elif defined(ESP32) +// BLINKER_LOG(BLINKER_F("ESP32_MQTT initialized...")); +// #endif +// } + +// bool BlinkerESPMQTT::autoInit() +// { +// WiFi.mode(WIFI_STA); +// String _hostname = BLINKER_F("DiyArduino_"); +// _hostname += macDeviceName(); + +// #if defined(ESP8266) +// WiFi.hostname(_hostname.c_str()); +// #elif defined(ESP32) +// WiFi.setHostname(_hostname.c_str()); +// #endif + +// WiFi.begin(); +// ::delay(500); + +// BLINKER_LOG(BLINKER_F("Waiting for WiFi "), +// BLINKER_WIFI_AUTO_INIT_TIMEOUT / 1000, +// BLINKER_F("s, will enter SMARTCONFIG or "), +// BLINKER_F("APCONFIG while WiFi not connect!")); + +// uint8_t _times = 0; +// while (WiFi.status() != WL_CONNECTED) { +// ::delay(500); +// if (_times > BLINKER_WIFI_AUTO_INIT_TIMEOUT / 500) break; +// _times++; +// } + +// if (WiFi.status() != WL_CONNECTED) return false; +// else { +// BLINKER_LOG(BLINKER_F("WiFi Connected.")); +// BLINKER_LOG(BLINKER_F("IP Address: ")); +// BLINKER_LOG(WiFi.localIP()); + +// return true; +// } +// } + +// void BlinkerESPMQTT::smartconfig() +// { +// WiFi.mode(WIFI_STA); +// String _hostname = BLINKER_F("DiyArduino_"); +// _hostname += macDeviceName(); + +// #if defined(ESP8266) +// WiFi.hostname(_hostname.c_str()); +// #elif defined(ESP32) +// WiFi.setHostname(_hostname.c_str()); +// #endif + +// WiFi.beginSmartConfig(); + +// BLINKER_LOG(BLINKER_F("Waiting for SmartConfig.")); +// while (!WiFi.smartConfigDone()) { +// ::delay(500); +// } + +// BLINKER_LOG(BLINKER_F("SmartConfig received.")); + +// BLINKER_LOG(BLINKER_F("Waiting for WiFi")); +// while (WiFi.status() != WL_CONNECTED) { +// ::delay(500); +// } + +// BLINKER_LOG(BLINKER_F("WiFi Connected.")); + +// BLINKER_LOG(BLINKER_F("IP Address: ")); +// BLINKER_LOG(WiFi.localIP()); +// } + +// void BlinkerESPMQTT::softAPinit() +// { +// WiFiServer _server(80); +// WiFiClient _client; +// IPAddress apIP(192, 168, 4, 1); +// #if defined(ESP8266) +// IPAddress netMsk(255, 255, 255, 0); +// #endif + +// // _server = new WiFiServer(80); + +// WiFi.mode(WIFI_AP); +// String softAP_ssid = BLINKER_F("DiyArduino_"); +// softAP_ssid += macDeviceName(); + +// #if defined(ESP8266) +// WiFi.hostname(softAP_ssid.c_str()); +// WiFi.softAPConfig(apIP, apIP, netMsk); +// #elif defined(ESP32) +// WiFi.setHostname(softAP_ssid.c_str()); +// WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); +// #endif + +// WiFi.softAP(softAP_ssid.c_str(), ("12345678")); +// delay(100); + +// _server.begin(); +// BLINKER_LOG(BLINKER_F("AP IP address: "), WiFi.softAPIP()); +// BLINKER_LOG(BLINKER_F("HTTP _server started")); +// BLINKER_LOG(BLINKER_F("URL: http://"), WiFi.softAPIP()); + +// while(WiFi.status() != WL_CONNECTED) +// { +// // serverClient(); +// _client = _server.available(); +// // if (_client.status() == CLOSED) +// if (!_client.connected()) +// { +// _client.stop(); +// BLINKER_LOG(BLINKER_F("Connection closed on _client")); +// } +// else +// { +// if (_client.available()) +// { +// String data = _client.readStringUntil('\r'); + +// // data = data.substring(4, data.length() - 9); +// _client.flush(); + +// BLINKER_LOG(BLINKER_F("clientData: "), data); + +// if (STRING_contains_string(data, "ssid") && +// STRING_contains_string(data, "pswd")) +// { +// String msg = BLINKER_F("{\"hello\":\"world\"}"); + +// String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); +// s += BLINKER_F("Content-Type: application/json;"); +// s += BLINKER_F("charset=utf-8\r\n"); +// s += BLINKER_F("Content-Length: "); +// s += String(msg.length()); +// s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); +// s += msg; +// s += BLINKER_F("\r\n"); + +// _client.print(s); + +// _client.stop(); + +// parseUrl(data); +// } +// } +// } +// ::delay(10); +// } +// } + +// // void BlinkerESPMQTT::serverClient() +// // { +// // if (!_client) +// // { +// // _client = _server->available(); +// // } +// // else +// // { +// // // if (_client.status() == CLOSED) +// // if (!_client.connected()) +// // { +// // _client.stop(); +// // BLINKER_LOG(BLINKER_F("Connection closed on _client")); +// // } +// // else +// // { +// // if (_client.available()) +// // { +// // String data = _client.readStringUntil('\r'); + +// // // data = data.substring(4, data.length() - 9); +// // _client.flush(); + +// // BLINKER_LOG(BLINKER_F("clientData: "), data); + +// // if (STRING_contains_string(data, "ssid") && +// // STRING_contains_string(data, "pswd")) +// // { +// // String msg = BLINKER_F("{\"hello\":\"world\"}"); + +// // String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); +// // s += BLINKER_F("Content-Type: application/json;"); +// // s += BLINKER_F("charset=utf-8\r\n"); +// // s += BLINKER_F("Content-Length: "); +// // s += String(msg.length()); +// // s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); +// // s += msg; +// // s += BLINKER_F("\r\n"); + +// // _client.print(s); + +// // _client.stop(); + +// // parseUrl(data); +// // } +// // } +// // } +// // } +// // } + +// bool BlinkerESPMQTT::parseUrl(String data) +// { +// BLINKER_LOG(BLINKER_F("APCONFIG data: "), data); +// DynamicJsonBuffer jsonBuffer; +// JsonObject& wifi_data = jsonBuffer.parseObject(data); + +// if (!wifi_data.success()) { +// return false; +// } + +// String _ssid = wifi_data["ssid"]; +// String _pswd = wifi_data["pswd"]; + +// BLINKER_LOG(BLINKER_F("ssid: "), _ssid); +// BLINKER_LOG(BLINKER_F("pswd: "), _pswd); + +// // free(_server); +// connectWiFi(_ssid, _pswd); +// return true; +// } + +// void BlinkerESPMQTT::connectWiFi(String _ssid, String _pswd) +// { +// connectWiFi(_ssid.c_str(), _pswd.c_str()); +// } + +// void BlinkerESPMQTT::connectWiFi(const char* _ssid, const char* _pswd) +// { +// uint32_t connectTime = millis(); + +// BLINKER_LOG(BLINKER_F("Connecting to "), _ssid); + +// WiFi.mode(WIFI_STA); +// String _hostname = BLINKER_F("DiyArduinoMQTT_"); +// _hostname += macDeviceName(); + +// #if defined(ESP8266) +// WiFi.hostname(_hostname.c_str()); +// #elif defined(ESP32) +// WiFi.setHostname(_hostname.c_str()); +// #endif + +// if (_pswd && strlen(_pswd)) { +// WiFi.begin(_ssid, _pswd); +// } +// else { +// WiFi.begin(_ssid); +// } + +// while (WiFi.status() != WL_CONNECTED) { +// ::delay(50); + +// if (millis() - connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { +// connectTime = millis(); +// BLINKER_LOG(BLINKER_F("WiFi connect timeout, please check ssid and pswd!")); +// BLINKER_LOG(BLINKER_F("Retring WiFi connect again!")); +// } +// } +// BLINKER_LOG(BLINKER_F("Connected")); + +// IPAddress myip = WiFi.localIP(); +// BLINKER_LOG(BLINKER_F("Your IP is: "), myip); +// } + +#endif + +#endif diff --git a/blinker-library/src/BlinkerESPMQTTAT.h b/blinker-library/src/BlinkerESPMQTTAT.h new file mode 100644 index 0000000..b5b8833 --- /dev/null +++ b/blinker-library/src/BlinkerESPMQTTAT.h @@ -0,0 +1,62 @@ +#ifndef BLINKER_ESP_MQTT_AT_H +#define BLINKER_ESP_MQTT_AT_H + +#if defined(ESP8266) || defined(ESP32) + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerMQTTAT.h" +#include "Blinker/BlinkerApi.h" + +typedef BlinkerApi BApi; + +class BlinkerESPMQTTAT : public BlinkerApi +{ + public : + void begin() + { + BApi::begin(); + + ::delay(100); + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_SERIALCFG, serialSet); + + uint32_t ss_baud = serialSet >> 8 & 0x00FFFFFF; + ss_cfg = serConfig(); + + if (ss_baud != 300 || ss_baud != 1200 || ss_baud != 2400 || + ss_baud != 4800 || ss_baud != 9600 || ss_baud != 19200 || + ss_baud != 38400 || ss_baud != 57600 || ss_baud != 74880 || + ss_baud != 115200 || ss_baud != 230400 || ss_baud != 250000 || + ss_baud != 500000 || ss_baud != 1000000 || ss_baud != 2000000) + { + serialSet = BLINKER_SERIAL_DEFAULT; + ss_baud = 9600; + ss_cfg = SERIAL_8N1; + + EEPROM.put(BLINKER_EEP_ADDR_SERIALCFG, serialSet); + } + + EEPROM.commit(); + EEPROM.end(); + + Serial.begin(ss_baud, ss_cfg); + Transp.serialBegin(Serial, true); + transport(Transp); + BApi::atBegin(); + // strcpy(BApi::_authKey, this->conn.authKey().c_str()); + // strcpy(BApi::_deviceName, this->conn.deviceName().c_str()); + BApi::loadTimer(); + BLINKER_LOG(BLINKER_F("BLINKER_MQTT_AT initialized...")); + } + + private : + BlinkerMQTTAT Transp; +}; + +#endif + +#endif diff --git a/blinker-library/src/BlinkerESPMQTTAUTO.h b/blinker-library/src/BlinkerESPMQTTAUTO.h new file mode 100644 index 0000000..9ab7b6e --- /dev/null +++ b/blinker-library/src/BlinkerESPMQTTAUTO.h @@ -0,0 +1,32 @@ +#ifndef BLINKER_ESP_MQTT_AUTO_H +#define BLINKER_ESP_MQTT_AUTO_H + +#if defined(ESP8266) || defined(ESP32) + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerMQTTAUTO.h" +#include "Blinker/BlinkerApi.h" + +typedef BlinkerApi BApi; + +class BlinkerESPMQTTAUTO : public BlinkerApi +{ + public : + void begin(const char* _key, const char* _type) + { + transport(Transp); + BApi::begin(_key, _type); + BApi::loadTimer(); + BLINKER_LOG(BLINKER_F("ESP8266_MQTT_AUTO initialized...")); + } + + private : + BlinkerMQTTAUTO Transp; +}; + +#endif + +#endif diff --git a/blinker-library/src/BlinkerESPMQTTLP.h b/blinker-library/src/BlinkerESPMQTTLP.h new file mode 100644 index 0000000..c9fc070 --- /dev/null +++ b/blinker-library/src/BlinkerESPMQTTLP.h @@ -0,0 +1,520 @@ +// #ifndef BLINKER_ESP_MQTT_LP_H +// #define BLINKER_ESP_MQTT_LP_H + +// #if defined(ESP8266) || defined(ESP32) + +// #ifndef BLINKER_ARDUINOJSON +// #define BLINKER_ARDUINOJSON +// #endif + +// #include "Adapters/BlinkerMQTTLP.h" +// #include "Blinker/BlinkerApi.h" +// #include "modules/ArduinoJson/ArduinoJson.h" + +// #if defined(ESP8266) +// #include +// #include +// #include +// #elif defined(ESP32) +// #include +// #include +// #include +// #endif + +// typedef BlinkerApi BApi; + +// class BlinkerESPMQTTLP : public BlinkerApi +// { +// public : +// #if defined(BLINKER_ESP_SMARTCONFIG) || defined(BLINKER_APCONFIG) +// void begin(const char* _auth) +// { +// #if defined(BLINKER_ALIGENIE_LIGHT) +// String _aliType = BLINKER_F("&aliType=light"); +// #elif defined(BLINKER_ALIGENIE_OUTLET) +// String _aliType = BLINKER_F("&aliType=outlet"); +// #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) +// String _aliType = BLINKER_F("&aliType=multi_outlet"); +// #elif defined(BLINKER_ALIGENIE_SENSOR) +// String _aliType = BLINKER_F("&aliType=sensor"); +// #else +// String _aliType = BLINKER_F(""); +// #endif + +// #if defined(BLINKER_DUEROS_LIGHT) +// String _duerType = BLINKER_F("&duerType=LIGHT"); +// #elif defined(BLINKER_DUEROS_OUTLET) +// String _duerType = BLINKER_F("&duerType=SOCKET"); +// #elif defined(BLINKER_DUEROS_MULTI_OUTLET) +// String _duerType = BLINKER_F("&duerType=MULTI_SOCKET"); +// #elif defined(BLINKER_DUEROS_SENSOR) +// String _duerType = BLINKER_F("&duerType=AIR_MONITOR"); +// #else +// String _duerType = BLINKER_F(""); +// #endif + +// BApi::begin(); + +// Transp.aliType(_aliType); +// Transp.duerType(_duerType); +// Transp.begin(_auth); + +// transport(Transp); + +// #if defined(BLINKER_ESP_SMARTCONFIG) +// Transp.smartconfigBegin(); +// #elif defined(BLINKER_APCONFIG) +// Transp.apconfigBegin(); +// #endif + +// BApi::loadTimer(); + +// // #if defined(BLINKER_ESP_SMARTCONFIG) +// // smartconfigBegin(_auth, _aliType, _duerType); +// // #elif defined(BLINKER_APCONFIG) +// // apconfigBegin(_auth, _aliType, _duerType); +// // #endif + +// // __auth = _auth; + +// // #ifndef BLINKER_ESP_TASK +// // beginMQTT(); +// // #endif +// } +// #else +// void begin( const char* _auth, +// const char* _ssid, +// const char* _pswd ) +// { +// #if defined(BLINKER_ALIGENIE_LIGHT) +// String _aliType = BLINKER_F("&aliType=light"); +// #elif defined(BLINKER_ALIGENIE_OUTLET) +// String _aliType = BLINKER_F("&aliType=outlet"); +// #elif defined(BLINKER_ALIGENIE_MULTI_OUTLET) +// String _aliType = BLINKER_F("&aliType=multi_outlet"); +// #elif defined(BLINKER_ALIGENIE_SENSOR) +// String _aliType = BLINKER_F("&aliType=sensor"); +// #else +// String _aliType = BLINKER_F(""); +// #endif + +// #if defined(BLINKER_DUEROS_LIGHT) +// String _duerType = BLINKER_F("&duerType=LIGHT"); +// #elif defined(BLINKER_DUEROS_OUTLET) +// String _duerType = BLINKER_F("&duerType=SOCKET"); +// #elif defined(BLINKER_DUEROS_MULTI_OUTLET) +// String _duerType = BLINKER_F("&duerType=MULTI_SOCKET"); +// #elif defined(BLINKER_DUEROS_SENSOR) +// String _duerType = BLINKER_F("&duerType=AIR_MONITOR"); +// #else +// String _duerType = BLINKER_F(""); +// #endif + +// BApi::begin(); + +// Transp.aliType(_aliType); +// Transp.duerType(_duerType); +// Transp.begin(_auth); + +// transport(Transp); + +// Transp.commonBegin(_ssid, _pswd); +// BApi::loadTimer(); +// // __auth = _auth; +// // __ssid = _ssid; +// // __pswd = _pswd; + +// // #ifndef BLINKER_ESP_TASK +// // beginMQTT(); +// // #endif +// } +// #endif +// // void beginMQTT() +// // { +// // #if defined(BLINKER_ALIGENIE_LIGHT) +// // String _aliType = BLINKER_F("&aliType=light"); +// // #elif defined(BLINKER_ALIGENIE_OUTLET) +// // String _aliType = BLINKER_F("&aliType=outlet"); +// // #elif defined(BLINKER_ALIGENIE_SENSOR) +// // String _aliType = BLINKER_F("&aliType=sensor"); +// // #else +// // String _aliType = BLINKER_F(""); +// // #endif + +// // #if defined(BLINKER_DUEROS_LIGHT) +// // String _duerType = BLINKER_F("&duerType=LIGHT"); +// // #elif defined(BLINKER_DUEROS_OUTLET) +// // String _duerType = BLINKER_F("&duerType=SOCKET"); +// // #elif defined(BLINKER_DUEROS_SENSOR) +// // String _duerType = BLINKER_F("&duerType=AIR_MONITOR"); +// // #else +// // String _duerType = BLINKER_F(""); +// // #endif + +// // #if defined(BLINKER_ESP_SMARTCONFIG) +// // smartconfigBegin(__auth, _aliType, _duerType); +// // #elif defined(BLINKER_APCONFIG) +// // apconfigBegin(__auth, _aliType, _duerType); +// // #else +// // commonBegin(__auth, __ssid, __pswd, _aliType, _duerType); +// // #endif +// // } + +// private : +// // void commonBegin(const char* _auth, +// // const char* _ssid, +// // const char* _pswd, +// // String & _alitype, +// // String & _duertype); +// // void smartconfigBegin(const char* _auth, String & _alitype, String & _duertype); +// // void apconfigBegin(const char* _auth, String & _alitype, String & _duertype); + +// // bool autoInit(); +// // void smartconfig(); +// // void softAPinit(); +// // // void serverClient(); +// // bool parseUrl(String data); + +// // void connectWiFi(String _ssid, String _pswd); +// // void connectWiFi(const char* _ssid, const char* _pswd); + +// // const char* __auth; +// // const char* __ssid; +// // const char* __pswd; + +// BlinkerMQTTLP Transp; +// }; + +// // void BlinkerESPMQTTLP::commonBegin(const char* _auth, +// // const char* _ssid, +// // const char* _pswd, +// // String & _alitype, +// // String & _duertype) +// // { +// // BApi::begin(); +// // connectWiFi(_ssid, _pswd); +// // // BApi::loadOTA(); +// // Transp.aliType(_alitype); +// // Transp.duerType(_duertype); +// // Transp.begin(_auth); +// // transport(Transp); +// // BApi::loadTimer(); + +// // #if defined(ESP8266) +// // BLINKER_LOG(BLINKER_F("ESP8266_MQTT initialized...")); +// // #elif defined(ESP32) +// // BLINKER_LOG(BLINKER_F("ESP32_MQTT initialized...")); +// // #endif +// // } + +// // void BlinkerESPMQTTLP::smartconfigBegin(const char* _auth, String & _alitype, +// // String & _duertype) +// // { +// // BApi::begin(); +// // if (!autoInit()) smartconfig(); +// // // BApi::loadOTA(); +// // Transp.aliType(_alitype); +// // Transp.duerType(_duertype); +// // Transp.begin(_auth); +// // transport(Transp); +// // BApi::loadTimer(); + +// // #if defined(ESP8266) +// // BLINKER_LOG(BLINKER_F("ESP8266_MQTT initialized...")); +// // #elif defined(ESP32) +// // BLINKER_LOG(BLINKER_F("ESP32_MQTT initialized...")); +// // #endif +// // } + +// // void BlinkerESPMQTTLP::apconfigBegin(const char* _auth, String & _alitype, +// // String & _duertype) +// // { +// // BApi::begin(); +// // if (!autoInit()) +// // { +// // softAPinit(); +// // // while(WiFi.status() != WL_CONNECTED) +// // // { +// // // serverClient(); +// // // ::delay(10); +// // // } +// // } +// // // BApi::loadOTA(); + +// // Transp.aliType(_alitype); +// // Transp.duerType(_duertype); +// // Transp.begin(_auth); +// // transport(Transp); +// // BApi::loadTimer(); + +// // #if defined(ESP8266) +// // BLINKER_LOG(BLINKER_F("ESP8266_MQTT initialized...")); +// // #elif defined(ESP32) +// // BLINKER_LOG(BLINKER_F("ESP32_MQTT initialized...")); +// // #endif +// // } + +// // bool BlinkerESPMQTTLP::autoInit() +// // { +// // WiFi.mode(WIFI_STA); +// // String _hostname = BLINKER_F("DiyArduino_"); +// // _hostname += macDeviceName(); + +// // #if defined(ESP8266) +// // WiFi.hostname(_hostname.c_str()); +// // #elif defined(ESP32) +// // WiFi.setHostname(_hostname.c_str()); +// // #endif + +// // WiFi.begin(); +// // ::delay(500); + +// // BLINKER_LOG(BLINKER_F("Waiting for WiFi "), +// // BLINKER_WIFI_AUTO_INIT_TIMEOUT / 1000, +// // BLINKER_F("s, will enter SMARTCONFIG or "), +// // BLINKER_F("APCONFIG while WiFi not connect!")); + +// // uint8_t _times = 0; +// // while (WiFi.status() != WL_CONNECTED) { +// // ::delay(500); +// // if (_times > BLINKER_WIFI_AUTO_INIT_TIMEOUT / 500) break; +// // _times++; +// // } + +// // if (WiFi.status() != WL_CONNECTED) return false; +// // else { +// // BLINKER_LOG(BLINKER_F("WiFi Connected.")); +// // BLINKER_LOG(BLINKER_F("IP Address: ")); +// // BLINKER_LOG(WiFi.localIP()); + +// // return true; +// // } +// // } + +// // void BlinkerESPMQTTLP::smartconfig() +// // { +// // WiFi.mode(WIFI_STA); +// // String _hostname = BLINKER_F("DiyArduino_"); +// // _hostname += macDeviceName(); + +// // #if defined(ESP8266) +// // WiFi.hostname(_hostname.c_str()); +// // #elif defined(ESP32) +// // WiFi.setHostname(_hostname.c_str()); +// // #endif + +// // WiFi.beginSmartConfig(); + +// // BLINKER_LOG(BLINKER_F("Waiting for SmartConfig.")); +// // while (!WiFi.smartConfigDone()) { +// // ::delay(500); +// // } + +// // BLINKER_LOG(BLINKER_F("SmartConfig received.")); + +// // BLINKER_LOG(BLINKER_F("Waiting for WiFi")); +// // while (WiFi.status() != WL_CONNECTED) { +// // ::delay(500); +// // } + +// // BLINKER_LOG(BLINKER_F("WiFi Connected.")); + +// // BLINKER_LOG(BLINKER_F("IP Address: ")); +// // BLINKER_LOG(WiFi.localIP()); +// // } + +// // void BlinkerESPMQTTLP::softAPinit() +// // { +// // WiFiServer _server(80); +// // WiFiClient _client; +// // IPAddress apIP(192, 168, 4, 1); +// // #if defined(ESP8266) +// // IPAddress netMsk(255, 255, 255, 0); +// // #endif + +// // // _server = new WiFiServer(80); + +// // WiFi.mode(WIFI_AP); +// // String softAP_ssid = BLINKER_F("DiyArduino_"); +// // softAP_ssid += macDeviceName(); + +// // #if defined(ESP8266) +// // WiFi.hostname(softAP_ssid.c_str()); +// // WiFi.softAPConfig(apIP, apIP, netMsk); +// // #elif defined(ESP32) +// // WiFi.setHostname(softAP_ssid.c_str()); +// // WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); +// // #endif + +// // WiFi.softAP(softAP_ssid.c_str(), ("12345678")); +// // delay(100); + +// // _server.begin(); +// // BLINKER_LOG(BLINKER_F("AP IP address: "), WiFi.softAPIP()); +// // BLINKER_LOG(BLINKER_F("HTTP _server started")); +// // BLINKER_LOG(BLINKER_F("URL: http://"), WiFi.softAPIP()); + +// // while(WiFi.status() != WL_CONNECTED) +// // { +// // // serverClient(); +// // _client = _server.available(); +// // // if (_client.status() == CLOSED) +// // if (!_client.connected()) +// // { +// // _client.stop(); +// // BLINKER_LOG(BLINKER_F("Connection closed on _client")); +// // } +// // else +// // { +// // if (_client.available()) +// // { +// // String data = _client.readStringUntil('\r'); + +// // // data = data.substring(4, data.length() - 9); +// // _client.flush(); + +// // BLINKER_LOG(BLINKER_F("clientData: "), data); + +// // if (STRING_contains_string(data, "ssid") && +// // STRING_contains_string(data, "pswd")) +// // { +// // String msg = BLINKER_F("{\"hello\":\"world\"}"); + +// // String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); +// // s += BLINKER_F("Content-Type: application/json;"); +// // s += BLINKER_F("charset=utf-8\r\n"); +// // s += BLINKER_F("Content-Length: "); +// // s += String(msg.length()); +// // s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); +// // s += msg; +// // s += BLINKER_F("\r\n"); + +// // _client.print(s); + +// // _client.stop(); + +// // parseUrl(data); +// // } +// // } +// // } +// // ::delay(10); +// // } +// // } + +// // // void BlinkerESPMQTTLP::serverClient() +// // // { +// // // if (!_client) +// // // { +// // // _client = _server->available(); +// // // } +// // // else +// // // { +// // // // if (_client.status() == CLOSED) +// // // if (!_client.connected()) +// // // { +// // // _client.stop(); +// // // BLINKER_LOG(BLINKER_F("Connection closed on _client")); +// // // } +// // // else +// // // { +// // // if (_client.available()) +// // // { +// // // String data = _client.readStringUntil('\r'); + +// // // // data = data.substring(4, data.length() - 9); +// // // _client.flush(); + +// // // BLINKER_LOG(BLINKER_F("clientData: "), data); + +// // // if (STRING_contains_string(data, "ssid") && +// // // STRING_contains_string(data, "pswd")) +// // // { +// // // String msg = BLINKER_F("{\"hello\":\"world\"}"); + +// // // String s= BLINKER_F("HTTP/1.1 200 OK\r\n"); +// // // s += BLINKER_F("Content-Type: application/json;"); +// // // s += BLINKER_F("charset=utf-8\r\n"); +// // // s += BLINKER_F("Content-Length: "); +// // // s += String(msg.length()); +// // // s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); +// // // s += msg; +// // // s += BLINKER_F("\r\n"); + +// // // _client.print(s); + +// // // _client.stop(); + +// // // parseUrl(data); +// // // } +// // // } +// // // } +// // // } +// // // } + +// // bool BlinkerESPMQTTLP::parseUrl(String data) +// // { +// // BLINKER_LOG(BLINKER_F("APCONFIG data: "), data); +// // DynamicJsonBuffer jsonBuffer; +// // JsonObject& wifi_data = jsonBuffer.parseObject(data); + +// // if (!wifi_data.success()) { +// // return false; +// // } + +// // String _ssid = wifi_data["ssid"]; +// // String _pswd = wifi_data["pswd"]; + +// // BLINKER_LOG(BLINKER_F("ssid: "), _ssid); +// // BLINKER_LOG(BLINKER_F("pswd: "), _pswd); + +// // // free(_server); +// // connectWiFi(_ssid, _pswd); +// // return true; +// // } + +// // void BlinkerESPMQTTLP::connectWiFi(String _ssid, String _pswd) +// // { +// // connectWiFi(_ssid.c_str(), _pswd.c_str()); +// // } + +// // void BlinkerESPMQTTLP::connectWiFi(const char* _ssid, const char* _pswd) +// // { +// // uint32_t connectTime = millis(); + +// // BLINKER_LOG(BLINKER_F("Connecting to "), _ssid); + +// // WiFi.mode(WIFI_STA); +// // String _hostname = BLINKER_F("DiyArduinoMQTT_"); +// // _hostname += macDeviceName(); + +// // #if defined(ESP8266) +// // WiFi.hostname(_hostname.c_str()); +// // #elif defined(ESP32) +// // WiFi.setHostname(_hostname.c_str()); +// // #endif + +// // if (_pswd && strlen(_pswd)) { +// // WiFi.begin(_ssid, _pswd); +// // } +// // else { +// // WiFi.begin(_ssid); +// // } + +// // while (WiFi.status() != WL_CONNECTED) { +// // ::delay(50); + +// // if (millis() - connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { +// // connectTime = millis(); +// // BLINKER_LOG(BLINKER_F("WiFi connect timeout, please check ssid and pswd!")); +// // BLINKER_LOG(BLINKER_F("Retring WiFi connect again!")); +// // } +// // } +// // BLINKER_LOG(BLINKER_F("Connected")); + +// // IPAddress myip = WiFi.localIP(); +// // BLINKER_LOG(BLINKER_F("Your IP is: "), myip); +// // } + +// #endif + +// #endif diff --git a/blinker-library/src/BlinkerESPPRO.h b/blinker-library/src/BlinkerESPPRO.h new file mode 100644 index 0000000..4c882f9 --- /dev/null +++ b/blinker-library/src/BlinkerESPPRO.h @@ -0,0 +1,32 @@ +#ifndef BLINKER_ESP_PRO_H +#define BLINKER_ESP_PRO_H + +#if defined(ESP8266) || defined(ESP32) + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerPRO.h" +#include "Blinker/BlinkerApi.h" + +typedef BlinkerApi BApi; + +class BlinkerESPPRO : public BlinkerApi +{ + public : + void begin(const char* _type = BLINKER_AIR_DETECTOR) + { + transport(Transp); + BApi::begin(_type); + BApi::loadTimer(); + BLINKER_LOG(BLINKER_F("ESP8266_PRO initialized...")); + } + + private : + BlinkerPRO Transp; +}; + +#endif + +#endif diff --git a/blinker-library/src/BlinkerESPPROESP.h b/blinker-library/src/BlinkerESPPROESP.h new file mode 100644 index 0000000..561b5c6 --- /dev/null +++ b/blinker-library/src/BlinkerESPPROESP.h @@ -0,0 +1,32 @@ +#ifndef BLINKER_ESP_PRO_ESP_H +#define BLINKER_ESP_PRO_ESP_H + +#if defined(ESP8266) || defined(ESP32) + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerPROESP.h" +#include "Blinker/BlinkerApi.h" + +typedef BlinkerApi BApi; + +class BlinkerESPPROESP : public BlinkerApi +{ + public : + void begin(const char* _key, const char* _type) + { + transport(Transp); + BApi::begin(_key, _type); + BApi::loadTimer(); + BLINKER_LOG(BLINKER_F("ESP_PRO initialized...")); + } + + private : + BlinkerPROESP Transp; +}; + +#endif + +#endif diff --git a/blinker-library/src/BlinkerESPSubDevice.h b/blinker-library/src/BlinkerESPSubDevice.h new file mode 100644 index 0000000..b0fcf39 --- /dev/null +++ b/blinker-library/src/BlinkerESPSubDevice.h @@ -0,0 +1,27 @@ +#ifndef BLINKER_ESP_SUBDEVICE_H +#define BLINKER_ESP_SUBDEVICE_H + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerSubDevice.h" +#include "Blinker/BlinkerApi.h" + +typedef BlinkerApi BApi; + +class BlinkerESPSubDevice : public BlinkerApi +{ + public : + void begin(const char* _key, const char* _type) + { + transport(Transp); + BApi::begin(_key, _type); + BLINKER_LOG(BLINKER_F("Blinker SubDevice initialized...")); + } + + private : + BlinkerSubDevice Transp; +}; + +#endif diff --git a/blinker-library/src/BlinkerLUATPRO.h b/blinker-library/src/BlinkerLUATPRO.h new file mode 100644 index 0000000..7daa8a1 --- /dev/null +++ b/blinker-library/src/BlinkerLUATPRO.h @@ -0,0 +1,165 @@ +#ifndef BLINKER_LUAT_PRO_H +#define BLINKER_LUAT_PRO_H + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerPROAIR202.h" +#include "Blinker/BlinkerApi.h" + +#if defined(ESP32) + #include + + HardwareSerial *HSerial; +#else + #include + + SoftwareSerial *SSerial; +#endif + +typedef BlinkerApi BApi; + +void listening() +{ + yield(); + + #if defined(__AVR__) || defined(ESP8266) + if (!SSerial->isListening()) + { + SSerial->listen(); + ::delay(100); + } + #endif +} + +class BlinkerLUATPRO : public BlinkerApi +{ + public : + void begin( const char* _type = BLINKER_AIR_DETECTOR, + uint8_t _rx_pin = 2, + uint8_t _tx_pin = 3, + uint32_t _baud = 9600) + { + serialBegin(_type, _rx_pin, _tx_pin, _baud); + // BApi::begin(_type); + ::delay(100); + // BApi::atInit(); + BLINKER_LOG(BLINKER_F("Blinker NBIoT initialized...")); + } + + private : + void serialBegin(const char* _type, + uint8_t ss_rx_pin, + uint8_t ss_tx_pin, + uint32_t ss_baud) + { + #if defined (__AVR__) + if (ss_rx_pin == 0 && ss_tx_pin == 1){ + // BApi::begin(); + #if defined (__AVR_ATmega32U4__) + Serial1.begin(ss_baud); + Transp.initStream(Serial1, true, listening); + transport(Transp); + + BApi::begin(_type, Serial1, true, listening); + #else + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + + BApi::begin(_type, Serial, true, listening); + #endif + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + #if defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__SAM3X8E__) + else if (ss_rx_pin == 19 && ss_tx_pin == 18){ + // BApi::begin(); + Serial1.begin(ss_baud); + Transp.initStream(Serial1, true, listening); + transport(Transp); + BLINKER_LOG_ALL(BLINKER_F("Serial1 initialized...")); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial1, true, listening); + return; + } + else if (ss_rx_pin == 17 && ss_tx_pin == 16){ + // BApi::begin(); + Serial2.begin(ss_baud); + Transp.initStream(Serial2, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial2, true, listening); + return; + } + else if (ss_rx_pin == 15 && ss_tx_pin == 14){ + // BApi::begin(); + Serial3.begin(ss_baud); + Transp.initStream(Serial3, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial3, true, listening); + return; + } + #endif + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); + } +#elif defined(ESP8266) + if (ss_rx_pin == RX && ss_tx_pin == TX) { + // BApi::begin(); + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial, true, listening); + return; + } + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); + } +#elif defined(ESP32) + // BApi::begin(); + HSerial = new HardwareSerial(1); + HSerial->begin(ss_baud, SERIAL_8N1, ss_rx_pin, ss_tx_pin); + Transp.initStream(*HSerial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *HSerial, true, listening); +#else + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); +#endif + } + + private : + BlinkerProAIR202 Transp; +}; + +#endif diff --git a/blinker-library/src/BlinkerLowPowerGPRS.h b/blinker-library/src/BlinkerLowPowerGPRS.h new file mode 100644 index 0000000..852fbc1 --- /dev/null +++ b/blinker-library/src/BlinkerLowPowerGPRS.h @@ -0,0 +1,161 @@ +#ifndef BLINKER_LOW_POWER_GPRS_H +#define BLINKER_LOW_POWER_GPRS_H + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerAIR202LP.h" +#include "Blinker/BlinkerApi.h" + +#if defined(ESP32) + #include + + HardwareSerial *HSerial; +#else + #include + + SoftwareSerial *SSerial; +#endif + +typedef BlinkerApi BApi; + +void listening() +{ + yield(); + + #if defined(__AVR__) || defined(ESP8266) + if (!SSerial->isListening()) + { + SSerial->listen(); + ::delay(100); + } + #endif +} + +class BlinkerLowPowerGPRS : public BlinkerApi +{ + public : + void begin(const char* _key, const char* _type, + uint8_t _rx_pin = 2, uint8_t _tx_pin = 3, + uint32_t _baud = 9600) + { + serialBegin(_key, _type, _rx_pin, _tx_pin, _baud); + ::delay(100); + BLINKER_LOG(BLINKER_F("Blinker GPRS initialized...")); + } + + private : + void serialBegin(const char* _key, + const char* _type, + uint8_t ss_rx_pin, + uint8_t ss_tx_pin, + uint32_t ss_baud) + { + #if defined (__AVR__) + if (ss_rx_pin == 0 && ss_tx_pin == 1){ + // BApi::begin(); + #if defined (__AVR_ATmega32U4__) + Serial1.begin(ss_baud); + Transp.initStream(Serial1, true, listening); + transport(Transp); + + BApi::begin(_key, _type, Serial1, true, listening); + #else + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + + BApi::begin(_key, _type, Serial, true, listening); + #endif + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + #if defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__SAM3X8E__) + else if (ss_rx_pin == 19 && ss_tx_pin == 18){ + // BApi::begin(); + Serial1.begin(ss_baud); + Transp.initStream(Serial1, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_key, _type, Serial1, true, listening); + return; + } + else if (ss_rx_pin == 17 && ss_tx_pin == 16){ + // BApi::begin(); + Serial2.begin(ss_baud); + Transp.initStream(Serial2, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_key, _type, Serial2, true, listening); + return; + } + else if (ss_rx_pin == 15 && ss_tx_pin == 14){ + // BApi::begin(); + Serial3.begin(ss_baud); + Transp.initStream(Serial3, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_key, _type, Serial3, true, listening); + return; + } + #endif + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_key, _type, *SSerial, false, listening); + } +#elif defined(ESP8266) + if (ss_rx_pin == RX && ss_tx_pin == TX) { + // BApi::begin(); + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_key, _type, Serial, true, listening); + return; + } + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_key, _type, *SSerial, false, listening); + } +#elif defined(ESP32) + // BApi::begin(); + HSerial = new HardwareSerial(1); + HSerial->begin(ss_baud, SERIAL_8N1, ss_rx_pin, ss_tx_pin); + Transp.initStream(*HSerial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_key, _type, *HSerial, true, listening); +#else + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_key, _type, *SSerial, false, listening); +#endif + } + + BlinkerAIR202LP Transp; +}; + +#endif diff --git a/blinker-library/src/BlinkerQRCodeSIM7000NBIOT.h b/blinker-library/src/BlinkerQRCodeSIM7000NBIOT.h new file mode 100644 index 0000000..ee4af64 --- /dev/null +++ b/blinker-library/src/BlinkerQRCodeSIM7000NBIOT.h @@ -0,0 +1,194 @@ +#ifndef BLINKER_QRCODE_SERIAL_SIM7000_NBIOT_H +#define BLINKER_QRCODE_SERIAL_SIM7000_NBIOT_H + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerQRCodeSIM7000.h" +#include "Blinker/BlinkerApi.h" + +#if defined(ESP32) + #include + + HardwareSerial *HSerial; +#else + #include + + SoftwareSerial *SSerial; +#endif + +typedef BlinkerApi BApi; + +void listening() +{ + yield(); + + #if defined(__AVR__) || defined(ESP8266) + if (!SSerial->isListening()) + { + SSerial->listen(); + ::delay(100); + } + #endif +} + +class BlinkerQRCodeSerialSIM7000NBIoT : public BlinkerApi +{ + public : + // void begin( const char* _type = BLINKER_AIR_DETECTOR, + // uint8_t _rx_pin = 2, + // uint8_t _tx_pin = 3, + // uint32_t _baud = 9600) + void begin( const char* _type = BLINKER_AIR_DETECTOR, + const char* _auth = BLINKER_AIR_DETECTOR, + uint8_t _rx_pin = 2, + uint8_t _tx_pin = 3, + uint32_t _baud = 9600) + { + #if defined(BLINKER_ALIGENIE_LIGHT) + String _aliType = BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + String _aliType = BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + String _aliType = BLINKER_F("&aliType=sensor"); + #else + String _aliType = BLINKER_F(""); + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + String _duerType = BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + String _duerType = BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + String _duerType = BLINKER_F("&duerType=AIR_MONITOR"); + #else + String _duerType = BLINKER_F(""); + #endif + + Transp.aliType(_aliType); + Transp.duerType(_duerType); + + serialBegin(_type, _auth, _rx_pin, _tx_pin, _baud); + // BApi::begin(_type); + ::delay(100); + // BApi::atInit(); + BLINKER_LOG(BLINKER_F("Blinker NBIoT initialized...")); + } + + private : + void serialBegin(const char* _type, + const char* _auth, + uint8_t ss_rx_pin, + uint8_t ss_tx_pin, + uint32_t ss_baud) + { + #if defined (__AVR__) + if (ss_rx_pin == 0 && ss_tx_pin == 1){ + // BApi::begin(); + #if defined (__AVR_ATmega32U4__) + Serial1.begin(ss_baud); + Transp.initStream(Serial1, true, listening); + transport(Transp); + + BApi::begin(Serial1, true, listening); + #else + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + + BApi::begin(_type, _auth, Serial, true, listening); + #endif + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + #if defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__SAM3X8E__) + else if (ss_rx_pin == 19 && ss_tx_pin == 18){ + // BApi::begin(); + Serial1.begin(ss_baud); + Serial1.println("test!!!"); + Transp.initStream(Serial1, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, Serial1, true, listening); + return; + } + else if (ss_rx_pin == 17 && ss_tx_pin == 16){ + // BApi::begin(); + Serial2.begin(ss_baud); + Transp.initStream(Serial2, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, Serial2, true, listening); + return; + } + else if (ss_rx_pin == 15 && ss_tx_pin == 14){ + // BApi::begin(); + Serial3.begin(ss_baud); + Transp.initStream(Serial3, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, Serial3, true, listening); + return; + } + #endif + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, *SSerial, false, listening); + } +#elif defined(ESP8266) + if (ss_rx_pin == RX && ss_tx_pin == TX) { + // BApi::begin(); + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, Serial, true, listening); + return; + } + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, *SSerial, false, listening); + } +#elif defined(ESP32) + // BApi::begin(); + HSerial = new HardwareSerial(1); + HSerial->begin(ss_baud, SERIAL_8N1, ss_rx_pin, ss_tx_pin); + Transp.initStream(*HSerial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, *HSerial, true, listening); +#else + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, *SSerial, false, listening); +#endif + } + + private : + BlinkerQRCodeSIM7000 Transp; +}; + +#endif diff --git a/blinker-library/src/BlinkerQRCodeSIMNBIOT.h b/blinker-library/src/BlinkerQRCodeSIMNBIOT.h new file mode 100644 index 0000000..59121ab --- /dev/null +++ b/blinker-library/src/BlinkerQRCodeSIMNBIOT.h @@ -0,0 +1,194 @@ +#ifndef BLINKER_QRCODE_SERIAL_SIM_NBIOT_H +#define BLINKER_QRCODE_SERIAL_SIM_NBIOT_H + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerQRCodeSIM7020.h" +#include "Blinker/BlinkerApi.h" + +#if defined(ESP32) + #include + + HardwareSerial *HSerial; +#else + #include + + SoftwareSerial *SSerial; +#endif + +typedef BlinkerApi BApi; + +void listening() +{ + yield(); + + #if defined(__AVR__) || defined(ESP8266) + if (!SSerial->isListening()) + { + SSerial->listen(); + ::delay(100); + } + #endif +} + +class BlinkerQRCodeSerialSIMNBIoT : public BlinkerApi +{ + public : + // void begin( const char* _type = BLINKER_AIR_DETECTOR, + // uint8_t _rx_pin = 2, + // uint8_t _tx_pin = 3, + // uint32_t _baud = 9600) + void begin( const char* _type = BLINKER_AIR_DETECTOR, + const char* _auth = BLINKER_AIR_DETECTOR, + uint8_t _rx_pin = 2, + uint8_t _tx_pin = 3, + uint32_t _baud = 9600) + { + #if defined(BLINKER_ALIGENIE_LIGHT) + String _aliType = BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + String _aliType = BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + String _aliType = BLINKER_F("&aliType=sensor"); + #else + String _aliType = BLINKER_F(""); + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + String _duerType = BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + String _duerType = BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + String _duerType = BLINKER_F("&duerType=AIR_MONITOR"); + #else + String _duerType = BLINKER_F(""); + #endif + + Transp.aliType(_aliType); + Transp.duerType(_duerType); + + serialBegin(_type, _auth, _rx_pin, _tx_pin, _baud); + // BApi::begin(_type); + ::delay(100); + // BApi::atInit(); + BLINKER_LOG(BLINKER_F("Blinker NBIoT initialized...")); + } + + private : + void serialBegin(const char* _type, + const char* _auth, + uint8_t ss_rx_pin, + uint8_t ss_tx_pin, + uint32_t ss_baud) + { + #if defined (__AVR__) + if (ss_rx_pin == 0 && ss_tx_pin == 1){ + // BApi::begin(); + #if defined (__AVR_ATmega32U4__) + Serial1.begin(ss_baud); + Transp.initStream(Serial1, true, listening); + transport(Transp); + + BApi::begin(Serial1, true, listening); + #else + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + + BApi::begin(_type, _auth, Serial, true, listening); + #endif + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + #if defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__SAM3X8E__) + else if (ss_rx_pin == 19 && ss_tx_pin == 18){ + // BApi::begin(); + Serial1.begin(ss_baud); + Serial1.println("test!!!"); + Transp.initStream(Serial1, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, Serial1, true, listening); + return; + } + else if (ss_rx_pin == 17 && ss_tx_pin == 16){ + // BApi::begin(); + Serial2.begin(ss_baud); + Transp.initStream(Serial2, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, Serial2, true, listening); + return; + } + else if (ss_rx_pin == 15 && ss_tx_pin == 14){ + // BApi::begin(); + Serial3.begin(ss_baud); + Transp.initStream(Serial3, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, Serial3, true, listening); + return; + } + #endif + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, *SSerial, false, listening); + } +#elif defined(ESP8266) + if (ss_rx_pin == RX && ss_tx_pin == TX) { + // BApi::begin(); + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, Serial, true, listening); + return; + } + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, *SSerial, false, listening); + } +#elif defined(ESP32) + // BApi::begin(); + HSerial = new HardwareSerial(1); + HSerial->begin(ss_baud, SERIAL_8N1, ss_rx_pin, ss_tx_pin); + Transp.initStream(*HSerial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, *HSerial, true, listening); +#else + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, _auth, *SSerial, false, listening); +#endif + } + + private : + BlinkerQRCodeSIM7020 Transp; +}; + +#endif diff --git a/blinker-library/src/BlinkerSIMPRO.h b/blinker-library/src/BlinkerSIMPRO.h new file mode 100644 index 0000000..5f16fb7 --- /dev/null +++ b/blinker-library/src/BlinkerSIMPRO.h @@ -0,0 +1,188 @@ +#ifndef BLINKER_SIM_PRO_H +#define BLINKER_SIM_PRO_H + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerPROSIM7020.h" +#include "Blinker/BlinkerApi.h" + +#if defined(ESP32) + #include + + HardwareSerial *HSerial; +#else + #include + + SoftwareSerial *SSerial; +#endif + +typedef BlinkerApi BApi; + +void listening() +{ + yield(); + + #if defined(__AVR__) || defined(ESP8266) + if (!SSerial->isListening()) + { + SSerial->listen(); + ::delay(100); + } + #endif +} + +class BlinkerSIMPRO : public BlinkerApi +{ + public : + void begin( const char* _type = BLINKER_AIR_DETECTOR, + uint8_t _rx_pin = 2, + uint8_t _tx_pin = 3, + uint32_t _baud = 9600) + { + // #if defined(BLINKER_ALIGENIE_LIGHT) + // String _aliType = BLINKER_F("&aliType=light"); + // #elif defined(BLINKER_ALIGENIE_OUTLET) + // String _aliType = BLINKER_F("&aliType=outlet"); + // #elif defined(BLINKER_ALIGENIE_SENSOR) + // String _aliType = BLINKER_F("&aliType=sensor"); + // #else + // String _aliType = BLINKER_F(""); + // #endif + + // #if defined(BLINKER_DUEROS_LIGHT) + // String _duerType = BLINKER_F("&duerType=LIGHT"); + // #elif defined(BLINKER_DUEROS_OUTLET) + // String _duerType = BLINKER_F("&duerType=SOCKET"); + // #elif defined(BLINKER_DUEROS_SENSOR) + // String _duerType = BLINKER_F("&duerType=AIR_MONITOR"); + // #else + // String _duerType = BLINKER_F(""); + // #endif + + // Transp.aliType(_aliType); + // Transp.duerType(_duerType); + + serialBegin(_type, _rx_pin, _tx_pin, _baud); + // BApi::begin(_type); + ::delay(100); + // BApi::atInit(); + BLINKER_LOG(BLINKER_F("Blinker NBIoT initialized...")); + } + + private : + void serialBegin(const char* _type, + uint8_t ss_rx_pin, + uint8_t ss_tx_pin, + uint32_t ss_baud) + { + #if defined (__AVR__) + if (ss_rx_pin == 0 && ss_tx_pin == 1){ + // BApi::begin(); + #if defined (__AVR_ATmega32U4__) + Serial1.begin(ss_baud); + Transp.initStream(Serial1, true, listening); + transport(Transp); + + BApi::begin(_type, Serial1, true, listening); + #else + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + + BApi::begin(_type, Serial, true, listening); + #endif + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + #if defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__SAM3X8E__) + else if (ss_rx_pin == 19 && ss_tx_pin == 18){ + // BApi::begin(); + Serial1.begin(ss_baud); + Transp.initStream(Serial1, true, listening); + transport(Transp); + BLINKER_LOG_ALL(BLINKER_F("Serial1 initialized...")); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial1, true, listening); + return; + } + else if (ss_rx_pin == 17 && ss_tx_pin == 16){ + // BApi::begin(); + Serial2.begin(ss_baud); + Transp.initStream(Serial2, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial2, true, listening); + return; + } + else if (ss_rx_pin == 15 && ss_tx_pin == 14){ + // BApi::begin(); + Serial3.begin(ss_baud); + Transp.initStream(Serial3, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial3, true, listening); + return; + } + #endif + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); + } +#elif defined(ESP8266) + if (ss_rx_pin == RX && ss_tx_pin == TX) { + // BApi::begin(); + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial, true, listening); + return; + } + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); + } +#elif defined(ESP32) + // BApi::begin(); + HSerial = new HardwareSerial(1); + HSerial->begin(ss_baud, SERIAL_8N1, ss_rx_pin, ss_tx_pin); + Transp.initStream(*HSerial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *HSerial, true, listening); +#else + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); +#endif + } + + private : + BlinkerProSIM7020 Transp; +}; + +#endif diff --git a/blinker-library/src/BlinkerSerialBLE.h b/blinker-library/src/BlinkerSerialBLE.h new file mode 100644 index 0000000..17eacf6 --- /dev/null +++ b/blinker-library/src/BlinkerSerialBLE.h @@ -0,0 +1,173 @@ +#ifndef BLINKER_SERIAL_BLE_H +#define BLINKER_SERIAL_BLE_H + +#if !defined (__AVR__) + #ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON + #endif + #ifndef ARDUINOJSON_VERSION_MAJOR + #include "modules/ArduinoJson/ArduinoJson.h" + #endif + + #if defined(ESP32) + #include + #elif defined (__AVR__) || defined(ESP8266) + #include + #endif +#else + #if defined (BLINKER_ARDUINOJSON) + #ifndef ARDUINOJSON_VERSION_MAJOR + #include "modules/ArduinoJson/ArduinoJson.h" + #endif + #endif +#endif + +#include "Adapters/BlinkerSerial.h" +#include "Blinker/BlinkerApi.h" + +typedef BlinkerApi BApi; + +class BlinkerSerialBLE : public BlinkerApi +{ + public : + void begin( uint8_t ss_rx_pin = 2, + uint8_t ss_tx_pin = 3, + uint32_t ss_baud = 9600) + { + #if defined (__AVR__) + if (ss_rx_pin == 0 && ss_tx_pin == 1){ + BApi::begin(); + #if defined (__AVR_ATmega32U4__) + Serial1.begin(ss_baud); + Transp.begin(Serial1, true); + transport(Transp); + // this->conn.begin(Serial1, true); + #else + Serial.begin(ss_baud); + Transp.begin(Serial, true); + transport(Transp); + // this->conn.begin(Serial, true); + #endif + BLINKER_LOG(BLINKER_F("SerialBLE initialized...")); + return; + } + #if defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__SAM3X8E__) + else if (ss_rx_pin == 19 && ss_tx_pin == 18){ + BApi::begin(); + Serial1.begin(ss_baud); + Transp.begin(Serial1, true); + transport(Transp); + // this->conn.begin(Serial1, true); + BLINKER_LOG(BLINKER_F("SerialBLE initialized...")); + return; + } + else if (ss_rx_pin == 17 && ss_tx_pin == 16){ + BApi::begin(); + Serial2.begin(ss_baud); + Transp.begin(Serial2, true); + transport(Transp); + // this->conn.begin(Serial2, true); + BLINKER_LOG(BLINKER_F("SerialBLE initialized...")); + return; + } + else if (ss_rx_pin == 15 && ss_tx_pin == 14){ + BApi::begin(); + Serial3.begin(ss_baud); + Transp.begin(Serial3, true); + transport(Transp); + // this->conn.begin(Serial3, true); + BLINKER_LOG(BLINKER_F("SerialBLE initialized...")); + return; + } + #endif + else { + BApi::begin(); + SSerialBLE = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerialBLE->begin(ss_baud); + Transp.begin(*SSerialBLE, false); + transport(Transp); + // this->conn.begin(*SSerialBLE, false); + BLINKER_LOG(BLINKER_F("SerialBLE initialized...")); + } + #elif defined(ESP8266) + if (ss_rx_pin == RX && ss_tx_pin == TX) { + BApi::begin(); + Serial.begin(ss_baud); + Transp.begin(Serial, true); + transport(Transp); + // this->conn.begin(Serial, true); + BLINKER_LOG(BLINKER_F("SerialBLE initialized...")); + return; + } + else { + BApi::begin(); + SSerialBLE = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerialBLE->begin(ss_baud); + Transp.begin(*SSerialBLE, false); + transport(Transp); + // this->conn.begin(*SSerialBLE, false); + BLINKER_LOG(BLINKER_F("SerialBLE initialized...")); + return; + } + #elif defined(ESP32) + BApi::begin(); + HSerialBLE = new HardwareSerial(1); + HSerialBLE->begin(ss_baud, SERIAL_8N1, ss_rx_pin, ss_tx_pin); + Transp.begin(*HSerialBLE, true); + transport(Transp); + // this->conn.begin(*HSerialBLE, true); + BLINKER_LOG(BLINKER_F("SerialBLE initialized...")); + #elif defined(ARDUINO_SAM_DUE) + if (ss_rx_pin == 0 && ss_tx_pin == 1){ + BApi::begin(); + Serial.begin(ss_baud); + Transp.begin(Serial, true); + transport(Transp); + BLINKER_LOG(BLINKER_F("SerialBLE initialized...")); + return; + } + else if (ss_rx_pin == 19 && ss_tx_pin == 18){ + BApi::begin(); + Serial1.begin(ss_baud); + Transp.begin(Serial1, true); + transport(Transp); + BLINKER_LOG(BLINKER_F("SerialBLE initialized...")); + return; + } + else if (ss_rx_pin == 17 && ss_tx_pin == 16){ + BApi::begin(); + Serial2.begin(ss_baud); + Transp.begin(Serial2, true); + transport(Transp); + BLINKER_LOG(BLINKER_F("SerialBLE initialized...")); + return; + } + else if (ss_rx_pin == 15 && ss_tx_pin == 14){ + BApi::begin(); + Serial3.begin(ss_baud); + Transp.begin(Serial3, true); + transport(Transp); + BLINKER_LOG(BLINKER_F("SerialBLE initialized...")); + return; + } + else + { + BLINKER_ERR_LOG(BLINKER_F("Arduino DUE, Please set right Hardware Serial!")); + return; + } + #else + BApi::begin(); + SSerialBLE = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerialBLE->begin(ss_baud); + Transp.begin(*SSerialBLE, false); + transport(Transp); + // this->conn.begin(*SSerialBLE, false); + BLINKER_LOG(BLINKER_F("SerialBLE initialized...")); + #endif + } + + private : + BlinkerSerial Transp; +}; + +#endif diff --git a/blinker-library/src/BlinkerSerialESPMQTT.h b/blinker-library/src/BlinkerSerialESPMQTT.h new file mode 100644 index 0000000..5b815fa --- /dev/null +++ b/blinker-library/src/BlinkerSerialESPMQTT.h @@ -0,0 +1,150 @@ +#ifndef BLINKER_SERIAL_ESP_MQTT_H +#define BLINKER_SERIAL_ESP_MQTT_H + +#include "Adapters/BlinkerSerialMQTT.h" +#include "Blinker/BlinkerApi.h" + +#if defined(ESP32) + #include +#else + #include +#endif + +typedef BlinkerApi BApi; + +class BlinkerSerialESPMQTT : public BlinkerApi +{ + public : +#if defined(BLINKER_ESP_SMARTCONFIG) + void begin( const char* _auth, + uint8_t _rx_pin = 2, + uint8_t _tx_pin = 3, + uint32_t _baud = 9600) + { + BApi::begin(); + ::delay(100); + serialBegin(_rx_pin, _tx_pin, _baud); + BApi::atInit(_auth); + BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + } +#elif defined(BLINKER_APCONFIG) + void begin( const char* _auth, + uint8_t _rx_pin = 2, + uint8_t _tx_pin = 3, + uint32_t _baud = 9600) + { + BApi::begin(); + ::delay(100); + serialBegin(_rx_pin, _tx_pin, _baud); + BApi::atInit(_auth); + BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + } +#endif + + void begin( const char* _auth, + const char* _ssid, + const char* _pswd, + uint8_t _rx_pin = 2, + uint8_t _tx_pin = 3, + uint32_t _baud = 9600) + { + BApi::begin(); + ::delay(100); + serialBegin(_rx_pin, _tx_pin, _baud); + BApi::atInit(_auth, _ssid, _pswd); + BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + } + + private : + void serialBegin(uint8_t ss_rx_pin, + uint8_t ss_tx_pin, + uint32_t ss_baud) + { + #if defined (__AVR__) + if (ss_rx_pin == 0 && ss_tx_pin == 1){ + // BApi::begin(); + #if defined (__AVR_ATmega32U4__) + Serial1.begin(ss_baud); + Transp.begin(Serial1, true); + transport(Transp); + #else + Serial.begin(ss_baud); + Transp.begin(Serial, true); + transport(Transp); + #endif + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + #if defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__SAM3X8E__) + else if (ss_rx_pin == 19 && ss_tx_pin == 18){ + // BApi::begin(); + Serial1.begin(ss_baud); + Transp.begin(Serial1, true); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + else if (ss_rx_pin == 17 && ss_tx_pin == 16){ + // BApi::begin(); + Serial2.begin(ss_baud); + Transp.begin(Serial2, true); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + else if (ss_rx_pin == 15 && ss_tx_pin == 14){ + // BApi::begin(); + Serial3.begin(ss_baud); + Transp.begin(Serial3, true); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + #endif + else { + // BApi::begin(); + SSerialMQTT = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerialMQTT->begin(ss_baud); + Transp.begin(*SSerialMQTT, false); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + } +#elif defined(ESP8266) + if (ss_rx_pin == RX && ss_tx_pin == TX) { + // BApi::begin(); + Serial.begin(ss_baud); + Transp.begin(Serial, true); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + else { + // BApi::begin(); + SSerialMQTT = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerialMQTT->begin(ss_baud); + Transp.begin(*SSerialMQTT, false); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + } +#elif defined(ESP32) + // BApi::begin(); + HSerialMQTT = new HardwareSerial(1); + HSerialMQTT->begin(ss_baud, SERIAL_8N1, ss_rx_pin, ss_tx_pin); + Transp.begin(*HSerialMQTT, true); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); +#else + // BApi::begin(); + SSerialMQTT = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerialMQTT->begin(ss_baud); + Transp.begin(*SSerialMQTT, false); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); +#endif + } + + private : + BlinkerSerialMQTT Transp; +}; + +#endif diff --git a/blinker-library/src/BlinkerSerialLUATGPRS.h b/blinker-library/src/BlinkerSerialLUATGPRS.h new file mode 100644 index 0000000..fdc961c --- /dev/null +++ b/blinker-library/src/BlinkerSerialLUATGPRS.h @@ -0,0 +1,164 @@ +#ifndef BLINKER_SERIAL_LUAT_GPRS_H +#define BLINKER_SERIAL_LUAT_GPRS_H + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerSerialAIR202.h" +#include "Blinker/BlinkerApi.h" + +#if defined(ESP32) + #include + + HardwareSerial *HSerial; +#else + #include + + SoftwareSerial *SSerial; +#endif + +typedef BlinkerApi BApi; + +void listening() +{ + yield(); + + #if defined(__AVR__) || defined(ESP8266) + if (!SSerial->isListening()) + { + SSerial->listen(); + ::delay(100); + } + #endif +} + +class BlinkerSerialLUATGPRS : public BlinkerApi +{ + public : + void begin( const char* _type = BLINKER_AIR_DETECTOR, + uint8_t _rx_pin = 2, + uint8_t _tx_pin = 3, + uint32_t _baud = 9600) + { + serialBegin(_type, _rx_pin, _tx_pin, _baud); + // BApi::begin(_type); + ::delay(100); + // BApi::atInit(); + BLINKER_LOG(BLINKER_F("Blinker GPRS initialized...")); + } + + private : + void serialBegin(const char* _type, + uint8_t ss_rx_pin, + uint8_t ss_tx_pin, + uint32_t ss_baud) + { + #if defined (__AVR__) + if (ss_rx_pin == 0 && ss_tx_pin == 1){ + // BApi::begin(); + #if defined (__AVR_ATmega32U4__) + Serial1.begin(ss_baud); + Transp.initStream(Serial1, true, listening); + transport(Transp); + + BApi::begin(_type, Serial1, true, listening); + #else + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + + BApi::begin(_type, Serial, true, listening); + #endif + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + #if defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__SAM3X8E__) + else if (ss_rx_pin == 19 && ss_tx_pin == 18){ + // BApi::begin(); + Serial1.begin(ss_baud); + Transp.initStream(Serial1, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial1, true, listening); + return; + } + else if (ss_rx_pin == 17 && ss_tx_pin == 16){ + // BApi::begin(); + Serial2.begin(ss_baud); + Transp.initStream(Serial2, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial2, true, listening); + return; + } + else if (ss_rx_pin == 15 && ss_tx_pin == 14){ + // BApi::begin(); + Serial3.begin(ss_baud); + Transp.initStream(Serial3, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial3, true, listening); + return; + } + #endif + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); + } +#elif defined(ESP8266) + if (ss_rx_pin == RX && ss_tx_pin == TX) { + // BApi::begin(); + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial, true, listening); + return; + } + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); + } +#elif defined(ESP32) + // BApi::begin(); + HSerial = new HardwareSerial(1); + HSerial->begin(ss_baud, SERIAL_8N1, ss_rx_pin, ss_tx_pin); + Transp.initStream(*HSerial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *HSerial, true, listening); +#else + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); +#endif + } + + private : + BlinkerSerialAIR202 Transp; +}; + +#endif diff --git a/blinker-library/src/BlinkerSerialSIM7000NBIoT.h b/blinker-library/src/BlinkerSerialSIM7000NBIoT.h new file mode 100644 index 0000000..f458ca6 --- /dev/null +++ b/blinker-library/src/BlinkerSerialSIM7000NBIoT.h @@ -0,0 +1,188 @@ +#ifndef BLINKER_SERIAL_SIM7000_NBIOT_H +#define BLINKER_SERIAL_SIM7000_NBIOT_H + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerSerialSIM7000.h" +#include "Blinker/BlinkerApi.h" + +#if defined(ESP32) + #include + + HardwareSerial *HSerial; +#else + #include + + SoftwareSerial *SSerial; +#endif + +typedef BlinkerApi BApi; + +void listening() +{ + yield(); + + #if defined(__AVR__) || defined(ESP8266) + if (!SSerial->isListening()) + { + SSerial->listen(); + ::delay(100); + } + #endif +} + +class BlinkerSerialSIM7000NBIoT : public BlinkerApi +{ + public : + void begin( const char* _type = BLINKER_AIR_DETECTOR, + uint8_t _rx_pin = 2, + uint8_t _tx_pin = 3, + uint32_t _baud = 9600) + { + #if defined(BLINKER_ALIGENIE_LIGHT) + String _aliType = BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + String _aliType = BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + String _aliType = BLINKER_F("&aliType=sensor"); + #else + String _aliType = BLINKER_F(""); + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + String _duerType = BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + String _duerType = BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + String _duerType = BLINKER_F("&duerType=AIR_MONITOR"); + #else + String _duerType = BLINKER_F(""); + #endif + + Transp.aliType(_aliType); + Transp.duerType(_duerType); + + serialBegin(_type, _rx_pin, _tx_pin, _baud); + // BApi::begin(_type); + ::delay(100); + // BApi::atInit(); + BLINKER_LOG(BLINKER_F("Blinker NBIoT initialized...")); + } + + private : + void serialBegin(const char* _type, + uint8_t ss_rx_pin, + uint8_t ss_tx_pin, + uint32_t ss_baud) + { + #if defined (__AVR__) + if (ss_rx_pin == 0 && ss_tx_pin == 1){ + // BApi::begin(); + #if defined (__AVR_ATmega32U4__) + Serial1.begin(ss_baud); + Transp.initStream(Serial1, true, listening); + transport(Transp); + + BApi::begin(_type, Serial1, true, listening); + #else + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + + BApi::begin(_type, Serial, true, listening); + #endif + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + #if defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__SAM3X8E__) + else if (ss_rx_pin == 19 && ss_tx_pin == 18){ + // BApi::begin(); + Serial1.begin(ss_baud); + Serial1.println("test!!!"); + Transp.initStream(Serial1, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial1, true, listening); + return; + } + else if (ss_rx_pin == 17 && ss_tx_pin == 16){ + // BApi::begin(); + Serial2.begin(ss_baud); + Transp.initStream(Serial2, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial2, true, listening); + return; + } + else if (ss_rx_pin == 15 && ss_tx_pin == 14){ + // BApi::begin(); + Serial3.begin(ss_baud); + Transp.initStream(Serial3, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial3, true, listening); + return; + } + #endif + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); + } +#elif defined(ESP8266) + if (ss_rx_pin == RX && ss_tx_pin == TX) { + // BApi::begin(); + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial, true, listening); + return; + } + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); + } +#elif defined(ESP32) + // BApi::begin(); + HSerial = new HardwareSerial(1); + HSerial->begin(ss_baud, SERIAL_8N1, ss_rx_pin, ss_tx_pin); + Transp.initStream(*HSerial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *HSerial, true, listening); +#else + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); +#endif + } + + private : + BlinkerSerialSIM7000 Transp; +}; + +#endif diff --git a/blinker-library/src/BlinkerSerialSIMNBIoT.h b/blinker-library/src/BlinkerSerialSIMNBIoT.h new file mode 100644 index 0000000..6423825 --- /dev/null +++ b/blinker-library/src/BlinkerSerialSIMNBIoT.h @@ -0,0 +1,188 @@ +#ifndef BLINKER_SERIAL_SIM_NBIOT_H +#define BLINKER_SERIAL_SIM_NBIOT_H + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerSerialSIM7020.h" +#include "Blinker/BlinkerApi.h" + +#if defined(ESP32) + #include + + HardwareSerial *HSerial; +#else + #include + + SoftwareSerial *SSerial; +#endif + +typedef BlinkerApi BApi; + +void listening() +{ + yield(); + + #if defined(__AVR__) || defined(ESP8266) + if (!SSerial->isListening()) + { + SSerial->listen(); + ::delay(100); + } + #endif +} + +class BlinkerSerialSIMNBIoT : public BlinkerApi +{ + public : + void begin( const char* _type = BLINKER_AIR_DETECTOR, + uint8_t _rx_pin = 2, + uint8_t _tx_pin = 3, + uint32_t _baud = 9600) + { + #if defined(BLINKER_ALIGENIE_LIGHT) + String _aliType = BLINKER_F("&aliType=light"); + #elif defined(BLINKER_ALIGENIE_OUTLET) + String _aliType = BLINKER_F("&aliType=outlet"); + #elif defined(BLINKER_ALIGENIE_SENSOR) + String _aliType = BLINKER_F("&aliType=sensor"); + #else + String _aliType = BLINKER_F(""); + #endif + + #if defined(BLINKER_DUEROS_LIGHT) + String _duerType = BLINKER_F("&duerType=LIGHT"); + #elif defined(BLINKER_DUEROS_OUTLET) + String _duerType = BLINKER_F("&duerType=SOCKET"); + #elif defined(BLINKER_DUEROS_SENSOR) + String _duerType = BLINKER_F("&duerType=AIR_MONITOR"); + #else + String _duerType = BLINKER_F(""); + #endif + + Transp.aliType(_aliType); + Transp.duerType(_duerType); + + serialBegin(_type, _rx_pin, _tx_pin, _baud); + // BApi::begin(_type); + ::delay(100); + // BApi::atInit(); + BLINKER_LOG(BLINKER_F("Blinker NBIoT initialized...")); + } + + private : + void serialBegin(const char* _type, + uint8_t ss_rx_pin, + uint8_t ss_tx_pin, + uint32_t ss_baud) + { + #if defined (__AVR__) + if (ss_rx_pin == 0 && ss_tx_pin == 1){ + // BApi::begin(); + #if defined (__AVR_ATmega32U4__) + Serial1.begin(ss_baud); + Transp.initStream(Serial1, true, listening); + transport(Transp); + + BApi::begin(_type, Serial1, true, listening); + #else + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + + BApi::begin(_type, Serial, true, listening); + #endif + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + #if defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__SAM3X8E__) + else if (ss_rx_pin == 19 && ss_tx_pin == 18){ + // BApi::begin(); + Serial1.begin(ss_baud); + Serial1.println("test!!!"); + Transp.initStream(Serial1, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial1, true, listening); + return; + } + else if (ss_rx_pin == 17 && ss_tx_pin == 16){ + // BApi::begin(); + Serial2.begin(ss_baud); + Transp.initStream(Serial2, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial2, true, listening); + return; + } + else if (ss_rx_pin == 15 && ss_tx_pin == 14){ + // BApi::begin(); + Serial3.begin(ss_baud); + Transp.initStream(Serial3, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial3, true, listening); + return; + } + #endif + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); + } +#elif defined(ESP8266) + if (ss_rx_pin == RX && ss_tx_pin == TX) { + // BApi::begin(); + Serial.begin(ss_baud); + Transp.initStream(Serial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, Serial, true, listening); + return; + } + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); + } +#elif defined(ESP32) + // BApi::begin(); + HSerial = new HardwareSerial(1); + HSerial->begin(ss_baud, SERIAL_8N1, ss_rx_pin, ss_tx_pin); + Transp.initStream(*HSerial, true, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *HSerial, true, listening); +#else + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.initStream(*SSerial, false, listening); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + + BApi::begin(_type, *SSerial, false, listening); +#endif + } + + private : + BlinkerSerialSIM7020 Transp; +}; + +#endif diff --git a/blinker-library/src/BlinkerSerialWHNBIoT.h b/blinker-library/src/BlinkerSerialWHNBIoT.h new file mode 100644 index 0000000..bca8b8f --- /dev/null +++ b/blinker-library/src/BlinkerSerialWHNBIoT.h @@ -0,0 +1,121 @@ +#ifndef BLINKER_SERIAL_WH_NBIOT_H +#define BLINKER_SERIAL_WH_NBIOT_H + +#include "Adapters/BlinkerSerialNBIoT.h" +#include "Blinker/BlinkerApi.h" + +#if defined(ESP32) + #include +#else + #include +#endif + +typedef BlinkerApi BApi; + +class BlinkerSerialWHNBIoT : public BlinkerApi +{ + public : + void begin( uint8_t _rx_pin = 2, + uint8_t _tx_pin = 3, + uint32_t _baud = 9600) + { + BApi::begin(); + ::delay(100); + serialBegin(_rx_pin, _tx_pin, _baud); + BApi::atInit(); + BLINKER_LOG(BLINKER_F("Blinker NBIoT initialized...")); + } + + private : + void serialBegin(uint8_t ss_rx_pin, + uint8_t ss_tx_pin, + uint32_t ss_baud) + { + #if defined (__AVR__) + if (ss_rx_pin == 0 && ss_tx_pin == 1){ + // BApi::begin(); + #if defined (__AVR_ATmega32U4__) + Serial1.begin(ss_baud); + Transp.begin(Serial1, true); + transport(Transp); + #else + Serial.begin(ss_baud); + Transp.begin(Serial, true); + transport(Transp); + #endif + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + #if defined (__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__SAM3X8E__) + else if (ss_rx_pin == 19 && ss_tx_pin == 18){ + // BApi::begin(); + Serial1.begin(ss_baud); + Transp.begin(Serial1, true); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + else if (ss_rx_pin == 17 && ss_tx_pin == 16){ + // BApi::begin(); + Serial2.begin(ss_baud); + Transp.begin(Serial2, true); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + else if (ss_rx_pin == 15 && ss_tx_pin == 14){ + // BApi::begin(); + Serial3.begin(ss_baud); + Transp.begin(Serial3, true); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + #endif + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.begin(*SSerial, false); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + } +#elif defined(ESP8266) + if (ss_rx_pin == RX && ss_tx_pin == TX) { + // BApi::begin(); + Serial.begin(ss_baud); + Transp.begin(Serial, true); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + return; + } + else { + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.begin(*SSerial, false); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); + } +#elif defined(ESP32) + // BApi::begin(); + HSerial = new HardwareSerial(1); + HSerial->begin(ss_baud, SERIAL_8N1, ss_rx_pin, ss_tx_pin); + Transp.begin(*HSerial, true); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); +#else + // BApi::begin(); + SSerial = new SoftwareSerial(ss_rx_pin, ss_tx_pin); + SSerial->begin(ss_baud); + Transp.begin(*SSerial, false); + transport(Transp); + // BLINKER_LOG(BLINKER_F("SerialMQTT initialized...")); +#endif + } + + private : + BlinkerSerialNBIoT Transp; +}; + +#endif diff --git a/blinker-library/src/BlinkerSubDevice.h b/blinker-library/src/BlinkerSubDevice.h new file mode 100644 index 0000000..d909c34 --- /dev/null +++ b/blinker-library/src/BlinkerSubDevice.h @@ -0,0 +1,28 @@ +#ifndef BLINKER_SUBDEVICE_H +#define BLINKER_SUBDEVICE_H + +#ifndef BLINKER_ARDUINOJSON + #define BLINKER_ARDUINOJSON +#endif + +#include "Adapters/BlinkerSubStream.h" +#include "Blinker/BlinkerApi.h" + +typedef BlinkerApi BApi; + +class BlinkerSubDevice : public BlinkerApi +{ + public : + void begin(const char* _auth) + { + BApi::begin(); + Transp.begin(_auth); + transport(Transp); + BLINKER_LOG(BLINKER_F("Blinker SubDevice initialized...")); + } + + private : + BlinkerSubStream Transp; +}; + +#endif diff --git a/blinker-library/src/BlinkerWidgets.h b/blinker-library/src/BlinkerWidgets.h new file mode 100644 index 0000000..338e561 --- /dev/null +++ b/blinker-library/src/BlinkerWidgets.h @@ -0,0 +1,54 @@ +#ifndef BLINKER_WIDGETS_H +#define BLINKER_WIDGETS_H + +#if defined(BLINKER_MQTT) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_MQTT_AUTO) + #include "Functions/BlinkerBridge.h" +#endif + +#include "Functions/BlinkerButton.h" +#include "Functions/BlinkerNumber.h" +#include "Functions/BlinkerImage.h" +#include "Functions/BlinkerRGB.h" +// #if defined(BLINKER_BLE) + #include "Functions/BlinkerJoystick.h" +// #endif +#include "Functions/BlinkerSlider.h" +#include "Functions/BlinkerSwitch.h" +#include "Functions/BlinkerTab.h" +#include "Functions/BlinkerText.h" + +#if defined(BLINKER_ALIGENIE) + #include "Functions/BlinkerAliGenie.h" + + BLINKERALIGENIE BlinkerAliGenie; +#endif + +#if defined(BLINKER_DUEROS) + #include "Functions/BlinkerDuerOS.h" + + BLINKERDUEROS BlinkerDuerOS; +#endif + +#if defined(BLINKER_MIOT) + #include "Functions/BlinkerMIOT.h" + + BLINKERMIOT BlinkerMIOT; +#endif + +#if defined(BLINKER_BLE) || defined(BLINKER_WIFI) || \ + defined(BLINKER_MQTT) || defined(BLINKER_PRO) || \ + defined(BLINKER_NBIOT_WH) || defined(BLINKER_WIFI_GATEWAY) || \ + defined(BLINKER_MQTT_AUTO) || defined(BLINKER_PRO_ESP) || \ + defined(BLINKE_HTTP) + + BlinkerSwitch BUILTIN_SWITCH; +#endif + +#if defined(BLINKER_PRO_ESP) + #include "Functions/BlinkerEvent.h" + + BLINKEREVENT BlinkerEvent; +#endif + +#endif diff --git a/blinker-library/src/Functions/.pydio b/blinker-library/src/Functions/.pydio new file mode 100644 index 0000000..5dcd60b --- /dev/null +++ b/blinker-library/src/Functions/.pydio @@ -0,0 +1 @@ +0bf25fb8-7abb-45d2-84c4-7b568cf00839 \ No newline at end of file diff --git a/blinker-library/src/Functions/BlinkerAIR202.h b/blinker-library/src/Functions/BlinkerAIR202.h new file mode 100644 index 0000000..c6e6947 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerAIR202.h @@ -0,0 +1,814 @@ +#ifndef BLINKER_AIR202_H +#define BLINKER_AIR202_H + +#if defined(ARDUINO) + #if ARDUINO >= 100 + #include + #else + #include + #endif +#endif + +#include "../Blinker/BlinkerATMaster.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +// #if defined(ESP32) +// #include + +// HardwareSerial *HSerial_API; +// #else +// #include + +// SoftwareSerial *SSerial_API; +// #endif + +#include + +#define BLINKER_AIR202_DATA_BUFFER_SIZE 1024 + +enum air202_status_t +{ + air202_cgtt_state_ver_check, + air202_cgtt_state_ver_check_success, + air202_cgtt_state, + air202_cgtt_state_req, + air202_cgtt_state_success, + air202_sapbar_pdp_req, + air202_sapbar_pdp_success, + air202_sapbar_pdp_failed, + air202_sapbar_apn_req, + air202_sapbar_apn_success, + air202_sapbar_apn_failed, + air202_sapbar_save_req, + air202_sapbar_save_success, + air202_sapbar_save_failed, + air202_sapbar_fresh_req, + air202_sapbar_fresh_success, + air202_sapbar_fresh_failed, +}; + +class BlinkerAIR202 +{ + public : + BlinkerAIR202() : + isHWS(false) + {} + + ~BlinkerAIR202() { flush(); } + + time_t _ntpTime = 0; + + void setStream(Stream& s, bool isHardware, blinker_callback_t _func) + { stream = &s; isHWS = isHardware; listenFunc = _func; } + + void setTimezone(float tz) { _timezone = tz; } + String lang() { return _LANG; } + String lat() { return _LAT; } + // int16_t year() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_year + 1900; + // } + // return -1; + // } + + // int8_t month() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_mon + 1; + // } + // return -1; + // } + + // int8_t mday() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_mday; + // } + // return -1; + // } + + // int8_t wday() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_wday; + // } + // return -1; + // } + + // int8_t hour() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_hour; + // } + // return -1; + // } + + // int8_t minute() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_min; + // } + // return -1; + // } + + // int8_t second() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_sec; + // } + // return -1; + // } + + // time_t time() + // { + // if (_ntpTime) + // { + // return _ntpTime - _timezone * 3600; + // } + // return millis(); + // } + + // int32_t dtime() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_hour * 60 * 60 + timeinfo.tm_min * 60 + timeinfo.tm_sec; + // } + // return -1; + // } + + bool getNTP(float tz = 8.0) + { + streamPrint(BLINKER_CMD_CNTP_REQ); + uint32_t os_time = millis(); + + while(millis() - os_time < _airTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + break; + } + } + } + + streamPrint(BLINKER_CMD_CCLK_REQ); + os_time = millis(); + + while(millis() - os_time < _airTimeout * 10) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CCLK) + { + struct tm timeinfo; + + timeinfo.tm_year = _masterAT->getParam(0).substring(2, 4).toInt() + 130; + timeinfo.tm_mon = _masterAT->getParam(0).substring(5, 7).toInt() - 1; + timeinfo.tm_mday = _masterAT->getParam(0).substring(8, 10).toInt() - 1; + + timeinfo.tm_hour = _masterAT->getParam(1).substring(0, 2).toInt(); + timeinfo.tm_min = _masterAT->getParam(1).substring(3, 5).toInt(); + timeinfo.tm_sec = _masterAT->getParam(1).substring(6, 8).toInt(); + + // BLINKER_LOG_ALL(BLINKER_F("year: "), timeinfo.tm_year); + // BLINKER_LOG_ALL(BLINKER_F("mon: "), timeinfo.tm_mon); + // BLINKER_LOG_ALL(BLINKER_F("mday: "), timeinfo.tm_mday); + // BLINKER_LOG_ALL(BLINKER_F("hour: "), timeinfo.tm_hour); + // BLINKER_LOG_ALL(BLINKER_F("mins: "), timeinfo.tm_min); + // BLINKER_LOG_ALL(BLINKER_F("secs: "), timeinfo.tm_sec); + + #if defined(ESP8266) || defined(ESP32) + _ntpTime = mktime(&timeinfo); + #else + _ntpTime = mk_gmtime(&timeinfo); + #endif + + BLINKER_LOG_ALL(BLINKER_F("year: "), timeinfo.tm_year); + BLINKER_LOG_ALL(BLINKER_F("mon: "), timeinfo.tm_mon); + BLINKER_LOG_ALL(BLINKER_F("mday: "), timeinfo.tm_mday); + BLINKER_LOG_ALL(BLINKER_F("hour: "), timeinfo.tm_hour); + BLINKER_LOG_ALL(BLINKER_F("mins: "), timeinfo.tm_min); + BLINKER_LOG_ALL(BLINKER_F("secs: "), timeinfo.tm_sec); + + // ::delay(200); + + // _ntpTime = mktime(&timeinfo); + // _ntpTime -= _timezone * 3600; + + BLINKER_LOG_ALL(BLINKER_F("==_ntpTime: "), _ntpTime); + BLINKER_LOG_ALL(BLINKER_F("==_ntpTime: "), timeinfo.tm_hour); + BLINKER_LOG_ALL(BLINKER_F("==Current time: "), asctime(&timeinfo)); + + free(_masterAT); + return true; + } + + free(_masterAT); + } + } + return false; + } + + bool getAMGSMLOC(float tz = 8.0) + { + uint32_t os_time = millis(); + streamPrint(BLINKER_CMD_AMGSMLOC_REQ); + + while(millis() - os_time < _airTimeout * 10) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_AMGSMLOC && + _masterAT->getParam(0) == " 0") + { + strcpy(_LANG, _masterAT->getParam(1).c_str()); + strcpy(_LAT, _masterAT->getParam(2).c_str()); + + BLINKER_LOG_ALL(BLINKER_F("LANG.: "), _LANG); + BLINKER_LOG_ALL(BLINKER_F("LAT.: "), _LAT); + + struct tm timeinfo; + + timeinfo.tm_year = _masterAT->getParam(3).substring(0, 4).toInt() - 1870; + timeinfo.tm_mon = _masterAT->getParam(3).substring(5, 7).toInt() - 1; + timeinfo.tm_mday = _masterAT->getParam(3).substring(8, 10).toInt() - 1; + + BLINKER_LOG_ALL(BLINKER_F("year: "), timeinfo.tm_year); + BLINKER_LOG_ALL(BLINKER_F("mon: "), timeinfo.tm_mon); + BLINKER_LOG_ALL(BLINKER_F("mday: "), timeinfo.tm_mday); + + timeinfo.tm_hour = _masterAT->getParam(4).substring(0, 2).toInt(); + timeinfo.tm_min = _masterAT->getParam(4).substring(3, 5).toInt(); + timeinfo.tm_sec = _masterAT->getParam(4).substring(6, 8).toInt(); + + BLINKER_LOG_ALL(BLINKER_F("hour: "), timeinfo.tm_hour); + BLINKER_LOG_ALL(BLINKER_F("mins: "), timeinfo.tm_min); + BLINKER_LOG_ALL(BLINKER_F("secs: "), timeinfo.tm_sec); + + #if defined(ESP8266) || defined(ESP32) + _ntpTime = mktime(&timeinfo); + #else + _ntpTime = mk_gmtime(&timeinfo); + #endif + // _ntpTime -= _timezone * 3600; + + BLINKER_LOG_ALL(BLINKER_F("_ntpTime: "), _ntpTime); + + free(_masterAT); + return true; + } + + free(_masterAT); + } + } + return false; + } + + int checkCGTT() + { + uint32_t http_time = millis(); + air202_status_t cgtt_status = air202_cgtt_state_ver_check; + + streamPrint(BLINKER_CMD_CGMMR_REQ); + + cgtt_status = air202_cgtt_state_ver_check; + + while(millis() - http_time < _airTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_CGMMR_RESP) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_cgtt_state_ver_check_success")); + cgtt_status = air202_cgtt_state_ver_check_success; + break; + } + } + } + + if (cgtt_status != air202_cgtt_state_ver_check_success) return false; + + streamPrint(BLINKER_CMD_CGQTT_REQ); + cgtt_status = air202_cgtt_state; + http_time = millis(); + + while(millis() - http_time < _airTimeout) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CGATT && + _masterAT->getParam(0).toInt() == 1) + { + BLINKER_LOG_ALL(BLINKER_F("air202_cgtt_state_req")); + cgtt_status = air202_cgtt_state_req; + free(_masterAT); + break; + } + + free(_masterAT); + } + } + + if (cgtt_status != air202_cgtt_state_req) return false; + // http_time = millis(); + + // while(millis() - http_time < _airTimeout) + // { + // if (available()) + // { + // if (strcmp(streamData, BLINKER_CMD_OK) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("air202_cgtt_state_success")); + // cgtt_status = air202_cgtt_state_success; + // break; + // } + // } + // } + + // if (cgtt_status != air202_cgtt_state_success) return false; + + BLINKER_LOG_ALL(BLINKER_F("check CGTT success")); + + return true; + + // stream->println(BLINKER_CMD_CGQTT_REQ); + + // cgtt_status = air202_cgtt_state; + } + + bool powerCheck() + { + streamPrint(BLINKER_CMD_AT); + streamPrint("ATE0"); + + if (!checkCGTT()) return false; + + BLINKER_LOG_ALL(BLINKER_F("power check")); + streamPrint(BLINKER_CMD_AT); + uint32_t dev_time = millis(); + + while(millis() - dev_time < _airTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("power on")); + + // SAPBR(); + + return SAPBR(); + } + } + } + + return false; + } + + bool SAPBR() + { + streamPrint(STRING_format(BLINEKR_CMD_SAPBR_REQ) + \ + "=3,1,\"CONTYPE\",\"GPRS\""); + + air202_status_t sapbar_status = air202_sapbar_pdp_req; + uint32_t dev_time = millis(); + + while(millis() - dev_time < _airTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_sapbar_pdp_success")); + + sapbar_status = air202_sapbar_pdp_success; + break; + } + } + } + + if (sapbar_status != air202_sapbar_pdp_success) return false; + + streamPrint(STRING_format(BLINEKR_CMD_SAPBR_REQ) + \ + "=3,1,\"APN\",\"CMNET\""); + + sapbar_status = air202_sapbar_apn_req; + dev_time = millis(); + + while(millis() - dev_time < _airTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_sapbar_apn_success")); + + sapbar_status = air202_sapbar_apn_success; + break; + } + } + } + + if (sapbar_status != air202_sapbar_apn_success) return false; + + streamPrint(STRING_format(BLINEKR_CMD_SAPBR_REQ) + "=5,1"); + + sapbar_status = air202_sapbar_save_req; + dev_time = millis(); + + while(millis() - dev_time < _airTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_sapbar_save_success")); + + sapbar_status = air202_sapbar_save_success; + break; + } + } + } + + if (sapbar_status != air202_sapbar_save_success) return false; + + streamPrint(STRING_format(BLINEKR_CMD_SAPBR_REQ) + "=1,1"); + + sapbar_status = air202_sapbar_fresh_req; + dev_time = millis(); + + while(millis() - dev_time < _airTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_sapbar_fresh_success")); + + sapbar_status = air202_sapbar_fresh_success; + break; + } + } + } + + if (sapbar_status != air202_sapbar_fresh_success) return false; + + return true; + } + + String getIMEI() + { + uint32_t dev_time = millis(); + + streamPrint(BLINEKR_CMD_CGSN_REQ); + + char _imei[16]; + + while(millis() - dev_time < _airTimeout) + { + if (available()) + { + BLINKER_LOG_ALL(BLINKER_F("get IMEI: "), streamData, + BLINKER_F(", length: "), strlen(streamData)); + if (strlen(streamData) == 15) + { + strcpy(_imei, streamData); + } + } + } + + dev_time = millis(); + + while(millis() - dev_time < _airTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("get IMEI: "), _imei, + BLINKER_F(", length: "), strlen(streamData)); + return _imei; + } + } + } + + BLINKER_LOG_ALL(BLINKER_F("get IMEI: "), _imei, + BLINKER_F(", length: "), strlen(streamData)); + + return _imei; + } + + String getICCID() + { + uint32_t dev_time = millis(); + + streamPrint(BLINKER_CMD_ICCID_REQ); + + char _iccid[21]; + + while(millis() - dev_time < _airTimeout) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_ICCID) + { + String get_iccid = _masterAT->getParam(0); + + if (_masterAT->getParam(0).length() == 20) + { + strcpy(_iccid, _masterAT->getParam(0).c_str()); + free(_masterAT); + + BLINKER_LOG_ALL(BLINKER_F("get ICCID: "), _iccid, + BLINKER_F(", length: "), strlen(_iccid)); + break; + } + } + + free(_masterAT); + } + } + + dev_time = millis(); + + while(millis() - dev_time < _airTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("get ICCID: "), _iccid, + BLINKER_F(", length: "), strlen(streamData)); + return _iccid; + } + } + } + + BLINKER_LOG_ALL(BLINKER_F("get ICCID: "), _iccid, + BLINKER_F(", length: "), strlen(streamData)); + + return _iccid; + } + + bool isReboot() + { + streamPrint(BLINKER_CMD_AT); + uint32_t dev_time = millis(); + + while(millis() - dev_time < _airTimeout) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_AT, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("device reboot")); + + // SAPBR(); + streamPrint("ATE0"); + + return true; + } + // else if (strcmp(streamData, BLINKER_CMD_OK) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("device not reboot")); + // return false; + // } + } + } + streamPrint("ATE0"); + + return false; + } + + void flush() + { + if (isFresh) free(streamData); + } + + protected : + class BlinkerMasterAT * _masterAT; + blinker_callback_t listenFunc = NULL; + Stream* stream; + // char streamData[128]; + char* streamData; + bool isFresh = false; + bool isHWS = false; + uint16_t _airTimeout = 1000; + + // time_t _ntpTime = 0; + + float _timezone = 8.0; + + char _LANG[14]; + char _LAT[14]; + // int16_t _year = -1; + // int8_t _mon = -1; + // int8_t _mday = -1; + // int16_t _hour = -1; + // int8_t _mins = -1; + // int8_t _secs = -1; + + void streamPrint(const String & s) + { + stream->println(s); + BLINKER_LOG_ALL(s); + } + + int timedRead() + { + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; + } + + bool available() + { + yield(); + + if (!isHWS) + { + // #if defined(__AVR__) || defined(ESP8266) + // if (!SSerial_API->isListening()) + // { + // SSerial_API->listen(); + // ::delay(100); + // } + // #endif + + if (listenFunc) listenFunc(); + } + + // char _data[BLINKER_AIR202_DATA_BUFFER_SIZE];// = { '\0' }; + // memset(_data, '\0', BLINKER_AIR202_DATA_BUFFER_SIZE); + + if (stream->available()) + { + // strcpy(_data, stream->readStringUntil('\n').c_str()); + String _data = stream->readStringUntil('\n'); + BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), _data); + // _data[strlen(_data) - 1] = '\0'; + if (isFresh) + { + free(streamData); + isFresh = false; + } + + if (_data.length() <= 1) return false; + + streamData = (char*)malloc((_data.length() + 1)*sizeof(char)); + strcpy(streamData, _data.c_str()); + if (_data.length() > 0) streamData[_data.length() - 1] = '\0'; + isFresh = true; + return true; +// // streamData = ""; +// // memset(streamData, '\0', 128); +// if (isFresh) free(streamData); +// streamData = (char*)malloc(1*sizeof(char)); + +// // strcpy(streamData, stream->readStringUntil('\n').c_str()); + +// // int16_t dNum = strlen(streamData); + +// // BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), streamData, +// // BLINKER_F(", dNum: "), dNum); +// // // stream->readString(); + +// int16_t dNum = 0; +// int c_d = timedRead(); +// while (dNum < BLINKER_MAX_READ_SIZE && +// c_d >=0 && c_d != '\n') +// { +// // if (c_d != '\r') +// { +// streamData[dNum] = (char)c_d; +// dNum++; +// streamData = (char*)realloc(streamData, (dNum+1)*sizeof(char)); +// } + +// c_d = timedRead(); +// } +// // dNum++; +// // // // streamData = (char*)realloc(streamData, dNum*sizeof(char)); + +// // streamData[dNum-1] = '\0'; +// // stream->flush(); +// // 7b2264657461696c223a207b2262726f6b6572223a2022616c6979756e222c20226465766963654e616d65223a20223237383636394232304d3235423634323230354e33435850222c2022696f744964223a20225346455467613255784b784e386a69716e4e516730303130356435343030222c2022696f74546f6b656e223a20226331353530643464346334623432666338376431343639373333363166353539222c202270726f647563744b6579223a20224a67434762486c6e64677a222c202275756964223a20223733633762356134623266323231633061373264376234313238653430323337227d2c20226d657373616765223a20313030307d + +// // BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, +// // BLINKER_F(" , dNum: "), dNum); +// // BLINKER_LOG_FreeHeap_ALL(); + +// if (dNum < BLINKER_MAX_READ_SIZE && dNum > 0) +// { +// // if (streamData[dNum - 1] == '\r') +// streamData[dNum - 1] = '\0'; +// BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, +// BLINKER_F(" , dNum: "), dNum); + +// isFresh = true; +// return true; +// } +// else +// { +// return false; +// } + } + else + { + return false; + } + } +}; + +// BlinkerAIR202 BLINKER_AIR202; + +#endif diff --git a/blinker-library/src/Functions/BlinkerAliGenie.h b/blinker-library/src/Functions/BlinkerAliGenie.h new file mode 100644 index 0000000..5e4a78e --- /dev/null +++ b/blinker-library/src/Functions/BlinkerAliGenie.h @@ -0,0 +1,619 @@ +#ifndef BLINKER_ALIGENIE_H +#define BLINKER_ALIGENIE_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BLINKERALIGENIE +{ + public : + BLINKERALIGENIE() {} + + void attachPowerState(blinker_callback_with_string_uint8_arg_t newFunction) + { + Blinker.attachAliGenieSetPowerState(newFunction); + } + + void attachPowerState(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachAliGenieSetPowerState(newFunction); + } + + void attachHSwing(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachAliGenieSetHSwingState(newFunction); + } + + void attachVSwing(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachAliGenieSetVSwingState(newFunction); + } + + void attachColor(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachAliGenieSetColor(newFunction); + } + + void attachMode(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachAliGenieSetMode(newFunction); + } + + void attachCancelMode(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachAliGenieSetcMode(newFunction); + } + + void attachLevel(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachAliGenieSetLevel(newFunction); + } + + void attachLevel(blinker_callback_with_uint8_arg_t newFunction) + { + Blinker.attachAliGenieSetLevel(newFunction); + } + + void attachRelativeLevel(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachAliGenieRelativeLevel(newFunction); + } + + void attachTemp(blinker_callback_with_uint8_arg_t newFunction) + { + Blinker.attachAliGenieSetTemp(newFunction); + } + + void attachRelativeTemp(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachAliGenieRelativeTemp(newFunction); + } + + void attachBrightness(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachAliGenieSetBrightness(newFunction); + } + + void attachRelativeBrightness(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachAliGenieRelativeBrightness(newFunction); + } + + void attachColorTemperature(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachAliGenieSetColorTemperature(newFunction); + } + + void attachRelativeColorTemperature(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachAliGenieRelativeColorTemperature(newFunction); + } + + void attachQuery(blinker_callback_with_int32_uint8_arg_t newFunction) + { + Blinker.attachAliGenieQuery(newFunction); + } + + void attachQuery(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachAliGenieQuery(newFunction); + } + + void powerState(const String & state, uint8_t num) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_POWERSTATE); + payload += BLINKER_F("\":\""); + payload += state; + if (num != 0) + { + payload += BLINKER_F("\",\"num\":"); + payload += STRING_format(num); + } + else + { + payload += BLINKER_F("\""); + } + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 0 & 0x01) { + free(aState); + } + + aState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aState, payload.c_str()); + + _fresh |= 0x01 << 0; + } + + void powerState(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_POWERSTATE); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 0 & 0x01) { + free(aState); + } + + aState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aState, payload.c_str()); + + _fresh |= 0x01 << 0; + } + + void color(const String & clr) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_COLOR_); + payload += BLINKER_F("\":\""); + payload += clr; + payload += BLINKER_F("\","); + payload += BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_COLOR); + payload += BLINKER_F("\":\""); + payload += clr; + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 1 & 0x01) { + free(aColor); + } + + aColor = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aColor, payload.c_str()); + + _fresh |= 0x01 << 1; + } + + void mode(const String & md) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_MODE); + payload += BLINKER_F("\":\""); + payload += md; + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 2 & 0x01) { + free(aMode); + } + + aMode = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aMode, payload.c_str()); + + _fresh |= 0x01 << 2; + } + + void colorTemp(int clrTemp) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_COLORTEMP); + payload += BLINKER_F("\":\""); + payload += STRING_format(clrTemp); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 3 & 0x01) { + free(aCtemp); + } + + aCtemp = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aCtemp, payload.c_str()); + + _fresh |= 0x01 << 3; + } + + void brightness(int bright) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_BRIGHTNESS); + payload += BLINKER_F("\":\""); + payload += STRING_format(bright); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 4 & 0x01) { + free(aBright); + } + + aBright = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aBright, payload.c_str()); + + _fresh |= 0x01 << 4; + } + + void temp(double _temp) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_TEMP); + payload += BLINKER_F("\":\""); + payload += STRING_format(_temp); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 5 & 0x01) { + free(aTemp); + } + + aTemp = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aTemp, payload.c_str()); + + _fresh |= 0x01 << 5; + } + + void temp(float _temp) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_TEMP); + payload += BLINKER_F("\":\""); + payload += STRING_format(_temp); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 5 & 0x01) { + free(aTemp); + } + + aTemp = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aTemp, payload.c_str()); + + _fresh |= 0x01 << 5; + } + + void temp(int _temp) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_TEMP); + payload += BLINKER_F("\":\""); + payload += STRING_format(_temp); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 5 & 0x01) { + free(aTemp); + } + + aTemp = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aTemp, payload.c_str()); + + _fresh |= 0x01 << 5; + } + + void humi(double _humi) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_HUMI); + payload += BLINKER_F("\":\""); + payload += STRING_format(_humi); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 6 & 0x01) { + free(aHumi); + } + + aHumi = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aHumi, payload.c_str()); + + _fresh |= 0x01 << 6; + } + + void humi(float _humi) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_HUMI); + payload += BLINKER_F("\":\""); + payload += STRING_format(_humi); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 6 & 0x01) { + free(aHumi); + } + + aHumi = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aHumi, payload.c_str()); + + _fresh |= 0x01 << 6; + } + + void humi(int _humi) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_HUMI); + payload += BLINKER_F("\":\""); + payload += STRING_format(_humi); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 6 & 0x01) { + free(aHumi); + } + + aHumi = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aHumi, payload.c_str()); + + _fresh |= 0x01 << 6; + } + + void pm25(double _pm25) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_PM25); + payload += BLINKER_F("\":\""); + payload += STRING_format(_pm25); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 7 & 0x01) { + free(aPm25); + } + + aPm25 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aPm25, payload.c_str()); + + _fresh |= 0x01 << 7; + } + + void pm25(float _pm25) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_PM25); + payload += BLINKER_F("\":\""); + payload += STRING_format(_pm25); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 7 & 0x01) { + free(aPm25); + } + + aPm25 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aPm25, payload.c_str()); + + _fresh |= 0x01 << 7; + } + + void pm25(int _pm25) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_PM25); + payload += BLINKER_F("\":\""); + payload += STRING_format(_pm25); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 7 & 0x01) { + free(aPm25); + } + + aPm25 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aPm25, payload.c_str()); + + _fresh |= 0x01 << 7; + } + + void level(uint8_t _level) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_LEVEL); + payload += BLINKER_F("\":\""); + payload += STRING_format(_level); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 8 & 0x01) { + free(aLevel); + } + + aLevel = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aLevel, payload.c_str()); + + _fresh |= 0x01 << 8; + } + + void level(const String & _level) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_LEVEL); + payload += BLINKER_F("\":\""); + payload += _level; + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 8 & 0x01) { + free(aLevel); + } + + aLevel = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aLevel, payload.c_str()); + + _fresh |= 0x01 << 8; + } + + void hswing(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_HSTATE); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + if (_fresh >> 9 & 0x01) { + free(ahState); + } + + ahState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(ahState, payload.c_str()); + + _fresh |= 0x01 << 9; + } + + void vswing(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_VSTATE); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + if (_fresh >> 10 & 0x01) { + free(avState); + } + + avState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(avState, payload.c_str()); + + _fresh |= 0x01 << 10; + } + + void print() + { + if (_fresh == 0) return; + + String aliData; + + if (_fresh >> 0 & 0x01) { + if (aliData.length()) aliData += BLINKER_F(","); + else aliData += BLINKER_F("{"); + + aliData += aState; + + free(aState); + } + + if (_fresh >> 1 & 0x01) { + if (aliData.length()) aliData += BLINKER_F(","); + else aliData += BLINKER_F("{"); + + aliData += aColor; + + free(aColor); + } + + if (_fresh >> 2 & 0x01) { + if (aliData.length()) aliData += BLINKER_F(","); + else aliData += BLINKER_F("{"); + + aliData += aMode; + + free(aMode); + } + + if (_fresh >> 3 & 0x01) { + if (aliData.length()) aliData += BLINKER_F(","); + else aliData += BLINKER_F("{"); + + aliData += aCtemp; + + free(aCtemp); + } + + if (_fresh >> 4 & 0x01) { + if (aliData.length()) aliData += BLINKER_F(","); + else aliData += BLINKER_F("{"); + + aliData += aBright; + + free(aBright); + } + + if (_fresh >> 5 & 0x01) { + if (aliData.length()) aliData += BLINKER_F(","); + else aliData += BLINKER_F("{"); + + aliData += aTemp; + + free(aTemp); + } + + if (_fresh >> 6 & 0x01) { + if (aliData.length()) aliData += BLINKER_F(","); + else aliData += BLINKER_F("{"); + + aliData += aHumi; + + free(aHumi); + } + + if (_fresh >> 7 & 0x01) { + if (aliData.length()) aliData += BLINKER_F(","); + else aliData += BLINKER_F("{"); + + aliData += aPm25; + + free(aPm25); + } + + if (_fresh >> 8 & 0x01) { + if (aliData.length()) aliData += BLINKER_F(","); + else aliData += BLINKER_F("{"); + + aliData += aLevel; + + free(aLevel); + } + + if (_fresh >> 9 & 0x01) { + if (aliData.length()) aliData += BLINKER_F(","); + else aliData += BLINKER_F("{"); + + aliData += ahState; + + free(ahState); + } + + if (_fresh >> 10 & 0x01) { + if (aliData.length()) aliData += BLINKER_F(","); + else aliData += BLINKER_F("{"); + + aliData += avState; + + free(avState); + } + + aliData += BLINKER_F("}"); + + _fresh = 0; + + Blinker.aligeniePrint(aliData); + } + + private : + char * aState; + char * aColor; + char * aMode; + char * aCtemp; + char * aBright; + char * aTemp; + char * aHumi; + char * aPm25; + + char * aLevel; + char * ahState; + char * avState; + uint16_t _fresh = 0; +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerBridge.h b/blinker-library/src/Functions/BlinkerBridge.h new file mode 100644 index 0000000..d95d655 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerBridge.h @@ -0,0 +1,65 @@ +#ifndef BLINKER_BRIDGE_H +#define BLINKER_BRIDGE_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BlinkerBridge +{ + public : + BlinkerBridge(char _key[], blinker_callback_with_string_arg_t _func = NULL) + { + bNum = Blinker.attachBridge(_key, _func); + } + + void attach(blinker_callback_with_string_arg_t _func) + { + if (bNum == 0) return; + + Blinker.freshAttachBridge(Blinker.bridgeKey(bNum), _func); + } + + template + void print(T1 n1) + { + BLINKER_LOG_ALL(BLINKER_F("Bridge to: "), bNum, BLINKER_F(", data: "), n1); + if (strcmp(Blinker.bridgeName(bNum), BLINKER_CMD_FALSE) != 0) + { + Blinker.bridgePrint(Blinker.bridgeName(bNum), STRING_format(n1)); + } + } + + template + void print(T1 n1, T2 n2) + { + if (strcmp(Blinker.bridgeName(bNum), BLINKER_CMD_FALSE) != 0) + { + String msg = BLINKER_F("{\""); + msg += STRING_format(n1); + msg += BLINKER_F("\":\""); + msg += STRING_format(n2); + msg += BLINKER_F("\"}"); + + Blinker.bridgePrint(Blinker.bridgeName(bNum), msg); + } + } + + // void name(char name[]) + // { + // _bName = (char*)malloc((strlen(name)+1)*sizeof(char)); + // strcpy(_bName, name); + // } + // char * getName() { return _bName; } + // void freshBridge(const String & name) + // { + // bridgeName = (char*)malloc((name.length()+1)*sizeof(char)); + // strcpy(bridgeName, name.c_str()); + // } + // char * getBridge() { return bridgeName; } + // bool checkName(char name[]) { return strcmp(_bName, name) == 0; } + + private : + uint8_t bNum; +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerButton.h b/blinker-library/src/Functions/BlinkerButton.h new file mode 100644 index 0000000..875626c --- /dev/null +++ b/blinker-library/src/Functions/BlinkerButton.h @@ -0,0 +1,220 @@ +#ifndef BlinkerButton_H +#define BlinkerButton_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BlinkerButton +{ + public : + BlinkerButton(char _name[], blinker_callback_with_string_arg_t _func = NULL) + { + wNum = Blinker.attachWidget(_name, _func); + } + + void attach(blinker_callback_with_string_arg_t _func) + { + if (wNum == 0) return; + + Blinker.freshAttachWidget(Blinker.widgetName_str(wNum), _func); + } + + void icon(const String & _icon) + { + if (_fresh >> 0 & 0x01) free(bicon); + + bicon = (char*)malloc((_icon.length()+1)*sizeof(char)); + strcpy(bicon, _icon.c_str()); + + _fresh |= 0x01 << 0; + } + + void color(const String & _clr) + { + if (_fresh >> 1 & 0x01) free(iconClr); + + iconClr = (char*)malloc((_clr.length()+1)*sizeof(char)); + strcpy(iconClr, _clr.c_str()); + + _fresh |= 0x01 << 1; + } + + template + void content(T _con) + { + if (_fresh >> 2 & 0x01) free(bcon); + + String _bcon = STRING_format(_con); + bcon = (char*)malloc((_bcon.length()+1)*sizeof(char)); + strcpy(bcon, _bcon.c_str()); + + _fresh |= 0x01 << 2; + } + + template + void text(T _text) + { + if (_fresh >> 3 & 0x01) free(btext); + + String _btext = STRING_format(_text); + btext = (char*)malloc((_btext.length()+1)*sizeof(char)); + strcpy(btext, _btext.c_str()); + + _fresh |= 0x01 << 3; + } + + template + void text(T1 _text1, T2 _text2) + { + if (_fresh >> 3 & 0x01) free(btext); + + String _btext = STRING_format(_text1); + btext = (char*)malloc((_btext.length()+1)*sizeof(char)); + strcpy(btext, _btext.c_str()); + + _fresh |= 0x01 << 3; + + if (_fresh >> 4 & 0x01) free(btext1); + + _btext = STRING_format(_text2); + btext1 = (char*)malloc((_btext.length()+1)*sizeof(char)); + strcpy(btext1, _btext.c_str()); + + _fresh |= 0x01 << 4; + } + + void textColor(const String & _clr) + { + if (_fresh >> 5 & 0x01) free(textClr); + + textClr = (char*)malloc((_clr.length()+1)*sizeof(char)); + strcpy(textClr, _clr.c_str()); + + _fresh |= 0x01 << 5; + } + + void print() { print(""); } + + void print(const String & _state) + { + if ((_fresh == 0 && _state.length() == 0) || \ + wNum == 0) + { + return; + } + + String buttonData; + + if (_state.length()) + { + buttonData += BLINKER_F("{\""); + buttonData += BLINKER_F(BLINKER_CMD_SWITCH); + buttonData += BLINKER_F("\":\""); + buttonData += (_state); + buttonData += BLINKER_F("\""); + } + + if (_fresh >> 0 & 0x01) + { + if (buttonData.length()) buttonData += BLINKER_F(","); + else buttonData += BLINKER_F("{"); + + buttonData += BLINKER_F("\""); + buttonData += BLINKER_F(BLINKER_CMD_ICON); + buttonData += BLINKER_F("\":\""); + buttonData += (bicon); + buttonData += BLINKER_F("\""); + + free(bicon); + } + + if (_fresh >> 1 & 0x01) + { + if (buttonData.length()) buttonData += BLINKER_F(","); + else buttonData += STRING_format(BLINKER_F("{")); + + buttonData += BLINKER_F("\""); + buttonData += BLINKER_F(BLINKER_CMD_COLOR); + buttonData += BLINKER_F("\":\""); + buttonData += (iconClr); + buttonData += BLINKER_F("\""); + + free(iconClr); + } + + if (_fresh >> 2 & 0x01) + { + if (buttonData.length()) buttonData += BLINKER_F(","); + else buttonData += BLINKER_F("{"); + + buttonData += BLINKER_F("\""); + buttonData += BLINKER_F(BLINKER_CMD_CONTENT); + buttonData += BLINKER_F("\":\""); + buttonData += (bcon); + buttonData += BLINKER_F("\""); + + free(bcon); + } + + if (_fresh >> 3 & 0x01) + { + if (buttonData.length()) buttonData += BLINKER_F(","); + else buttonData += BLINKER_F("{"); + + buttonData += BLINKER_F("\""); + buttonData += BLINKER_F(BLINKER_CMD_TEXT); + buttonData += BLINKER_F("\":\""); + buttonData += (btext); + buttonData += BLINKER_F("\""); + + free(btext); + } + + if (_fresh >> 4 & 0x01) + { + if (buttonData.length()) buttonData += BLINKER_F(","); + else buttonData += BLINKER_F("{"); + + buttonData += BLINKER_F("\""); + buttonData += BLINKER_F(BLINKER_CMD_TEXT1); + buttonData += BLINKER_F("\":\""); + buttonData += (btext1); + buttonData += BLINKER_F("\""); + + free(btext1); + } + + if (_fresh >> 5 & 0x01) + { + if (buttonData.length()) buttonData += BLINKER_F(","); + else buttonData += BLINKER_F("{"); + + buttonData += BLINKER_F("\""); + buttonData += BLINKER_F(BLINKER_CMD_TEXTCOLOR); + buttonData += BLINKER_F("\":\""); + buttonData += (textClr); + buttonData += BLINKER_F("\""); + + free(textClr); + } + + buttonData += BLINKER_F("}"); + + _fresh = 0; + + Blinker.printArray(Blinker.widgetName_str(wNum), buttonData); + } + + private : + uint8_t wNum; + + char * bicon; + char * iconClr; + char * bcon; + char * btext; + char * btext1; + char * textClr; + uint8_t _fresh = 0; +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerChart.h b/blinker-library/src/Functions/BlinkerChart.h new file mode 100644 index 0000000..dc02513 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerChart.h @@ -0,0 +1,69 @@ +#ifndef BLINKER_REAL_TIME_DATA_H +#define BLINKER_REAL_TIME_DATA_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BlinkerRealTimeData +{ + public : + BlinkerRealTimeData(char _name[], blinker_callback_t _func = NULL) + { + Blinker.attachRTData(_name, _func); + } + + void saveData(char key[], int32_t data) + { + if (_count = 0) + { + strcpy(_keys, key); + } + + _datas[_count] = data; + _times[_count] = Blinker.time(); + + _count++; + } + + void print() + { + String rtData; + + if (_count > 0) + { + rtData = BLINKER_F("{\"rt\":\"{\""); + rtData += STRING_format(_keys); + rtData += BLINKER_F("\":["); + + for (uint8_t i = 0; i < _count; i++) + { + rtData += BLINKER_F("{\"value\":"); + rtData += STRING_format(_datas[i]); + rtData += BLINKER_F(",\"date\":"); + rtData += STRING_format(_times[i]); + rtData += BLINKER_F("}"); + + if (i < _count - 1) + { + rtData += BLINKER_F(","); + } + } + + rtData += BLINKER_F("]}}"); + + Blinker.printObject(Blinker.widgetName_str(wNum), buttonData); + + _count = 0; + } + } + + private : + uint8_t wNum; + + uint8_t _count = 0; + int32_t _datas[12]; + time_t _times[12]; + char _keys[12]; +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerDuerOS.h b/blinker-library/src/Functions/BlinkerDuerOS.h new file mode 100644 index 0000000..59d443b --- /dev/null +++ b/blinker-library/src/Functions/BlinkerDuerOS.h @@ -0,0 +1,935 @@ +#ifndef BLINKER_DUEROS_H +#define BLINKER_DUEROS_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BLINKERDUEROS +{ + public : + BLINKERDUEROS() {} + + void attachPowerState(blinker_callback_with_string_uint8_arg_t newFunction) + { + Blinker.attachDuerOSSetPowerState(newFunction); + } + + void attachPowerState(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachDuerOSSetPowerState(newFunction); + } + + void attachColor(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachDuerOSSetColor(newFunction); + } + + void attachMode(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachDuerOSSetMode(newFunction); + } + + void attachCancelMode(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachDuerOSSetcMode(newFunction); + } + + void attachLevel(blinker_callback_with_uint8_arg_t newFunction) + { + Blinker.attachDuerOSSetLevel(newFunction); + } + + void attachRelativeLevel(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachDuerOSRelativeLevel(newFunction); + } + + void attachTemp(blinker_callback_with_uint8_arg_t newFunction) + { + Blinker.attachDuerOSSetTemp(newFunction); + } + + void attachRelativeTemp(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachDuerOSRelativeTemp(newFunction); + } + + void attachBrightness(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachDuerOSSetBrightness(newFunction); + } + + void attachRelativeBrightness(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachDuerOSRelativeBrightness(newFunction); + } + + void attachColorTemperature(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachDuerOSSetColorTemperature(newFunction); + } + + void attachRelativeColorTemperature(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachDuerOSRelativeColorTemperature(newFunction); + } + + void attachQuery(blinker_callback_with_int32_uint8_arg_t newFunction) + { + Blinker.attachDuerOSQuery(newFunction); + } + + void attachQuery(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachDuerOSQuery(newFunction); + } + + void powerState(const String & state, uint8_t num) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_POWERSTATE); + payload += BLINKER_F("\":\""); + payload += state; + if (num != 0) + { + payload += BLINKER_F("\",\"num\":"); + payload += STRING_format(num); + } + else + { + payload += BLINKER_F("\""); + } + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 0 & 0x01) { + free(aState); + } + + aState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aState, payload.c_str()); + + _fresh |= 0x01 << 0; + } + + void powerState(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_POWERSTATE); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 0 & 0x01) { + free(aState); + } + + aState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aState, payload.c_str()); + + _fresh |= 0x01 << 0; + } + + void color(int32_t clr) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_COLOR_); + payload += BLINKER_F("\":\""); + payload += clr; + payload += BLINKER_F("\","); + payload += BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_COLOR); + payload += BLINKER_F("\":\""); + payload += clr; + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 1 & 0x01) { + free(aColor); + } + + aColor = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aColor, payload.c_str()); + + _fresh |= 0x01 << 1; + } + + void mode(const String & now_md) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_MODE); + payload += BLINKER_F("\":[\"\",\""); + payload += now_md; + payload += BLINKER_F("\"]"); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 2 & 0x01) { + free(aMode); + } + + aMode = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aMode, payload.c_str()); + + _fresh |= 0x01 << 2; + } + + void mode(const String & pre_md, const String & now_md) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_MODE); + payload += BLINKER_F("\":[\""); + payload += pre_md; + payload += BLINKER_F("\",\""); + payload += now_md; + payload += BLINKER_F("\"]"); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 2 & 0x01) { + free(aMode); + } + + aMode = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aMode, payload.c_str()); + + _fresh |= 0x01 << 2; + } + + void colorTemp(int clrTemp) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_COLORTEMP); + payload += BLINKER_F("\":\""); + payload += STRING_format(clrTemp); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 3 & 0x01) { + free(aCtemp); + } + + aCtemp = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aCtemp, payload.c_str()); + + _fresh |= 0x01 << 3; + } + + void brightness(int now_bright) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_BRIGHTNESS); + payload += BLINKER_F("\":[\"\","); + payload += STRING_format(now_bright); + payload += BLINKER_F("]"); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 4 & 0x01) { + free(aBright); + } + + aBright = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aBright, payload.c_str()); + + _fresh |= 0x01 << 4; + } + + void brightness(int pre_bright, int now_bright) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_BRIGHTNESS); + payload += BLINKER_F("\":["); + payload += STRING_format(pre_bright); + payload += BLINKER_F(","); + payload += STRING_format(now_bright); + payload += BLINKER_F("]"); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 4 & 0x01) { + free(aBright); + } + + aBright = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aBright, payload.c_str()); + + _fresh |= 0x01 << 4; + } + + void temp(double _temp) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_TEMP); + payload += BLINKER_F("\":[\"\","); + payload += STRING_format(_temp); + payload += BLINKER_F("]"); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 5 & 0x01) { + free(aTemp); + } + + aTemp = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aTemp, payload.c_str()); + + _fresh |= 0x01 << 5; + } + + void temp(float _temp) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_TEMP); + payload += BLINKER_F("\":[\"\","); + payload += STRING_format(_temp); + payload += BLINKER_F("]"); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 5 & 0x01) { + free(aTemp); + } + + aTemp = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aTemp, payload.c_str()); + + _fresh |= 0x01 << 5; + } + + void temp(int _temp) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_TEMP); + payload += BLINKER_F("\":[\"\","); + payload += STRING_format(_temp); + payload += BLINKER_F("]"); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 5 & 0x01) { + free(aTemp); + } + + aTemp = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aTemp, payload.c_str()); + + _fresh |= 0x01 << 5; + } + + void humi(double _humi) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_HUMI); + payload += BLINKER_F("\":\""); + payload += STRING_format(_humi); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 6 & 0x01) { + free(aHumi); + } + + aHumi = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aHumi, payload.c_str()); + + _fresh |= 0x01 << 6; + } + + void humi(float _humi) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_HUMI); + payload += BLINKER_F("\":\""); + payload += STRING_format(_humi); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 6 & 0x01) { + free(aHumi); + } + + aHumi = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aHumi, payload.c_str()); + + _fresh |= 0x01 << 6; + } + + void humi(int _humi) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_HUMI); + payload += BLINKER_F("\":\""); + payload += STRING_format(_humi); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 6 & 0x01) { + free(aHumi); + } + + aHumi = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aHumi, payload.c_str()); + + _fresh |= 0x01 << 6; + } + + void pm25(double _pm25) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_PM25); + payload += BLINKER_F("\":\""); + payload += STRING_format(_pm25); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 7 & 0x01) { + free(aPm25); + } + + aPm25 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aPm25, payload.c_str()); + + _fresh |= 0x01 << 7; + } + + void pm25(float _pm25) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_PM25); + payload += BLINKER_F("\":\""); + payload += STRING_format(_pm25); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 7 & 0x01) { + free(aPm25); + } + + aPm25 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aPm25, payload.c_str()); + + _fresh |= 0x01 << 7; + } + + void pm25(int _pm25) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_PM25); + payload += BLINKER_F("\":\""); + payload += STRING_format(_pm25); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 7 & 0x01) { + free(aPm25); + } + + aPm25 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aPm25, payload.c_str()); + + _fresh |= 0x01 << 7; + } + + void pm10(double _pm10) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_PM10); + payload += BLINKER_F("\":\""); + payload += STRING_format(_pm10); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 8 & 0x01) { + free(aPm10); + } + + aPm10 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aPm10, payload.c_str()); + + _fresh |= 0x01 << 8; + } + + void pm10(float _pm10) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_PM10); + payload += BLINKER_F("\":\""); + payload += STRING_format(_pm10); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 8 & 0x01) { + free(aPm10); + } + + aPm10 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aPm10, payload.c_str()); + + _fresh |= 0x01 << 8; + } + + void pm10(int _pm10) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_PM10); + payload += BLINKER_F("\":\""); + payload += STRING_format(_pm10); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 8 & 0x01) { + free(aPm10); + } + + aPm10 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aPm10, payload.c_str()); + + _fresh |= 0x01 << 8; + } + + void co2(double _co2) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_CO2); + payload += BLINKER_F("\":\""); + payload += STRING_format(_co2); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 9 & 0x01) { + free(aCO2); + } + + aCO2 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aCO2, payload.c_str()); + + _fresh |= 0x01 << 9; + } + + void co2(float _co2) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_CO2); + payload += BLINKER_F("\":\""); + payload += STRING_format(_co2); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 9 & 0x01) { + free(aCO2); + } + + aCO2 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aCO2, payload.c_str()); + + _fresh |= 0x01 << 9; + } + + void co2(int _co2) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_CO2); + payload += BLINKER_F("\":\""); + payload += STRING_format(_co2); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 9 & 0x01) { + free(aCO2); + } + + aCO2 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aCO2, payload.c_str()); + + _fresh |= 0x01 << 9; + } + + void aqi(int _aqi) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_AQI); + payload += BLINKER_F("\":\""); + payload += STRING_format(_aqi); + payload += BLINKER_F("\""); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 10 & 0x01) { + free(aAQI); + } + + aAQI = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aAQI, payload.c_str()); + + _fresh |= 0x01 << 10; + } + + void time(uint32_t _time) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_TIME_ALL); + payload += BLINKER_F("\":"); + payload += STRING_format(_time/1000); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 11 & 0x01) { + free(aTIME); + } + + aTIME = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aTIME, payload.c_str()); + + _fresh |= 0x01 << 11; + } + + void level(uint8_t _level) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_LEVEL); + payload += BLINKER_F("\":"); + payload += STRING_format(_level); + + // Blinker.DuerOSPrint(payload); + + if (_fresh >> 12 & 0x01) { + free(aLevel); + } + + aLevel = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aLevel, payload.c_str()); + + _fresh |= 0x01 << 12; + } + + void print() + { + if (_fresh == 0) return; + + String duerData; + + if (_fresh >> 0 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aState; + + free(aState); + } + + if (_fresh >> 1 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aColor; + + free(aColor); + } + + if (_fresh >> 2 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aMode; + + free(aMode); + } + + if (_fresh >> 3 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aCtemp; + + free(aCtemp); + } + + if (_fresh >> 4 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aBright; + + free(aBright); + } + + if (_fresh >> 5 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aTemp; + + free(aTemp); + } + + if (_fresh >> 6 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aHumi; + + free(aHumi); + } + + if (_fresh >> 7 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aPm25; + + free(aPm25); + } + + if (_fresh >> 8 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aPm10; + + free(aPm10); + } + + if (_fresh >> 9 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aCO2; + + free(aCO2); + } + + if (_fresh >> 10 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aAQI; + + free(aAQI); + } + + if (_fresh >> 11 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aTIME; + + free(aTIME); + } + + if (_fresh >> 12 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aLevel; + + free(aLevel); + } + + duerData += BLINKER_F("}"); + + _fresh = 0; + + Blinker.duerPrint(duerData); + } + + void report() + { + if (_fresh == 0) return; + + String duerData; + bool isCheck = false; + + if (_fresh >> 0 & 0x01) { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aState; + + isCheck = true; + + free(aState); + } + + if (_fresh >> 1 & 0x01) { + if (!isCheck) + { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aColor; + + isCheck = true; + } + + free(aColor); + } + + if (_fresh >> 2 & 0x01) { + if (!isCheck) + { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aMode; + + isCheck = true; + } + + free(aMode); + } + + if (_fresh >> 3 & 0x01) { + if (!isCheck) + { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aBright; + + isCheck = true; + } + + free(aBright); + } + + if (_fresh >> 4 & 0x01) { + if (!isCheck) + { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aTemp; + + isCheck = true; + } + + free(aTemp); + } + + if (_fresh >> 5 & 0x01) { + if (!isCheck) + { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aHumi; + + isCheck = true; + } + + free(aHumi); + } + + if (_fresh >> 6 & 0x01) { + if (!isCheck) + { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aPm25; + + isCheck = true; + } + + free(aPm25); + } + + if (_fresh >> 7 & 0x01) { + if (!isCheck) + { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aPm10; + + isCheck = true; + } + + free(aPm10); + } + + if (_fresh >> 8 & 0x01) { + if (!isCheck) + { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aCO2; + + isCheck = true; + } + + free(aCO2); + } + + if (_fresh >> 9 & 0x01) { + if (!isCheck) + { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aAQI; + + isCheck = true; + } + + free(aAQI); + } + + if (_fresh >> 10 & 0x01) { + if (!isCheck) + { + if (duerData.length()) duerData += BLINKER_F(","); + else duerData += BLINKER_F("{"); + + duerData += aTIME; + + isCheck = true; + } + + free(aTIME); + } + + duerData += BLINKER_F("}"); + + _fresh = 0; + + Blinker.duerPrint(duerData, true); + } + + private : + char * aState; + char * aColor; + char * aMode; + char * aCtemp; + char * aBright; + char * aTemp; + char * aHumi; + char * aPm25; + char * aPm10; + char * aCO2; + char * aAQI; + char * aTIME; + + char * aLevel; + uint16_t _fresh = 0; +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerEvent.h b/blinker-library/src/Functions/BlinkerEvent.h new file mode 100644 index 0000000..cbd6211 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerEvent.h @@ -0,0 +1,32 @@ +#ifndef BLINKER_EVENT_H +#define BLINKER_EVENT_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BLINKEREVENT +{ + public : + BLINKEREVENT() + {} + + void warning(const String & msg) + { + Blinker.eventWarn(msg); + } + + void error(const String & msg) + { + Blinker.eventError(msg); + } + + void message(const String & msg) + { + Blinker.eventMsg(msg); + } + + private : + +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerHTTPAIR202.h b/blinker-library/src/Functions/BlinkerHTTPAIR202.h new file mode 100644 index 0000000..8035205 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerHTTPAIR202.h @@ -0,0 +1,881 @@ +#ifndef BLINKER_HTTP_AIR202_H +#define BLINKER_HTTP_AIR202_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +// #include "Adapters/BlinkerSerialM QTT.h" +#include "../Blinker/BlinkerATMaster.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +// #if defined(ESP32) +// #include + +// HardwareSerial *HSerial_HTTP; +// #else +// #include + +// SoftwareSerial *SSerial_HTTP; +// #endif + +#define BLINKER_HTTP_AIR202_DEFAULT_TIMEOUT 5000UL +#define BLINKER_HTTP_AIR202_DATA_BUFFER_SIZE 1024 + +enum air202_http_status_t +{ + air202_init, + air202_init_success, + air202_ver_check, + air202_ver_check_success, + air202_cgtt, + air202_cgtt_resp, + air202_cgtt_success, + air202_spbar_1, + air202_spbar_1_success, + air202_spbar_2, + air202_spbar_2_success, + air202_http_init, + air202_http_init_success, + air202_http_init_failed, + air202_http_para_set, + air202_http_para_set_success, + air202_http_para_set_failed, + air202_http_start, + air202_http_start_success, + air202_http_start_failed, + air202_http_data_set, + air202_http_data_set_success, + air202_http_data_set_failed, + air202_http_data_post, + air202_http_data_post_success, + air202_http_data_post_failed, + air202_http_upload_success, + air202_http_upload_failed, + air202_http_read_response, + air202_http_read_success, + air202_http_read_failed, + air202_http_read_paylaod, + air202_http_end, + air202_http_end_failed, + air202_http_end_success +}; + +enum air202_status_sap_t +{ + air202_sap_cgtt_state_ver_check, + air202_sap_cgtt_state_ver_check_success, + air202_sap_cgtt_state, + air202_sap_cgtt_state_resp, + air202_sap_cgtt_state_success, + air202_sap_sapbar_pdp_REQ, + air202_sap_sapbar_pdp_success, + air202_sap_sapbar_pdp_failed, + air202_sap_sapbar_apn_REQ, + air202_sap_sapbar_apn_success, + air202_sap_sapbar_apn_failed, + air202_sap_sapbar_save_REQ, + air202_sap_sapbar_save_success, + air202_sap_sapbar_save_failed, + air202_sap_sapbar_fresh_REQ, + air202_sap_sapbar_fresh_success, + air202_sap_sapbar_fresh_failed, +}; + +class BlinkerHTTPAIR202 +{ + public : + BlinkerHTTPAIR202(Stream& s, bool isHardware, blinker_callback_t func) + { stream = &s; isHWS = isHardware; listenFunc = func; } + + ~BlinkerHTTPAIR202() { flush(); } + + void streamPrint(const String & s) + { + // stream->flush(); + BLINKER_LOG_ALL(s); + stream->println(s); + } + + int checkCGTT() + { + uint32_t http_time = millis(); + air202_http_status_t http_status = air202_init; + + streamPrint(BLINKER_CMD_AT); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_init_success")); + http_status = air202_init_success; + break; + } + } + } + + if (http_status != air202_init_success) return false; + + streamPrint(BLINKER_CMD_CGMMR_REQ); + + http_status = air202_ver_check; + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_CGMMR_RESP) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_ver_check_success")); + http_status = air202_ver_check_success; + break; + } + } + } + + if (http_status != air202_ver_check_success) return false; + + streamPrint(BLINKER_CMD_CGQTT_REQ); + + http_status = air202_cgtt; + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CGATT && + _masterAT->getParam(0).toInt() == 1) + { + BLINKER_LOG_ALL(BLINKER_F("air202_cgtt_resp")); + http_status = air202_cgtt_resp; + } + + free(_masterAT); + + break; + } + } + + if (http_status != air202_cgtt_resp) return false; + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_cgtt_success")); + http_status = air202_cgtt_success; + break; + } + } + } + + if (http_status != air202_cgtt_success) return false; + + // stream->println(BLINKER_CMD_CGQTT_REQ); + + // http_status = air202_cgtt; + } + + bool begin(String host, String uri) { _host = host; _uri = uri; } + void setTimeout(uint16_t timeout) { _httpTimeout = timeout; } + bool GET() + { + // streamPrint(STRING_format(BLINKER_CMD_MDISCONNECT_REQ)); + // uint32_t mqtt_time = millis(); + // uint8_t status_get = 0; + + // while(millis() - mqtt_time < _httpTimeout) + // { + // if (available()) + // { + // BLINKER_LOG_ALL(BLINKER_F("== disconnect available ==")); + // if (strcmp(streamData, BLINKER_CMD_CONNACK_OK) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("mqtt disconnect")); + // // return true; + // break; + // } + // } + // } + + // streamPrint(STRING_format(BLINKER_CMD_MIPCLOSE_REQ)); + // mqtt_time = millis(); + + // while(millis() - mqtt_time < _httpTimeout) + // { + // if (available()) + // { + // BLINKER_LOG_ALL(BLINKER_F("== disconnect available ==")); + // if (strcmp(streamData, BLINKER_CMD_CONNACK_OK) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("mqtt disconnect")); + // // return true; + // break; + // } + // } + // } + + // streamPrint(STRING_format(BLINKER_CMD_CIPSHUT_REQ)); + // mqtt_time = millis(); + + // while(millis() - mqtt_time < _httpTimeout) + // { + // if (available()) + // { + // BLINKER_LOG_ALL(BLINKER_F("== disconnect available ==")); + // if (strcmp(streamData, BLINKER_CMD_CONNACK_OK) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("mqtt disconnect")); + // return true; + // // break; + // } + // } + // } + + streamPrint(BLINKER_CMD_HTTPINIT_REQ); + uint32_t http_time = millis(); + air202_http_status_t http_status = air202_http_init; + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_init_success")); + http_status = air202_http_init_success; + break; + } + } + } + + if (http_status != air202_http_init_success) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_init_failed")); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_HTTPPARA_REQ) + "=\"CID\",1"); + + http_status = air202_http_para_set; + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_para_set_success 1")); + http_status = air202_http_para_set_success; + break; + } + } + } + + if (http_status != air202_http_para_set_success) return false; + + streamPrint(STRING_format(BLINKER_CMD_HTTPPARA_REQ) + \ + "=\"URL\",\"" + _host + _uri + "\""); + + http_status = air202_http_para_set; + http_time = millis(); + + while(millis() - http_time < _httpTimeout*2) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_para_set_success 2")); + http_status = air202_http_para_set_success; + break; + } + else if (strcmp(streamData, BLINKER_CMD_ERROR) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_para_set_failed 2")); + // streamPrint("AT+CPOWD"); + break; + } + } + } + + // http_status = air202_http_para_set_success;// TBD + + if (http_status != air202_http_para_set_success) + { + // streamPrint(STRING_format(BLINKER_CMD_HTTPERM_REQ)); + // streamPrint("AT+CPOWD"); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_HTTPACTION_REQ) + "=0"); + + http_status = air202_http_start; + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_start_success")); + http_status = air202_http_start_success; + break; + } + else if (strcmp(streamData, BLINKER_CMD_ERROR) == 0) + { + streamPrint(STRING_format(BLINKER_CMD_HTTPREAD_REQ)); + ::delay(500); + + streamPrint(STRING_format(BLINKER_CMD_HTTPERM_REQ)); + ::delay(500); + + break; + } + } + } + + if (http_status != air202_http_start_success) + { + streamPrint(STRING_format(BLINKER_CMD_HTTPERM_REQ)); + return false; + } + + http_time = millis(); + + while(millis() - http_time < _httpTimeout*10) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_HTTPACTION) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_upload_success")); + http_status = air202_http_upload_success; + free(_masterAT); + break; + } + + free(_masterAT); + + // break; + } + } + + // if (http_status != air202_http_upload_success) return false; + + streamPrint(STRING_format(BLINKER_CMD_HTTPREAD_REQ)); + http_status = air202_http_read_response; + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_HTTPREAD) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_read_success")); + http_status = air202_http_read_success; + free(_masterAT); + break; + } + + free(_masterAT); + + // break; + } + } + + if (http_status != air202_http_read_success) return false; + + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) != 0) + { + // payload = streamData; + + if (isFreshPayload) free(payload); + + isFreshPayload = true; + // char data_buff[1024] = { '\0' }; + payload = (char*)malloc((strlen(streamData) + 1)*sizeof(char)); + strcpy(payload, streamData); + + BLINKER_LOG_ALL(BLINKER_F("payload: "), payload); + } + } + } + + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + break; + } + } + } + + streamPrint(STRING_format(BLINKER_CMD_HTTPERM_REQ)); + http_status = air202_http_end; + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_end_success")); + http_status = air202_http_end_success; + return true; + } + } + } + + if (http_status != air202_http_end_success) return false; + } + + bool POST(String _msg, String _type, String _application) + { + + + uint32_t http_time = millis(); + air202_http_status_t http_status = air202_http_init; + + streamPrint(BLINKER_CMD_HTTPINIT_REQ); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_init_success")); + http_status = air202_http_init_success; + break; + } + } + } + + if (http_status != air202_http_init_success) return false; + + streamPrint(STRING_format(BLINKER_CMD_HTTPPARA_REQ) + "=\"CID\",1"); + http_status = air202_http_para_set; + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_para_set_success 1")); + http_status = air202_http_para_set_success; + break; + } + } + } + + if (http_status != air202_http_para_set_success) return false; + + streamPrint(STRING_format(BLINKER_CMD_HTTPPARA_REQ) + \ + "=\"URL\",\"" + _host + _uri + "\""); + + http_status = air202_http_para_set; + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_para_set_success 2")); + http_status = air202_http_para_set_success; + break; + } + } + } + + if (http_status != air202_http_para_set_success) return false; + + // streamPrint(STRING_format(BLINKER_CMD_HTTPPARA_REQ) + \ + // "=\"" + _type + "\",\"" + _application + "\""); + + // http_status = air202_http_para_set; + // http_time = millis(); + + // while(millis() - http_time < _httpTimeout) + // { + // if (available()) + // { + // if (strcmp(streamData, BLINKER_CMD_OK) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("air202_http_para_set_success 3")); + // http_status = air202_http_para_set_success; + // break; + // } + // } + // } + + // if (http_status != air202_http_para_set_success) return false; + // _msg.replace("\"", "\\22"); + + // _msg = "\"" + _msg + "\""; + streamPrint(STRING_format(BLINKER_CMD_HTTPDATA_REQ) + \ + "=" + _msg.length() + ",10000"); + + http_status = air202_http_data_set; + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_DOWNLOAD) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_data_set_success")); + http_status = air202_http_data_set_success; + break; + } + } + } + + if (http_status != air202_http_data_set_success) return false; + + streamPrint(_msg); + http_status = air202_http_data_post; + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_data_post_success")); + http_status = air202_http_data_post_success; + break; + } + } + } + + if (http_status != air202_http_data_post_success) return false; + + streamPrint(STRING_format(BLINKER_CMD_HTTPACTION_REQ) + "=1"); + + http_status = air202_http_start; + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_start_success")); + http_status = air202_http_start_success; + break; + } + } + } + + if (http_status != air202_http_start_success) + { + streamPrint(STRING_format(BLINKER_CMD_HTTPERM_REQ)); + return false; + } + http_time = millis(); + + while(millis() - http_time < _httpTimeout*2) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_HTTPACTION) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_upload_success")); + http_status = air202_http_upload_success; + free(_masterAT); + break; + } + + free(_masterAT); + + // break; + } + } + + if (http_status != air202_http_upload_success) + { + streamPrint(STRING_format(BLINKER_CMD_HTTPERM_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_HTTPREAD_REQ)); + + http_status = air202_http_read_response; + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_HTTPREAD) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_read_success, data len: "), _masterAT->getParam(0)); + http_status = air202_http_read_success; + free(_masterAT); + break; + } + + free(_masterAT); + + // break; + } + } + + if (http_status != air202_http_read_success) return false; + + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) != 0) + { + // payload = streamData; + if (isFreshPayload) free(payload); + + isFreshPayload = true; + char data_buff[1024] = { '\0' }; + payload = (char*)malloc((strlen(streamData) + 1)*sizeof(char)); + strcpy(payload, streamData); + + BLINKER_LOG_ALL(BLINKER_F("payload: "), payload); + } + } + } + + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + break; + } + } + } + + streamPrint(STRING_format(BLINKER_CMD_HTTPERM_REQ)); + + http_status = air202_http_end; + http_time = millis(); + + while(millis() - http_time < _httpTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("air202_http_end_success")); + http_status = air202_http_end_success; + break; + } + } + } + + if (http_status != air202_http_end_success) return false; + + return true; + } + + String getString() + { + return payload;//TBD + } + + void flush() + { + if (isFreshPayload) free(payload); + if (isFresh) free(streamData); + } + + protected : + class BlinkerMasterAT * _masterAT; + Stream* stream; + // String streamData; + // char streamData[1024]; + char* streamData; + // String payload = ""; + char* payload; + bool isFreshPayload = false; + bool isFresh = false; + bool isHWS = false; + String _host; + String _uri; + + blinker_callback_t listenFunc = NULL; + + uint16_t _httpTimeout = BLINKER_HTTP_AIR202_DEFAULT_TIMEOUT; + + int timedRead() + { + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; + } + + bool available() + { + yield(); + + if (!isHWS) + { + // #if defined(__AVR__) || defined(ESP8266) + // if (!SSerial_HTTP->isListening()) + // { + // SSerial_HTTP->listen(); + // ::delay(100); + // } + // #endif + if (listenFunc) listenFunc(); + } + + // char _data[BLINKER_HTTP_AIR202_DATA_BUFFER_SIZE];// = { '\0' }; + // memset(_data, '\0', BLINKER_HTTP_AIR202_DATA_BUFFER_SIZE); + + // if (!isFresh) streamData = (char*)malloc(BLINKER_HTTP_AIR202_DATA_BUFFER_SIZE*sizeof(char)); + // else memset(streamData, '\0', BLINKER_HTTP_AIR202_DATA_BUFFER_SIZE); + + if (stream->available()) + { + // strcpy(_data, stream->readStringUntil('\n').c_str()); + String _data = stream->readStringUntil('\n'); + BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), _data, BLINKER_F(", len: "), _data.length()); + // _data[strlen(_data) - 1] = '\0'; + if (isFresh) + { + free(streamData); + isFresh = false; + } + + if (_data.length() <= 1) return false; + + streamData = (char*)malloc((_data.length() + 1)*sizeof(char)); + strcpy(streamData, _data.c_str()); + if (_data.length() > 0 && streamData[_data.length() - 1] == '\r') streamData[_data.length() - 1] = '\0'; + isFresh = true; + return true; + // if (isFresh) free(streamData); + // streamData = (char*)malloc(1*sizeof(char)); + // // streamData = ""; + + // // memset(streamData, '\0', 1024); + + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), stream->readString()); + + // // strcpy(streamData, stream->readStringUntil('\n').c_str()); + + // // int16_t dNum = strlen(streamData); + + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), streamData, + // // BLINKER_F(", dNum: "), dNum); + + // int16_t dNum = 0; + // int c_d = timedRead(); + // while (dNum < BLINKER_MAX_READ_SIZE && + // c_d >=0 && c_d != '\n') + // { + // // if (c_d != '\r') + // { + // streamData[dNum] = (char)c_d; + // dNum++; + // streamData = (char*)realloc(streamData, (dNum+1)*sizeof(char)); + // } + + // c_d = timedRead(); + // } + // // dNum++; + // // // streamData = (char*)realloc(streamData, dNum*sizeof(char)); + + // // streamData[dNum-1] = '\0'; + + // // strcpy(streamData, stream->readStringUntil('\n').c_str()); + // // int16_t dNum = strlen(streamData); + // // streamData[dNum-1] = '\0'; + + // // stream->flush(); + + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, + // // BLINKER_F(" , dNum: "), dNum); + // // BLINKER_LOG_FreeHeap_ALL(); + + // if (dNum < BLINKER_MAX_READ_SIZE && dNum > 0) + // { + // // if (streamData[dNum - 1] == '\r') + // streamData[dNum - 1] = '\0'; + // BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, + // BLINKER_F(" , dNum: "), dNum); + + // isFresh = true; + // return true; + // } + // else + // { + // return false; + // } + } + else + { + return false; + } + } +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerHTTPSIM7000.h b/blinker-library/src/Functions/BlinkerHTTPSIM7000.h new file mode 100644 index 0000000..aa7b6b8 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerHTTPSIM7000.h @@ -0,0 +1,1051 @@ +#ifndef BLINKER_HTTP_SIM7000_H +#define BLINKER_HTTP_SIM7000_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +// #include "Adapters/BlinkerSerialMQTT.h" +#include "../Blinker/BlinkerATMaster.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +// #if defined(ESP32) +// #include + +// HardwareSerial *HSerial_HTTP; +// #else +// #include + +// SoftwareSerial *SSerial_HTTP; +// #endif + +#define BLINKER_HTTP_SIM7000_DEFAULT_TIMEOUT 5000UL +#define BLINKER_HTTP_SIM7000_DATA_BUFFER_SIZE 1024 + +enum sim7000_http_status_t +{ + sim7000_http_url_set, + sim7000_http_url_success, + sim7000_http_body_set, + sim7000_http_body_success, + sim7000_http_header_set, + sim7000_http_header_success, + sim7000_http_con_set, + sim7000_http_con_success, + sim7000_http_state_req, + sim7000_http_state_success, + sim7000_http_chead_set, + sim7000_http_chead_success, + sim7000_http_ahead_set, + sim7000_http_ahead_success, + // sim7000_http_body_set, + // sim7000_http_body_success, + sim7000_http_send_set, + sim7000_http_send_success, + sim7000_http_get_set, + sim7000_http_get_success, + sim7000_http_read_set, + sim7000_http_read_success, + sim7000_http_disc_set, + sim7000_http_disc_success, +}; + +class BlinkerHTTPSIM7000 +{ + public : + BlinkerHTTPSIM7000(Stream& s, bool isHardware, blinker_callback_t func) + { + stream = &s; isHWS = isHardware; listenFunc = func; + // streamData = (char*)malloc(BLINKER_HTTP_SIM7000_DATA_BUFFER_SIZE*sizeof(char)); + } + + ~BlinkerHTTPSIM7000() { flush(); } + + void streamPrint(const String & s) + { + // stream->flush(); + BLINKER_LOG_ALL(BLINKER_F("HTTP streamPrint: "), s); + stream->println(s); + } + + void _streamPrint(const String & s) + { + // stream->flush(); + BLINKER_LOG_ALL(BLINKER_F("HTTP streamPrint: "), s); + stream->print(s); + } + + void _streamPrint() + { + // stream->flush(); + BLINKER_LOG_ALL(BLINKER_F("HTTP streamPrint: ")); + stream->println(); + } + + bool begin(String host, String uri) { _host = host; _uri = uri; } + void setTimeout(uint16_t timeout) { _httpTimeout = timeout; } + + void reboot() + { + // streamPrint(BLINKER_CMD_CRESET_RESQ); + // ::delay(500); + // streamPrint(BLINKER_CMD_AT); + // streamPrint("ATE0"); + } + + bool GET() + { + streamPrint(STRING_format(BLINKER_CMD_SHCONF_REQ) + \ + "=\"URL\",\"" + _host + "\""); + uint8_t h_id = 0; + uint32_t http_time = millis(); + sim7000_http_status_t http_status = sim7000_http_url_set; + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + BLINKER_LOG_ALL(BLINKER_F("sim7000_http_url_set check")); + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7000_http_url_success")); + http_status = sim7000_http_url_success; + break; + } + } + } + + if (http_status != sim7000_http_url_success) + { + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHCONF_REQ) + + "=\"BODYLEN\",350"); + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_body_success; + break; + } + } + } + + if (http_status != sim7000_http_body_success) + { + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHCONF_REQ) + \ + "=\"HEADERLEN\",350"); + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_header_success; + break; + } + } + } + + if (http_status != sim7000_http_header_success) + { + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHCONN_REQ)); + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_con_success; + break; + } + } + } + + if (http_status != sim7000_http_con_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHSTATE_REQ) + + "?"); + http_time = millis(); + + http_status = sim7000_http_state_req; + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_SHSTATE) + { + uint8_t get_state = _masterAT->getParam(0).toInt(); + BLINKER_LOG_ALL(BLINKER_F("sim7000_http_state_req, get_state: "), get_state); + http_status = sim7000_http_state_success; + free(_masterAT); + break; + } + + free(_masterAT); + } + } + + // if (http_status != sim7000_http_state_success) + // { + // streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + // return false; + // } + + streamPrint(STRING_format(BLINKER_CMD_SHCHEAD_REQ)); + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_chead_success; + break; + } + } + } + + if (http_status != sim7000_http_chead_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHAHEAD_REQ) + \ + "=\"User-Agent\",\"curl/7.47.0\""); + http_time = millis(); + + http_status = sim7000_http_ahead_set; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_ahead_success; + break; + } + } + } + + if (http_status != sim7000_http_ahead_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHAHEAD_REQ) + \ + "=\"Cache-control\",\"no-cache\""); + http_time = millis(); + + http_status = sim7000_http_ahead_set; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_ahead_success; + break; + } + } + } + + if (http_status != sim7000_http_ahead_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHAHEAD_REQ) + \ + "=\"Connection\",\"keep-alive\""); + http_time = millis(); + + http_status = sim7000_http_ahead_set; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_ahead_success; + break; + } + } + } + + if (http_status != sim7000_http_ahead_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHAHEAD_REQ) + \ + "=\"Accept\",\"*/*\""); + http_time = millis(); + + http_status = sim7000_http_ahead_set; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_ahead_success; + break; + } + } + } + + if (http_status != sim7000_http_ahead_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHREQ_REQ) + \ + "=\"" + _uri + "\",1"); + http_time = millis(); + + http_status = sim7000_http_send_set; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_send_success; + break; + } + } + } + + if (http_status != sim7000_http_send_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + String get_string; + uint16_t get_code; + uint16_t get_len; + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_SHREQ) + { + get_string = _masterAT->getParam(0); + get_code = _masterAT->getParam(1).toInt(); + get_len = _masterAT->getParam(2).toInt(); + BLINKER_LOG_ALL(BLINKER_F("get_string: "), get_string, \ + BLINKER_F(", get_code: "), get_code, \ + BLINKER_F(", get_len: "), get_len); + http_status = sim7000_http_get_success; + free(_masterAT); + break; + } + + free(_masterAT); + } + } + + if (http_status != sim7000_http_get_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHREAD_REQ) + \ + "=0," + get_len + ""); + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_SHREAD) + { + String read_string = _masterAT->getParam(0); + BLINKER_LOG_ALL(BLINKER_F("read_string: "), read_string); + http_status = sim7000_http_read_success; + free(_masterAT); + break; + } + + free(_masterAT); + } + } + + if (http_status != sim7000_http_read_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + String http_data = STRING_format(streamData); + BLINKER_LOG_ALL(BLINKER_F("http_data: "), http_data); + + if (isFreshPayload) free(payload); + payload = (char*)malloc((http_data.length() + 1)*sizeof(char)); + memset(payload, '\0', (http_data.length() + 1)); + strcpy(payload, http_data.c_str()); + isFreshPayload = true; + break; + } + } + + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_disc_success; + break; + } + } + } + + if (http_status != sim7000_http_disc_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + return true; + } + + bool POST(String _msg, String _type, String _application) + { + streamPrint(STRING_format(BLINKER_CMD_SHCONF_REQ) + \ + "=\"URL\",\"" + _host + "\""); + uint8_t h_id = 0; + uint32_t http_time = millis(); + sim7000_http_status_t http_status = sim7000_http_url_set; + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + BLINKER_LOG_ALL(BLINKER_F("sim7000_http_url_set check")); + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7000_http_url_success")); + http_status = sim7000_http_url_success; + break; + } + } + } + + if (http_status != sim7000_http_url_success) + { + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHCONF_REQ) + + "=\"BODYLEN\",350"); + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_body_success; + break; + } + } + } + + if (http_status != sim7000_http_body_success) + { + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHCONF_REQ) + \ + "=\"HEADERLEN\",350"); + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_header_success; + break; + } + } + } + + if (http_status != sim7000_http_header_success) + { + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHCONN_REQ)); + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_con_success; + break; + } + } + } + + if (http_status != sim7000_http_con_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHSTATE_REQ) + + "?"); + http_time = millis(); + + http_status = sim7000_http_state_req; + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_SHSTATE) + { + uint8_t get_state = _masterAT->getParam(0).toInt(); + BLINKER_LOG_ALL(BLINKER_F("sim7000_http_state_req, get_state: "), get_state); + http_status = sim7000_http_state_success; + free(_masterAT); + break; + } + + free(_masterAT); + } + } + + // if (http_status != sim7000_http_state_success) + // { + // streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + // return false; + // } + + streamPrint(STRING_format(BLINKER_CMD_SHCHEAD_REQ)); + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_chead_success; + break; + } + } + } + + if (http_status != sim7000_http_chead_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHAHEAD_REQ) + \ + "=\"Content-Type\",\"application/json\""); + http_time = millis(); + + http_status = sim7000_http_ahead_set; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_ahead_success; + break; + } + } + } + + if (http_status != sim7000_http_ahead_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHAHEAD_REQ) + \ + "=\"Cache-control\",\"no-cache\""); + http_time = millis(); + + http_status = sim7000_http_ahead_set; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_ahead_success; + break; + } + } + } + + if (http_status != sim7000_http_ahead_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHAHEAD_REQ) + \ + "=\"Connection\",\"keep-alive\""); + http_time = millis(); + + http_status = sim7000_http_ahead_set; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_ahead_success; + break; + } + } + } + + if (http_status != sim7000_http_ahead_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHAHEAD_REQ) + \ + "=\"Accept\",\"*/*\""); + http_time = millis(); + + http_status = sim7000_http_ahead_set; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_ahead_success; + break; + } + } + } + + if (http_status != sim7000_http_ahead_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + uint16_t _msg_len = _msg.length(); + _msg.replace("\"", "\\\""); + streamPrint(STRING_format(BLINKER_CMD_SHBOD_REQ) + \ + "=\"" + _msg + "\"," + STRING_format(_msg_len)); + http_time = millis(); + + http_status = sim7000_http_body_set; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_body_success; + break; + } + } + } + + if (http_status != sim7000_http_body_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHREQ_REQ) + \ + "=\"" + _uri + "\",3"); + http_time = millis(); + + http_status = sim7000_http_send_set; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_send_success; + break; + } + } + } + + if (http_status != sim7000_http_send_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + String get_string; + uint16_t get_code; + uint16_t get_len; + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_SHREQ) + { + get_string = _masterAT->getParam(0); + get_code = _masterAT->getParam(1).toInt(); + get_len = _masterAT->getParam(2).toInt(); + BLINKER_LOG_ALL(BLINKER_F("get_string: "), get_string, \ + BLINKER_F(", get_code: "), get_code, \ + BLINKER_F(", get_len: "), get_len); + if (get_code == 200) + { + http_status = sim7000_http_get_success; + } + free(_masterAT); + break; + } + + free(_masterAT); + } + } + + if (http_status != sim7000_http_get_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHREAD_REQ) + \ + "=0," + get_len + ""); + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + // _masterAT = new BlinkerMasterAT(); + // _masterAT->update(STRING_format(streamData)); + + // if (_masterAT->getState() != AT_M_NONE && + // _masterAT->reqName() == BLINKER_CMD_SHREAD) + // { + // String read_string = _masterAT->getParam(0); + // BLINKER_LOG_ALL(BLINKER_F("read_string: "), read_string); + // http_status = sim7000_http_read_success; + // free(_masterAT); + // break; + // } + + // free(_masterAT); + + BLINKER_LOG_ALL(BLINKER_F("read_string: "), streamData); + } + } + + if (http_status != sim7000_http_get_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + http_status = sim7000_http_disc_success; + break; + } + } + } + + if (http_status != sim7000_http_disc_success) + { + streamPrint(STRING_format(BLINKER_CMD_SHDISC_REQ)); + return false; + } + return true; + } + + String getString() + { + if (isFreshPayload) return payload;//TBD + return ""; + } + + void flush() + { + if (isFreshPayload) free(payload); + if (isFresh) free(streamData); + + BLINKER_LOG_ALL(BLINKER_F("flush sim7000 http")); + } + + protected : + class BlinkerMasterAT * _masterAT; + Stream* stream; + // String streamData; + // char streamData[1024]; + char* streamData; + // char streamBuffer[2048] = { '\0' }; + char* payload; + bool isFreshPayload = false; + bool isFresh = false; + bool isHWS = false; + String _host; + String _uri; + + blinker_callback_t listenFunc = NULL; + + uint16_t _httpTimeout = BLINKER_HTTP_SIM7000_DEFAULT_TIMEOUT; + + char c_hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + + int8_t dcode_data(char d_test) + { + for (uint8_t num = 0; num < 16; num++) + { + if (d_test == c_hex[num]) return num; + } + + return -1; + } + + char ecode_data(uint8_t d_test) + { + return c_hex[d_test]; + } + + String encode(String data) + { + // char _d[2048] = {'\0'}; + + String _d = ""; + + BLINKER_LOG_FreeHeap_ALL(); + BLINKER_LOG_ALL("encode data: ", data); + BLINKER_LOG_ALL("encode len: ", data.length()); + + for(uint16_t num = 0; num < data.length(); num++) + { + _d += (ecode_data((uint8_t)data.c_str()[num] >> 4)); + _d += (ecode_data((uint8_t)data.c_str()[num] & 0x0F)); + } + + BLINKER_LOG_ALL("encode data: ", _d); + + return _d; + } + + // String encode(char data[]) + // { + // // char _d[2048] = {'\0'}; + // String _d = ""; + + // BLINKER_LOG_FreeHeap_ALL(); + // BLINKER_LOG_ALL("encode data: ", data); + // BLINKER_LOG_ALL("encode len: ", strlen(data)); + + // for(uint16_t num = 0; num < strlen(data); num++) + // { + // _d += (ecode_data(data[num] >> 4)); + // _d += (ecode_data(data[num] & 0x0F)); + // } + + // BLINKER_LOG_ALL("encode data: ", _d); + + // return _d; + // } + + // for(uint16_t num = 0; num < strlen(test); num++) + // { + // Serial.print(ecode_data(test[num] >> 4)); + // Serial.print(ecode_data(test[num] & 0x0F)); + // } + // Serial.println(); + + int timedRead() + { + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; + } + + bool available(const char *str) + { + uint32_t http_time = millis(); + char _data[1024];// = { '\0' }; + memset(_data, '\0', 1024); + + BLINKER_LOG_ALL(BLINKER_F("available str: "), str); + while(millis() - http_time < _httpTimeout * 4) + { + if (stream->available()) + { + // if (isFresh) free(streamData); + // streamData = (char*)malloc(1*sizeof(char)); + // isFresh = true; + // if (strspn(streamData, str)) return true; + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), stream->readStringUntil('\n')); + + strcpy(_data, stream->readStringUntil('\n').c_str()); + BLINKER_LOG_ALL(BLINKER_F("handleSerial rs available(const char *str): "), _data); + if (strstr(_data, str)) + { + _data[strlen(_data) - 1] = '\0'; + if (isFresh) free(streamData); + streamData = (char*)malloc((strlen(_data) + 1)*sizeof(char)); + strcpy(streamData, _data); + isFresh = true; + return true; + } + BLINKER_LOG_ALL(BLINKER_F("strstr(_data, str): "), strstr(_data, str)); + memset(_data, '\0', 1024); + } + yield(); + // delay(100); + } + + return false; + } + + bool available() + { + yield(); + + if (!isHWS) + { + // #if defined(__AVR__) || defined(ESP8266) + // if (!SSerial_HTTP->isListening()) + // { + // SSerial_HTTP->listen(); + // ::delay(100); + // } + // #endif + if (listenFunc) listenFunc(); + } + + // char _data[BLINKER_HTTP_SIM7000_DATA_BUFFER_SIZE];// = { '\0' }; + // memset(_data, '\0', BLINKER_HTTP_SIM7000_DATA_BUFFER_SIZE); + + // if (!isFresh) streamData = (char*)malloc(BLINKER_HTTP_SIM7000_DATA_BUFFER_SIZE*sizeof(char)); + + if (stream->available()) + { + // strcpy(_data, stream->readStringUntil('\n').c_str()); + String _data = stream->readStringUntil('\n'); + // if ( _data[_data.length() - 1] == '\n') + // _data[_data.length() - 1] = '\0'; + BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), _data); + if (isFresh) + { + free(streamData); + isFresh = false; + } + + if (_data.length() <= 1) return false; + + streamData = (char*)malloc((_data.length() + 1)*sizeof(char)); + strcpy(streamData, _data.c_str()); + if (_data.length() > 0) streamData[_data.length()] = '\0'; + isFresh = true; + return true; + } + else + { + return false; + } + } +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerHTTPSIM7020.h b/blinker-library/src/Functions/BlinkerHTTPSIM7020.h new file mode 100644 index 0000000..b08aecc --- /dev/null +++ b/blinker-library/src/Functions/BlinkerHTTPSIM7020.h @@ -0,0 +1,1230 @@ +#ifndef BLINKER_HTTP_SIM7020_H +#define BLINKER_HTTP_SIM7020_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +// #include "Adapters/BlinkerSerialMQTT.h" +#include "../Blinker/BlinkerATMaster.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +// #if defined(ESP32) +// #include + +// HardwareSerial *HSerial_HTTP; +// #else +// #include + +// SoftwareSerial *SSerial_HTTP; +// #endif + +#define BLINKER_HTTP_SIM7020_DEFAULT_TIMEOUT 5000UL +#define BLINKER_HTTP_SIM7020_DATA_BUFFER_SIZE 1024 + +enum sim7020_http_status_t +{ + sim7020_http_creat_req, + sim7020_http_creat_resp, + sim7020_http_creat_success, + sim7020_http_con_req, + sim7020_http_con_success, + sim7020_http_send_req, + sim7020_http_send_success, + sim7020_http_nmih_wait, + sim7020_http_nmih_success, + sim7020_http_nmic_wait, + sim7020_http_nmic_success, + sim7020_http_discon_req, + sim7020_http_discon_success, + sim7020_http_destroy_req, + sim7020_http_destroy_success, +}; + +class BlinkerHTTPSIM7020 +{ + public : + BlinkerHTTPSIM7020(Stream& s, bool isHardware, blinker_callback_t func) + { + stream = &s; isHWS = isHardware; listenFunc = func; + // streamData = (char*)malloc(BLINKER_HTTP_SIM7020_DATA_BUFFER_SIZE*sizeof(char)); + } + + ~BlinkerHTTPSIM7020() { flush(); } + + void streamPrint(const String & s) + { + // stream->flush(); + BLINKER_LOG_ALL(BLINKER_F("HTTP streamPrint: "), s); + stream->println(s); + } + + void _streamPrint(const String & s) + { + // stream->flush(); + BLINKER_LOG_ALL(BLINKER_F("HTTP streamPrint: "), s); + stream->print(s); + } + + void _streamPrint() + { + // stream->flush(); + BLINKER_LOG_ALL(BLINKER_F("HTTP streamPrint: ")); + stream->println(); + } + + bool begin(String host, String uri) { _host = host; _uri = uri; } + void setTimeout(uint16_t timeout) { _httpTimeout = timeout; } + + void reboot() + { + // streamPrint(BLINKER_CMD_CRESET_RESQ); + // ::delay(500); + // streamPrint(BLINKER_CMD_AT); + // streamPrint("ATE0"); + } + + bool GET() + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPCREATE_REQ) + \ + "=\"" + _host + "/\""); + uint8_t h_id = 0; + uint32_t http_time = millis(); + sim7020_http_status_t http_status = sim7020_http_creat_req; + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CHTTPCREATE) + { + h_id = _masterAT->getParam(0).toInt(); + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_creat_resp, h_id: "), h_id); + http_status = sim7020_http_creat_resp; + free(_masterAT); + break; + } + + free(_masterAT); + } + } + + if (http_status != sim7020_http_creat_resp) + { + for (uint8_t id_num = 0; id_num < 5; id_num++) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(id_num)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(id_num)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + } + + reboot(); + + return false; + } + + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_creat_success check")); + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_creat_success")); + http_status = sim7020_http_creat_success; + break; + } + } + } + + if (http_status != sim7020_http_creat_success) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + + reboot(); + + return false; + } + + streamPrint(STRING_format(BLINEKR_CMD_CHTTPCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + http_status = sim7020_http_con_req; + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_con_success")); + http_status = sim7020_http_con_success; + break; + } + } + } + + if (http_status != sim7020_http_con_success) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + + reboot(); + + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_CHTTPSEND_REQ) + \ + "=" + STRING_format(h_id) + ",0,\"" + _uri + "\""); + http_time = millis(); + http_status = sim7020_http_send_req; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_send_success")); + http_status = sim7020_http_send_success; + break; + } + } + } + + if (http_status != sim7020_http_send_success) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + + reboot(); + + return false; + } + + http_time = millis(); + http_status = sim7020_http_nmih_wait; + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CHTTPNMIH) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_nmih_success")); + http_status = sim7020_http_nmih_success; + free(_masterAT); + break; + } + + free(_masterAT); + } + } + + if (http_status != sim7020_http_nmih_success) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + + reboot(); + + return false; + } + + http_time = millis(); + http_status = sim7020_http_nmic_wait; + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + if (strstr(streamData, BLINKER_CMD_CHTTPNMIC)) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CHTTPNMIC) + { + // streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + // "=" + STRING_format(h_id)); + + String http_data = STRING_format(streamData); + // delay(100); + time_t now_time = millis(); + while (millis() - now_time < 5000) + { + if (stream->available()) + { + http_data += stream->readStringUntil('\n').c_str(); + } + // delay(1000); + } + + // _masterAT->update(http_data); + + BLINKER_LOG_ALL(BLINKER_F("http_data: "), http_data); + + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_nmic_success")); + http_status = sim7020_http_nmic_success; + + if (strlen(strrchr(http_data.c_str(), ',')) < 1024) + { + if (isFreshPayload) free(payload); + + isFreshPayload = true; + char data_buff[1024] = { '\0' }; + + memcpy(data_buff,strrchr(http_data.c_str(), ',')+1, strlen(strrchr(http_data.c_str(), ','))); + + payload = (char*)malloc((strlen(data_buff)/2 + 1)*sizeof(char)); + + memset(payload, '\0', (strlen(data_buff)/2 + 1)); + + // memcpy(payload,strrchr(streamData, ',')+1, strlen(strrchr(streamData, ','))); + + for(uint16_t num = 0; num < strlen(data_buff)/2; num++) + { + payload[num] = (char)(dcode_data(data_buff[num*2])<< 4 | dcode_data(data_buff[num*2+1])); + } + + BLINKER_LOG_ALL(BLINKER_F("data_buff: "), data_buff); + BLINKER_LOG_ALL(BLINKER_F("data_buff num: "), strlen(data_buff)/2); + BLINKER_LOG_ALL(BLINKER_F("payload: "), payload); + + free(_masterAT); + break; + } + else + { + free(_masterAT); + } + } + + free(_masterAT); + } + } + } + + if (http_status != sim7020_http_nmic_success) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + + reboot(); + + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + http_status = sim7020_http_discon_req; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_discon_success")); + http_status = sim7020_http_discon_success; + break; + } + } + } + + if (http_status != sim7020_http_discon_success) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + + reboot(); + + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + http_status = sim7020_http_destroy_req; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_destroy_success")); + http_status = sim7020_http_destroy_success; + return true; + } + } + } + + if (http_status != sim7020_http_discon_success) + { + + reboot(); + + return false; + } + } + + bool POST(String _msg, String _type, String _application) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPCREATE_REQ) + \ + "=\"" + _host + "/\""); + uint8_t h_id = 0; + uint32_t http_time = millis(); + sim7020_http_status_t http_status = sim7020_http_creat_req; + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CHTTPCREATE) + { + h_id = _masterAT->getParam(0).toInt(); + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_creat_resp, h_id: "), h_id); + http_status = sim7020_http_creat_resp; + free(_masterAT); + break; + } + + free(_masterAT); + } + } + + if (http_status != sim7020_http_creat_resp) + { + for (uint8_t id_num = 0; id_num < 5; id_num++) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(id_num)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(id_num)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + } + + reboot(); + + return false; + } + + http_time = millis(); + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_creat_success")); + http_status = sim7020_http_creat_success; + break; + } + } + } + + if (http_status != sim7020_http_creat_success) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + + reboot(); + + return false; + } + + streamPrint(STRING_format(BLINEKR_CMD_CHTTPCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + http_status = sim7020_http_con_req; + + while(millis() - http_time < _httpTimeout * 20) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_con_success")); + http_status = sim7020_http_con_success; + break; + } + } + } + + if (http_status != sim7020_http_con_success) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + + reboot(); + + return false; + } + + _streamPrint(STRING_format(BLINKER_CMD_CHTTPSEND_REQ));// + + _streamPrint("=" + STRING_format(h_id) + ",1,\"" + _uri);// + + _streamPrint("\",4163636570743a202a2f2a0d0a436f6e6");// + + _streamPrint("e656374696f6e3a204b6565702d416c6976650d0a557365722d41");// + + _streamPrint("67656e743a2053494d434f4d5f4d4f44554c450d0a,\"");// + + _streamPrint("application/json\",");// + + _streamPrint(encode(_msg)); + _streamPrint(); + http_time = millis(); + http_status = sim7020_http_send_req; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_send_success")); + http_status = sim7020_http_send_success; + break; + } + } + } + + if (http_status != sim7020_http_send_success) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + + reboot(); + + return false; + } + + http_time = millis(); + http_status = sim7020_http_nmih_wait; + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CHTTPNMIH) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_nmih_success")); + http_status = sim7020_http_nmih_success; + free(_masterAT); + break; + } + + free(_masterAT); + } + } + + if (http_status != sim7020_http_nmih_success) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + + reboot(); + + return false; + } + + http_time = millis(); + http_status = sim7020_http_nmic_wait; + + while(millis() - http_time < _httpTimeout * 4) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CHTTPNMIC) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + + String http_data = STRING_format(streamData); + delay(1000); + while (available()) + { + http_data += STRING_format(streamData); + delay(1000); + } + + _masterAT->update(http_data); + + BLINKER_LOG_ALL(BLINKER_F("http_data: "), http_data); + + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_nmic_success")); + http_status = sim7020_http_nmic_success; + + if (strlen(strrchr(streamData, ',')) < 1024) + { + if (isFreshPayload) free(payload); + + isFreshPayload = true; + char data_buff[1024] = { '\0' }; + + memcpy(data_buff,strrchr(streamData, ',')+1, strlen(strrchr(streamData, ','))); + + payload = (char*)malloc((strlen(data_buff)/2 + 1)*sizeof(char)); + + memset(payload, '\0', (strlen(data_buff)/2 + 1)); + + // memcpy(payload,strrchr(streamData, ',')+1, strlen(strrchr(streamData, ','))); + + for(uint16_t num = 0; num < strlen(data_buff)/2; num++) + { + payload[num] = (char)(dcode_data(data_buff[num*2])<< 4 | dcode_data(data_buff[num*2+1])); + } + + BLINKER_LOG_ALL(payload); + } + + free(_masterAT); + break; + } + + free(_masterAT); + } + } + + if (http_status != sim7020_http_nmic_success) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + + reboot(); + + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + http_status = sim7020_http_discon_req; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_discon_success")); + http_status = sim7020_http_discon_success; + break; + } + } + } + + if (http_status != sim7020_http_discon_success) + { + streamPrint(STRING_format(BLINKER_CMD_CHTTPDISCON_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + break; + } + } + } + + reboot(); + + return false; + } + + // streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + + // "=" + STRING_format(h_id)); + // http_time = millis(); + // http_status = sim7020_http_destroy_req; + + // while(millis() - http_time < _httpTimeout * 2) + // { + // if (available()) + // { + // if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + // { + // // BLINKER_LOG_ALL(BLINKER_F("sim7020_http_destroy_success")); + // // http_status = sim7020_http_destroy_success; + // // return true; + // break; + // } + // } + // } + + // if (http_status != sim7020_http_discon_success) return false; + + streamPrint(STRING_format(BLINKER_CMD_CHTTPDESTROY_REQ) + + "=" + STRING_format(h_id)); + http_time = millis(); + http_status = sim7020_http_destroy_req; + + while(millis() - http_time < _httpTimeout * 2) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_http_destroy_success")); + http_status = sim7020_http_destroy_success; + return true; + } + } + } + + if (http_status != sim7020_http_discon_success) + { + + reboot(); + + return false; + } + } + + String getString() + { + if (isFreshPayload) return payload;//TBD + return ""; + } + + void flush() + { + if (isFreshPayload) free(payload); + if (isFresh) free(streamData); + + BLINKER_LOG_ALL(BLINKER_F("flush sim7020 http")); + } + + protected : + class BlinkerMasterAT * _masterAT; + Stream* stream; + // String streamData; + // char streamData[1024]; + char* streamData; + // char streamBuffer[2048] = { '\0' }; + char* payload; + bool isFreshPayload = false; + bool isFresh = false; + bool isHWS = false; + String _host; + String _uri; + + blinker_callback_t listenFunc = NULL; + + uint16_t _httpTimeout = BLINKER_HTTP_SIM7020_DEFAULT_TIMEOUT; + + char c_hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + + int8_t dcode_data(char d_test) + { + for (uint8_t num = 0; num < 16; num++) + { + if (d_test == c_hex[num]) return num; + } + + return -1; + } + + char ecode_data(uint8_t d_test) + { + return c_hex[d_test]; + } + + String encode(String data) + { + // char _d[2048] = {'\0'}; + + String _d = ""; + + BLINKER_LOG_FreeHeap_ALL(); + BLINKER_LOG_ALL("encode data: ", data); + BLINKER_LOG_ALL("encode len: ", data.length()); + + for(uint16_t num = 0; num < data.length(); num++) + { + _d += (ecode_data((uint8_t)data.c_str()[num] >> 4)); + _d += (ecode_data((uint8_t)data.c_str()[num] & 0x0F)); + } + + BLINKER_LOG_ALL("encode data: ", _d); + + return _d; + } + + // String encode(char data[]) + // { + // // char _d[2048] = {'\0'}; + // String _d = ""; + + // BLINKER_LOG_FreeHeap_ALL(); + // BLINKER_LOG_ALL("encode data: ", data); + // BLINKER_LOG_ALL("encode len: ", strlen(data)); + + // for(uint16_t num = 0; num < strlen(data); num++) + // { + // _d += (ecode_data(data[num] >> 4)); + // _d += (ecode_data(data[num] & 0x0F)); + // } + + // BLINKER_LOG_ALL("encode data: ", _d); + + // return _d; + // } + + // for(uint16_t num = 0; num < strlen(test); num++) + // { + // Serial.print(ecode_data(test[num] >> 4)); + // Serial.print(ecode_data(test[num] & 0x0F)); + // } + // Serial.println(); + + int timedRead() + { + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; + } + + bool available(const char *str) + { + uint32_t http_time = millis(); + char _data[1024];// = { '\0' }; + memset(_data, '\0', 1024); + + BLINKER_LOG_ALL(BLINKER_F("available str: "), str); + while(millis() - http_time < _httpTimeout * 4) + { + if (stream->available()) + { + // if (isFresh) free(streamData); + // streamData = (char*)malloc(1*sizeof(char)); + // isFresh = true; + // if (strspn(streamData, str)) return true; + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), stream->readStringUntil('\n')); + + strcpy(_data, stream->readStringUntil('\n').c_str()); + BLINKER_LOG_ALL(BLINKER_F("handleSerial rs available(const char *str): "), _data); + if (strstr(_data, str)) + { + _data[strlen(_data) - 1] = '\0'; + if (isFresh) free(streamData); + streamData = (char*)malloc((strlen(_data) + 1)*sizeof(char)); + strcpy(streamData, _data); + isFresh = true; + return true; + } + BLINKER_LOG_ALL(BLINKER_F("strstr(_data, str): "), strstr(_data, str)); + memset(_data, '\0', 1024); + } + yield(); + // delay(100); + } + + return false; + } + + bool available() + { + yield(); + + if (!isHWS) + { + // #if defined(__AVR__) || defined(ESP8266) + // if (!SSerial_HTTP->isListening()) + // { + // SSerial_HTTP->listen(); + // ::delay(100); + // } + // #endif + if (listenFunc) listenFunc(); + } + + // char _data[BLINKER_HTTP_SIM7020_DATA_BUFFER_SIZE];// = { '\0' }; + // memset(_data, '\0', BLINKER_HTTP_SIM7020_DATA_BUFFER_SIZE); + + // if (!isFresh) streamData = (char*)malloc(BLINKER_HTTP_SIM7020_DATA_BUFFER_SIZE*sizeof(char)); + + if (stream->available()) + { + // strcpy(_data, stream->readStringUntil('\n').c_str()); + String _data = stream->readStringUntil('\n'); + // if ( _data[_data.length() - 1] == '\n') + // _data[_data.length() - 1] = '\0'; + BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), _data); + if (isFresh) + { + free(streamData); + isFresh = false; + } + + if (_data.length() <= 1) return false; + + streamData = (char*)malloc((_data.length() + 1)*sizeof(char)); + strcpy(streamData, _data.c_str()); + if (_data.length() > 0) streamData[_data.length()] = '\0'; + isFresh = true; + return true; + } + else + { + return false; + } + } +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerImage.h b/blinker-library/src/Functions/BlinkerImage.h new file mode 100644 index 0000000..e3a6551 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerImage.h @@ -0,0 +1,43 @@ +#ifndef BlinkerImage_H +#define BlinkerImage_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BlinkerImage +{ + public : + BlinkerImage(char _name[], blinker_callback_with_int32_arg_t _func = NULL) + { + wNum = Blinker.attachWidget(_name, _func); + // numName = (char*)malloc((strlen(_name)+1)*sizeof(char)); + // strcpy(numName, _name); + } + + void attach(blinker_callback_with_int32_arg_t _func) + { + if (wNum == 0) return; + + Blinker.freshAttachWidget(Blinker.widgetName_int(wNum), _func); + } + + uint8_t getNum() { return num; } + + void print(uint8_t _num) + { + num = _num; + + String ImageData = BLINKER_F("{\"img\":"); + ImageData += STRING_format(num); + ImageData += BLINKER_F("}"); + + // Blinker.printArray(numName, ImageData); + Blinker.printArray(Blinker.widgetName_int(wNum), ImageData); + } + + private : + uint8_t wNum; + uint8_t num = 0; +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerJoystick.h b/blinker-library/src/Functions/BlinkerJoystick.h new file mode 100644 index 0000000..bcc2bd4 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerJoystick.h @@ -0,0 +1,31 @@ +#ifndef BLINKER_JOYSTICK_H +#define BLINKER_JOYSTICK_H + +// #if defined(BLINKER_BLE) + #include "../Blinker/BlinkerConfig.h" + #include "../Blinker/BlinkerUtility.h" + + class BlinkerJoystick + { + public : + BlinkerJoystick(char _name[], blinker_callback_with_joy_arg_t _func = NULL) + // : jName(_name) + { + wNum = Blinker.attachWidget(_name, _func); + } + + void attach(blinker_callback_with_joy_arg_t _func) + { + if (wNum == 0) { + return; + } + + Blinker.freshAttachWidget(Blinker.widgetName_joy(wNum), _func); + } + + private : + uint8_t wNum; + }; +// #endif + +#endif diff --git a/blinker-library/src/Functions/BlinkerMIOT.h b/blinker-library/src/Functions/BlinkerMIOT.h new file mode 100644 index 0000000..71c2d80 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerMIOT.h @@ -0,0 +1,977 @@ +#ifndef BLINKER_MIOT_H +#define BLINKER_MIOT_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BLINKERMIOT +{ + public : + BLINKERMIOT() {} + + void attachPowerState(blinker_callback_with_string_uint8_arg_t newFunction) + { + Blinker.attachMIOTSetPowerState(newFunction); + } + + void attachPowerState(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachMIOTSetPowerState(newFunction); + } + + void attachHSwing(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachMIOTSetHSwingState(newFunction); + } + + void attachVSwing(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachMIOTSetVSwingState(newFunction); + } + + void attachECO(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachMIOTSetECO(newFunction); + } + + void attachAnion(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachMIOTSetAnion(newFunction); + } + + void attachHeater(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachMIOTSetHeater(newFunction); + } + + void attachDryer(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachMIOTSetDryer(newFunction); + } + + void attachSleep(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachMIOTSetSleep(newFunction); + } + + void attachSoft(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachMIOTSetSoft(newFunction); + } + + void attachUV(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachMIOTSetUV(newFunction); + } + + void attachUnStraightBlow(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachMIOTSetUNSB(newFunction); + } + + void attachColor(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachMIOTSetColor(newFunction); + } + + void attachMode(blinker_callback_with_string_string_arg_t newFunction) + { + Blinker.attachMIOTSetMode(newFunction); + } + + void attachMode(blinker_callback_with_uint8_arg_t newFunction) + { + Blinker.attachMIOTSetMode(newFunction); + } + + void attachLevel(blinker_callback_with_uint8_arg_t newFunction) + { + Blinker.attachMIOTSetLevel(newFunction); + } + + void attachTemp(blinker_callback_with_uint8_arg_t newFunction) + { + Blinker.attachMIOTSetTemp(newFunction); + } + + void attachHumi(blinker_callback_with_uint8_arg_t newFunction) + { + Blinker.attachMIOTSetHumi(newFunction); + } + + // void attachCancelMode(blinker_callback_with_string_arg_t newFunction) + // { + // Blinker.attachMIOTSetcMode(newFunction); + // } + + void attachBrightness(blinker_callback_with_string_arg_t newFunction) + { + Blinker.attachMIOTSetBrightness(newFunction); + } + + // void attachRelativeBrightness(blinker_callback_with_int32_arg_t newFunction) + // { + // Blinker.attachMIOTRelativeBrightness(newFunction); + // } + + void attachColorTemperature(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachMIOTSetColorTemperature(newFunction); + } + + // void attachRelativeColorTemperature(blinker_callback_with_int32_arg_t newFunction) + // { + // Blinker.attachMIOTRelativeColorTemperature(newFunction); + // } + + void attachQuery(blinker_callback_with_int32_uint8_arg_t newFunction) + { + Blinker.attachMIOTQuery(newFunction); + } + + void attachQuery(blinker_callback_with_int32_arg_t newFunction) + { + Blinker.attachMIOTQuery(newFunction); + } + + void powerState(const String & state, uint8_t num) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_POWERSTATE); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + if (num != 0) + { + payload += BLINKER_F(",\"num\":"); + payload += STRING_format(num); + } + else + { + payload += BLINKER_F(""); + } + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 0 & 0x01) { + free(aState); + } + + aState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aState, payload.c_str()); + + _fresh |= 0x01 << 0; + } + + void powerState(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_POWERSTATE); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + // if (state == "on") + // { + // payload += "true"; + // } + // else + // { + // payload += "false"; + // } + + // payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 0 & 0x01) { + free(aState); + } + + aState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aState, payload.c_str()); + + _fresh |= 0x01 << 0; + } + + void color(uint32_t clr) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_COLOR_); + payload += BLINKER_F("\":"); + payload += STRING_format(clr); + payload += BLINKER_F(","); + payload += BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_COLOR); + payload += BLINKER_F("\":"); + payload += STRING_format(clr); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 1 & 0x01) { + free(aColor); + } + + aColor = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aColor, payload.c_str()); + + _fresh |= 0x01 << 1; + } + + void mode(uint8_t md) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_MODE); + payload += BLINKER_F("\":\""); + payload += STRING_format(md); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 2 & 0x01) { + free(aMode); + } + + aMode = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aMode, payload.c_str()); + + _fresh |= 0x01 << 2; + } + + void mode(const String & mode, const String & state) + { + String payload = BLINKER_F("\""); + payload += mode; + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 2 & 0x01) { + free(aMode); + } + + aMode = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aMode, payload.c_str()); + + _fresh |= 0x01 << 2; + } + + void colorTemp(int clrTemp) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_COLORTEMP); + payload += BLINKER_F("\":\""); + payload += STRING_format(clrTemp); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 3 & 0x01) { + free(aCtemp); + } + + aCtemp = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aCtemp, payload.c_str()); + + _fresh |= 0x01 << 3; + } + + void brightness(int bright) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_BRIGHTNESS); + payload += BLINKER_F("\":\""); + payload += STRING_format(bright); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 4 & 0x01) { + free(aBright); + } + + aBright = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aBright, payload.c_str()); + + _fresh |= 0x01 << 4; + } + + void temp(double _temp) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_TEMP); + payload += BLINKER_F("\":\""); + payload += STRING_format(_temp); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 5 & 0x01) { + free(aTemp); + } + + aTemp = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aTemp, payload.c_str()); + + _fresh |= 0x01 << 5; + } + + void temp(float _temp) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_TEMP); + payload += BLINKER_F("\":\""); + payload += STRING_format(_temp); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 5 & 0x01) { + free(aTemp); + } + + aTemp = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aTemp, payload.c_str()); + + _fresh |= 0x01 << 5; + } + + void temp(int _temp) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_TEMP); + payload += BLINKER_F("\":\""); + payload += STRING_format(_temp); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 5 & 0x01) { + free(aTemp); + } + + aTemp = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aTemp, payload.c_str()); + + _fresh |= 0x01 << 5; + } + + void humi(int _humi) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_HUMI); + payload += BLINKER_F("\":\""); + payload += STRING_format(_humi); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 6 & 0x01) { + free(aHumi); + } + + aHumi = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aHumi, payload.c_str()); + + _fresh |= 0x01 << 6; + } + + void pm25(double _pm25) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_PM25); + payload += BLINKER_F("\":\""); + payload += STRING_format(_pm25); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 7 & 0x01) { + free(aPm25); + } + + aPm25 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aPm25, payload.c_str()); + + _fresh |= 0x01 << 7; + } + + void pm25(float _pm25) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_PM25); + payload += BLINKER_F("\":\""); + payload += STRING_format(_pm25); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 7 & 0x01) { + free(aPm25); + } + + aPm25 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aPm25, payload.c_str()); + + _fresh |= 0x01 << 7; + } + + void pm25(int _pm25) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_PM25); + payload += BLINKER_F("\":\""); + payload += STRING_format(_pm25); + payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 7 & 0x01) { + free(aPm25); + } + + aPm25 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aPm25, payload.c_str()); + + _fresh |= 0x01 << 7; + } + + void co2(double _co2) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_CO2); + payload += BLINKER_F("\":\""); + payload += STRING_format(_co2); + payload += BLINKER_F("\""); + + if (_fresh >> 8 & 0x01) { + free(aCO2); + } + + aCO2 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aCO2, payload.c_str()); + + _fresh |= 0x01 << 8; + } + + void co2(float _co2) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_CO2); + payload += BLINKER_F("\":\""); + payload += STRING_format(_co2); + payload += BLINKER_F("\""); + + if (_fresh >> 8 & 0x01) { + free(aCO2); + } + + aCO2 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aCO2, payload.c_str()); + + _fresh |= 0x01 << 8; + } + + void co2(int _co2) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_CO2); + payload += BLINKER_F("\":\""); + payload += STRING_format(_co2); + payload += BLINKER_F("\""); + + if (_fresh >> 8 & 0x01) { + free(aCO2); + } + + aCO2 = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aCO2, payload.c_str()); + + _fresh |= 0x01 << 8; + } + + void level(int _lvl) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_LEVEL); + payload += BLINKER_F("\":\""); + payload += STRING_format(_lvl); + payload += BLINKER_F("\""); + + if (_fresh >> 9 & 0x01) { + free(aLevel); + } + + aLevel = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(aLevel, payload.c_str()); + + _fresh |= 0x01 << 9; + } + + void hswing(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_HSTATE); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + // if (state == "on") + // { + // payload += "true"; + // } + // else + // { + // payload += "false"; + // } + + // payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 10 & 0x01) { + free(ahState); + } + + ahState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(ahState, payload.c_str()); + + _fresh |= 0x01 << 10; + } + + void vswing(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_VSTATE); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + // if (state == "on") + // { + // payload += "true"; + // } + // else + // { + // payload += "false"; + // } + + // payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 11 & 0x01) { + free(avState); + } + + avState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(avState, payload.c_str()); + + _fresh |= 0x01 << 11; + } + + void eco(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_ECO); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + // if (state == "on") + // { + // payload += "true"; + // } + // else + // { + // payload += "false"; + // } + + // payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 12 & 0x01) { + free(ecoState); + } + + ecoState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(ecoState, payload.c_str()); + + _fresh |= 0x01 << 12; + } + + void anion(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_ANION); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + // if (state == "on") + // { + // payload += "true"; + // } + // else + // { + // payload += "false"; + // } + + // payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 13 & 0x01) { + free(anionState); + } + + anionState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(anionState, payload.c_str()); + + _fresh |= 0x01 << 13; + } + + void heater(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_HEATER); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + // if (state == "on") + // { + // payload += "true"; + // } + // else + // { + // payload += "false"; + // } + + // payload += BLINKER_F("\""); + + // Blinker.aligeniePrint(payload); + + if (_fresh >> 14 & 0x01) { + free(heaterState); + } + + heaterState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(heaterState, payload.c_str()); + + _fresh |= 0x01 << 14; + } + + void dryer(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_DRYER); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + if (_fresh >> 15 & 0x01) { + free(dryerState); + } + + dryerState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(dryerState, payload.c_str()); + + _fresh |= 0x01 << 15; + } + + void sleep(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_SLEEP); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + if (_fresh >> 16 & 0x01) { + free(sleepState); + } + + sleepState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(sleepState, payload.c_str()); + + _fresh |= 0x01 << 16; + } + + void soft(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_SOFT); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + if (_fresh >> 17 & 0x01) { + free(softState); + } + + softState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(softState, payload.c_str()); + + _fresh |= 0x01 << 17; + } + + void uv(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_UV); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + if (_fresh >> 18 & 0x01) { + free(uvState); + } + + uvState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(uvState, payload.c_str()); + + _fresh |= 0x01 << 18; + } + + void unStraightBlow(const String & state) + { + String payload = BLINKER_F("\""); + payload += STRING_format(BLINKER_CMD_UNSB); + payload += BLINKER_F("\":\""); + payload += state; + payload += BLINKER_F("\""); + + if (_fresh >> 19 & 0x01) { + free(unsbState); + } + + unsbState = (char*)malloc((payload.length()+1)*sizeof(char)); + strcpy(unsbState, payload.c_str()); + + _fresh |= 0x01 << 19; + } + + void print() + { + if (_fresh == 0) return; + + String miData; + + if (_fresh >> 0 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += aState; + + free(aState); + } + + if (_fresh >> 1 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += aColor; + + free(aColor); + } + + if (_fresh >> 2 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += aMode; + + free(aMode); + } + + if (_fresh >> 3 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += aCtemp; + + free(aCtemp); + } + + if (_fresh >> 4 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += aBright; + + free(aBright); + } + + if (_fresh >> 5 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += aTemp; + + free(aTemp); + } + + if (_fresh >> 6 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += aHumi; + + free(aHumi); + } + + if (_fresh >> 7 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += aPm25; + + free(aPm25); + } + + if (_fresh >> 8 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += aCO2; + + free(aCO2); + } + + if (_fresh >> 9 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += aLevel; + + free(aLevel); + } + + if (_fresh >> 10 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += ahState; + + free(ahState); + } + + if (_fresh >> 11 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += avState; + + free(avState); + } + + if (_fresh >> 12 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += ecoState; + + free(ecoState); + } + + if (_fresh >> 13 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += anionState; + + free(anionState); + } + + if (_fresh >> 14 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += heaterState; + + free(heaterState); + } + + if (_fresh >> 15 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += dryerState; + + free(dryerState); + } + + if (_fresh >> 16 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += sleepState; + + free(sleepState); + } + + if (_fresh >> 17 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += softState; + + free(softState); + } + + if (_fresh >> 18 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += uvState; + + free(uvState); + } + + if (_fresh >> 19 & 0x01) { + if (miData.length()) miData += BLINKER_F(","); + else miData += BLINKER_F("{"); + + miData += unsbState; + + free(unsbState); + } + + miData += BLINKER_F("}"); + + _fresh = 0; + + Blinker.miotPrint(miData); + } + + private : + char * aState; + char * aColor; + char * aMode; + char * aCtemp; + char * aBright; + char * aTemp; + char * aHumi; + char * aPm25; + char * aCO2; + + char * aLevel; + char * ahState; + char * avState; + char * ecoState; + char * anionState; + char * heaterState; + char * dryerState; + char * sleepState; + char * softState; + char * uvState; + char * unsbState; + uint32_t _fresh = 0; +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerMQTTAIR202.h b/blinker-library/src/Functions/BlinkerMQTTAIR202.h new file mode 100644 index 0000000..db22366 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerMQTTAIR202.h @@ -0,0 +1,764 @@ +#ifndef BLINKER_MQTT_AIR202_H +#define BLINKER_MQTT_AIR202_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerATMaster.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +// #if defined(ESP32) +// #include + +// HardwareSerial *HSerial_MQTT; +// #else +// #include + +// SoftwareSerial *SSerial_MQTT; +// #endif + +#define BLINKER_MQTT_AIR202_DEFAULT_TIMEOUT 5000UL +#define BLINKER_MQTT_AIR202_DATA_BUFFER_SIZE 1024 + +enum air202_mqtt_status_t +{ + mqtt_init, + mqtt_init_success, + mqtt_set, + mqtt_set_ok, + mqtt_set_connect_ok, + mqtt_connect, + mqtt_connect_ok, + mqtt_connect_success, + mqtt_set_sub_topic, + mqtt_set_sub_ok, + mqtt_set_sub_success, + mqtt_set_pub, + mqtt_set_pub_ok, + mqtt_set_pub_success +}; + +class BlinkerMQTTAIR202 +{ + public : + BlinkerMQTTAIR202(Stream& s, bool isHardware, + const char * server, uint16_t port, + const char * cid, const char * user, + const char * pass, blinker_callback_t func) + { + stream = &s; isHWS = isHardware; + servername = server; portnum = port; + clientid = cid; username = user; + password = pass; listenFunc = func; + } + + ~BlinkerMQTTAIR202() { flush(); } + + int connect(); + int connected(); + int disconnect(); + void subscribe(const char * topic); + int publish(const char * topic, const char * msg); + int readSubscription(uint16_t time_out = 1000); + + char* lastRead; + const char* subTopic; + // char streamData[1024]; + char* streamData; + + void flush() + { + if(isFresh) free(streamData); + if(isRead) free(lastRead); + + isFresh = false; + isRead = false; + } + + protected : + class BlinkerMasterAT * _masterAT; + blinker_callback_t listenFunc = NULL; + Stream* stream; + // char* streamData; + bool isFresh = false; + bool isHWS = false; + bool isConnected = false; + bool isFreshSub = false; + bool isRead = false; + const char * servername; + uint16_t portnum; + const char * clientid; + const char * username; + const char * password; + uint32_t mqtt_time; + uint32_t connect_time; + uint16_t _mqttTimeout = 5000; + uint32_t _debug_time; + air202_mqtt_status_t mqtt_status; + + bool streamAvailable(); + + void streamPrint(const String & s) + { + BLINKER_LOG_ALL(s); + stream->println(s); + } + + int timedRead() + { + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; + } +}; + +int BlinkerMQTTAIR202::connect() +{ + streamPrint(STRING_format(BLINKER_CMD_CSTT_REQ) + + "=\"" + BLINKER_CMD_CMNET + "\""); + // BLINKER_LOG_ALL(STRING_format(BLINKER_CMD_MCONFIG_REQ) + + // "=\"" + clientid + "\",\"" + username + + // "\",\"" + password + "\""); + + mqtt_status = mqtt_init; + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt cstt success")); + // mqtt_status = mqtt_init_success; + break; + } + } + } + + streamPrint(STRING_format(BLINKER_CMD_CIICR_REQ)); + // BLINKER_LOG_ALL(STRING_format(BLINKER_CMD_MCONFIG_REQ) + + // "=\"" + clientid + "\",\"" + username + + // "\",\"" + password + "\""); + + mqtt_status = mqtt_init; + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt ciicr success")); + // mqtt_status = mqtt_init_success; + break; + } + } + } + + streamPrint(STRING_format(BLINKER_CMD_MCONFIG_REQ) + + "=\"" + clientid + "\",\"" + username + + "\",\"" + password + "\""); + // BLINKER_LOG_ALL(STRING_format(BLINKER_CMD_MCONFIG_REQ) + + // "=\"" + clientid + "\",\"" + username + + // "\",\"" + password + "\""); + + mqtt_status = mqtt_init; + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt init success")); + mqtt_status = mqtt_init_success; + break; + } + } + } + + if (mqtt_status != mqtt_init_success) return false; + + streamPrint(STRING_format(BLINKER_CMD_SSLMIPSTART) + + "=\"" + servername + "\"," + STRING_format(portnum)); + // BLINKER_LOG_ALL(STRING_format(BLINKER_CMD_SSLMIPSTART) + + // "=\"" + servername + "\"," + STRING_format(portnum)); + mqtt_status = mqtt_set; + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt set ok")); + mqtt_status = mqtt_set_ok; + break; + } + } + } + + if (mqtt_status != mqtt_set_ok) return false; + + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_CONNECT_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt set connect ok, can connect now")); + mqtt_status = mqtt_set_connect_ok; + break; + } + } + } + + streamPrint(STRING_format(BLINKER_CMD_MCONNECT_REQ) + + "=1,300"); + mqtt_status = mqtt_connect; + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt set connect, get ok, wait connact")); + mqtt_status = mqtt_connect_ok; + break; + } + } + } + + if (mqtt_status != mqtt_connect_ok) return false; + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_CONNACK_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt connacted")); + mqtt_status = mqtt_connect_success; + break; + } + } + } + + if (mqtt_status != mqtt_connect_success) return false; + + isConnected = true; + + // return true; + streamPrint(STRING_format(BLINKER_CMD_MSUB_REQ) + + "=\"" + subTopic + "\",0"); + mqtt_status = mqtt_set_sub_topic; + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt set sub ok")); + mqtt_status = mqtt_set_sub_ok; + break; + } + } + } + + if (mqtt_status != mqtt_set_sub_ok) return false; + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_SUBACK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt set sub success")); + mqtt_status = mqtt_set_sub_success; + break; + } + } + } + + if (mqtt_status != mqtt_set_sub_success) return false; + + return true; +} + +int BlinkerMQTTAIR202::connected() +{ + // if (isConnected && millis() - connect_time <= 30000) + // { + // while(millis() - mqtt_time < _mqttTimeout) + // { + // if (millis() - _debug_time >= 2000) + // { + // _debug_time = millis(); + // BLINKER_LOG_ALL(BLINKER_F("== connected, readSubscription ==")); + // } + + // if (streamAvailable()) + // { + // BLINKER_LOG_ALL(BLINKER_F("== connected available readSubscription ==")); + + // _masterAT = new BlinkerMasterAT(); + // _masterAT->update(STRING_format(streamData)); + + // if (_masterAT->getState() != AT_M_NONE && + // _masterAT->reqName() == BLINKER_CMD_MQTTSTATUS) + // { + // if(_masterAT->getParam(0).toInt() == 1) + // { + // free(_masterAT); + // connect_time = millis(); + // isConnected = true; + // return true; + // } + // else + // { + // BLINKER_LOG_ALL("mqtt not connected!"); + // isConnected = false; + // free(_masterAT); + // return false; + // } + + // } + // else if (_masterAT->getState() != AT_M_NONE && + // _masterAT->reqName() == BLINKER_CMD_MSUB) + // { + // String subData = String(streamData).substring( + // _masterAT->getParam(0).length() + + // _masterAT->getParam(1).length() + + // 10); + + // BLINKER_LOG_ALL("sub data: ", subData); + + // if (isFreshSub) free(lastRead); + // lastRead = (char*)malloc((subData.length()+1)*sizeof(char)); + // strcpy(lastRead, subData.c_str()); + + // isFreshSub = true; + + // connect_time = millis(); + + // free(_masterAT); + // return true; + // } + + // free(_masterAT); + + // BLINKER_LOG_ALL("== free connected at master =="); + // } + // } + + // return true; + // } + // else + { + if (isFreshSub) + { + connect_time = millis(); + return true; + } + + if (!isConnected || millis() - connect_time >= 15000) + { + streamPrint(STRING_format(BLINKER_CMD_MQTTSTATU_REQ)); + // connect_time = millis(); + // } + mqtt_time = millis(); + uint8_t status_get = 0; + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + BLINKER_LOG_ALL(BLINKER_F("== connected available ==")); + + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_MQTTSTATUS) + { + if(_masterAT->getParam(0).toInt() == 1) + { + free(_masterAT); + connect_time = millis(); + isConnected = true; + return true; + } + else + { + BLINKER_LOG_ALL("mqtt not connected!"); + isConnected = false; + free(_masterAT); + return false; + } + + } + else if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_MSUB) + { + String subData = String(streamData).substring( + _masterAT->getParam(0).length() + + _masterAT->getParam(1).length() + + 10); + + BLINKER_LOG_ALL("sub data: ", subData); + + if (isRead) free(lastRead); + lastRead = (char*)malloc((subData.length()+1)*sizeof(char)); + strcpy(lastRead, subData.c_str()); + + isFreshSub = true; + isConnected = true; + isRead = true; + connect_time = millis(); + + free(_masterAT); + + BLINKER_LOG_ALL("== free at master, return =="); + return true; + } + + free(_masterAT); + + BLINKER_LOG_ALL("== free connected at master =="); + } + } + } + } + + return isConnected; + + // return status_get; +} + +int BlinkerMQTTAIR202::disconnect() +{ + streamPrint(STRING_format(BLINKER_CMD_MDISCONNECT_REQ)); + mqtt_time = millis(); + uint8_t status_get = 0; + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + BLINKER_LOG_ALL(BLINKER_F("== disconnect available ==")); + if (strcmp(streamData, BLINKER_CMD_CONNACK_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt disconnect")); + // return true; + break; + } + } + } + + streamPrint(STRING_format(BLINKER_CMD_MIPCLOSE_REQ)); + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + BLINKER_LOG_ALL(BLINKER_F("== disconnect available ==")); + if (strcmp(streamData, BLINKER_CMD_CONNACK_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt disconnect")); + // return true; + break; + } + } + } + + streamPrint(STRING_format(BLINKER_CMD_CIPSHUT_REQ)); + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + BLINKER_LOG_ALL(BLINKER_F("== disconnect available ==")); + if (strcmp(streamData, BLINKER_CMD_CONNACK_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt disconnect")); + return true; + // break; + } + } + } + + return false; +} + +void BlinkerMQTTAIR202::subscribe(const char * topic) +{ + subTopic = topic; + // streamPrint(STRING_format(BLINKER_CMD_MPUB_REQ) + + // "=\"" + topic + "\",0"); + // mqtt_status = mqtt_set_sub_topic; + // mqtt_time = millis(); + + // while(millis() - mqtt_time < _mqttTimeout) + // { + // if (streamAvailable()) + // { + // if (strcmp(streamData, BLINKER_CMD_OK) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("mqtt set sub ok")); + // mqtt_status = mqtt_set_sub_ok; + // break; + // } + // } + // } + + // if (mqtt_status != mqtt_set_sub_ok) return false; + // mqtt_time = millis(); + + // while(millis() - mqtt_time < _mqttTimeout) + // { + // if (streamAvailable()) + // { + // if (strcmp(streamData, BLINKER_CMD_SUBACK) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("mqtt set sub success")); + // mqtt_status = mqtt_set_sub_success; + // break; + // } + // } + // } + + // if (mqtt_status != mqtt_set_sub_success) return false; + + // return true; +} + +int BlinkerMQTTAIR202::publish(const char * topic, const char * msg) +{ + streamPrint(STRING_format(BLINKER_CMD_MPUB_REQ) + + "=\"" + topic + "\",0,0,\"" + msg + "\""); + mqtt_status = mqtt_set_pub; + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt set pub ok")); + mqtt_status = mqtt_set_pub_ok; + break; + } + } + } + + if (mqtt_status != mqtt_set_pub_ok) return false; + + // mqtt_time = millis(); + + // while(millis() - mqtt_time < _mqttTimeout) + // { + // if (streamAvailable()) + // { + // if (strcmp(streamData, BLINKER_CMD_PUBACK) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("mqtt set pub success")); + // mqtt_status = mqtt_set_pub_success; + // break; + // } + // } + // } + + // if (mqtt_status != mqtt_set_pub_success) return false; + + return true; +} + +int BlinkerMQTTAIR202::readSubscription(uint16_t time_out) +{ + // if (millis() - _debug_time >= 2000) + // { + // _debug_time = millis(); + // BLINKER_LOG_ALL(BLINKER_F("== readSubscription ==")); + // } + + if (isFreshSub) + { + isFreshSub = false; + return true; + } + else + { + // return false; + // } + mqtt_time = millis(); + + while(millis() - mqtt_time < time_out) + { + if (streamAvailable()) + { + BLINKER_LOG_ALL(BLINKER_F("readSubscription")); + + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_MSUB) + { + String subData = String(streamData).substring( + _masterAT->getParam(0).length() + + _masterAT->getParam(1).length() + + 8); + BLINKER_LOG_ALL(BLINKER_F("mqtt sub data: "), subData); + + if (isRead) free(lastRead); + lastRead = (char*)malloc((subData.length()+1)*sizeof(char)); + strcpy(lastRead, subData.c_str()); + + isFreshSub = false; + isConnected = true; + isRead = true; + connect_time = millis(); + + free(_masterAT); + + return true; + } + + free(_masterAT); + } + } + + return false; + } +} + +bool BlinkerMQTTAIR202::streamAvailable() +{ + yield(); + + if (!isHWS) + { + // #if defined(__AVR__) || defined(ESP8266) + // if (!SSerial_MQTT->isListening()) + // { + // SSerial_MQTT->listen(); + // ::delay(100); + // } + // #endif + + if (listenFunc) listenFunc(); + } + + // char _data[BLINKER_MQTT_AIR202_DATA_BUFFER_SIZE];// = { '\0' }; + // memset(_data, '\0', BLINKER_MQTT_AIR202_DATA_BUFFER_SIZE); + + // if (!isFresh) streamData = (char*)malloc(BLINKER_MQTT_AIR202_DATA_BUFFER_SIZE*sizeof(char)); + + if (stream->available()) + { + // strcpy(_data, stream->readStringUntil('\n').c_str()); + String _data = stream->readStringUntil('\n'); + BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), _data); + // _data[strlen(_data) - 1] = '\0'; + if (isFresh) + { + free(streamData); + isFresh = false; + } + + if (_data.length() <= 1) return false; + + streamData = (char*)malloc((_data.length() + 1)*sizeof(char)); + strcpy(streamData, _data.c_str()); + if (_data.length() > 0) streamData[_data.length() - 1] = '\0'; + isFresh = true; + return true; + // if (isFresh) free(streamData); + // streamData = (char*)malloc(1*sizeof(char)); + // // streamData = ""; + // // memset(streamData, '\0', 1024); + + // // strcpy(streamData, stream->readStringUntil('\n').c_str()); + + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), streamData); + + // // int16_t dNum = strlen(streamData); + + // int16_t dNum = 0; + // int c_d = timedRead(); + // while (dNum < BLINKER_MAX_READ_SIZE && + // c_d >=0 && c_d != '\n') + // { + // // if (c_d != '\r') + // { + // streamData[dNum] = (char)c_d; + // dNum++; + // streamData = (char*)realloc(streamData, (dNum+1)*sizeof(char)); + // } + + // c_d = timedRead(); + // } + // // dNum++; + // // streamData = (char*)realloc(streamData, dNum*sizeof(char)); + + // // streamData[dNum-1] = '\0'; + + // // streamData = stream->readStringUntil('\n'); + // // streamData[streamData.length()-1] = '\0'; + + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial TEST: "), stream->readStringUntil('\n')); + + // // stream->flush(); + + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, + // // BLINKER_F(" , dNum: "), dNum); + // // BLINKER_LOG_FreeHeap_ALL(); + + // if (dNum < BLINKER_MAX_READ_SIZE && dNum > 0) + // { + // // if (streamData[strlen(streamData) - 1] == '\r') + // streamData[dNum - 1] = '\0'; + // BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, + // BLINKER_F(" , dNum: "), dNum); + + // isFresh = true; + // return true; + // } + // else + // { + // // free(streamData); + // return false; + // } + } + else + { + return false; + } +} + +#endif diff --git a/blinker-library/src/Functions/BlinkerMQTTSIM7000.h b/blinker-library/src/Functions/BlinkerMQTTSIM7000.h new file mode 100644 index 0000000..93ed46b --- /dev/null +++ b/blinker-library/src/Functions/BlinkerMQTTSIM7000.h @@ -0,0 +1,663 @@ +#ifndef BLINKER_MQTT_SIM7000_H +#define BLINKER_MQTT_SIM7000_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerATMaster.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +// #if defined(ESP32) +// #include + +// HardwareSerial *HSerial_MQTT; +// #else +// #include + +// SoftwareSerial *SSerial_MQTT; +// #endif + +#define BLINKER_MQTT_SIM7000_DEFAULT_TIMEOUT 5000UL +#define BLINKER_MQTT_SIM7000_DATA_BUFFER_SIZE 1024 + +enum sim7000_mqtt_status_t +{ + sim7000_mqtt_url_set, + sim7000_mqtt_url_success, + sim7000_mqtt_user_set, + sim7000_mqtt_user_success, + sim7000_mqtt_pswd_set, + sim7000_mqtt_pswd_success, + sim7000_mqtt_cid_set, + sim7000_mqtt_cid_success, + sim7000_mqtt_kat_set, + sim7000_mqtt_kat_success, + sim7000_mqtt_connect, + sim7000_mqtt_connect_success, + sim7000_mqtt_set_sub, + sim7000_mqtt_set_sub_success +}; + + + +class BlinkerMQTTSIM7000 +{ + public : + BlinkerMQTTSIM7000(Stream& s, bool isHardware, + const char * server, uint16_t port, + const char * cid, const char * user, + const char * pass, blinker_callback_t func) + { + stream = &s; isHWS = isHardware; + servername = server; portnum = port; + clientid = cid; username = user; + password = pass; listenFunc = func; + // streamData = (char*)malloc(BLINKER_HTTP_SIM7000_DATA_BUFFER_SIZE*sizeof(char)); + } + + ~BlinkerMQTTSIM7000() { flush(); } + + int connect(); + int connected(); + int disconnect(); + void subscribe(const char * topic); + int publish(const char * topic, const char * msg); + int readSubscription(uint16_t time_out = 1000); + + char* lastRead; + const char* subTopic; + // char streamData[1024]; + char* streamData; + + void flush() + { + if(isFresh) free(streamData); + if(isRead) free(lastRead); + + isFresh = false; + isRead = false; + } + + protected : + class BlinkerMasterAT * _masterAT; + blinker_callback_t listenFunc = NULL; + Stream* stream; + // char* streamData; + bool isFresh = false; + bool isHWS = false; + bool isConnected = false; + bool isFreshSub = false; + bool isRead = false; + const char * servername; + uint16_t portnum; + const char * clientid; + const char * username; + const char * password; + uint32_t mqtt_time; + uint32_t ping_time; + uint32_t connect_time; + uint16_t _mqttTimeout = 5000; + uint32_t _debug_time; + sim7000_mqtt_status_t mqtt_status; + + char c_hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; + + int8_t dcode_data(char d_test) + { + for (uint8_t num = 0; num < 16; num++) + { + if (d_test == c_hex[num]) return num; + } + + return -1; + } + + char ecode_data(uint8_t d_test) + { + return c_hex[d_test]; + } + + String encode(char data[]) + { + char _d[1024] = {'\0'}; + + for(uint16_t num = 0; num < strlen(data); num++) + { + _d[num*2] = (ecode_data(data[num] >> 4)); + _d[num*2+1] = (ecode_data(data[num] & 0x0F)); + } + + return _d; + } + + String encode(String data) + { + char _d[1024] = {'\0'}; + + for(uint16_t num = 0; num < data.length(); num++) + { + _d[num*2] = (ecode_data((uint8_t)data[num] >> 4)); + _d[num*2+1] = (ecode_data((uint8_t)data[num] & 0x0F)); + } + + return _d; + } + + bool streamAvailable(); + + void streamPrint(const String & s) + { + BLINKER_LOG_ALL(BLINKER_F("SIM MQTT: "), s); + stream->println(s); + } + + int timedRead() + { + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; + } +}; + +int BlinkerMQTTSIM7000::connect() +{ + streamPrint(STRING_format(BLINKER_CMD_SMCONF_REQ) + \ + "=url," + STRING_format(servername) + \ + "," + STRING_format(portnum)); + + mqtt_status = sim7000_mqtt_url_set; + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + mqtt_status = sim7000_mqtt_url_success; + break; + } + } + } + + if (mqtt_status != sim7000_mqtt_url_success) + { + return false; + } + + // streamPrint(STRING_format(BLINKER_CMD_SMCONF_REQ) + \ + // "=\"KEEPTIME\",60"); + // mqtt_time = millis(); + + // mqtt_status = sim7000_mqtt_url_set; + + // while(millis() - mqtt_time < _mqttTimeout) + // { + // if (streamAvailable()) + // { + // if (strcmp(streamData, BLINKER_CMD_OK) == 0) + // { + // mqtt_status = sim7000_mqtt_user_success; + // break; + // } + // } + // } + + // if (mqtt_status != sim7000_mqtt_user_success) + // { + // return false; + // } + + streamPrint(STRING_format(BLINKER_CMD_SMCONF_REQ) + \ + "=username," + username); + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + mqtt_status = sim7000_mqtt_user_success; + break; + } + } + } + + if (mqtt_status != sim7000_mqtt_user_success) + { + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SMCONF_REQ) + \ + "=password," + password); + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + mqtt_status = sim7000_mqtt_pswd_success; + break; + } + } + } + + if (mqtt_status != sim7000_mqtt_pswd_success) + { + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SMCONF_REQ) + \ + "=clientid,\"" + clientid + "\""); + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + mqtt_status = sim7000_mqtt_cid_success; + break; + } + } + } + + if (mqtt_status != sim7000_mqtt_cid_success) + { + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SMCONN_REQ)); + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + mqtt_status = sim7000_mqtt_connect_success; + break; + } + } + } + + if (mqtt_status != sim7000_mqtt_connect_success) + { + return false; + } + + streamPrint(STRING_format(BLINKER_CMD_SMUNSUB_REQ) + \ + "=\"" + subTopic + "\""); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + break; + } + } + } + + streamPrint(STRING_format(BLINKER_CMD_SMSUB_REQ) + \ + "=\"" + subTopic + "\",0"); + mqtt_time = millis(); + + mqtt_status = sim7000_mqtt_set_sub; + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + mqtt_status = sim7000_mqtt_set_sub_success; + break; + } + } + } + + if (mqtt_status != sim7000_mqtt_set_sub_success) + { + return false; + } + + return true; +} + +int BlinkerMQTTSIM7000::connected() +{ + streamPrint(STRING_format(BLINKER_CMD_SMSTATE_REQ) + \ + "?"); + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + BLINKER_LOG_ALL(BLINKER_F("connected query")); + + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_SMSTATE && + _masterAT->getParam(0).toInt() == 1) + { + isConnected = true; + } + else + { + isConnected = false; + } + + free(_masterAT); + BLINKER_LOG_ALL(BLINKER_F("isConnected: "), isConnected); + break; + } + } + + // streamPrint(STRING_format(BLINKER_CMD_SMSUB_REQ) + \ + // "=\"" + subTopic + "\",0"); + + // while(millis() - mqtt_time < _mqttTimeout) + // { + // if (streamAvailable()) + // { + // if (strcmp(streamData, BLINKER_CMD_OK) == 0) + // { + // break; + // } + // } + // } + + return isConnected; +} + +int BlinkerMQTTSIM7000::disconnect() +{ + streamPrint(STRING_format(BLINKER_CMD_SMDISC_REQ)); + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt disconnect")); + return true; + } + } + } + + return false; +} + +void BlinkerMQTTSIM7000::subscribe(const char * topic) +{ + subTopic = topic; +} + +int BlinkerMQTTSIM7000::publish(const char * topic, const char * msg) +{ + streamPrint(STRING_format(BLINKER_CMD_SMPUB_REQ) + + "=\"" + topic + "\"," + + STRING_format(strlen(msg)) + ",0,0"); + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strncmp(streamData, ">", 1) == 0) + { + // return true; + break; + } + } + } + + streamPrint(msg); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + return true; + } + } + } + + return false; +} + +int BlinkerMQTTSIM7000::readSubscription(uint16_t time_out) +{ + if (isFreshSub) + { + isFreshSub = false; + return true; + } + else + { + // BLINKER_LOG_ALL(BLINKER_F("readSubscription in")); + mqtt_time = millis(); + + while(millis() - mqtt_time < time_out) + { + if (streamAvailable()) + { + BLINKER_LOG_ALL(BLINKER_F("readSubscription")); + BLINKER_LOG_FreeHeap_ALL(); + + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_SMSUB) + { + String _Data = STRING_format(streamData); + + time_t now_time = millis(); + while (millis() - now_time < 1500) + { + if (stream->available()) + { + _Data += stream->readStringUntil('\n').c_str(); + } + // delay(1000); + } + BLINKER_LOG_ALL(BLINKER_F("_Data: "), _Data); + + // String subData = _Data.substring( + // _masterAT->getParam(0).length() + + // _masterAT->getParam(1).length() + + // _masterAT->getParam(2).length() + + // _masterAT->getParam(3).length() + + // _masterAT->getParam(4).length() + + // _masterAT->getParam(5).length() + + // 15, _Data.length() - 1); + String subData = _Data.substring(_Data.indexOf(",") + 2, _Data.length() - 1);//_masterAT->getParam(1); + + // BLINKER_LOG_ALL(BLINKER_F("leng 0: "), _masterAT->getParam(0).length()); + // BLINKER_LOG_ALL(BLINKER_F("leng 1: "), _masterAT->getParam(1).length()); + // BLINKER_LOG_ALL(BLINKER_F("leng 2: "), _masterAT->getParam(2).length()); + // BLINKER_LOG_ALL(BLINKER_F("leng 3: "), _masterAT->getParam(3).length()); + // BLINKER_LOG_ALL(BLINKER_F("leng 4: "), _masterAT->getParam(4).length()); + // BLINKER_LOG_ALL(BLINKER_F("leng 5: "), _masterAT->getParam(5).length()); + BLINKER_LOG_ALL(BLINKER_F("mqtt sub data: "), subData); + + if (isRead) free(lastRead); + lastRead = (char*)malloc((subData.length()+1)*sizeof(char)); + // strcpy(lastRead, subData.c_str()); + + memset(lastRead, '\0', subData.length()+1); + + strcpy(lastRead, subData.c_str()); + + isFreshSub = false; + isConnected = true; + isRead = true; + connect_time = millis(); + + free(_masterAT); + + return true; + } + else if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CMQDISCON) + { + free(_masterAT); + + isConnected = false; + + return false; + } + + + free(_masterAT); + } + } + + return false; + } +} + +bool BlinkerMQTTSIM7000::streamAvailable() +{ + yield(); + + if (!isHWS) + { + // #if defined(__AVR__) || defined(ESP8266) + // if (!SSerial_MQTT->isListening()) + // { + // SSerial_MQTT->listen(); + // ::delay(100); + // } + // #endif + + if (listenFunc) listenFunc(); + } + + // char _data[BLINKER_MQTT_SIM7000_DATA_BUFFER_SIZE];// = { '\0' }; + // memset(_data, '\0', BLINKER_MQTT_SIM7000_DATA_BUFFER_SIZE); + // if (!isFresh) streamData = (char*)malloc(BLINKER_MQTT_SIM7000_DATA_BUFFER_SIZE*sizeof(char)); + + if (stream->available()) + { + // strcpy(_data, stream->readStringUntil('\n').c_str()); + String _data = stream->readStringUntil('\n'); + + // time_t now_time = millis(); + // while (millis() - now_time < 1500) + // { + // if (stream->available()) + // { + // _data += stream->readStringUntil('\n').c_str(); + // } + // // delay(1000); + // } + + BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), _data); + BLINKER_LOG_ALL("len: ", _data.length()); + // _data[strlen(_data) - 1] = '\0'; + + // stream->flush(); + + if (isFresh) + { + free(streamData); + isFresh = false; + } + + if (_data.length() <= 1) return false; + + streamData = (char*)malloc((_data.length() + 1)*sizeof(char)); + strcpy(streamData, _data.c_str()); + if (streamData[_data.length() - 1] == '\r') streamData[_data.length() - 1] = '\0'; + isFresh = true; + return true; + // if (isFresh) free(streamData); + // streamData = (char*)malloc(1*sizeof(char)); + // // streamData = ""; + // // memset(streamData, '\0', 1024); + + // // strcpy(streamData, stream->readStringUntil('\n').c_str()); + + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), streamData); + + // // int16_t dNum = strlen(streamData); + + // int16_t dNum = 0; + // int c_d = timedRead(); + // while (dNum < BLINKER_MAX_READ_SIZE && + // c_d >=0 && c_d != '\n') + // { + // // if (c_d != '\r') + // { + // streamData[dNum] = (char)c_d; + // dNum++; + // streamData = (char*)realloc(streamData, (dNum+1)*sizeof(char)); + // } + + // c_d = timedRead(); + // } + // // dNum++; + // // streamData = (char*)realloc(streamData, dNum*sizeof(char)); + + // // streamData[dNum-1] = '\0'; + + // // streamData = stream->readStringUntil('\n'); + // // streamData[streamData.length()-1] = '\0'; + + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial TEST: "), stream->readStringUntil('\n')); + + // // stream->flush(); + + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, + // // BLINKER_F(" , dNum: "), dNum); + // // BLINKER_LOG_FreeHeap_ALL(); + + // if (dNum < BLINKER_MAX_READ_SIZE && dNum > 0) + // { + // // if (streamData[strlen(streamData) - 1] == '\r') + // streamData[dNum - 1] = '\0'; + // BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, + // BLINKER_F(" , dNum: "), dNum); + + // isFresh = true; + // return true; + // } + // else + // { + // // free(streamData); + // return false; + // } + } + else + { + return false; + } +} + +#endif diff --git a/blinker-library/src/Functions/BlinkerMQTTSIM7020.h b/blinker-library/src/Functions/BlinkerMQTTSIM7020.h new file mode 100644 index 0000000..d69289a --- /dev/null +++ b/blinker-library/src/Functions/BlinkerMQTTSIM7020.h @@ -0,0 +1,570 @@ +#ifndef BLINKER_MQTT_SIM7020_H +#define BLINKER_MQTT_SIM7020_H + +#if ARDUINO >= 100 + #include +#else + #include +#endif + +#include "../Blinker/BlinkerATMaster.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +// #if defined(ESP32) +// #include + +// HardwareSerial *HSerial_MQTT; +// #else +// #include + +// SoftwareSerial *SSerial_MQTT; +// #endif + +#define BLINKER_MQTT_SIM7020_DEFAULT_TIMEOUT 5000UL +#define BLINKER_MQTT_SIM7020_DATA_BUFFER_SIZE 1024 + +enum sim7020_mqtt_status_t +{ + sim7020_mqtt_init, + sim7020_mqtt_init_success, + sim7020_mqtt_connect, + sim7020_mqtt_connect_success, + sim7020_mqtt_set_sub, + sim7020_mqtt_set_sub_success +}; + +class BlinkerMQTTSIM7020 +{ + public : + BlinkerMQTTSIM7020(Stream& s, bool isHardware, + const char * server, uint16_t port, + const char * cid, const char * user, + const char * pass, blinker_callback_t func) + { + stream = &s; isHWS = isHardware; + servername = server; portnum = port; + clientid = cid; username = user; + password = pass; listenFunc = func; + // streamData = (char*)malloc(BLINKER_HTTP_SIM7020_DATA_BUFFER_SIZE*sizeof(char)); + } + + ~BlinkerMQTTSIM7020() { flush(); } + + int connect(); + int connected(); + int disconnect(); + void subscribe(const char * topic); + int publish(const char * topic, const char * msg); + int readSubscription(uint16_t time_out = 1000); + + char* lastRead; + const char* subTopic; + // char streamData[1024]; + char* streamData; + + void flush() + { + if(isFresh) free(streamData); + if(isRead) free(lastRead); + + isFresh = false; + isRead = false; + } + + protected : + class BlinkerMasterAT * _masterAT; + blinker_callback_t listenFunc = NULL; + Stream* stream; + // char* streamData; + bool isFresh = false; + bool isHWS = false; + bool isConnected = false; + bool isFreshSub = false; + bool isRead = false; + const char * servername; + uint16_t portnum; + const char * clientid; + const char * username; + const char * password; + uint32_t mqtt_time; + uint32_t ping_time; + uint32_t connect_time; + uint16_t _mqttTimeout = 5000; + uint32_t _debug_time; + sim7020_mqtt_status_t mqtt_status; + + char c_hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; + + int8_t dcode_data(char d_test) + { + for (uint8_t num = 0; num < 16; num++) + { + if (d_test == c_hex[num]) return num; + } + + return -1; + } + + char ecode_data(uint8_t d_test) + { + return c_hex[d_test]; + } + + String encode(char data[]) + { + char _d[1024] = {'\0'}; + + for(uint16_t num = 0; num < strlen(data); num++) + { + _d[num*2] = (ecode_data(data[num] >> 4)); + _d[num*2+1] = (ecode_data(data[num] & 0x0F)); + } + + return _d; + } + + String encode(String data) + { + char _d[1024] = {'\0'}; + + for(uint16_t num = 0; num < data.length(); num++) + { + _d[num*2] = (ecode_data((uint8_t)data[num] >> 4)); + _d[num*2+1] = (ecode_data((uint8_t)data[num] & 0x0F)); + } + + return _d; + } + + bool streamAvailable(); + + void streamPrint(const String & s) + { + BLINKER_LOG_ALL(BLINKER_F("SIM MQTT: "), s); + stream->println(s); + } + + int timedRead() + { + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; + } +}; + +int BlinkerMQTTSIM7020::connect() +{ + streamPrint(STRING_format(BLINKER_CMD_CMQNEW_REQ) + \ + "=\"" + servername + "\",\"" + STRING_format(portnum) + \ + "\",12000,1024"); + + mqtt_status = sim7020_mqtt_init; + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CMQNEW && + _masterAT->getParam(0).toInt() == 0) + { + free(_masterAT); + + mqtt_status = sim7020_mqtt_init_success; + break; + } + free(_masterAT); + } + } + + if (mqtt_status != sim7020_mqtt_init_success) return false; + + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + break; + } + } + } + + streamPrint(STRING_format(BLINKER_CMD_CMQCON_REQ) + + "=0,3,\"" + clientid + "\",600,0,0,\"" + + username + "\",\"" + password + "\""); + mqtt_status = sim7020_mqtt_connect; + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + mqtt_status = sim7020_mqtt_connect_success; + // return true; + break; + } + } + } + + if (mqtt_status != sim7020_mqtt_connect_success) return false; + + // isConnected = true; + + streamPrint(STRING_format(BLINKER_CMD_CMQSUB_REQ) + + "=0,\"" + subTopic + "\",0"); + mqtt_status = sim7020_mqtt_set_sub; + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("mqtt set sub ok")); + mqtt_status = sim7020_mqtt_set_sub_success; + + isConnected = true; + + ping_time = millis(); + + return true; + } + } + } + + if (mqtt_status != sim7020_mqtt_set_sub_success) return false; +} + +int BlinkerMQTTSIM7020::connected() +{ + // yield(); + + // BLINKER_LOG_ALL(BLINKER_F(">>>>>> mqtt connected check <<<<<<")); + + if (isConnected && (millis() - ping_time) <= 10000) + { + yield(); + return isConnected; + } + + if ((millis() - ping_time) <= 60000) return false; + + BLINKER_LOG_ALL(BLINKER_F(">>>>>> mqtt connected check ping_time<<<<<<")); + streamPrint(STRING_format(BLINKER_CMD_CMQCON_REQ) + "?"); + mqtt_time = millis(); + ping_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + BLINKER_LOG_ALL(BLINKER_F("connected query")); + + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CMQCON && + _masterAT->getParam(0).toInt() == 0) + { + if (_masterAT->getParam(1) == "1") + { + isConnected = true; + } + else + { + isConnected = false; + } + free(_masterAT); + BLINKER_LOG_ALL(BLINKER_F("isConnected: "), isConnected); + break; + } + + free(_masterAT); + } + } + + while(streamAvailable()) { delay(10); } + + return isConnected; +} + +int BlinkerMQTTSIM7020::disconnect() +{ + streamPrint(STRING_format(BLINKER_CMD_CMQDISCON_RESQ) + "=0"); + mqtt_time = millis(); + + isConnected = false; + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + // isConnected = false; + + return true; + } + } + } + + return false; +} + +void BlinkerMQTTSIM7020::subscribe(const char * topic) +{ + subTopic = topic; +} + +int BlinkerMQTTSIM7020::publish(const char * topic, const char * msg) +{ + streamPrint(STRING_format(BLINKER_CMD_CMQPUB_REQ) + + "=0,\"" + topic + "\",0,0,0," + + STRING_format(strlen(msg)*2) + ",\"" + + encode(msg) + "\""); + mqtt_time = millis(); + + while(millis() - mqtt_time < _mqttTimeout) + { + if (streamAvailable()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + return true; + } + } + } + + return false; +} + +int BlinkerMQTTSIM7020::readSubscription(uint16_t time_out) +{ + if (isFreshSub) + { + isFreshSub = false; + return true; + } + else + { + mqtt_time = millis(); + + while(millis() - mqtt_time < time_out) + { + if (streamAvailable()) + { + BLINKER_LOG_ALL(BLINKER_F("readSubscription")); + BLINKER_LOG_FreeHeap_ALL(); + + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CMQPUB) + { + String _Data = STRING_format(streamData); + + time_t now_time = millis(); + while (millis() - now_time < 1500) + { + if (stream->available()) + { + _Data += stream->readStringUntil('\n').c_str(); + } + // delay(1000); + } + BLINKER_LOG_ALL(BLINKER_F("_Data: "), _Data); + + String subData = _Data.substring( + _masterAT->getParam(0).length() + + _masterAT->getParam(1).length() + + _masterAT->getParam(2).length() + + _masterAT->getParam(3).length() + + _masterAT->getParam(4).length() + + _masterAT->getParam(5).length() + + 15, _Data.length() - 1); + + // BLINKER_LOG_ALL(BLINKER_F("leng 0: "), _masterAT->getParam(0).length()); + // BLINKER_LOG_ALL(BLINKER_F("leng 1: "), _masterAT->getParam(1).length()); + // BLINKER_LOG_ALL(BLINKER_F("leng 2: "), _masterAT->getParam(2).length()); + // BLINKER_LOG_ALL(BLINKER_F("leng 3: "), _masterAT->getParam(3).length()); + // BLINKER_LOG_ALL(BLINKER_F("leng 4: "), _masterAT->getParam(4).length()); + // BLINKER_LOG_ALL(BLINKER_F("leng 5: "), _masterAT->getParam(5).length()); + BLINKER_LOG_ALL(BLINKER_F("mqtt sub data: "), subData); + + if (isRead) free(lastRead); + lastRead = (char*)malloc((subData.length()/2+1)*sizeof(char)); + // strcpy(lastRead, subData.c_str()); + + memset(lastRead, '\0', subData.length()/2+1); + + for(uint16_t num = 0; num < subData.length()/2; num++) + { + lastRead[num] = (char)(dcode_data(subData[num*2])<< 4 | dcode_data(subData[num*2+1])); + } + + isFreshSub = false; + isConnected = true; + isRead = true; + connect_time = millis(); + + free(_masterAT); + + return true; + } + else if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CMQDISCON) + { + free(_masterAT); + + isConnected = false; + + return false; + } + + + free(_masterAT); + } + } + + return false; + } +} + +bool BlinkerMQTTSIM7020::streamAvailable() +{ + yield(); + + if (!isHWS) + { + // #if defined(__AVR__) || defined(ESP8266) + // if (!SSerial_MQTT->isListening()) + // { + // SSerial_MQTT->listen(); + // ::delay(100); + // } + // #endif + + if (listenFunc) listenFunc(); + } + + // char _data[BLINKER_MQTT_SIM7020_DATA_BUFFER_SIZE];// = { '\0' }; + // memset(_data, '\0', BLINKER_MQTT_SIM7020_DATA_BUFFER_SIZE); + // if (!isFresh) streamData = (char*)malloc(BLINKER_MQTT_SIM7020_DATA_BUFFER_SIZE*sizeof(char)); + + if (stream->available()) + { + // strcpy(_data, stream->readStringUntil('\n').c_str()); + String _data = stream->readStringUntil('\n'); + + // time_t now_time = millis(); + // while (millis() - now_time < 1500) + // { + // if (stream->available()) + // { + // _data += stream->readStringUntil('\n').c_str(); + // } + // // delay(1000); + // } + + BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), _data); + BLINKER_LOG_ALL("len: ", _data.length()); + // _data[strlen(_data) - 1] = '\0'; + + // stream->flush(); + + if (isFresh) + { + free(streamData); + isFresh = false; + } + + if (_data.length() <= 1) return false; + + streamData = (char*)malloc((_data.length() + 1)*sizeof(char)); + strcpy(streamData, _data.c_str()); + if (streamData[_data.length() - 1] == '\r') streamData[_data.length() - 1] = '\0'; + isFresh = true; + return true; + // if (isFresh) free(streamData); + // streamData = (char*)malloc(1*sizeof(char)); + // // streamData = ""; + // // memset(streamData, '\0', 1024); + + // // strcpy(streamData, stream->readStringUntil('\n').c_str()); + + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), streamData); + + // // int16_t dNum = strlen(streamData); + + // int16_t dNum = 0; + // int c_d = timedRead(); + // while (dNum < BLINKER_MAX_READ_SIZE && + // c_d >=0 && c_d != '\n') + // { + // // if (c_d != '\r') + // { + // streamData[dNum] = (char)c_d; + // dNum++; + // streamData = (char*)realloc(streamData, (dNum+1)*sizeof(char)); + // } + + // c_d = timedRead(); + // } + // // dNum++; + // // streamData = (char*)realloc(streamData, dNum*sizeof(char)); + + // // streamData[dNum-1] = '\0'; + + // // streamData = stream->readStringUntil('\n'); + // // streamData[streamData.length()-1] = '\0'; + + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial TEST: "), stream->readStringUntil('\n')); + + // // stream->flush(); + + // // BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, + // // BLINKER_F(" , dNum: "), dNum); + // // BLINKER_LOG_FreeHeap_ALL(); + + // if (dNum < BLINKER_MAX_READ_SIZE && dNum > 0) + // { + // // if (streamData[strlen(streamData) - 1] == '\r') + // streamData[dNum - 1] = '\0'; + // BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, + // BLINKER_F(" , dNum: "), dNum); + + // isFresh = true; + // return true; + // } + // else + // { + // // free(streamData); + // return false; + // } + } + else + { + return false; + } +} + +#endif diff --git a/blinker-library/src/Functions/BlinkerNumber.h b/blinker-library/src/Functions/BlinkerNumber.h new file mode 100644 index 0000000..c8da0b2 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerNumber.h @@ -0,0 +1,157 @@ +#ifndef BlinkerNUM_H +#define BlinkerNUM_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BlinkerNumber +{ + public : + BlinkerNumber(char _name[]) + { + numName = (char*)malloc((strlen(_name)+1)*sizeof(char)); + strcpy(numName, _name); + } + + void icon(const String & _icon) + { + if (_fresh >> 0 & 0x01) free(nicon); + + nicon = (char*)malloc((_icon.length()+1)*sizeof(char)); + strcpy(nicon, _icon.c_str()); + + _fresh |= 0x01 << 0; + } + + void color(const String & _clr) + { + if (_fresh >> 1 & 0x01) free(ncolor); + + ncolor = (char*)malloc((_clr.length()+1)*sizeof(char)); + strcpy(ncolor, _clr.c_str()); + + _fresh |= 0x01 << 1; + } + + void unit(const String & _unit) + { + if (_fresh >> 2 & 0x01) free(nunit); + + nunit = (char*)malloc((_unit.length()+1)*sizeof(char)); + strcpy(nunit, _unit.c_str()); + + _fresh |= 0x01 << 2; + } + + template + void text(T _text) + { + // if (isnan(_text)) return; + + if (_fresh >> 3 & 0x01) free(ntext); + + String _ntext = STRING_format(_text); + ntext = (char*)malloc((_ntext.length()+1)*sizeof(char)); + strcpy(ntext, _ntext.c_str()); + + _fresh |= 0x01 << 3; + } + + void print(char value) { _print(STRING_format(value)); } + void print(unsigned char value) { _print(STRING_format(value)); } + void print(int value) { _print(STRING_format(value)); } + void print(unsigned int value) { _print(STRING_format(value)); } + void print(long value) { _print(STRING_format(value)); } + void print(unsigned long value) { _print(STRING_format(value)); } + void print(double value) { _print(STRING_format(value)); } + void print() { _print(""); } + + private : + char * numName; + char * nicon;// = ""; + char * ncolor;// = ""; + char * nunit;// = ""; + char * ntext; + uint8_t _fresh = 0; + + void _print(const String & value) + { + if (_fresh == 0 && value.length() == 0) return; + + String numberData = ""; + + if (value.length()) + { + numberData += BLINKER_F("{\""); + numberData += BLINKER_F(BLINKER_CMD_VALUE); + numberData += BLINKER_F("\":"); + numberData += value; + + Blinker.printNumArray(numName, value); + } + + if (_fresh >> 0 & 0x01) + { + if (numberData.length()) numberData += BLINKER_F(","); + else numberData += BLINKER_F("{"); + + numberData += BLINKER_F("\""); + numberData += BLINKER_F(BLINKER_CMD_ICON); + numberData += BLINKER_F("\":\""); + numberData += nicon; + numberData += BLINKER_F("\""); + + free(nicon); + } + + if (_fresh >> 1 & 0x01) + { + if (numberData.length()) numberData += BLINKER_F(","); + else numberData += BLINKER_F("{"); + + numberData += BLINKER_F("\""); + numberData += BLINKER_F(BLINKER_CMD_COLOR); + numberData += BLINKER_F("\":\""); + numberData += ncolor; + numberData += BLINKER_F("\""); + + free(ncolor); + } + + if (_fresh >> 2 & 0x01) + { + if (numberData.length()) numberData += BLINKER_F(","); + else numberData += BLINKER_F("{"); + + numberData += BLINKER_F("\""); + numberData += BLINKER_F(BLINKER_CMD_UNIT); + numberData += BLINKER_F("\":\""); + numberData += nunit; + numberData += BLINKER_F("\""); + + free(nunit); + } + + if (_fresh >> 3 & 0x01) + { + if (numberData.length()) numberData += BLINKER_F(","); + else numberData += BLINKER_F("{"); + + numberData += BLINKER_F("\""); + numberData += BLINKER_F(BLINKER_CMD_TEXT); + numberData += BLINKER_F("\":\""); + numberData += (ntext); + numberData += BLINKER_F("\""); + + free(ntext); + } + + numberData += BLINKER_F("}"); + + _fresh = 0; + + Blinker.printArray(numName, numberData); + } +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerOTA.h b/blinker-library/src/Functions/BlinkerOTA.h new file mode 100644 index 0000000..e7f5f11 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerOTA.h @@ -0,0 +1,583 @@ +#ifndef BLINKER_OTA_H +#define BLINKER_OTA_H + +#if (defined(ESP8266) || defined(ESP32)) + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include +#if defined(ESP8266) + #include + #include + + #ifndef BLINKER_WITHOUT_SSL + extern BearSSL::WiFiClientSecure client_mqtt; + #endif +#elif defined(ESP32) + #include + #include + + // extern WiFiClient client_s; + extern WiFiClientSecure client_s; +#endif + +#include "BlinkerUpdater.h" + +// extern WiFiClientSecure client_s; + +enum bota_status_t{ + BLINKER_UPGRADE_DISABLE, + BLINKER_UPGRADE_BEGIN, + BLINKER_UPGRADE_START, + BLINKER_UPGRADE_FAIL, + BLINKER_UPGRADE_LOAD_FAIL, + BLINKER_UPGRADE_VERI_FAIL, + BLINKER_UPGRADE_SUCCESS +}; +// #define VERSIONPARAM "1.0.1" + +// if (loadOTACheck()) { +// if (!loadVersion()) { +// saveVersion(); +// UPGRADE_STATUS = UPGRADE_SUCCESS; +// } +// else { +// UPGRADE_STATUS = UPGRADE_FAIL; +// } +// } + +class BlinkerOTA +{ + public : + BlinkerOTA() {} + // void parseData(char *OTAdata); + void host(String _host) { ota_host = _host; } + void url(String _url) { ota_url = _url; } + void setURL(String urlstr); + void config(String _host, String _url, String _fingerPrint, String _md5) + { + // #if defined(ESP8266) + BLINKER_LOG_ALL(_host.indexOf("https")); + if (_host.indexOf("https") != -1) + { + ota_host = _host.substring(8); + } + else + { + ota_host = _host; + } + // #else + // ota_host = _host; + // #endif + ota_url = _url; + ota_fingerPrint = _fingerPrint; + ota_md5 = _md5; + } + bool update(); + // bool run(); + bota_status_t status() { + return _status; + } + uint8_t loadOTACheck(); + void saveOTARun(); + void saveOTACheck(); + void clearOTACheck(); + bool loadVersion(); + void saveVersion(); + + private : + String getHeaderValue(String header, String headerName) { + return header.substring(strlen(headerName.c_str())); + } + + protected : + // #if defined(ESP32) + // uint8_t OTACheck; + // #endif + String ota_host; + String ota_url; + String ota_fingerPrint; + String ota_md5; + uint16_t ota_port = 443; + char *otaUrl; + bota_status_t _status; + // int + size_t contentLength = 0; + bool isValidContentType = false; +}; + +void BlinkerOTA::setURL(String url) { + otaUrl = (char*)malloc(url.length()*sizeof(char)); + strcpy(otaUrl,url.c_str()); + + BLINKER_LOG_ALL(BLINKER_F("ota url: "), otaUrl); + + _status = BLINKER_UPGRADE_START; + + update(); +} + +bool BlinkerOTA::update() { + saveOTACheck(); + +#if defined(ESP8266) + // #ifndef BLINKER_WITHOUT_SSL + BearSSL::WiFiClientSecure client_s; + + BLINKER_LOG_FreeHeap(); + #ifndef BLINKER_WITHOUT_SSL + client_mqtt.stop(); + #endif + ::delay(100); + + bool mfln = client_s.probeMaxFragmentLength(ota_host, ota_port, 1024); + if (mfln) { + client_s.setBufferSizes(1024, 1024); + } + + // client_s.setFingerprint(ota_fingerPrint.c_str()); + + BLINKER_LOG_FreeHeap(); + + client_s.setInsecure(); + + // BLINKER_LOG_ALL(BLINKER_F("Connecting to: "), ota_host); + + // t_httpUpdate_return ret = BlinkerhttpUpdate.update(client_s, ota_host + ota_url, ota_md5, ""); + + // switch (ret) { + // case HTTP_UPDATE_FAILED: + // // USE_SERIAL.printf("HTTP_UPDATE_FAILD Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); + // // break; + // BLINKER_LOG_ALL(BLINKER_F("HTTP_UPDATE_FAILD Error : "), BlinkerhttpUpdate.getLastError()); + // return false; + + // case HTTP_UPDATE_NO_UPDATES: + // // USE_SERIAL.println("HTTP_UPDATE_NO_UPDATES"); + // // break; + // BLINKER_LOG_ALL(BLINKER_F("HTTP_UPDATE_NO_UPDATES")); + // return false; + + // case HTTP_UPDATE_OK: + // // USE_SERIAL.println("HTTP_UPDATE_OK"); + // // break; + // BLINKER_LOG_ALL(BLINKER_F("HTTP_UPDATE_OK")); + // return true; + // } + + // #else + // WiFiClient client_s; + // #endif + +#elif defined(ESP32) + client_s.stop(); +#endif + + BlinkerUpdater.setMD5(ota_md5.c_str()); + + while (1) { + if (!client_s.connect(ota_host.c_str(), ota_port)) { + BLINKER_ERR_LOG(BLINKER_F("server connection failed")); + BLINKER_LOG_FreeHeap(); + ::delay(1000); + } + else { + BLINKER_LOG_ALL(BLINKER_F("connection succeed")); + BLINKER_LOG_FreeHeap(); + BLINKER_LOG_ALL(BLINKER_F("Fetching Bin: "), ota_url); + + String _ota_url = BLINKER_F("GET "); + _ota_url += ota_url; + _ota_url += BLINKER_F(" HTTP/1.1\r\nHost: "); + _ota_url += ota_host; + _ota_url += BLINKER_F("\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n"); + + // client_s.print(String("GET ") + ota_url + " HTTP/1.1\r\n" + + // "Host: " + ota_host + "\r\n" + + // "Cache-Control: no-cache\r\n" + + // "Connection: close\r\n\r\n"); + + client_s.print(_ota_url); + + BLINKER_LOG_ALL(BLINKER_F("_ota_url: "), _ota_url); + + unsigned long timeout = millis(); + while (client_s.available() == 0) { + if (millis() - timeout > 5000) { + BLINKER_LOG_ALL(BLINKER_F("Client Timeout !")); + client_s.stop(); + + _status = BLINKER_UPGRADE_LOAD_FAIL; + return false; + } + } + // Once the response is available, + // check stuff + + while (client_s.available()) { + // read line till /n + String line = client_s.readStringUntil('\n'); + // remove space, to check if the line is end of headers + line.trim(); + + // if the the line is empty, + // this is end of headers + // break the while and feed the + // remaining `client_s` to the + // Update.writeStream(); + if (!line.length()) { + //headers ended + break; // and get the OTA started + } + + BLINKER_LOG_ALL(BLINKER_F("line: "), line); + + // Check if the HTTP Response is 200 + // else break and Exit Update + if (line.startsWith("HTTP/1.1")) { + if (line.indexOf("200") < 0) { + BLINKER_LOG_ALL(BLINKER_F("Got a non 200 status code from server. Exiting OTA Update.")); + break; + } + } + + // extract headers here + // Start with content length + if (line.startsWith("Content-Length: ")) { + contentLength = atoi((getHeaderValue(line, "Content-Length: ")).c_str()); + BLINKER_LOG_ALL(BLINKER_F("Got "), contentLength, BLINKER_F(" bytes from server")); + } + + // Next, the content type + if (line.startsWith("Content-Type: ")) { + String contentType = getHeaderValue(line, "Content-Type: "); + BLINKER_LOG_ALL(BLINKER_F("Got "), contentType, BLINKER_F(" payload.")); + if (contentType == "application/octet-stream") { + isValidContentType = true; + } + } + } + + // Check what is the contentLength and if content type is `application/octet-stream` + BLINKER_LOG_ALL(BLINKER_F("contentLength : "), + contentLength, + BLINKER_F(", isValidContentType : "), + isValidContentType); + + // check contentLength and content type + if (contentLength && isValidContentType) + { + // Check if there is enough to OTA Update + bool canBegin = BlinkerUpdater.begin(contentLength); + + // If yes, begin + if (canBegin) { + BLINKER_LOG(BLINKER_F("Begin OTA. This may take 2 - 5 mins to complete. Things might be quite for a while.. Patience!")); + // No activity would appear on the Serial monitor + // So be patient. This may take 2 - 5mins to complete + size_t written = BlinkerUpdater.writeStream(client_s); + + if (written == contentLength) { + BLINKER_LOG(BLINKER_F("Written : "), written, BLINKER_F(" successfully")); + } + else { + BLINKER_LOG(BLINKER_F("Written only : "), written, + BLINKER_F("/"), contentLength, BLINKER_F(". Retry?")); + } + + if (BlinkerUpdater.end()) { + BLINKER_LOG(BLINKER_F("OTA done!")); + if (BlinkerUpdater.isFinished()) { + BLINKER_LOG(BLINKER_F("Update successfully completed. Rebooting.")); + _status = BLINKER_UPGRADE_SUCCESS; + // ESP.restart(); + + return true; + } else { + BLINKER_LOG(BLINKER_F("Update not finished? Something went wrong!")); + _status = BLINKER_UPGRADE_FAIL; + + return false; + } + } + else { + BLINKER_LOG(BLINKER_F("Error Occurred. Error #: "), BlinkerUpdater.getError()); + _status = BLINKER_UPGRADE_FAIL; + + // return false; + } + } + else { + // not enough space to begin OTA + // Understand the partitions and + // space availability + BLINKER_LOG(BLINKER_F("Not enough space to begin OTA")); + client_s.flush(); + _status = BLINKER_UPGRADE_FAIL; + + return false; + } + } + else { + BLINKER_LOG(BLINKER_F("There was no content in the response")); + client_s.flush(); + _status = BLINKER_UPGRADE_FAIL; + + return false; + } + } + } +// #endif +} + +// bool BlinkerOTA::run() +// { +// while (1) { +// if (!client_s.connect(ota_host.c_str(), ota_port)) { +// BLINKER_ERR_LOG(BLINKER_F("server connection failed")); +// BLINKER_LOG_FreeHeap(); +// ::delay(1000); +// } +// else { +// BLINKER_LOG_ALL(BLINKER_F("connection succeed")); +// BLINKER_LOG_FreeHeap(); +// BLINKER_LOG_ALL(BLINKER_F("Fetching Bin: "), ota_url); + +// client_s.print(String("GET ") + ota_url + " HTTP/1.1\r\n" + +// "Host: " + ota_host + "\r\n" + +// "Cache-Control: no-cache\r\n" + +// "Connection: close\r\n\r\n"); + +// unsigned long timeout = millis(); +// while (client_s.available() == 0) { +// if (millis() - timeout > 5000) { +// BLINKER_LOG_ALL(BLINKER_F("Client Timeout !")); +// client_s.stop(); + +// _status = BLINKER_UPGRADE_LOAD_FAIL; +// return false; +// } +// } +// // Once the response is available, +// // check stuff + +// while (client_s.available()) { +// // read line till /n +// String line = client_s.readStringUntil('\n'); +// // remove space, to check if the line is end of headers +// line.trim(); + +// // if the the line is empty, +// // this is end of headers +// // break the while and feed the +// // remaining `client_s` to the +// // Update.writeStream(); +// if (!line.length()) { +// //headers ended +// break; // and get the OTA started +// } + +// // Check if the HTTP Response is 200 +// // else break and Exit Update +// if (line.startsWith("HTTP/1.1")) { +// if (line.indexOf("200") < 0) { +// BLINKER_LOG_ALL(BLINKER_F("Got a non 200 status code from server. Exiting OTA Update.")); +// break; +// } +// } + +// // extract headers here +// // Start with content length +// if (line.startsWith("Content-Length: ")) { +// contentLength = atoi((getHeaderValue(line, "Content-Length: ")).c_str()); +// BLINKER_LOG_ALL(BLINKER_F("Got "), contentLength, BLINKER_F(" bytes from server")); +// } + +// // Next, the content type +// if (line.startsWith("Content-Type: ")) { +// String contentType = getHeaderValue(line, "Content-Type: "); +// BLINKER_LOG_ALL(BLINKER_F("Got "), contentType, BLINKER_F(" payload.")); +// if (contentType == "application/octet-stream") { +// isValidContentType = true; +// } +// } +// } + +// // Check what is the contentLength and if content type is `application/octet-stream` +// BLINKER_LOG_ALL(BLINKER_F("contentLength : "), +// contentLength, +// BLINKER_F(", isValidContentType : "), +// isValidContentType); + +// // check contentLength and content type +// if (contentLength && isValidContentType) +// { +// // Check if there is enough to OTA Update +// bool canBegin = BlinkerUpdater.begin(contentLength); + +// // If yes, begin +// if (canBegin) { +// BLINKER_LOG(BLINKER_F("Begin OTA. This may take 2 - 5 mins to complete. Things might be quite for a while.. Patience!")); +// // No activity would appear on the Serial monitor +// // So be patient. This may take 2 - 5mins to complete +// size_t written = BlinkerUpdater.writeStream(client_s); + +// if (written == contentLength) { +// BLINKER_LOG(BLINKER_F("Written : "), written, BLINKER_F(" successfully")); +// } +// else { +// BLINKER_LOG(BLINKER_F("Written only : "), written, +// BLINKER_F("/"), contentLength, BLINKER_F(". Retry?")); +// } + +// if (BlinkerUpdater.end()) { +// BLINKER_LOG(BLINKER_F("OTA done!")); +// if (BlinkerUpdater.isFinished()) { +// BLINKER_LOG(BLINKER_F("Update successfully completed. Rebooting.")); +// _status = BLINKER_UPGRADE_SUCCESS; +// // ESP.restart(); + +// return true; +// } else { +// BLINKER_LOG(BLINKER_F("Update not finished? Something went wrong!")); +// _status = BLINKER_UPGRADE_FAIL; + +// return false; +// } +// } +// else { +// BLINKER_LOG(BLINKER_F("Error Occurred. Error #: "), BlinkerUpdater.getError()); +// _status = BLINKER_UPGRADE_FAIL; + +// // return false; +// } +// } +// else { +// // not enough space to begin OTA +// // Understand the partitions and +// // space availability +// BLINKER_LOG(BLINKER_F("Not enough space to begin OTA")); +// client_s.flush(); +// _status = BLINKER_UPGRADE_FAIL; + +// return false; +// } +// } +// else { +// BLINKER_LOG(BLINKER_F("There was no content in the response")); +// client_s.flush(); +// _status = BLINKER_UPGRADE_FAIL; + +// return false; +// } +// } +// } +// } + +uint8_t BlinkerOTA::loadOTACheck() { + // #if defined(ESP8266) + static uint8_t OTACheck; + // #endif + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_OTA_CHECK, OTACheck); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("OTA Check: "), OTACheck); + // BLINKER_LOG_ALL(BLINKER_F("BLINKER_EEP_ADDR_OTA_CHECK: "), BLINKER_EEP_ADDR_OTA_CHECK); + + return OTACheck; + + // if (OTACheck != BLINKER_OTA_START) { + // BLINKER_LOG_ALL(BLINKER_F("OTA NOT START")); + // return false; + // } + // else { + // BLINKER_LOG_ALL(BLINKER_F("OTA START")); + // return true; + // } +} + +void BlinkerOTA::saveOTARun() { + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_OTA_CHECK, BLINKER_OTA_RUN); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("OTA RUN: "), BLINKER_OTA_RUN); +} + +void BlinkerOTA::saveOTACheck() { + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_OTA_CHECK, BLINKER_OTA_START); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("OTA START: "), BLINKER_OTA_START); +} + +void BlinkerOTA::clearOTACheck() { + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_OTA_CHECK, BLINKER_OTA_CLEAR); + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("OTA CLEAR: "), BLINKER_OTA_CLEAR); + _status = BLINKER_UPGRADE_DISABLE; +} + +bool BlinkerOTA::loadVersion() { +// #if defined(BLINKER_PRO) +// uint32_t versionCheck; +// EEPROM.begin(BLINKER_EEP_SIZE); +// EEPROM.get(BLINKER_EEP_ADDR_OTA_INFO, versionCheck);//+BUNDLINGSIZE+isBundling +// EEPROM.commit(); +// EEPROM.end(); + +// BLINKER_LOG_ALL(BLINKER_F("loadVersion: "), versionCheck); + +// if (versionCheck != BLINKER_OTA_VERSION_CODE) { +// BLINKER_LOG_ALL(BLINKER_F("OTA SUCCESS BLINKER_OTA_VERSION_CODE NOT UPGRADE")); +// _status = BLINKER_UPGRADE_SUCCESS; +// return false; +// } +// else { +// BLINKER_LOG_ALL(BLINKER_F("OTA FAIL OR NOT START OTA")); +// _status = BLINKER_UPGRADE_FAIL; +// return true; +// } +// #else + char versionCheck[11]; + + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.get(BLINKER_EEP_ADDR_OTA_INFO, versionCheck);//+BUNDLINGSIZE+isBundling + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("loadVersion: "), versionCheck); + + if (strcmp(versionCheck, BLINKER_OTA_VERSION_CODE)) { + BLINKER_LOG_ALL(BLINKER_F("OTA SUCCESS BLINKER_OTA_VERSION_CODE NOT UPGRADE")); + _status = BLINKER_UPGRADE_SUCCESS; + return false; + } + else { + BLINKER_LOG_ALL(BLINKER_F("OTA FAIL OR NOT START OTA")); + _status = BLINKER_UPGRADE_FAIL; + return true; + } +// #endif +} + +void BlinkerOTA::saveVersion() { + EEPROM.begin(BLINKER_EEP_SIZE); + EEPROM.put(BLINKER_EEP_ADDR_OTA_INFO, BLINKER_OTA_VERSION_CODE);//+BUNDLINGSIZE+isBundling + EEPROM.commit(); + EEPROM.end(); + + BLINKER_LOG_ALL(BLINKER_F("SAVE BLINKER_OTA_VERSION_CODE")); +} + +#endif + +#endif diff --git a/blinker-library/src/Functions/BlinkerRGB.h b/blinker-library/src/Functions/BlinkerRGB.h new file mode 100644 index 0000000..16d6a0d --- /dev/null +++ b/blinker-library/src/Functions/BlinkerRGB.h @@ -0,0 +1,66 @@ +#ifndef BlinkerRGB_H +#define BlinkerRGB_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BlinkerRGB +{ + public : + BlinkerRGB(char _name[], blinker_callback_with_rgb_arg_t _func = NULL) + // : rgbName(_name) + { + wNum = Blinker.attachWidget(_name, _func); + } + + void attach(blinker_callback_with_rgb_arg_t _func) + { + if (wNum == 0) return; + + Blinker.freshAttachWidget(Blinker.widgetName_rgb(wNum), _func); + } + + void brightness(uint8_t _bright) { rgbrightness = _bright; } + + void print(uint8_t _r, uint8_t _g, uint8_t _b) + { + if (wNum == 0) return; + + String rgbData = BLINKER_F("["); + rgbData += STRING_format(_r); + rgbData += BLINKER_F(","); + rgbData += STRING_format(_g); + rgbData += BLINKER_F(","); + rgbData += STRING_format(_b); + rgbData += BLINKER_F(","); + rgbData += STRING_format(rgbrightness); + rgbData += BLINKER_F("]"); + + Blinker.printArray(Blinker.widgetName_rgb(wNum), rgbData); + } + + void print(uint8_t _r, uint8_t _g, uint8_t _b, uint8_t _bright) + { + if (wNum == 0) { + return; + } + + String rgbData = BLINKER_F("["); + rgbData += STRING_format(_r); + rgbData += BLINKER_F(","); + rgbData += STRING_format(_g); + rgbData += BLINKER_F(","); + rgbData += STRING_format(_b); + rgbData += BLINKER_F(","); + rgbData += STRING_format(_bright); + rgbData += BLINKER_F("]"); + + Blinker.printArray(Blinker.widgetName_rgb(wNum), rgbData); + } + + private : + uint8_t wNum; + uint8_t rgbrightness = 0; +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerSIM7000.h b/blinker-library/src/Functions/BlinkerSIM7000.h new file mode 100644 index 0000000..0e12abc --- /dev/null +++ b/blinker-library/src/Functions/BlinkerSIM7000.h @@ -0,0 +1,542 @@ +#ifndef BLINKER_SIM7000_H +#define BLINKER_SIM7000_H + +#if defined(ARDUINO) + #if ARDUINO >= 100 + #include + #else + #include + #endif +#endif + +#include "../Blinker/BlinkerATMaster.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +#include + +#define BLINKER_SIM7000_DATA_BUFFER_SIZE 1024 + +enum sim7000_status_t +{ + sim7000_cpin_REQ, + sim7000_cpin_success, + sim7000_csq_REQ, + sim7000_csq_success, + sim7000_cgreg_REQ, + sim7000_cgreg_success, + sim7000_cgact_REQ, + sim7000_cgact_success, + sim7000_cops_REQ, + sim7000_cops_success, + sim7000_cnact_REQ, + sim7000_cnact_success, + sim7000_cgcontrdp_REQ, + sim7000_cgcontrdp_success, +}; + +class BlinkerSIM7000 +{ + public : + BlinkerSIM7000() : + isHWS(false) + {} + + ~BlinkerSIM7000() { flush(); } + + time_t _ntpTime = 0; + + void setStream(Stream& s, bool isHardware, blinker_callback_t _func) + { stream = &s; isHWS = isHardware; listenFunc = _func; } + + bool getSNTP(float _tz = 8.0, char _url[] = "120.25.108.11") + { + // uint32_t os_time = millis(); + // _timezone = _tz; + // streamPrint(STRING_format(BLINKER_CMD_CNTP_REQ) + \ + // "=" + STRING_format(_url) + \ + // "," + STRING_format((int8_t)(_tz * 4))); + + // while(millis() - os_time < _simTimeout * 10) + // { + // if (available()) + // { + // _masterAT = new BlinkerMasterAT(); + // _masterAT->update(STRING_format(streamData)); + + // if (_masterAT->getState() != AT_M_NONE && + // _masterAT->reqName() == BLINKER_CMD_CNTP) + // { + // free(_masterAT); + // return true; + // } + // free(_masterAT); + // } + // } + // return false; + return true; + } + + int checkPDN() + { + uint32_t sim_time = millis(); + sim7000_status_t pdn_status = sim7000_cpin_REQ; + + streamPrint(BLINKER_CMD_CPIN_REQ); + + while(millis() - sim_time < _simTimeout) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CPIN && + _masterAT->getParam(0) == BLINKER_CMD_READY) + { + BLINKER_LOG_ALL(BLINKER_F("sim7000_cpin_success")); + pdn_status = sim7000_cpin_success; + free(_masterAT); + break; + } + free(_masterAT); + } + } + + if (pdn_status != sim7000_cpin_success) return false; + + // streamPrint(BLINKER_CMD_CSQ_REQ); + // sim_time = millis(); + + // while(millis() - sim_time < _simTimeout) + // { + // if (available()) + // { + // _masterAT = new BlinkerMasterAT(); + // _masterAT->update(STRING_format(streamData)); + + // if (_masterAT->getState() != AT_M_NONE && + // _masterAT->reqName() == BLINKER_CMD_CSQ && + // _masterAT->getParam(0).toInt() != 99) + // { + // BLINKER_LOG_ALL(BLINKER_F("sim7000_csq_success")); + // pdn_status = sim7000_csq_success; + // free(_masterAT); + // break; + // } + // free(_masterAT); + // } + // } + + // if (pdn_status != sim7000_csq_success) return false; + + // streamPrint(BLINKER_CMD_COPS_REQ); + // sim_time = millis(); + + // while(millis() - sim_time < _simTimeout) + // { + // if (available()) + // { + // _masterAT = new BlinkerMasterAT(); + // _masterAT->update(STRING_format(streamData)); + + // if (_masterAT->getState() != AT_M_NONE && + // _masterAT->reqName() == BLINKER_CMD_COPS) + // // && + // // _masterAT->getParam(3).toInt() == 9) + // { + // BLINKER_LOG_ALL(BLINKER_F("sim7000_cops_success")); + // pdn_status = sim7000_cops_success; + // free(_masterAT); + // break; + // } + // free(_masterAT); + // } + // } + + // if (pdn_status != sim7000_cops_success) return false; + + streamPrint(STRING_format(BLINKER_CMD_CNACT_REQ) + "=?"); + sim_time = millis(); + + while(millis() - sim_time < _simTimeout) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == "CNACT" && + _masterAT->getParam(0).toInt() == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7000_cops_success")); + pdn_status = sim7000_cops_success; + free(_masterAT); + break; + } + free(_masterAT); + // return true; + } + } + + streamPrint(STRING_format(BLINKER_CMD_CNACT_REQ) + "=1,\"cmnet\""); + sim_time = millis(); + + while(millis() - sim_time < _simTimeout) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + //return true; + pdn_status = sim7000_cnact_success; + } + } + } + + delay(2000); + + while(millis() - sim_time < _simTimeout) + { + if (available()) + { + if (strstr(streamData, "ACTIVE") && strstr(streamData, "DEACTIVED") == 0) + { + return true; + // pdn_status = sim7000_cnact_success; + } + } + } + + return true; + } + + String getIMEI() + { + uint32_t dev_time = millis(); + + streamPrint(BLINEKR_CMD_GSN_REQ); + + char _imei[16]; + + while(millis() - dev_time < _simTimeout) + { + if (available()) + { + BLINKER_LOG_ALL(BLINKER_F("get IMEI: "), streamData, + BLINKER_F(", length: "), strlen(streamData)); + if (strlen(streamData) == 15) + { + strcpy(_imei, streamData); + } + } + } + + dev_time = millis(); + + while(millis() - dev_time < _simTimeout) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("get IMEI: "), _imei, + BLINKER_F(", length: "), strlen(streamData)); + return _imei; + } + } + } + + BLINKER_LOG_ALL(BLINKER_F("get IMEI: "), _imei, + BLINKER_F(", length: "), strlen(streamData)); + + return _imei; + } + + String getICCID() + { + uint32_t dev_time = millis(); + + streamPrint(BLINKER_CMD_CCID_REQ); + + char _iccid[21]; + + while(millis() - dev_time < _simTimeout) + { + if (available()) + { + BLINKER_LOG_ALL(BLINKER_F("get ICCID: "), streamData, + BLINKER_F(", length: "), strlen(streamData)); + if (strlen(streamData) == 20) + { + strcpy(_iccid, streamData); + } + } + } + + dev_time = millis(); + + while(millis() - dev_time < _simTimeout) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("get ICCID: "), _iccid, + BLINKER_F(", length: "), strlen(streamData)); + return _iccid; + } + } + } + + BLINKER_LOG_ALL(BLINKER_F("get ICCID: "), _iccid, + BLINKER_F(", length: "), strlen(streamData)); + + return _iccid; + } + + bool powerCheck() + { + // streamPrint(BLINKER_CMD_AT); + streamPrint("ATE0"); + uint32_t dev_time = millis(); + + while(millis() - dev_time < _simTimeout) + { + if (available()) + { + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("ATE0")); + } + } + } + + if (!checkPDN()) return false; + + // BLINKER_LOG_ALL(BLINKER_F("power check")); + // streamPrint(BLINKER_CMD_AT); + // uint32_t dev_time = millis(); + + // while(millis() - dev_time < _simTimeout) + // { + // if (available()) + // { + // if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("power on")); + + // // SAPBR(); + + return true; + // } + // } + // } + + // return false; + } + + bool isReboot() + { + streamPrint(BLINKER_CMD_AT); + uint32_t dev_time = millis(); + + while(millis() - dev_time < _simTimeout) + { + if (available()) + { + BLINKER_LOG_ALL(BLINKER_F("data len: "), strlen(streamData)); + if (strncmp(streamData, BLINKER_CMD_AT, 2) == 0 || \ + (strlen(streamData) != 0 && strncmp(streamData, BLINKER_CMD_OK, 2) != 0 && \ + strncmp(streamData, BLINKER_CMD_ERROR, 5) != 0)) + { + BLINKER_LOG_ALL(BLINKER_F("device reboot")); + + // SAPBR(); + // streamPrint("ATE0"); + + return true; + } + + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) return false; + // else if (strcmp(streamData, BLINKER_CMD_OK) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("device not reboot")); + // return false; + // } + } + } + + return false; + } + + bool isAlive() + { + streamPrint(BLINKER_CMD_AT, "isAlive"); + uint32_t dev_time = millis(); + + while(millis() - dev_time < _simTimeout * 2) + { + if (available()) + { + BLINKER_LOG_ALL(BLINKER_F("alive")); + return true; + } + } + + BLINKER_LOG_ALL(BLINKER_F("not alive")); + + return false; + } + + void flush() + { + if (isFresh) free(streamData); + + BLINKER_LOG_ALL(BLINKER_F("flush sim7000")); + } + + bool checkStream(char * data) + { + bool _check_ = strcmp(data, streamData); + + BLINKER_LOG_ALL(BLINKER_F("checkStream: "), _check_); + + return _check_ == 0; + } + + bool available() + { + yield(); + + if (!isHWS) + { + // #if defined(__AVR__) || defined(ESP8266) + // if (!SSerial_API->isListening()) + // { + // SSerial_API->listen(); + // ::delay(100); + // } + // #endif + + if (listenFunc) listenFunc(); + } + + // char _data[BLINKER_SIM7000_DATA_BUFFER_SIZE];// = { '\0' }; + // memset(_data, '\0', BLINKER_SIM7000_DATA_BUFFER_SIZE); + + if (stream->available()) + { + // strcpy(_data, stream->readStringUntil('\n').c_str()); + String _data = stream->readStringUntil('\n'); + BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), _data); + // _data[strlen(_data) - 1] = '\0'; + if (isFresh) + { + free(streamData); + isFresh = false; + } + + if (_data.length() <= 1) return false; + + streamData = (char*)malloc((_data.length() + 1)*sizeof(char)); + strcpy(streamData, _data.c_str()); + if (_data.length() > 0) streamData[_data.length() - 1] = '\0'; + isFresh = true; + return true; +// // streamData = ""; +// // memset(streamData, '\0', 128); +// if (isFresh) free(streamData); +// streamData = (char*)malloc(1*sizeof(char)); + +// // strcpy(streamData, stream->readStringUntil('\n').c_str()); + +// // int16_t dNum = strlen(streamData); + +// // BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), streamData, +// // BLINKER_F(", dNum: "), dNum); +// // // stream->readString(); + +// int16_t dNum = 0; +// int c_d = timedRead(); +// while (dNum < BLINKER_MAX_READ_SIZE && +// c_d >=0 && c_d != '\n') +// { +// // if (c_d != '\r') +// { +// streamData[dNum] = (char)c_d; +// dNum++; +// streamData = (char*)realloc(streamData, (dNum+1)*sizeof(char)); +// } + +// c_d = timedRead(); +// } +// // dNum++; +// // // // streamData = (char*)realloc(streamData, dNum*sizeof(char)); + +// // streamData[dNum-1] = '\0'; +// // stream->flush(); +// // 7b2264657461696c223a207b2262726f6b6572223a2022616c6979756e222c20226465766963654e616d65223a20223237383636394232304d3235423634323230354e33435850222c2022696f744964223a20225346455467613255784b784e386a69716e4e516730303130356435343030222c2022696f74546f6b656e223a20226331353530643464346334623432666338376431343639373333363166353539222c202270726f647563744b6579223a20224a67434762486c6e64677a222c202275756964223a20223733633762356134623266323231633061373264376234313238653430323337227d2c20226d657373616765223a20313030307d + +// // BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, +// // BLINKER_F(" , dNum: "), dNum); +// BLINKER_LOG_FreeHeap_ALL(); + +// if (dNum < BLINKER_MAX_READ_SIZE && dNum > 0) +// { +// // if (streamData[dNum - 1] == '\r') +// streamData[dNum - 1] = '\0'; +// BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, +// BLINKER_F(" , dNum: "), dNum); + +// isFresh = true; +// return true; +// } +// else +// { +// return false; +// } + } + else + { + return false; + } + } + + protected : + class BlinkerMasterAT * _masterAT; + blinker_callback_t listenFunc = NULL; + Stream* stream; + // char streamData[128]; + char* streamData; + bool isFresh = false; + bool isHWS = false; + uint16_t _simTimeout = 1000; + + // time_t _ntpTime = 0; + + float _timezone = 8.0; + + void streamPrint(const String & s, String from = "") + { + stream->println(s); + BLINKER_LOG_ALL(from, BLINKER_F(" SIM: "), s); + } + + int timedRead() + { + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; + } +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerSIM7020.h b/blinker-library/src/Functions/BlinkerSIM7020.h new file mode 100644 index 0000000..90f75b5 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerSIM7020.h @@ -0,0 +1,695 @@ +#ifndef BLINKER_SIM7020_H +#define BLINKER_SIM7020_H + +#if defined(ARDUINO) + #if ARDUINO >= 100 + #include + #else + #include + #endif +#endif + +#include "../Blinker/BlinkerATMaster.h" +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "../Blinker/BlinkerStream.h" +#include "../Blinker/BlinkerUtility.h" + +#include + +#define BLINKER_SIM7020_DATA_BUFFER_SIZE 1024 + +enum sim7020_status_t +{ + sim7020_cpin_REQ, + sim7020_cpin_success, + sim7020_csq_REQ, + sim7020_csq_success, + sim7020_cgreg_REQ, + sim7020_cgreg_success, + sim7020_cgact_REQ, + sim7020_cgact_success, + sim7020_cops_REQ, + sim7020_cops_success, + sim7020_cgcontrdp_REQ, + sim7020_cgcontrdp_success, +}; + +class BlinkerSIM7020 +{ + public : + BlinkerSIM7020() : + isHWS(false) + {} + + ~BlinkerSIM7020() { flush(); } + + time_t _ntpTime = 0; + + void setStream(Stream& s, bool isHardware, blinker_callback_t _func) + { stream = &s; isHWS = isHardware; listenFunc = _func; } + + // int16_t year() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_year + 1900; + // } + // return -1; + // } + + // int8_t month() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_mon + 1; + // } + // return -1; + // } + + // int8_t mday() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_mday; + // } + // return -1; + // } + + // int8_t wday() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_wday; + // } + // return -1; + // } + + // int8_t hour() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_hour; + // } + // return -1; + // } + + // int8_t minute() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_min; + // } + // return -1; + // } + + // int8_t second() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_sec; + // } + // return -1; + // } + + // time_t time() + // { + // if (_ntpTime) + // { + // return _ntpTime - _timezone * 3600; + // } + // return millis(); + // } + + // // time_t now_ntp() + // // { + // // if (_ntpTime) + // // { + // // return _ntpTime; + // // } + // // return millis(); + // // } + + // int32_t dtime() + // { + // if (_ntpTime) + // { + // struct tm timeinfo; + // #if defined(ESP8266) || defined(__AVR__) + // gmtime_r(&_ntpTime, &timeinfo); + // #elif defined(ESP32) + // localtime_r(&_ntpTime, &timeinfo); + // #endif + + // return timeinfo.tm_hour * 60 * 60 + timeinfo.tm_min * 60 + timeinfo.tm_sec; + // } + // return -1; + // } + + bool getSNTP(float _tz = 8.0, char _url[] = "120.25.108.11") + { + uint32_t os_time = millis(); + _timezone = _tz; + streamPrint(STRING_format(BLINKER_CMD_CSNTPSTART_REQ) + \ + "=" + STRING_format(_url)); + + while(millis() - os_time < _simTimeout * 10) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CSNTP) + { + struct tm timeinfo; + + timeinfo.tm_year = _masterAT->getParam(0).substring(1, 3).toInt() + 130; + timeinfo.tm_mon = _masterAT->getParam(0).substring(4, 6).toInt() - 1; + timeinfo.tm_mday = _masterAT->getParam(0).substring(7, 9).toInt() - 1; + + timeinfo.tm_hour = _masterAT->getParam(1).substring(0, 2).toInt(); + timeinfo.tm_min = _masterAT->getParam(1).substring(3, 5).toInt(); + timeinfo.tm_sec = _masterAT->getParam(1).substring(6, 8).toInt(); + + #if defined(ESP8266) || defined(ESP32) + _ntpTime = mktime(&timeinfo) + (uint32_t)(_timezone * 3600); + #else + _ntpTime = mk_gmtime(&timeinfo) + (uint32_t)(_timezone * 3600); + #endif + // _ntpTime = mk_gmtime(&timeinfo) + (uint32_t)(_timezone * 3600); + + BLINKER_LOG_ALL(BLINKER_F("year: "), timeinfo.tm_year); + BLINKER_LOG_ALL(BLINKER_F("mon: "), timeinfo.tm_mon); + BLINKER_LOG_ALL(BLINKER_F("mday: "), timeinfo.tm_mday); + BLINKER_LOG_ALL(BLINKER_F("hour: "), timeinfo.tm_hour); + BLINKER_LOG_ALL(BLINKER_F("mins: "), timeinfo.tm_min); + BLINKER_LOG_ALL(BLINKER_F("secs: "), timeinfo.tm_sec); + + BLINKER_LOG_ALL(BLINKER_F("_ntpTime: "), _ntpTime); + // BLINKER_LOG_ALL(BLINKER_F("==Current time: "), mk_gmtime(&timeinfo)); + + free(_masterAT); + return true; + } + + free(_masterAT); + } + } + return false; + } + + int checkPDN() + { + uint32_t sim_time = millis(); + sim7020_status_t pdn_status = sim7020_cpin_REQ; + + streamPrint(BLINKER_CMD_CPIN_REQ); + + while(millis() - sim_time < _simTimeout) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CPIN && + _masterAT->getParam(0) == BLINKER_CMD_READY) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_cpin_success")); + pdn_status = sim7020_cpin_success; + free(_masterAT); + break; + } + free(_masterAT); + } + } + + if (pdn_status != sim7020_cpin_success) return false; + + streamPrint(BLINKER_CMD_CSQ_REQ); + sim_time = millis(); + + while(millis() - sim_time < _simTimeout) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CSQ && + _masterAT->getParam(0).toInt() != 99) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_csq_success")); + pdn_status = sim7020_csq_success; + free(_masterAT); + break; + } + free(_masterAT); + } + } + + if (pdn_status != sim7020_csq_success) return false; + + streamPrint(BLINKER_CMD_CGREG_REQ); + sim_time = millis(); + + while(millis() - sim_time < _simTimeout) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CGREG && + _masterAT->getParam(0).toInt() == 0) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_cgact_success")); + pdn_status = sim7020_cgact_success; + free(_masterAT); + break; + } + free(_masterAT); + } + } + + if (pdn_status != sim7020_cgact_success) return false; + + streamPrint(BLINKER_CMD_COPS_REQ); + sim_time = millis(); + + while(millis() - sim_time < _simTimeout) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_COPS) + // && + // _masterAT->getParam(3).toInt() == 9) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_cops_success")); + pdn_status = sim7020_cops_success; + free(_masterAT); + break; + } + free(_masterAT); + } + } + + if (pdn_status != sim7020_cops_success) return false; + + streamPrint(BLINKER_CMD_CGCONTRDP_REQ); + sim_time = millis(); + + while(millis() - sim_time < _simTimeout) + { + if (available()) + { + _masterAT = new BlinkerMasterAT(); + _masterAT->update(STRING_format(streamData)); + + if (_masterAT->getState() != AT_M_NONE && + _masterAT->reqName() == BLINKER_CMD_CGCONTRDP && + _masterAT->getParam(2).toInt() == 5) + { + BLINKER_LOG_ALL(BLINKER_F("sim7020_contrdp_success")); + // pdn_status = sim7020_cops_success; + free(_masterAT); + return true; + } + free(_masterAT); + } + } + + return true; + } + + String getIMEI() + { + uint32_t dev_time = millis(); + + streamPrint(BLINEKR_CMD_GSN_REQ); + + char _imei[16]; + + while(millis() - dev_time < _simTimeout) + { + if (available()) + { + BLINKER_LOG_ALL(BLINKER_F("get IMEI: "), streamData, + BLINKER_F(", length: "), strlen(streamData)); + if (strlen(streamData) == 15) + { + strcpy(_imei, streamData); + } + } + } + + dev_time = millis(); + + while(millis() - dev_time < _simTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("get IMEI: "), _imei, + BLINKER_F(", length: "), strlen(streamData)); + return _imei; + } + } + } + + BLINKER_LOG_ALL(BLINKER_F("get IMEI: "), _imei, + BLINKER_F(", length: "), strlen(streamData)); + + return _imei; + } + + String getICCID() + { + uint32_t dev_time = millis(); + + streamPrint(BLINKER_CMD_CCID_REQ); + + char _iccid[21]; + + while(millis() - dev_time < _simTimeout) + { + if (available()) + { + BLINKER_LOG_ALL(BLINKER_F("get ICCID: "), streamData, + BLINKER_F(", length: "), strlen(streamData)); + if (strlen(streamData) == 20) + { + strcpy(_iccid, streamData); + } + } + } + + dev_time = millis(); + + while(millis() - dev_time < _simTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("get ICCID: "), _iccid, + BLINKER_F(", length: "), strlen(streamData)); + return _iccid; + } + } + } + + BLINKER_LOG_ALL(BLINKER_F("get ICCID: "), _iccid, + BLINKER_F(", length: "), strlen(streamData)); + + return _iccid; + } + + bool powerCheck() + { + streamPrint(BLINKER_CMD_AT); + streamPrint("ATE0"); + + if (!checkPDN()) return false; + + BLINKER_LOG_ALL(BLINKER_F("power check")); + streamPrint(BLINKER_CMD_AT); + uint32_t dev_time = millis(); + + while(millis() - dev_time < _simTimeout) + { + if (available()) + { + if (strcmp(streamData, BLINKER_CMD_OK) == 0) + { + BLINKER_LOG_ALL(BLINKER_F("power on")); + + // SAPBR(); + + return true; + } + } + } + + return false; + } + + bool isReboot() + { + streamPrint(BLINKER_CMD_AT); + uint32_t dev_time = millis(); + + while(millis() - dev_time < _simTimeout) + { + if (available()) + { + BLINKER_LOG_ALL(BLINKER_F("data len: "), strlen(streamData)); + if (strncmp(streamData, BLINKER_CMD_AT, 2) == 0 || \ + (strlen(streamData) != 0 && strncmp(streamData, BLINKER_CMD_OK, 2) != 0 && \ + strncmp(streamData, BLINKER_CMD_ERROR, 5) != 0)) + { + BLINKER_LOG_ALL(BLINKER_F("device reboot")); + + // SAPBR(); + // streamPrint("ATE0"); + + return true; + } + + if (strncmp(streamData, BLINKER_CMD_OK, 2) == 0) return false; + // else if (strcmp(streamData, BLINKER_CMD_OK) == 0) + // { + // BLINKER_LOG_ALL(BLINKER_F("device not reboot")); + // return false; + // } + } + } + + return false; + } + + bool isAlive() + { + streamPrint(BLINKER_CMD_AT, "isAlive"); + uint32_t dev_time = millis(); + + while(millis() - dev_time < _simTimeout * 2) + { + if (available()) + { + BLINKER_LOG_ALL(BLINKER_F("alive")); + return true; + } + } + + BLINKER_LOG_ALL(BLINKER_F("not alive")); + + return false; + } + + void flush() + { + if (isFresh) free(streamData); + + BLINKER_LOG_ALL(BLINKER_F("flush sim7020")); + } + + bool checkStream(char * data) + { + bool _check_ = strcmp(data, streamData); + + BLINKER_LOG_ALL(BLINKER_F("checkStream: "), _check_); + + return _check_ == 0; + } + + bool available() + { + yield(); + + if (!isHWS) + { + // #if defined(__AVR__) || defined(ESP8266) + // if (!SSerial_API->isListening()) + // { + // SSerial_API->listen(); + // ::delay(100); + // } + // #endif + + if (listenFunc) listenFunc(); + } + + // char _data[BLINKER_SIM7020_DATA_BUFFER_SIZE];// = { '\0' }; + // memset(_data, '\0', BLINKER_SIM7020_DATA_BUFFER_SIZE); + + if (stream->available()) + { + // strcpy(_data, stream->readStringUntil('\n').c_str()); + String _data = stream->readStringUntil('\n'); + BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), _data); + // _data[strlen(_data) - 1] = '\0'; + if (isFresh) + { + free(streamData); + isFresh = false; + } + + if (_data.length() <= 1) return false; + + streamData = (char*)malloc((_data.length() + 1)*sizeof(char)); + strcpy(streamData, _data.c_str()); + if (_data.length() > 0) streamData[_data.length() - 1] = '\0'; + isFresh = true; + return true; +// // streamData = ""; +// // memset(streamData, '\0', 128); +// if (isFresh) free(streamData); +// streamData = (char*)malloc(1*sizeof(char)); + +// // strcpy(streamData, stream->readStringUntil('\n').c_str()); + +// // int16_t dNum = strlen(streamData); + +// // BLINKER_LOG_ALL(BLINKER_F("handleSerial rs: "), streamData, +// // BLINKER_F(", dNum: "), dNum); +// // // stream->readString(); + +// int16_t dNum = 0; +// int c_d = timedRead(); +// while (dNum < BLINKER_MAX_READ_SIZE && +// c_d >=0 && c_d != '\n') +// { +// // if (c_d != '\r') +// { +// streamData[dNum] = (char)c_d; +// dNum++; +// streamData = (char*)realloc(streamData, (dNum+1)*sizeof(char)); +// } + +// c_d = timedRead(); +// } +// // dNum++; +// // // // streamData = (char*)realloc(streamData, dNum*sizeof(char)); + +// // streamData[dNum-1] = '\0'; +// // stream->flush(); +// // 7b2264657461696c223a207b2262726f6b6572223a2022616c6979756e222c20226465766963654e616d65223a20223237383636394232304d3235423634323230354e33435850222c2022696f744964223a20225346455467613255784b784e386a69716e4e516730303130356435343030222c2022696f74546f6b656e223a20226331353530643464346334623432666338376431343639373333363166353539222c202270726f647563744b6579223a20224a67434762486c6e64677a222c202275756964223a20223733633762356134623266323231633061373264376234313238653430323337227d2c20226d657373616765223a20313030307d + +// // BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, +// // BLINKER_F(" , dNum: "), dNum); +// BLINKER_LOG_FreeHeap_ALL(); + +// if (dNum < BLINKER_MAX_READ_SIZE && dNum > 0) +// { +// // if (streamData[dNum - 1] == '\r') +// streamData[dNum - 1] = '\0'; +// BLINKER_LOG_ALL(BLINKER_F("handleSerial: "), streamData, +// BLINKER_F(" , dNum: "), dNum); + +// isFresh = true; +// return true; +// } +// else +// { +// return false; +// } + } + else + { + return false; + } + } + + protected : + class BlinkerMasterAT * _masterAT; + blinker_callback_t listenFunc = NULL; + Stream* stream; + // char streamData[128]; + char* streamData; + bool isFresh = false; + bool isHWS = false; + uint16_t _simTimeout = 1000; + + // time_t _ntpTime = 0; + + float _timezone = 8.0; + + void streamPrint(const String & s, String from = "") + { + stream->println(s); + BLINKER_LOG_ALL(from, BLINKER_F(" SIM: "), s); + } + + int timedRead() + { + int c; + uint32_t _startMillis = millis(); + do { + c = stream->read(); + if (c >= 0) return c; + } while(millis() - _startMillis < 1000); + return -1; + } +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerSlider.h b/blinker-library/src/Functions/BlinkerSlider.h new file mode 100644 index 0000000..57b4593 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerSlider.h @@ -0,0 +1,87 @@ +#ifndef BlinkerSlider_H +#define BlinkerSlider_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BlinkerSlider +{ + public : + BlinkerSlider(char _name[], blinker_callback_with_int32_arg_t _func = NULL) + // : sliderName(_name) + { + wNum = Blinker.attachWidget(_name, _func); + } + + void attach(blinker_callback_with_int32_arg_t _func) + { + if (wNum == 0) return; + + Blinker.freshAttachWidget(Blinker.widgetName_int(wNum), _func); + } + + void color(const String & _clr) + { + if (_fresh >> 0 & 0x01) free(textClr); + + textClr = (char*)malloc((_clr.length()+1)*sizeof(char)); + strcpy(textClr, _clr.c_str()); + + _fresh |= 0x01 << 0; + } + + void print(char value) { _print(STRING_format(value)); } + void print(unsigned char value) { _print(STRING_format(value)); } + void print(int value) { _print(STRING_format(value)); } + void print(unsigned int value) { _print(STRING_format(value)); } + void print(long value) { _print(STRING_format(value)); } + void print(unsigned long value) { _print(STRING_format(value)); } + void print(double value) { _print(STRING_format(value)); } + void print() { _print(""); } + + private : + uint8_t wNum; + char * textClr; + uint8_t _fresh = 0; + + void _print(const String & n) + { + if ((_fresh == 0 && n.length() == 0) || \ + wNum == 0) + { + return; + } + + String sliderData; + + if (n.length()) + { + sliderData += BLINKER_F("{\""); + sliderData += BLINKER_F(BLINKER_CMD_VALUE); + sliderData += BLINKER_F("\":"); + sliderData += n; + } + + if (_fresh >> 0 & 0x01) + { + if (sliderData.length()) sliderData += BLINKER_F(","); + else sliderData += BLINKER_F("{"); + + sliderData += BLINKER_F("\""); + sliderData += BLINKER_F(BLINKER_CMD_COLOR); + sliderData += BLINKER_F("\":\""); + sliderData += (textClr); + sliderData += BLINKER_F("\""); + + free(textClr); + } + + sliderData += BLINKER_F("}"); + + _fresh = 0; + + Blinker.printArray(Blinker.widgetName_int(wNum), sliderData); + } +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerSwitch.h b/blinker-library/src/Functions/BlinkerSwitch.h new file mode 100644 index 0000000..ab70f54 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerSwitch.h @@ -0,0 +1,27 @@ +#ifndef BlinkerSwitch_H +#define BlinkerSwitch_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BlinkerSwitch +{ + public : + BlinkerSwitch() + // : sName(BLINKER_CMD_BUILTIN_SWITCH) + {} + + void attach(blinker_callback_with_string_arg_t _func) + { + Blinker.attachSwitch(_func); + } + void print(const String & _state) + { + Blinker.print(BLINKER_CMD_BUILTIN_SWITCH, _state); + } + + private : + // String sName; +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerTab.h b/blinker-library/src/Functions/BlinkerTab.h new file mode 100644 index 0000000..ed968e6 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerTab.h @@ -0,0 +1,91 @@ +#ifndef BlinkerTab_H +#define BlinkerTab_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BlinkerTab +{ + public : + BlinkerTab(char _name[], blinker_callback_with_table_arg_t _func = NULL, + blinker_callback_t _func2 = NULL) + { + wNum = Blinker.attachWidget(_name, _func, _func2); + tabSet = 0; + } + + void attach(blinker_callback_with_table_arg_t _func, blinker_callback_t _func2) + { + if (wNum == 0) return; + + Blinker.freshAttachWidget(Blinker.widgetName_tab(wNum), _func, _func2); + } + + void tab(uint8_t num) + { + switch (num) + { + case 0: + tabSet |= 1 << 4; + break; + case 1: + tabSet |= 1 << 3; + break; + case 2: + tabSet |= 1 << 2; + break; + case 3: + tabSet |= 1 << 1; + break; + case 4: + tabSet |= 1 << 0; + break; + default: + break; + } + } + + void tab_0() { tabSet |= 1 << 4; } + void tab_1() { tabSet |= 1 << 3; } + void tab_2() { tabSet |= 1 << 2; } + void tab_3() { tabSet |= 1 << 1; } + void tab_4() { tabSet |= 1 << 0; } + + void print() + { + if (wNum == 0) return; + + String tabData = ""; + + tabData += BLINKER_F("{\""); + tabData += BLINKER_F(BLINKER_CMD_VALUE); + tabData += BLINKER_F("\":\""); + // tabData += (_state); + if (tabSet & 1 << 4) tabData += BLINKER_F("1"); + else tabData += BLINKER_F("0"); + + if (tabSet & 1 << 3) tabData += BLINKER_F("1"); + else tabData += BLINKER_F("0"); + + if (tabSet & 1 << 2) tabData += BLINKER_F("1"); + else tabData += BLINKER_F("0"); + + if (tabSet & 1 << 1) tabData += BLINKER_F("1"); + else tabData += BLINKER_F("0"); + + if (tabSet & 1 << 0) tabData += BLINKER_F("1"); + else tabData += BLINKER_F("0"); + + tabData += BLINKER_F("\"}"); + + tabSet = 0; + + Blinker.printArray(Blinker.widgetName_tab(wNum), tabData); + } + + private : + uint8_t wNum; + uint8_t tabSet; +}; + +#endif \ No newline at end of file diff --git a/blinker-library/src/Functions/BlinkerTable.h b/blinker-library/src/Functions/BlinkerTable.h new file mode 100644 index 0000000..ec20d39 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerTable.h @@ -0,0 +1,86 @@ +#ifndef BlinkerTable_H +#define BlinkerTable_H + +#include "Blinker/BlinkerConfig.h" +#include "Blinker/BlinkerUtility.h" + +class BlinkerTable +{ + public : + BlinkerTable(char _name[], blinker_callback_with_table_arg_t _func = NULL) + { + wNum = Blinker.attachWidget(_name, _func); + } + + void attach(blinker_callback_with_table_arg_t _func) + { + if (wNum == 0) return; + + Blinker.freshAttachWidget(Blinker.widgetName_tab(wNum), _func); + } + + void table_0() + { + tabSet = tabSet | (1 << 4); + } + + void table_1() + { + tabSet = tabSet | (1 << 3); + } + + void table_2() + { + tabSet = tabSet | (1 << 2); + } + + void table_3() + { + tabSet = tabSet | (1 << 1); + } + + void table_4() + { + tabSet = tabSet | (1 << 0); + } + + void print() + { + if (wNum == 0) return; + + String tabData; + + tabData += BLINKER_F("{\""); + tabData += BLINKER_F(BLINKER_CMD_VALUE); + tabData += BLINKER_F("\":\""); + + BLINKER_LOG_ALL(BLINKER_F("tabSet: "), tabSet); + + if ((tabSet >> 4) & 0x01) { tabData += "1"; } + else { tabData += "0"; } + + if ((tabSet >> 3) & 0x01) { tabData += "1"; } + else { tabData += "0"; } + + if ((tabSet >> 2) & 0x01) { tabData += "1"; } + else { tabData += "0"; } + + if ((tabSet >> 1) & 0x01) { tabData += "1"; } + else { tabData += "0"; } + + if ((tabSet >> 0) & 0x01) { tabData += "1"; } + else { tabData += "0"; } + + tabData += BLINKER_F("\"}"); + + tabSet = 0; + + Blinker.printArray(Blinker.widgetName_tab(wNum), tabData); + } + + private : + uint8_t wNum; + uint8_t tabSet = 0; +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerText.h b/blinker-library/src/Functions/BlinkerText.h new file mode 100644 index 0000000..d05b3d9 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerText.h @@ -0,0 +1,128 @@ +#ifndef BlinkerText_H +#define BlinkerText_H + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BlinkerText +{ + public : + BlinkerText(char _name[]) + { + textName = (char*)malloc((strlen(_name)+1)*sizeof(char)); + strcpy(textName, _name); + } + + template + void print(T _text) + { + // if (isnan(_text)) return; + + String textData = BLINKER_F("{\""); + textData += BLINKER_F(BLINKER_CMD_TEXT); + textData += BLINKER_F("\":\""); + textData += STRING_format(_text); + textData += BLINKER_F("\""); + if (_fresh >> 0 & 0x01) + { + + textData += BLINKER_F(",\""); + textData += BLINKER_F(BLINKER_CMD_ICON); + textData += BLINKER_F("\":\""); + textData += nicon; + textData += BLINKER_F("\""); + + free(nicon); + } + + if (_fresh >> 1 & 0x01) + { + textData += BLINKER_F(",\""); + textData += BLINKER_F(BLINKER_CMD_COLOR); + textData += BLINKER_F("\":\""); + textData += ncolor; + textData += BLINKER_F("\""); + + free(ncolor); + } + + textData += BLINKER_F("}"); + + _fresh = 0; + + Blinker.printArray(textName, textData); + } + + template + void print(T1 _text1, T2 _text2) + { + // if (isnan(_text1) || isnan(_text2)) return; + + String textData = BLINKER_F("{\""); + textData += BLINKER_F(BLINKER_CMD_TEXT); + textData += BLINKER_F("\":\""); + textData += STRING_format(_text1); + textData += BLINKER_F("\",\""); + textData += BLINKER_F(BLINKER_CMD_TEXT1); + textData += BLINKER_F("\":\""); + textData += STRING_format(_text2); + textData += BLINKER_F("\""); + + if (_fresh >> 0 & 0x01) + { + + textData += BLINKER_F(",\""); + textData += BLINKER_F(BLINKER_CMD_ICON); + textData += BLINKER_F("\":\""); + textData += nicon; + textData += BLINKER_F("\""); + + free(nicon); + } + + if (_fresh >> 1 & 0x01) + { + textData += BLINKER_F(",\""); + textData += BLINKER_F(BLINKER_CMD_COLOR); + textData += BLINKER_F("\":\""); + textData += ncolor; + textData += BLINKER_F("\""); + + free(ncolor); + } + + textData += BLINKER_F("}"); + + _fresh = 0; + + Blinker.printArray(textName, textData); + } + + void icon(const String & _icon) + { + if (_fresh >> 0 & 0x01) free(nicon); + + nicon = (char*)malloc((_icon.length()+1)*sizeof(char)); + strcpy(nicon, _icon.c_str()); + + _fresh |= 0x01 << 0; + } + + void color(const String & _clr) + { + if (_fresh >> 1 & 0x01) free(ncolor); + + ncolor = (char*)malloc((_clr.length()+1)*sizeof(char)); + strcpy(ncolor, _clr.c_str()); + + _fresh |= 0x01 << 1; + } + + private : + char * nicon;// = ""; + char * ncolor;// = ""; + char * textName; + uint8_t _fresh = 0; +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerTicker.h b/blinker-library/src/Functions/BlinkerTicker.h new file mode 100644 index 0000000..a6c3cf9 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerTicker.h @@ -0,0 +1,72 @@ +#ifndef BLINEKR_TICKER_H +#define BLINEKR_TICKER_H + +#if defined(ARDUINO) + #if ARDUINO >= 100 + #include + #else + #include + #endif +#endif + +#include "../Blinker/BlinkerDebug.h" + +extern "C" { + typedef void (*blinker_callback_t)(void); +} + +class BlinkerTicker +{ + public : + BlinkerTicker() {} + // : day_time(0) + // , os_time(0) + // {} + + // void freshTime(uint32_t time_s) { day_time = time_s; os_time = millis(); } + + void attach(uint32_t seconds, blinker_callback_t func) + { + aim_time = seconds; + tickerFunc = func; + + isRun = true; + } + + void detach() { isRun = false; } + + void run() + { + if (millis() - os_time >= 1000 && millis() - os_time < 2000) + { + os_time += 1000; + tick_time ++; + } + else if (millis() - os_time >= 2000) + { + tick_time += (millis() - os_time) / 1000; + os_time = millis(); + } + + if (isRun) + { + if (tick_time - aim_time >= 0 && tick_time - aim_time < 60) + { + BLINKER_LOG_ALL(BLINKER_F("ticker trigged")); + isRun = false; + + if (tickerFunc) tickerFunc(); + } + } + } + + protected : + uint32_t tick_time; + uint32_t os_time; + uint32_t aim_time; + bool isRun = false; + + blinker_callback_t tickerFunc = NULL; +}; + +#endif diff --git a/blinker-library/src/Functions/BlinkerTimingTimer.h b/blinker-library/src/Functions/BlinkerTimingTimer.h new file mode 100644 index 0000000..ce99670 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerTimingTimer.h @@ -0,0 +1,112 @@ +#ifndef BlinkerTimingTimer_H +#define BlinkerTimingTimer_H + +#if defined(ESP8266) || defined(ESP32) +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerUtility.h" + +class BlinkerTimingTimer +{ + public : + BlinkerTimingTimer() + : timerState(false) + , isLoopTask(false) + {} + + // BlinkerTimingTimer(uint32_t _timerData, String _action, String _text) + BlinkerTimingTimer(uint32_t _timerData, String _action) + : timerState(false) + , isLoopTask(false) + { + timerData = _timerData; + // actionData = _action; + + actionData = (char*)malloc((_action.length()+1)*sizeof(char)); + strcpy(actionData, _action.c_str()); + + // timerText = _text; + + isLoopTask = timerData >> 31; + timerState = timerData >> 23 & 0x0001; + timingDay = timerData >> 11 & 0x007F; + timingTime = timerData & 0x07FF; + } + + // BlinkerTimingTimer(bool _state, uint8_t _timingDay, uint16_t _timingTime, String _action, String _text, bool _isLoop) + BlinkerTimingTimer(bool _state, uint8_t _timingDay, uint16_t _timingTime, String _action, bool _isLoop) + : timerState(false) + , isLoopTask(false) + { + timerState = _state; + timingDay = _timingDay; + timingTime = _timingTime; + + actionData = (char*)malloc((_action.length()+1)*sizeof(char)); + strcpy(actionData, _action.c_str()); + + // actionData = _action; + // timerText = _text; + isLoopTask = _isLoop; + + timerData = isLoopTask << 31 | timerState << 23 | timingDay << 11 | timingTime; + } + + // void freshTimer(uint32_t _timerData, String _action, String _text) { + void freshTimer(uint32_t _timerData, String _action) { + timerData = _timerData; + + actionData = (char*)malloc((_action.length()+1)*sizeof(char)); + strcpy(actionData, _action.c_str()); + + // actionData = _action; + // timerText = _text; + + isLoopTask = timerData >> 31; + timerState = timerData >> 23 & 0x0001; + timingDay = timerData >> 11 & 0x007F; + timingTime = timerData & 0x07FF; + } + + bool isTimingDay(uint8_t _day) { + if (timingDay & (0x01 << _day)) return true; + else return false; + } + + uint8_t getTimingday() { return timingDay; } + + char * getAction() { return actionData; } + + // String getText() { return timerText; } + + uint32_t getTimerData() { return timerData; } + + uint16_t getTime() { return timingTime; } + + bool state() { return timerState; } + + bool isLoop() { return isLoopTask; } + + void disableTask() { + timerState = false; + + timerData = isLoopTask << 31 | timerState << 23 | timingDay << 11 | timingTime; + } + + private : + // - - - - - - - - | - - - - - - - - | - - - - - - - - | - - - - - - - - + // | | | | 11 0-0x7FF timingTime + // | | | 18 timingDay + // | | 24 timerState + // | 32 isLoopTask + uint32_t timerData; + uint8_t timingDay; + char* actionData; + // String timerText; + uint16_t timingTime; + bool timerState; + bool isLoopTask; +}; + +#endif + +#endif diff --git a/blinker-library/src/Functions/BlinkerUpdater.cpp b/blinker-library/src/Functions/BlinkerUpdater.cpp new file mode 100644 index 0000000..cc2b7a2 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerUpdater.cpp @@ -0,0 +1,1381 @@ +#if defined(ESP8266) || defined(ESP32) + +#include "../Blinker/BlinkerConfig.h" +#include "../Blinker/BlinkerDebug.h" +#include "BlinkerUpdater.h" + +#if defined(ESP8266) + +// #include "ESP8266httpUpdate.h" +// #include + +// extern "C" uint32_t _SPIFFS_start; +// extern "C" uint32_t _SPIFFS_end; + +// BlinkerHTTPUpdate::BlinkerHTTPUpdate(void) +// : _httpClientTimeout(8000), _followRedirects(false), _ledPin(-1) +// { +// } + +// BlinkerHTTPUpdate::BlinkerHTTPUpdate(int httpClientTimeout) +// : _httpClientTimeout(httpClientTimeout), _followRedirects(false), _ledPin(-1) +// { +// } + +// BlinkerHTTPUpdate::~BlinkerHTTPUpdate(void) +// { +// } + +// #ifdef HTTPUPDATE_1_2_COMPATIBLE +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::update(const String& url, const String& currentVersion, +// const String& httpsFingerprint, bool reboot) +// { +// rebootOnUpdate(reboot); +// #pragma GCC diagnostic push +// #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +// return update(url, currentVersion, httpsFingerprint); +// #pragma GCC diagnostic pop +// } + +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::update(const String& url, const String& currentVersion) +// { +// HTTPClient http; +// #pragma GCC diagnostic push +// #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +// http.begin(url); +// #pragma GCC diagnostic pop +// return handleUpdate(http, currentVersion, false); +// } + +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::update(const String& url, const String& currentVersion, +// const String& httpsFingerprint) +// { +// HTTPClient http; +// #pragma GCC diagnostic push +// #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +// http.begin(url, httpsFingerprint); +// #pragma GCC diagnostic pop +// return handleUpdate(http, currentVersion, false); +// } + +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::update(const String& url, const String& currentVersion, +// const uint8_t httpsFingerprint[20]) +// { +// HTTPClient http; +// #pragma GCC diagnostic push +// #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +// http.begin(url, httpsFingerprint); +// #pragma GCC diagnostic pop +// return handleUpdate(http, currentVersion, false); +// } +// #endif + +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::update(WiFiClient& client, const String& url, const String& currentVersion) +// { +// HTTPClient http; +// http.begin(client, url); +// return handleUpdate(http, currentVersion, false); +// } + +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::update(WiFiClient& client, const String& url, const String& md5, const String& currentVersion) +// { +// HTTPClient http; +// http.begin(client, url); +// return handleUpdate(http, currentVersion, false, md5); +// } + +// #ifdef HTTPUPDATE_1_2_COMPATIBLE +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::updateSpiffs(const String& url, const String& currentVersion, const String& httpsFingerprint) +// { +// HTTPClient http; +// #pragma GCC diagnostic push +// #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +// http.begin(url, httpsFingerprint); +// #pragma GCC diagnostic pop +// return handleUpdate(http, currentVersion, true); +// } + +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::updateSpiffs(const String& url, const String& currentVersion, const uint8_t httpsFingerprint[20]) +// { +// HTTPClient http; +// #pragma GCC diagnostic push +// #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +// http.begin(url, httpsFingerprint); +// #pragma GCC diagnostic pop +// return handleUpdate(http, currentVersion, true); +// } + +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::updateSpiffs(const String& url, const String& currentVersion) +// { +// HTTPClient http; +// #pragma GCC diagnostic push +// #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +// http.begin(url); +// #pragma GCC diagnostic pop +// return handleUpdate(http, currentVersion, true); +// } +// #endif + +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::updateSpiffs(WiFiClient& client, const String& url, const String& currentVersion) +// { +// HTTPClient http; +// http.begin(client, url); +// return handleUpdate(http, currentVersion, true); +// } + +// #ifdef HTTPUPDATE_1_2_COMPATIBLE +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::update(const String& host, uint16_t port, const String& uri, const String& currentVersion, +// bool https, const String& httpsFingerprint, bool reboot) +// { +// (void)https; +// rebootOnUpdate(reboot); +// if (httpsFingerprint.length() == 0) { +// #pragma GCC diagnostic push +// #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +// return update(host, port, uri, currentVersion); +// } else { +// return update(host, port, uri, currentVersion, httpsFingerprint); +// #pragma GCC diagnostic pop +// } +// } + +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::update(const String& host, uint16_t port, const String& uri, +// const String& currentVersion) +// { +// HTTPClient http; +// #pragma GCC diagnostic push +// #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +// http.begin(host, port, uri); +// #pragma GCC diagnostic pop +// return handleUpdate(http, currentVersion, false); +// } + +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::update(const String& host, uint16_t port, const String& url, +// const String& currentVersion, const String& httpsFingerprint) +// { +// HTTPClient http; +// #pragma GCC diagnostic push +// #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +// http.begin(host, port, url, httpsFingerprint); +// #pragma GCC diagnostic pop +// return handleUpdate(http, currentVersion, false); +// } + +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::update(const String& host, uint16_t port, const String& url, +// const String& currentVersion, const uint8_t httpsFingerprint[20]) +// { +// HTTPClient http; +// #pragma GCC diagnostic push +// #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +// http.begin(host, port, url, httpsFingerprint); +// #pragma GCC diagnostic pop +// return handleUpdate(http, currentVersion, false); +// } +// #endif + +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::update(WiFiClient& client, const String& host, uint16_t port, const String& uri, +// const String& currentVersion) +// { +// HTTPClient http; +// http.begin(client, host, port, uri); +// return handleUpdate(http, currentVersion, false); +// } + +// /** +// * return error code as int +// * @return int error code +// */ +// int BlinkerHTTPUpdate::getLastError(void) +// { +// return _lastError; +// } + +// /** +// * return error code as String +// * @return String error +// */ +// String BlinkerHTTPUpdate::getLastErrorString(void) +// { + +// if(_lastError == 0) { +// return String(); // no error +// } + +// // error from Update class +// if(_lastError > 0) { +// StreamString error; +// Update.printError(error); +// error.trim(); // remove line ending +// return String(F("Update error: ")) + error; +// } + +// // error from http client +// if(_lastError > -100) { +// return String(F("HTTP error: ")) + HTTPClient::errorToString(_lastError); +// } + +// switch(_lastError) { +// case HTTP_UE_TOO_LESS_SPACE: +// return F("Not Enough space"); +// case HTTP_UE_SERVER_NOT_REPORT_SIZE: +// return F("Server Did Not Report Size"); +// case HTTP_UE_SERVER_FILE_NOT_FOUND: +// return F("File Not Found (404)"); +// case HTTP_UE_SERVER_FORBIDDEN: +// return F("Forbidden (403)"); +// case HTTP_UE_SERVER_WRONG_HTTP_CODE: +// return F("Wrong HTTP Code"); +// case HTTP_UE_SERVER_FAULTY_MD5: +// return F("Wrong MD5"); +// case HTTP_UE_BIN_VERIFY_HEADER_FAILED: +// return F("Verify Bin Header Failed"); +// case HTTP_UE_BIN_FOR_WRONG_FLASH: +// return F("New Binary Does Not Fit Flash Size"); +// } + +// return String(); +// } + + +// /** +// * +// * @param http HTTPClient * +// * @param currentVersion const char * +// * @return BlinkerHTTPUpdateResult +// */ +// BlinkerHTTPUpdateResult BlinkerHTTPUpdate::handleUpdate(HTTPClient& http, const String& currentVersion, bool spiffs, const String& md5) +// { + +// BlinkerHTTPUpdateResult ret = HTTP_UPDATE_FAILED; + +// // use HTTP/1.0 for update since the update handler not support any transfer Encoding +// http.useHTTP10(true); +// http.setTimeout(_httpClientTimeout); +// http.setFollowRedirects(_followRedirects); +// http.setUserAgent(F("ESP8266-http-Update")); +// http.addHeader(F("x-ESP8266-STA-MAC"), WiFi.macAddress()); +// http.addHeader(F("x-ESP8266-AP-MAC"), WiFi.softAPmacAddress()); +// http.addHeader(F("x-ESP8266-free-space"), String(ESP.getFreeSketchSpace())); +// http.addHeader(F("x-ESP8266-sketch-size"), String(ESP.getSketchSize())); +// http.addHeader(F("x-ESP8266-sketch-md5"), String(ESP.getSketchMD5())); +// http.addHeader(F("x-ESP8266-chip-size"), String(ESP.getFlashChipRealSize())); +// http.addHeader(F("x-ESP8266-sdk-version"), ESP.getSdkVersion()); + +// if(spiffs) { +// http.addHeader(F("x-ESP8266-mode"), F("spiffs")); +// } else { +// http.addHeader(F("x-ESP8266-mode"), F("sketch")); +// } + +// if(currentVersion && currentVersion[0] != 0x00) { +// http.addHeader(F("x-ESP8266-version"), currentVersion); +// } + +// const char * headerkeys[] = { "x-MD5" }; +// size_t headerkeyssize = sizeof(headerkeys) / sizeof(char*); + +// // track these headers +// http.collectHeaders(headerkeys, headerkeyssize); + + +// int code = http.GET(); +// int len = http.getSize(); + +// if(code <= 0) { +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] HTTP error: "), http.errorToString(code).c_str()); +// _lastError = code; +// http.end(); +// return HTTP_UPDATE_FAILED; +// } + + +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] Header read fin.")); +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] Server header:")); +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] - code: "), code); +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] - len: "), len); + +// if(http.hasHeader("x-MD5")) { +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] - MD5: "), http.header("x-MD5").c_str()); +// } +// if(md5.length() > 1) { +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] - MD5: "), md5); +// } + +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] ESP8266 info:")); +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] - free Space: "), ESP.getFreeSketchSpace()); +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] - current Sketch Size: "), ESP.getSketchSize()); + +// if(currentVersion && currentVersion[0] != 0x00) { +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] - current version: "), currentVersion.c_str() ); +// } + +// switch(code) { +// case HTTP_CODE_OK: ///< OK (Start Update) +// if(len > 0) { +// bool startUpdate = true; +// if(spiffs) { +// size_t spiffsSize = ((size_t) &_SPIFFS_end - (size_t) &_SPIFFS_start); +// if(len > (int) spiffsSize) { +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] spiffsSize to low "), spiffsSize, BLINKER_F(" needed: "), len); +// startUpdate = false; +// } +// } else { +// if(len > (int) ESP.getFreeSketchSpace()) { +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] FreeSketchSpace to low "), ESP.getFreeSketchSpace(), BLINKER_F(" needed: "), len); +// startUpdate = false; +// } +// } + +// if(!startUpdate) { +// _lastError = HTTP_UE_TOO_LESS_SPACE; +// ret = HTTP_UPDATE_FAILED; +// } else { + +// WiFiClient * tcp = http.getStreamPtr(); + +// WiFiUDP::stopAll(); +// WiFiClient::stopAllExcept(tcp); + +// delay(100); + +// int command; + +// if(spiffs) { +// command = U_SPIFFS; +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] runUpdate spiffs...")); +// } else { +// command = U_FLASH; +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] runUpdate flash...")); +// } + +// if(!spiffs) { +// uint8_t buf[4]; +// if(tcp->peekBytes(&buf[0], 4) != 4) { +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] peekBytes magic header failed")); +// _lastError = HTTP_UE_BIN_VERIFY_HEADER_FAILED; +// http.end(); +// return HTTP_UPDATE_FAILED; +// } + +// // check for valid first magic byte +// if(buf[0] != 0xE9) { +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] Magic header does not start with 0xE9")); +// _lastError = HTTP_UE_BIN_VERIFY_HEADER_FAILED; +// http.end(); +// return HTTP_UPDATE_FAILED; + +// } + +// uint32_t bin_flash_size = ESP.magicFlashChipSize((buf[3] & 0xf0) >> 4); + +// // check if new bin fits to SPI flash +// if(bin_flash_size > ESP.getFlashChipRealSize()) { +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] New binary does not fit SPI Flash size")); +// _lastError = HTTP_UE_BIN_FOR_WRONG_FLASH; +// http.end(); +// return HTTP_UPDATE_FAILED; +// } +// } +// if (md5.length() > 1) +// { +// if(runUpdate(*tcp, len, md5, command)) { +// ret = HTTP_UPDATE_OK; +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] Update ok")); +// http.end(); + +// if(_rebootOnUpdate && !spiffs) { +// ESP.restart(); +// } + +// } else { +// ret = HTTP_UPDATE_FAILED; +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] Update failed")); +// } +// } +// else +// { +// if(runUpdate(*tcp, len, http.header("x-MD5"), command)) { +// ret = HTTP_UPDATE_OK; +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] Update ok")); +// http.end(); + +// if(_rebootOnUpdate && !spiffs) { +// ESP.restart(); +// } + +// } else { +// ret = HTTP_UPDATE_FAILED; +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] Update failed")); +// } +// } +// } +// } else { +// _lastError = HTTP_UE_SERVER_NOT_REPORT_SIZE; +// ret = HTTP_UPDATE_FAILED; +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] Content-Length was 0 or wasn't set by Server?!")); +// } +// break; +// case HTTP_CODE_NOT_MODIFIED: +// ///< Not Modified (No updates) +// ret = HTTP_UPDATE_NO_UPDATES; +// break; +// case HTTP_CODE_NOT_FOUND: +// _lastError = HTTP_UE_SERVER_FILE_NOT_FOUND; +// ret = HTTP_UPDATE_FAILED; +// break; +// case HTTP_CODE_FORBIDDEN: +// _lastError = HTTP_UE_SERVER_FORBIDDEN; +// ret = HTTP_UPDATE_FAILED; +// break; +// default: +// _lastError = HTTP_UE_SERVER_WRONG_HTTP_CODE; +// ret = HTTP_UPDATE_FAILED; +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] HTTP Code is "), code); +// //http.writeToStream(&Serial1); +// break; +// } + +// http.end(); +// return ret; +// } + +// /** +// * write Update to flash +// * @param in Stream& +// * @param size uint32_t +// * @param md5 String +// * @return true if Update ok +// */ +// bool BlinkerHTTPUpdate::runUpdate(Stream& in, uint32_t size, String md5, int command) +// { + +// StreamString error; + +// if(!Update.begin(size, command, _ledPin, _ledOn)) { +// _lastError = Update.getError(); +// Update.printError(error); +// error.trim(); // remove line ending +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] Update.begin failed! "), error.c_str()); +// return false; +// } + +// if(md5.length()) { +// if(!Update.setMD5(md5.c_str())) { +// _lastError = HTTP_UE_SERVER_FAULTY_MD5; +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] Update.setMD5 failed! "), md5.c_str()); +// return false; +// } +// } + +// if(Update.writeStream(in) != size) { +// _lastError = Update.getError(); +// Update.printError(error); +// error.trim(); // remove line ending +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] Update.writeStream failed! "), error.c_str()); +// return false; +// } + +// if(!Update.end()) { +// _lastError = Update.getError(); +// Update.printError(error); +// error.trim(); // remove line ending +// BLINKER_LOG_ALL(BLINKER_F("[httpUpdate] Update.end failed! "), error.c_str()); +// return false; +// } + +// return true; +// } + +// #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_HTTPUPDATE) +// BlinkerHTTPUpdate BlinkerhttpUpdate; +// #endif + +#include +#include +#include +#include +#include + +//#define DEBUG_UPDATER Serial + +extern "C" { + #include + #include + #include +} + +// #if defined _SPIFFS_start +extern "C" uint32_t _SPIFFS_start; +extern "C" uint32_t _SPIFFS_end; +// #elif defined _FS_start +// extern "C" uint32_t _FS_start; +// extern "C" uint32_t _FS_end; +// #endif + +BlinkerUpdaterClass::BlinkerUpdaterClass() +: _async(false) +, _error(0) +, _buffer(0) +, _bufferLen(0) +, _size(0) +, _progress_callback(NULL) +, _startAddress(0) +, _currentAddress(0) +, _command(U_FLASH) +{ +} + +BlinkerUpdaterClass& BlinkerUpdaterClass::onProgress(THandlerFunction_Progress fn) { + _progress_callback = fn; + return *this; +} + +void BlinkerUpdaterClass::_reset() { + if (_buffer) + delete[] _buffer; + _buffer = 0; + _bufferLen = 0; + _startAddress = 0; + _currentAddress = 0; + _size = 0; + _command = U_FLASH; + + // if(_ledPin != -1) { + // digitalWrite(_ledPin, !_ledOn); // off + // } +} + +bool BlinkerUpdaterClass::begin(size_t size, int command, int ledPin, uint8_t ledOn) { + if(_size > 0){ + // #ifdef DEBUG_UPDATER + // DEBUG_UPDATER.println(F("[begin] already running")); + // #endif + BLINKER_LOG_ALL(F("[begin] already running")); + return false; + } + + // _ledPin = ledPin; + // _ledOn = !!ledOn; // 0(LOW) or 1(HIGH) + + /* Check boot mode; if boot mode is 1 (UART download mode), + we will not be able to reset into normal mode once update is done. + Fail early to avoid frustration. + https://github.com/esp8266/Arduino/issues/1017#issuecomment-200605576 + */ + int boot_mode = (GPI >> 16) & 0xf; + if (boot_mode == 1) { + _setError(UPDATE_ERROR_BOOTSTRAP); + return false; + } + + // #ifdef DEBUG_UPDATER + if (command == U_SPIFFS) { + // DEBUG_UPDATER.println(F("[begin] Update SPIFFS.")); + BLINKER_LOG_ALL(F("[begin] Update SPIFFS.")); + } + // #endif + + if(size == 0) { + _setError(UPDATE_ERROR_SIZE); + return false; + } + + if(!ESP.checkFlashConfig(false)) { + _setError(UPDATE_ERROR_FLASH_CONFIG); + return false; + } + + _reset(); + clearError(); // _error = 0 + + wifi_set_sleep_type(NONE_SLEEP_T); + + uintptr_t updateStartAddress = 0; + if (command == U_FLASH) { + //size of current sketch rounded to a sector + size_t currentSketchSize = (ESP.getSketchSize() + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); + //address of the end of the space available for sketch and update + uintptr_t updateEndAddress; + // #if defined _SPIFFS_start + updateEndAddress = (uintptr_t)&_SPIFFS_start - 0x40200000; + // #elif defined _FS_start + // updateEndAddress = (uintptr_t)&_FS_start - 0x40200000; + // #endif + + // if ((uintptr_t)&_SPIFFS_start > (uintptr_t)&_SPIFFS_end) + // { + // updateEndAddress = (uintptr_t)&_SPIFFS_end - 0x40200000; + // } + // else + // { + // updateEndAddress = (uintptr_t)&_SPIFFS_start - 0x40200000; + // } + //size of the update rounded to a sector + size_t roundedSize = (size + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); + //address where we will start writing the update + updateStartAddress = (updateEndAddress > roundedSize)? (updateEndAddress - roundedSize) : 0; + + // #ifdef DEBUG_UPDATER + // DEBUG_UPDATER.printf("[begin] roundedSize: 0x%08zX (%zd)\n", roundedSize, roundedSize); + // DEBUG_UPDATER.printf("[begin] updateEndAddress: 0x%08zX (%zd)\n", updateEndAddress, updateEndAddress); + // DEBUG_UPDATER.printf("[begin] currentSketchSize: 0x%08zX (%zd)\n", currentSketchSize, currentSketchSize); + // #endif + // BLINKER_LOG_ALL(F("[begin] _SPIFFS_start: "), _SPIFFS_start, F(" "), _SPIFFS_start); + BLINKER_LOG_ALL(F("[begin] roundedSize: "), roundedSize, F(" "), roundedSize); + BLINKER_LOG_ALL(F("[begin] updateEndAddress: "), updateEndAddress, F(" "), updateEndAddress); + BLINKER_LOG_ALL(F("[begin] currentSketchSize: "), currentSketchSize, F(" "), currentSketchSize); + + //make sure that the size of both sketches is less than the total space (updateEndAddress) + if(updateStartAddress < currentSketchSize) { + _setError(UPDATE_ERROR_SPACE); + return false; + } + } + else if (command == U_SPIFFS) { + // #if defined _SPIFFS_start + updateStartAddress = (uintptr_t)&_SPIFFS_start - 0x40200000; + // #elif defined _FS_start + // updateStartAddress = (uintptr_t)&_FS_start - 0x40200000; + // #endif + } + else { + // unknown command + // #ifdef DEBUG_UPDATER + // DEBUG_UPDATER.println(F("[begin] Unknown update command.")); + // #endif + BLINKER_LOG_ALL(F("[begin] Unknown update command.")); + return false; + } + + //initialize + _startAddress = updateStartAddress; + _currentAddress = _startAddress; + _size = size; + if (ESP.getFreeHeap() > 2 * FLASH_SECTOR_SIZE) { + _bufferSize = FLASH_SECTOR_SIZE; + } else { + _bufferSize = 256; + } + _buffer = new uint8_t[_bufferSize]; + _command = command; + + // #ifdef DEBUG_UPDATER + // DEBUG_UPDATER.printf("[begin] _startAddress: 0x%08X (%d)\n", _startAddress, _startAddress); + // DEBUG_UPDATER.printf("[begin] _currentAddress: 0x%08X (%d)\n", _currentAddress, _currentAddress); + // DEBUG_UPDATER.printf("[begin] _size: 0x%08zX (%zd)\n", _size, _size); + // #endif + BLINKER_LOG_ALL(F("[begin] _startAddress: "), _startAddress, F(" "), _startAddress); + BLINKER_LOG_ALL(F("[begin] _currentAddress: "), _currentAddress, F(" "), _currentAddress); + BLINKER_LOG_ALL(F("[begin] _size: "), _size, F(" "), _size); + + _md5.begin(); + return true; +} + +bool BlinkerUpdaterClass::setMD5(const char * expected_md5){ + if(strlen(expected_md5) != 32) + { + return false; + } + _target_md5 = expected_md5; + return true; +} + +bool BlinkerUpdaterClass::end(bool evenIfRemaining){ + if(_size == 0){ + // #ifdef DEBUG_UPDATER + // DEBUG_UPDATER.println(F("no update")); + // #endif + BLINKER_LOG_ALL(F("no update")); + return false; + } + + if(hasError() || (!isFinished() && !evenIfRemaining)){ + // #ifdef DEBUG_UPDATER + // DEBUG_UPDATER.printf("premature end: res:%u, pos:%zu/%zu\n", getError(), progress(), _size); + // #endif + BLINKER_LOG_ALL(F("premature end: res: "), getError(), F(", pos:"), progress(), _size); + + _reset(); + return false; + } + + if(evenIfRemaining) { + if(_bufferLen > 0) { + _writeBuffer(); + } + _size = progress(); + } + + _md5.calculate(); + if(_target_md5.length()) { + if(strcasecmp(_target_md5.c_str(), _md5.toString().c_str()) != 0){ + _setError(UPDATE_ERROR_MD5); + _reset(); + return false; + } + // #ifdef DEBUG_UPDATER + // else DEBUG_UPDATER.printf("MD5 Success: %s\n", _target_md5.c_str()); + // #endif + BLINKER_LOG_ALL(F("MD5 Success: "), _target_md5.c_str()); + } + + if(!_verifyEnd()) { + _reset(); + return false; + } + + if (_command == U_FLASH) { + eboot_command ebcmd; + ebcmd.action = ACTION_COPY_RAW; + ebcmd.args[0] = _startAddress; + ebcmd.args[1] = 0x00000; + ebcmd.args[2] = _size; + eboot_command_write(&ebcmd); + + // #ifdef DEBUG_UPDATER + // DEBUG_UPDATER.printf("Staged: address:0x%08X, size:0x%08zX\n", _startAddress, _size); + BLINKER_LOG_ALL(F("Staged: address: "), _startAddress, F(", size: "), _size); + } + else if (_command == U_SPIFFS) { + // DEBUG_UPDATER.printf("SPIFFS: address:0x%08X, size:0x%08zX\n", _startAddress, _size); + // #endif + BLINKER_LOG_ALL(F("SPIFFS: address: "), _startAddress, F(", size: "), _size); + } + + _reset(); + return true; +} + +bool BlinkerUpdaterClass::_writeBuffer(){ + #define FLASH_MODE_PAGE 0 + #define FLASH_MODE_OFFSET 2 + + bool eraseResult = true, writeResult = true; + if (_currentAddress % FLASH_SECTOR_SIZE == 0) { + if(!_async) yield(); + eraseResult = ESP.flashEraseSector(_currentAddress/FLASH_SECTOR_SIZE); + } + + // If the flash settings don't match what we already have, modify them. + // But restore them after the modification, so the hash isn't affected. + // This is analogous to what esptool.py does when it receives a --flash_mode argument. + bool modifyFlashMode = false; + FlashMode_t flashMode = FM_QIO; + FlashMode_t bufferFlashMode = FM_QIO; + if (_currentAddress == _startAddress + FLASH_MODE_PAGE) { + flashMode = ESP.getFlashChipMode(); + // #ifdef DEBUG_UPDATER + // DEBUG_UPDATER.printf("Header: 0x%1X %1X %1X %1X\n", _buffer[0], _buffer[1], _buffer[2], _buffer[3]); + // #endif + BLINKER_LOG_ALL(F("Header: "), _buffer[0], F(" "), _buffer[1], F(" "), _buffer[2], F(" "), _buffer[3]); + + bufferFlashMode = ESP.magicFlashChipMode(_buffer[FLASH_MODE_OFFSET]); + if (bufferFlashMode != flashMode) { + // #ifdef DEBUG_UPDATER + // DEBUG_UPDATER.printf("Set flash mode from 0x%1X to 0x%1X\n", bufferFlashMode, flashMode); + // #endif + BLINKER_LOG_ALL(F("Set flash mode from "), bufferFlashMode, " to ", flashMode); + + _buffer[FLASH_MODE_OFFSET] = flashMode; + modifyFlashMode = true; + } + } + + if (eraseResult) { + if(!_async) yield(); + writeResult = ESP.flashWrite(_currentAddress, (uint32_t*) _buffer, _bufferLen); + } else { // if erase was unsuccessful + _currentAddress = (_startAddress + _size); + _setError(UPDATE_ERROR_ERASE); + return false; + } + + // Restore the old flash mode, if we modified it. + // Ensures that the MD5 hash will still match what was sent. + if (modifyFlashMode) { + _buffer[FLASH_MODE_OFFSET] = bufferFlashMode; + } + + if (!writeResult) { + _currentAddress = (_startAddress + _size); + _setError(UPDATE_ERROR_WRITE); + return false; + } + _md5.add(_buffer, _bufferLen); + _currentAddress += _bufferLen; + _bufferLen = 0; + return true; +} + +size_t BlinkerUpdaterClass::write(uint8_t *data, size_t len) { + if(hasError() || !isRunning()) + return 0; + + if(len > remaining()){ + //len = remaining(); + //fail instead + _setError(UPDATE_ERROR_SPACE); + return 0; + } + + size_t left = len; + + while((_bufferLen + left) > _bufferSize) { + size_t toBuff = _bufferSize - _bufferLen; + memcpy(_buffer + _bufferLen, data + (len - left), toBuff); + _bufferLen += toBuff; + if(!_writeBuffer()){ + return len - left; + } + left -= toBuff; + if(!_async) yield(); + } + //lets see whats left + memcpy(_buffer + _bufferLen, data + (len - left), left); + _bufferLen += left; + if(_bufferLen == remaining()){ + //we are at the end of the update, so should write what's left to flash + if(!_writeBuffer()){ + return len - left; + } + } + return len; +} + +bool BlinkerUpdaterClass::_verifyHeader(uint8_t data) { + if(_command == U_FLASH) { + // check for valid first magic byte (is always 0xE9) + if(data != 0xE9) { + _currentAddress = (_startAddress + _size); + _setError(UPDATE_ERROR_MAGIC_BYTE); + return false; + } + return true; + } else if(_command == U_SPIFFS) { + // no check of SPIFFS possible with first byte. + return true; + } + return false; +} + +bool BlinkerUpdaterClass::_verifyEnd() { + if(_command == U_FLASH) { + + uint8_t buf[4]; + if(!ESP.flashRead(_startAddress, (uint32_t *) &buf[0], 4)) { + _currentAddress = (_startAddress); + _setError(UPDATE_ERROR_READ); + return false; + } + + // check for valid first magic byte + if(buf[0] != 0xE9) { + _currentAddress = (_startAddress); + _setError(UPDATE_ERROR_MAGIC_BYTE); + return false; + } + + uint32_t bin_flash_size = ESP.magicFlashChipSize((buf[3] & 0xf0) >> 4); + + // check if new bin fits to SPI flash + if(bin_flash_size > ESP.getFlashChipRealSize()) { + _currentAddress = (_startAddress); + _setError(UPDATE_ERROR_NEW_FLASH_CONFIG); + return false; + } + + return true; + } else if(_command == U_SPIFFS) { + // SPIFFS is already over written checks make no sense any more. + return true; + } + return false; +} + +size_t BlinkerUpdaterClass::writeStream(Stream &data) { + size_t written = 0; + size_t toRead = 0; + if(hasError() || !isRunning()) + return 0; + + if(!_verifyHeader(data.peek())) { +// #ifdef DEBUG_UPDATER +// printError(DEBUG_UPDATER); +// #endif + BLINKER_LOG(printError()); + _reset(); + return 0; + } + + // if(_ledPin != -1) { + // pinMode(_ledPin, OUTPUT); + // } + + if (_progress_callback) { + _progress_callback(0, _size); + } + while(remaining()) { + // if(_ledPin != -1) { + // digitalWrite(_ledPin, _ledOn); // Switch LED on + // } + size_t bytesToRead = _bufferSize - _bufferLen; + if(bytesToRead > remaining()) { + bytesToRead = remaining(); + } + toRead = data.readBytes(_buffer + _bufferLen, bytesToRead); + if(toRead == 0) { //Timeout + delay(100); + toRead = data.readBytes(_buffer + _bufferLen, bytesToRead); + if(toRead == 0) { //Timeout + _currentAddress = (_startAddress + _size); + _setError(UPDATE_ERROR_STREAM); + _reset(); + return written; + } + } + // if(_ledPin != -1) { + // digitalWrite(_ledPin, !_ledOn); // Switch LED off + // } + _bufferLen += toRead; + if((_bufferLen == remaining() || _bufferLen == _bufferSize) && !_writeBuffer()) + return written; + written += toRead; + + if(_progress_callback) { + _progress_callback(progress(), _size); + } + yield(); + } + if(_progress_callback) { + _progress_callback(_size, _size); + } + return written; +} + +void BlinkerUpdaterClass::_setError(int error){ + _error = error; + // #ifdef DEBUG_UPDATER + // printError(DEBUG_UPDATER); + // #endif + BLINKER_LOG(printError()); +} + +String BlinkerUpdaterClass::printError(){ + String errData = BLINKER_F("ERROR: "); + errData += String(_error); + errData += BLINKER_F(" "); + // out.printf_P(PSTR("ERROR[%u]: "), _error); + if(_error == UPDATE_ERROR_OK){ + // out.println(F("No Error")); + errData += F("No Error"); + } else if(_error == UPDATE_ERROR_WRITE){ + // out.println(F("Flash Write Failed")); + errData += F("Flash Write Failed"); + } else if(_error == UPDATE_ERROR_ERASE){ + // out.println(F("Flash Erase Failed")); + errData += F("Flash Erase Failed"); + } else if(_error == UPDATE_ERROR_READ){ + // out.println(F("Flash Read Failed")); + errData += F("Flash Read Failed"); + } else if(_error == UPDATE_ERROR_SPACE){ + // out.println(F("Not Enough Space")); + errData += F("Not Enough Space"); + } else if(_error == UPDATE_ERROR_SIZE){ + // out.println(F("Bad Size Given")); + errData += F("Bad Size Given"); + } else if(_error == UPDATE_ERROR_STREAM){ + // out.println(F("Stream Read Timeout")); + errData += F("Stream Read Timeout"); + } else if(_error == UPDATE_ERROR_MD5){ + //out.println(F("MD5 Check Failed")); + // out.printf("MD5 Failed: expected:%s, calculated:%s\n", _target_md5.c_str(), _md5.toString().c_str()); + errData += F("MD5 Check Failed "); + errData += F("MD5 Failed: expected: "); + errData += _target_md5; + errData += F(" , calculated: "); + errData += _md5.toString(); + } else if(_error == UPDATE_ERROR_FLASH_CONFIG){ + // out.printf_P(PSTR("Flash config wrong real: %d IDE: %d\n"), ESP.getFlashChipRealSize(), ESP.getFlashChipSize()); + errData += F("Flash config wrong real: "); + errData += String(ESP.getFlashChipRealSize()); + errData += F(" IDE: "); + errData += String(ESP.getFlashChipSize()); + } else if(_error == UPDATE_ERROR_NEW_FLASH_CONFIG){ + // out.printf_P(PSTR("new Flash config wrong real: %d\n"), ESP.getFlashChipRealSize()); + errData += F("new Flash config wrong real: "); + errData += String(ESP.getFlashChipRealSize()); + } else if(_error == UPDATE_ERROR_MAGIC_BYTE){ + // out.println(F("Magic byte is wrong, not 0xE9")); + errData += F("Magic byte is wrong, not 0xE9"); + } else if (_error == UPDATE_ERROR_BOOTSTRAP){ + // out.println(F("Invalid bootstrapping state, reset ESP8266 before updating")); + errData += F("Invalid bootstrapping state, reset ESP8266 before updating"); + } else { + // out.println(F("UNKNOWN")); + errData += F("UNKNOWN"); + } + return errData; +} + +BlinkerUpdaterClass BlinkerUpdater; + +#elif defined(ESP32) + +#include "Update.h" +#include "Arduino.h" +#include "esp_spi_flash.h" +#include "esp_ota_ops.h" +#include "esp_image_format.h" + +static const char * _err2str(uint8_t _error){ + if(_error == UPDATE_ERROR_OK){ + return ("No Error"); + } else if(_error == UPDATE_ERROR_WRITE){ + return ("Flash Write Failed"); + } else if(_error == UPDATE_ERROR_ERASE){ + return ("Flash Erase Failed"); + } else if(_error == UPDATE_ERROR_READ){ + return ("Flash Read Failed"); + } else if(_error == UPDATE_ERROR_SPACE){ + return ("Not Enough Space"); + } else if(_error == UPDATE_ERROR_SIZE){ + return ("Bad Size Given"); + } else if(_error == UPDATE_ERROR_STREAM){ + return ("Stream Read Timeout"); + } else if(_error == UPDATE_ERROR_MD5){ + return ("MD5 Check Failed"); + } else if(_error == UPDATE_ERROR_MAGIC_BYTE){ + return ("Wrong Magic Byte"); + } else if(_error == UPDATE_ERROR_ACTIVATE){ + return ("Could Not Activate The Firmware"); + } else if(_error == UPDATE_ERROR_NO_PARTITION){ + return ("Partition Could Not be Found"); + } else if(_error == UPDATE_ERROR_BAD_ARGUMENT){ + return ("Bad Argument"); + } else if(_error == UPDATE_ERROR_ABORT){ + return ("Aborted"); + } + return ("UNKNOWN"); +} + +static bool _partitionIsBootable(const esp_partition_t* partition){ + uint8_t buf[4]; + if(!partition){ + return false; + } + if(!ESP.flashRead(partition->address, (uint32_t*)buf, 4)) { + return false; + } + + if(buf[0] != ESP_IMAGE_HEADER_MAGIC) { + return false; + } + return true; +} + +static bool _enablePartition(const esp_partition_t* partition){ + uint8_t buf[4]; + if(!partition){ + return false; + } + if(!ESP.flashRead(partition->address, (uint32_t*)buf, 4)) { + return false; + } + buf[0] = ESP_IMAGE_HEADER_MAGIC; + + return ESP.flashWrite(partition->address, (uint32_t*)buf, 4); +} + +BlinkerUpdaterClass::BlinkerUpdaterClass() +: _error(0) +, _buffer(0) +, _bufferLen(0) +, _size(0) +, _progress_callback(NULL) +, _progress(0) +, _command(U_FLASH) +, _partition(NULL) +{ +} + +BlinkerUpdaterClass& BlinkerUpdaterClass::onProgress(THandlerFunction_Progress fn) { + _progress_callback = fn; + return *this; +} + +void BlinkerUpdaterClass::_reset() { + if (_buffer) + delete[] _buffer; + _buffer = 0; + _bufferLen = 0; + _progress = 0; + _size = 0; + _command = U_FLASH; +} + +bool BlinkerUpdaterClass::canRollBack(){ + if(_buffer){ //Update is running + return false; + } + const esp_partition_t* partition = esp_ota_get_next_update_partition(NULL); + return _partitionIsBootable(partition); +} + +bool BlinkerUpdaterClass::rollBack(){ + if(_buffer){ //Update is running + return false; + } + const esp_partition_t* partition = esp_ota_get_next_update_partition(NULL); + return _partitionIsBootable(partition) && !esp_ota_set_boot_partition(partition); +} + +bool BlinkerUpdaterClass::begin(size_t size, int command) { + if(_size > 0){ + // log_w("already running"); + BLINKER_LOG_ALL(F("already running")); + return false; + } + + _reset(); + _error = 0; + + if(size == 0) { + _error = UPDATE_ERROR_SIZE; + return false; + } + + if (command == U_FLASH) { + _partition = esp_ota_get_next_update_partition(NULL); + if(!_partition){ + _error = UPDATE_ERROR_NO_PARTITION; + return false; + } + // log_d("OTA Partition: %s", _partition->label); + BLINKER_LOG_ALL(F("OTA Partition: "), _partition->label); + } + else if (command == U_SPIFFS) { + _partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_SPIFFS, NULL); + if(!_partition){ + _error = UPDATE_ERROR_NO_PARTITION; + return false; + } + } + else { + _error = UPDATE_ERROR_BAD_ARGUMENT; + // log_e("bad command %u", command); + BLINKER_LOG_ALL(F("bad command "), command); + return false; + } + + if(size == UPDATE_SIZE_UNKNOWN){ + size = _partition->size; + } else if(size > _partition->size){ + _error = UPDATE_ERROR_SIZE; + // log_e("too large %u > %u", size, _partition->size); + BLINKER_LOG_ALL(F("too large "), size, F(" > "), _partition->size); + return false; + } + + //initialize + _buffer = (uint8_t*)malloc(SPI_FLASH_SEC_SIZE); + if(!_buffer){ + // log_e("malloc failed"); + BLINKER_LOG_ALL(F("malloc failed")); + return false; + } + _size = size; + _command = command; + _md5.begin(); + return true; +} + +void BlinkerUpdaterClass::_abort(uint8_t err){ + _reset(); + _error = err; +} + +void BlinkerUpdaterClass::abort(){ + _abort(UPDATE_ERROR_ABORT); +} + +bool BlinkerUpdaterClass::_writeBuffer(){ + //first bytes of new firmware + if(!_progress && _command == U_FLASH){ + //check magic + if(_buffer[0] != ESP_IMAGE_HEADER_MAGIC){ + _abort(UPDATE_ERROR_MAGIC_BYTE); + return false; + } + //remove magic byte from the firmware now and write it upon success + //this ensures that partially written firmware will not be bootable + _buffer[0] = 0xFF; + } + if(!ESP.flashEraseSector((_partition->address + _progress)/SPI_FLASH_SEC_SIZE)){ + _abort(UPDATE_ERROR_ERASE); + return false; + } + if (!ESP.flashWrite(_partition->address + _progress, (uint32_t*)_buffer, _bufferLen)) { + _abort(UPDATE_ERROR_WRITE); + return false; + } + //restore magic or md5 will fail + if(!_progress && _command == U_FLASH){ + _buffer[0] = ESP_IMAGE_HEADER_MAGIC; + } + _md5.add(_buffer, _bufferLen); + _progress += _bufferLen; + _bufferLen = 0; + return true; +} + +bool BlinkerUpdaterClass::_verifyHeader(uint8_t data) { + if(_command == U_FLASH) { + if(data != ESP_IMAGE_HEADER_MAGIC) { + _abort(UPDATE_ERROR_MAGIC_BYTE); + return false; + } + return true; + } else if(_command == U_SPIFFS) { + return true; + } + return false; +} + +bool BlinkerUpdaterClass::_verifyEnd() { + if(_command == U_FLASH) { + if(!_enablePartition(_partition) || !_partitionIsBootable(_partition)) { + _abort(UPDATE_ERROR_READ); + return false; + } + + if(esp_ota_set_boot_partition(_partition)){ + _abort(UPDATE_ERROR_ACTIVATE); + return false; + } + _reset(); + return true; + } else if(_command == U_SPIFFS) { + _reset(); + return true; + } + return false; +} + +bool BlinkerUpdaterClass::setMD5(const char * expected_md5){ + if(strlen(expected_md5) != 32) + { + return false; + } + _target_md5 = expected_md5; + return true; +} + +bool BlinkerUpdaterClass::end(bool evenIfRemaining){ + if(hasError() || _size == 0){ + return false; + } + + if(!isFinished() && !evenIfRemaining){ + // log_e("premature end: res:%u, pos:%u/%u\n", getError(), progress(), _size); + BLINKER_LOG_ALL(F("premature end: res: "), getError(), \ + F(", pos:"), progress(), _size); + _abort(UPDATE_ERROR_ABORT); + return false; + } + + if(evenIfRemaining) { + if(_bufferLen > 0) { + _writeBuffer(); + } + _size = progress(); + } + + _md5.calculate(); + if(_target_md5.length()) { + if(_target_md5 != _md5.toString()){ + _abort(UPDATE_ERROR_MD5); + return false; + } + } + + return _verifyEnd(); +} + +size_t BlinkerUpdaterClass::write(uint8_t *data, size_t len) { + if(hasError() || !isRunning()){ + return 0; + } + + if(len > remaining()){ + _abort(UPDATE_ERROR_SPACE); + return 0; + } + + size_t left = len; + + while((_bufferLen + left) > SPI_FLASH_SEC_SIZE) { + size_t toBuff = SPI_FLASH_SEC_SIZE - _bufferLen; + memcpy(_buffer + _bufferLen, data + (len - left), toBuff); + _bufferLen += toBuff; + if(!_writeBuffer()){ + return len - left; + } + left -= toBuff; + } + memcpy(_buffer + _bufferLen, data + (len - left), left); + _bufferLen += left; + if(_bufferLen == remaining()){ + if(!_writeBuffer()){ + return len - left; + } + } + return len; +} + +size_t BlinkerUpdaterClass::writeStream(Stream &data) { + size_t written = 0; + size_t toRead = 0; + if(hasError() || !isRunning()) + return 0; + + if(!_verifyHeader(data.peek())) { + _reset(); + return 0; + } + if (_progress_callback) { + _progress_callback(0, _size); + } + while(remaining()) { + toRead = data.readBytes(_buffer + _bufferLen, (SPI_FLASH_SEC_SIZE - _bufferLen)); + if(toRead == 0) { //Timeout + delay(100); + toRead = data.readBytes(_buffer + _bufferLen, (SPI_FLASH_SEC_SIZE - _bufferLen)); + if(toRead == 0) { //Timeout + _abort(UPDATE_ERROR_STREAM); + return written; + } + } + _bufferLen += toRead; + if((_bufferLen == remaining() || _bufferLen == SPI_FLASH_SEC_SIZE) && !_writeBuffer()) + return written; + written += toRead; + if(_progress_callback) { + _progress_callback(_progress, _size); + } + } + if(_progress_callback) { + _progress_callback(_size, _size); + } + return written; +} + +void BlinkerUpdaterClass::printError(Stream &out){ + out.println(_err2str(_error)); +} + +BlinkerUpdaterClass BlinkerUpdater; + +#endif + +#endif diff --git a/blinker-library/src/Functions/BlinkerUpdater.h b/blinker-library/src/Functions/BlinkerUpdater.h new file mode 100644 index 0000000..cbe8b03 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerUpdater.h @@ -0,0 +1,487 @@ +#ifndef BLINKER_UPDATER_H +#define BLINKER_UPDATER_H + +#if defined(ESP8266) || defined(ESP32) + +#if defined(ESP8266) + +// #define HTTPUPDATE_1_2_COMPATIBLE + +// #include +// #include +// #include +// #include +// #include + +// #ifdef DEBUG_ESP_HTTP_UPDATE +// #ifdef DEBUG_ESP_PORT +// #define DEBUG_HTTP_UPDATE(fmt, ...) DEBUG_ESP_PORT.printf_P( (PGM_P)PSTR(fmt), ## __VA_ARGS__ ) +// #endif +// #endif + +// #ifndef DEBUG_HTTP_UPDATE +// #define DEBUG_HTTP_UPDATE(...) do { (void)0; } while(0) +// #endif + +// /// note we use HTTP client errors too so we start at 100 +// #define HTTP_UE_TOO_LESS_SPACE (-100) +// #define HTTP_UE_SERVER_NOT_REPORT_SIZE (-101) +// #define HTTP_UE_SERVER_FILE_NOT_FOUND (-102) +// #define HTTP_UE_SERVER_FORBIDDEN (-103) +// #define HTTP_UE_SERVER_WRONG_HTTP_CODE (-104) +// #define HTTP_UE_SERVER_FAULTY_MD5 (-105) +// #define HTTP_UE_BIN_VERIFY_HEADER_FAILED (-106) +// #define HTTP_UE_BIN_FOR_WRONG_FLASH (-107) + +// enum BlinkerHTTPUpdateResult { +// HTTP_UPDATE_FAILED, +// HTTP_UPDATE_NO_UPDATES, +// HTTP_UPDATE_OK +// }; + +// typedef BlinkerHTTPUpdateResult t_httpUpdate_return; // backward compatibility + +// class BlinkerHTTPUpdate +// { +// public: +// BlinkerHTTPUpdate(void); +// BlinkerHTTPUpdate(int httpClientTimeout); +// ~BlinkerHTTPUpdate(void); + +// void rebootOnUpdate(bool reboot) +// { +// _rebootOnUpdate = reboot; +// } + +// void followRedirects(bool follow) +// { +// _followRedirects = follow; +// } + +// void setLedPin(int ledPin = -1, uint8_t ledOn = HIGH) +// { +// _ledPin = ledPin; +// _ledOn = ledOn; +// } + +// #ifdef HTTPUPDATE_1_2_COMPATIBLE +// // This function is deprecated, use rebootOnUpdate and the next one instead +// t_httpUpdate_return update(const String& url, const String& currentVersion, +// const String& httpsFingerprint, bool reboot) __attribute__((deprecated)); +// t_httpUpdate_return update(const String& url, const String& currentVersion = "") __attribute__((deprecated)); +// t_httpUpdate_return update(const String& url, const String& currentVersion, +// const String& httpsFingerprint) __attribute__((deprecated)); +// t_httpUpdate_return update(const String& url, const String& currentVersion, +// const uint8_t httpsFingerprint[20]) __attribute__((deprecated)); // BearSSL +// #endif +// t_httpUpdate_return update(WiFiClient& client, const String& url, const String& currentVersion = ""); +// t_httpUpdate_return update(WiFiClient& client, const String& url, const String& md5, const String& currentVersion); + +// #ifdef HTTPUPDATE_1_2_COMPATIBLE +// // This function is deprecated, use one of the overloads below along with rebootOnUpdate +// t_httpUpdate_return update(const String& host, uint16_t port, const String& uri, const String& currentVersion, +// bool https, const String& httpsFingerprint, bool reboot) __attribute__((deprecated)); + +// t_httpUpdate_return update(const String& host, uint16_t port, const String& uri = "/", +// const String& currentVersion = "") __attribute__((deprecated)); +// t_httpUpdate_return update(const String& host, uint16_t port, const String& url, +// const String& currentVersion, const String& httpsFingerprint) __attribute__((deprecated)); +// t_httpUpdate_return update(const String& host, uint16_t port, const String& url, +// const String& currentVersion, const uint8_t httpsFingerprint[20]) __attribute__((deprecated)); // BearSSL +// #endif +// t_httpUpdate_return update(WiFiClient& client, const String& host, uint16_t port, const String& uri = "/", +// const String& currentVersion = ""); + +// #ifdef HTTPUPDATE_1_2_COMPATIBLE +// // This function is deprecated, use rebootOnUpdate and the next one instead +// t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion, +// const String& httpsFingerprint, bool reboot) __attribute__((deprecated)); +// t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion = "") __attribute__((deprecated)); +// t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion, const String& httpsFingerprint) __attribute__((deprecated)); +// t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion, const uint8_t httpsFingerprint[20]) __attribute__((deprecated)); // BearSSL +// #endif +// t_httpUpdate_return updateSpiffs(WiFiClient& client, const String& url, const String& currentVersion = ""); + + +// int getLastError(void); +// String getLastErrorString(void); + +// protected: +// t_httpUpdate_return handleUpdate(HTTPClient& http, const String& currentVersion, bool spiffs = false, const String& md5 = ""); +// bool runUpdate(Stream& in, uint32_t size, String md5, int command = U_FLASH); + +// int _lastError; +// bool _rebootOnUpdate = true; +// private: +// int _httpClientTimeout; +// bool _followRedirects; + +// int _ledPin; +// uint8_t _ledOn; +// }; + +// #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_HTTPUPDATE) +// extern BlinkerHTTPUpdate BlinkerhttpUpdate; +// #endif + +#include +#include +#include + +#define UPDATE_ERROR_OK (0) +#define UPDATE_ERROR_WRITE (1) +#define UPDATE_ERROR_ERASE (2) +#define UPDATE_ERROR_READ (3) +#define UPDATE_ERROR_SPACE (4) +#define UPDATE_ERROR_SIZE (5) +#define UPDATE_ERROR_STREAM (6) +#define UPDATE_ERROR_MD5 (7) +#define UPDATE_ERROR_FLASH_CONFIG (8) +#define UPDATE_ERROR_NEW_FLASH_CONFIG (9) +#define UPDATE_ERROR_MAGIC_BYTE (10) +#define UPDATE_ERROR_BOOTSTRAP (11) + +#define U_FLASH 0 +#define U_SPIFFS 100 +#define U_AUTH 200 + +// #ifdef DEBUG_ESP_UPDATER +// #ifdef DEBUG_ESP_PORT +// #define DEBUG_UPDATER DEBUG_ESP_PORT +// #endif +// #endif + +class BlinkerUpdaterClass { + public: + typedef std::function THandlerFunction_Progress; + + BlinkerUpdaterClass(); + + /* + This callback will be called when Update is receiving data + */ + BlinkerUpdaterClass& onProgress(THandlerFunction_Progress fn); + + /* + Call this to check the space needed for the update + Will return false if there is not enough space + */ + bool begin(size_t size, int command = U_FLASH, int ledPin = -1, uint8_t ledOn = LOW); + + /* + Run Updater from asynchronous callbacs + */ + void runAsync(bool async){ _async = async; } + + /* + Writes a buffer to the flash and increments the address + Returns the amount written + */ + size_t write(uint8_t *data, size_t len); + + /* + Writes the remaining bytes from the Stream to the flash + Uses readBytes() and sets UPDATE_ERROR_STREAM on timeout + Returns the bytes written + Should be equal to the remaining bytes when called + Usable for slow streams like Serial + */ + size_t writeStream(Stream &data); + + /* + If all bytes are written + this call will write the config to eboot + and return true + If there is already an update running but is not finished and !evenIfRemaining + or there is an error + this will clear everything and return false + the last error is available through getError() + evenIfRemaining is helpful when you update without knowing the final size first + */ + bool end(bool evenIfRemaining = false); + + /* + Prints the last error to an output stream + */ + String printError(); + + /* + sets the expected MD5 for the firmware (hexString) + */ + bool setMD5(const char * expected_md5); + + /* + returns the MD5 String of the sucessfully ended firmware + */ + String md5String(void){ return _md5.toString(); } + + /* + populated the result with the md5 bytes of the sucessfully ended firmware + */ + void md5(uint8_t * result){ return _md5.getBytes(result); } + + //Helpers + uint8_t getError(){ return _error; } + void clearError(){ _error = UPDATE_ERROR_OK; } + bool hasError(){ return _error != UPDATE_ERROR_OK; } + bool isRunning(){ return _size > 0; } + bool isFinished(){ return _currentAddress == (_startAddress + _size); } + size_t size(){ return _size; } + size_t progress(){ return _currentAddress - _startAddress; } + size_t remaining(){ return _size - (_currentAddress - _startAddress); } + + /* + Template to write from objects that expose + available() and read(uint8_t*, size_t) methods + faster than the writeStream method + writes only what is available + */ + template + size_t write(T &data){ + size_t written = 0; + if (hasError() || !isRunning()) + return 0; + + size_t available = data.available(); + while(available) { + if(_bufferLen + available > remaining()){ + available = remaining() - _bufferLen; + } + if(_bufferLen + available > _bufferSize) { + size_t toBuff = _bufferSize - _bufferLen; + data.read(_buffer + _bufferLen, toBuff); + _bufferLen += toBuff; + if(!_writeBuffer()) + return written; + written += toBuff; + } else { + data.read(_buffer + _bufferLen, available); + _bufferLen += available; + written += available; + if(_bufferLen == remaining()) { + if(!_writeBuffer()) { + return written; + } + } + } + if(remaining() == 0) + return written; + delay(1); + available = data.available(); + } + return written; + } + + private: + void _reset(); + bool _writeBuffer(); + + bool _verifyHeader(uint8_t data); + bool _verifyEnd(); + + void _setError(int error); + + bool _async; + uint8_t _error; + uint8_t *_buffer; + size_t _bufferLen; // amount of data written into _buffer + size_t _bufferSize; // total size of _buffer + size_t _size; + THandlerFunction_Progress _progress_callback; + uint32_t _startAddress; + uint32_t _currentAddress; + uint32_t _command; + + String _target_md5; + MD5Builder _md5; + + // int _ledPin; + // uint8_t _ledOn; +}; + +extern BlinkerUpdaterClass BlinkerUpdater; + +#elif defined(ESP32) + +#include +#include +#include +#include "esp_partition.h" + +#define UPDATE_ERROR_OK (0) +#define UPDATE_ERROR_WRITE (1) +#define UPDATE_ERROR_ERASE (2) +#define UPDATE_ERROR_READ (3) +#define UPDATE_ERROR_SPACE (4) +#define UPDATE_ERROR_SIZE (5) +#define UPDATE_ERROR_STREAM (6) +#define UPDATE_ERROR_MD5 (7) +#define UPDATE_ERROR_MAGIC_BYTE (8) +#define UPDATE_ERROR_ACTIVATE (9) +#define UPDATE_ERROR_NO_PARTITION (10) +#define UPDATE_ERROR_BAD_ARGUMENT (11) +#define UPDATE_ERROR_ABORT (12) + +#define UPDATE_SIZE_UNKNOWN 0xFFFFFFFF + +#define U_FLASH 0 +#define U_SPIFFS 100 +#define U_AUTH 200 + +class BlinkerUpdaterClass { + public: + typedef std::function THandlerFunction_Progress; + + BlinkerUpdaterClass(); + + /* + This callback will be called when Update is receiving data + */ + BlinkerUpdaterClass& onProgress(THandlerFunction_Progress fn); + + /* + Call this to check the space needed for the update + Will return false if there is not enough space + */ + bool begin(size_t size=UPDATE_SIZE_UNKNOWN, int command = U_FLASH); + + /* + Writes a buffer to the flash and increments the address + Returns the amount written + */ + size_t write(uint8_t *data, size_t len); + + /* + Writes the remaining bytes from the Stream to the flash + Uses readBytes() and sets UPDATE_ERROR_STREAM on timeout + Returns the bytes written + Should be equal to the remaining bytes when called + Usable for slow streams like Serial + */ + size_t writeStream(Stream &data); + + /* + If all bytes are written + this call will write the config to eboot + and return true + If there is already an update running but is not finished and !evenIfRemainanig + or there is an error + this will clear everything and return false + the last error is available through getError() + evenIfRemaining is helpfull when you update without knowing the final size first + */ + bool end(bool evenIfRemaining = false); + + /* + Aborts the running update + */ + void abort(); + + /* + Prints the last error to an output stream + */ + void printError(Stream &out); + + /* + sets the expected MD5 for the firmware (hexString) + */ + bool setMD5(const char * expected_md5); + + /* + returns the MD5 String of the sucessfully ended firmware + */ + String md5String(void){ return _md5.toString(); } + + /* + populated the result with the md5 bytes of the sucessfully ended firmware + */ + void md5(uint8_t * result){ return _md5.getBytes(result); } + + //Helpers + uint8_t getError(){ return _error; } + void clearError(){ _error = UPDATE_ERROR_OK; } + bool hasError(){ return _error != UPDATE_ERROR_OK; } + bool isRunning(){ return _size > 0; } + bool isFinished(){ return _progress == _size; } + size_t size(){ return _size; } + size_t progress(){ return _progress; } + size_t remaining(){ return _size - _progress; } + + /* + Template to write from objects that expose + available() and read(uint8_t*, size_t) methods + faster than the writeStream method + writes only what is available + */ + template + size_t write(T &data){ + size_t written = 0; + if (hasError() || !isRunning()) + return 0; + + size_t available = data.available(); + while(available) { + if(_bufferLen + available > remaining()){ + available = remaining() - _bufferLen; + } + if(_bufferLen + available > 4096) { + size_t toBuff = 4096 - _bufferLen; + data.read(_buffer + _bufferLen, toBuff); + _bufferLen += toBuff; + if(!_writeBuffer()) + return written; + written += toBuff; + } else { + data.read(_buffer + _bufferLen, available); + _bufferLen += available; + written += available; + if(_bufferLen == remaining()) { + if(!_writeBuffer()) { + return written; + } + } + } + if(remaining() == 0) + return written; + available = data.available(); + } + return written; + } + + /* + check if there is a firmware on the other OTA partition that you can bootinto + */ + bool canRollBack(); + /* + set the other OTA partition as bootable (reboot to enable) + */ + bool rollBack(); + + private: + void _reset(); + void _abort(uint8_t err); + bool _writeBuffer(); + bool _verifyHeader(uint8_t data); + bool _verifyEnd(); + + + uint8_t _error; + uint8_t *_buffer; + size_t _bufferLen; + size_t _size; + THandlerFunction_Progress _progress_callback; + uint32_t _progress; + uint32_t _command; + const esp_partition_t* _partition; + + String _target_md5; + MD5Builder _md5; +}; + +extern BlinkerUpdaterClass BlinkerUpdater; + +#endif + +#endif + +#endif diff --git a/blinker-library/src/Functions/BlinkerWlan.h b/blinker-library/src/Functions/BlinkerWlan.h new file mode 100644 index 0000000..c4bd417 --- /dev/null +++ b/blinker-library/src/Functions/BlinkerWlan.h @@ -0,0 +1,642 @@ +// #ifndef BLINKER_WLAN_H +// #define BLINKER_WLAN_H + +// #if defined(ESP8266) || defined(ESP32) + +// // #if defined(BLINKER_PRO) + +// // #include "Blinker/BlinkerConfig.h" +// // #include "modules/ArduinoJson/ArduinoJson.h" +// // #if defined(ESP8266) +// // #include +// // #elif defined(ESP32) +// // #include +// // #endif +// // #include + +// // static WiFiServer *_server; +// // static WiFiClient _client; +// // static IPAddress apIP(192, 168, 4, 1); +// // #if defined(ESP8266) +// // static IPAddress netMsk(255, 255, 255, 0); +// // #endif + +// #if ARDUINO >= 100 +// #include +// #else +// #include +// #endif + +// #include "../Blinker/BlinkerConfig.h" +// #include "../Blinker/BlinkerDebug.h" +// #include "../Blinker/BlinkerUtility.h" +// #include "BlinkerWlan.h" +// #ifndef ARDUINOJSON_VERSION_MAJOR +// #include "../modules/ArduinoJson/ArduinoJson.h" +// #endif + +// #if defined(ESP8266) +// #include +// #elif defined(ESP32) +// #include +// #endif + +// #include + +// // static WiFiServer *_server; +// // static WiFiClient _client; +// static IPAddress apIP(192, 168, 4, 1); +// #if defined(ESP8266) +// static IPAddress netMsk(255, 255, 255, 0); +// #endif + + +// enum bwl_status_t +// { +// BWL_CONFIG_CKECK, +// BWL_CONFIG_FAIL, +// BWL_CONFIG_SUCCESS, +// BWL_CONNECTING, +// BWL_CONNECTED, +// BWL_DISCONNECTED, +// BWL_SMARTCONFIG_BEGIN, +// BWL_SMARTCONFIG_DONE, +// BWL_SMARTCONFIG_TIMEOUT, +// BWL_STACONFIG_BEGIN, +// BWL_APCONFIG_BEGIN, +// BWL_APCONFIG_DONE, +// BWL_APCONFIG_TIMEOUT, +// BWL_CONNECTED_CHECK, +// BWL_RESET +// }; + +// class BlinkerWlan +// { +// public : +// BlinkerWlan() +// : _status(BWL_CONFIG_CKECK) +// {} + +// bool checkConfig(); +// void loadConfig(char *_ssid, char *_pswd); +// void saveConfig(char *_ssid, char *_pswd); +// void deleteConfig(); +// void smartconfigBegin(uint16_t _time = 15000); +// bool smartconfigDone(); +// void connect(); +// bool connected(); +// void disconnect(); +// void reset(); +// bool run(); +// bwl_status_t status() { return _status; } + +// void setType(const char* _type) { +// _deviceType = _type; + +// #ifdef BLINKER_DEBUG_ALL +// BLINKER_LOG(BLINKER_F("API deviceType: "), _type); +// #endif +// } + +// void softAPinit(); +// void serverClient(); +// void parseUrl(String data); +// void connectWiFi(String _ssid, String _pswd); +// void connectWiFi(const char* _ssid, const char* _pswd); + +// // uint8_t status() { return _status; } + +// private : + +// protected : +// char *SSID; +// char *PSWD; +// const char* _deviceType; +// uint32_t connectTime; +// uint16_t timeout; +// bwl_status_t _status; +// uint32_t debugStatusTime; +// }; + +// bool BlinkerWlan::checkConfig() { +// BLINKER_LOG_ALL(BLINKER_F("check wlan config")); + +// char ok[2 + 1]; +// EEPROM.begin(BLINKER_EEP_SIZE); +// EEPROM.get(BLINKER_EEP_ADDR_WLAN_CHECK, ok); +// EEPROM.commit(); +// EEPROM.end(); + +// if (String(ok) != String("OK")) { + +// BLINKER_LOG(BLINKER_F("wlan config check,fail")); + +// _status = BWL_CONFIG_FAIL; +// return false; +// } +// else { + +// BLINKER_LOG(BLINKER_F("wlan config check,success")); + +// _status = BWL_CONFIG_SUCCESS; +// return true; +// } +// } + +// void BlinkerWlan::loadConfig(char *_ssid, char *_pswd) { +// char loadssid[BLINKER_SSID_SIZE]; +// char loadpswd[BLINKER_PSWD_SIZE]; + +// EEPROM.begin(BLINKER_EEP_SIZE); +// EEPROM.get(BLINKER_EEP_ADDR_SSID, loadssid); +// EEPROM.get(BLINKER_EEP_ADDR_PSWD, loadpswd); +// // char ok[2 + 1]; +// // EEPROM.get(EEP_ADDR_WIFI_CFG + BLINKER_SSID_SIZE + BLINKER_PSWD_SIZE, ok); +// EEPROM.commit(); +// EEPROM.end(); + +// strcpy(_ssid, loadssid); +// strcpy(_pswd, loadpswd); + +// BLINKER_LOG(BLINKER_F("SSID: "), _ssid, BLINKER_F(" PASWD: "), _pswd); +// } + +// void BlinkerWlan::saveConfig(char *_ssid, char *_pswd) { +// char loadssid[BLINKER_SSID_SIZE]; +// char loadpswd[BLINKER_PSWD_SIZE]; + +// memcpy(loadssid, _ssid, BLINKER_SSID_SIZE); +// memcpy(loadpswd, _pswd, BLINKER_PSWD_SIZE); + +// EEPROM.begin(BLINKER_EEP_SIZE); +// EEPROM.put(BLINKER_EEP_ADDR_SSID, loadssid); +// EEPROM.put(BLINKER_EEP_ADDR_PSWD, loadpswd); +// char ok[2 + 1] = "OK"; +// EEPROM.put(BLINKER_EEP_ADDR_WLAN_CHECK, ok); +// EEPROM.commit(); +// EEPROM.end(); + +// BLINKER_LOG(BLINKER_F("Save wlan config")); +// } + +// void BlinkerWlan::deleteConfig() { +// char ok[3] = {0}; +// EEPROM.begin(BLINKER_EEP_SIZE); +// // for (int i = BLINKER_EEP_ADDR_WLAN_CHECK; i < BLINKER_WLAN_CHECK_SIZE; i++) +// // EEPROM.write(i, 0); +// EEPROM.put(BLINKER_EEP_ADDR_WLAN_CHECK, ok); +// EEPROM.commit(); +// EEPROM.end(); + +// BLINKER_LOG(BLINKER_F("Erase wlan config")); +// } + +// void BlinkerWlan::smartconfigBegin(uint16_t _time) { +// WiFi.mode(WIFI_STA); +// delay(100); +// String softAP_ssid = STRING_format(_deviceType) + "_" + macDeviceName(); + +// #if defined(ESP8266) +// WiFi.hostname(softAP_ssid); +// #elif defined(ESP32) +// WiFi.setHostname(softAP_ssid.c_str()); +// #endif + +// WiFi.beginSmartConfig(); +// connectTime = millis(); +// timeout = _time; +// _status = BWL_SMARTCONFIG_BEGIN; + +// BLINKER_LOG(BLINKER_F("Wait for Smartconfig")); +// } + +// bool BlinkerWlan::smartconfigDone() { +// if (WiFi.smartConfigDone()) +// { +// // WiFi.setAutoConnect(true); +// // WiFi.setAutoReconnect(true); +// connectTime = millis(); + +// _status = BWL_SMARTCONFIG_DONE; + +// BLINKER_LOG(BLINKER_F("SmartConfig Success")); +// #if defined(ESP8266) +// BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); +// // WiFi.begin(WiFi.SSID().c_str(), WiFi.psk().c_str()); +// connectWiFi(WiFi.SSID().c_str(), WiFi.psk().c_str()); +// // connectWiFi("有没有wifi", "i8888888"); +// #endif +// return true; +// } +// else { +// return false; +// } +// } + +// void BlinkerWlan::connect() { +// switch (_status) { +// case BWL_CONFIG_SUCCESS : +// // WiFi.setAutoConnect(false); +// // WiFi.setAutoReconnect(true); + +// SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); +// PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + +// loadConfig(SSID, PSWD); +// // WiFi.begin(SSID, PSWD); +// connectWiFi(SSID, PSWD); + +// free(SSID); +// free(PSWD); + +// _status = BWL_CONNECTING; +// break; +// case BWL_DISCONNECTED : +// if (millis() - connectTime > 30000 && WiFi.status() != WL_CONNECTED) { +// BLINKER_LOG(BLINKER_F("status: "), WiFi.status()); + +// disconnect(); +// // SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); +// // PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); +// // WiFi.reconnect(); + +// char _ssid_[BLINKER_SSID_SIZE]; +// char _pswd_[BLINKER_PSWD_SIZE]; + +// loadConfig(_ssid_, _pswd_); +// connectWiFi(_ssid_, _pswd_); + +// // WiFi.setAutoConnect(false); +// // WiFi.setAutoReconnect(true); + +// // free(SSID); +// // free(PSWD); +// connectTime = millis(); +// BLINKER_LOG(BLINKER_F("connecting BWL_DISCONNECTED")); + +// BLINKER_LOG(BLINKER_F("_ssid_: "), _ssid_, BLINKER_F(" _pswd_: "), _pswd_); +// } +// else if(WiFi.status() == WL_CONNECTED) { +// _status = BWL_CONNECTED; +// } +// break; +// } +// } + +// bool BlinkerWlan::connected() { +// switch (_status) { +// case BWL_SMARTCONFIG_DONE : +// if (WiFi.status() != WL_CONNECTED) { +// if (millis() - connectTime > 15000) +// { +// BLINKER_LOG(BLINKER_F("smartConfig time out")); + +// WiFi.stopSmartConfig(); +// _status = BWL_SMARTCONFIG_TIMEOUT; +// } +// return false; +// } +// else if (WiFi.status() == WL_CONNECTED) { +// // WiFi.stopSmartConfig(); + +// IPAddress deviceIP = WiFi.localIP(); +// BLINKER_LOG(BLINKER_F("WiFi connected")); +// BLINKER_LOG(BLINKER_F("IP address: ")); +// BLINKER_LOG(deviceIP); +// BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + +// SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); +// PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); +// memcpy(SSID,"\0",BLINKER_SSID_SIZE); +// memcpy(SSID,WiFi.SSID().c_str(),BLINKER_SSID_SIZE); +// memcpy(PSWD,"\0",BLINKER_PSWD_SIZE); +// memcpy(PSWD,WiFi.psk().c_str(),BLINKER_PSWD_SIZE); +// saveConfig(SSID, PSWD); +// free(SSID); +// free(PSWD); + +// // WiFi.setAutoConnect(true); +// // WiFi.setAutoReconnect(true); + +// _status = BWL_CONNECTED_CHECK; + +// BLINKER_LOG_FreeHeap_ALL(); + +// return true; +// } +// // break; +// case BWL_APCONFIG_DONE : +// if (WiFi.status() != WL_CONNECTED) { +// if (millis() - connectTime > 15000) +// { +// BLINKER_LOG(BLINKER_F("APConfig time out")); + +// // WiFi.stopSmartConfig(); +// _status = BWL_APCONFIG_TIMEOUT; +// } +// return false; +// } +// else if (WiFi.status() == WL_CONNECTED) { +// IPAddress deviceIP = WiFi.localIP(); +// BLINKER_LOG(BLINKER_F("WiFi connected")); +// BLINKER_LOG(BLINKER_F("IP address: ")); +// BLINKER_LOG(deviceIP); +// BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + +// // SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); +// // PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); +// // memcpy(SSID,"\0",BLINKER_SSID_SIZE); +// // memcpy(SSID,WiFi.SSID().c_str(),BLINKER_SSID_SIZE); +// // memcpy(PSWD,"\0",BLINKER_PSWD_SIZE); +// // memcpy(PSWD,WiFi.psk().c_str(),BLINKER_PSWD_SIZE); +// saveConfig(SSID, PSWD); +// free(SSID); +// free(PSWD); + +// // WiFi.setAutoConnect(true); +// // WiFi.setAutoReconnect(true); + +// _status = BWL_CONNECTED_CHECK; +// return true; +// } +// break; +// case BWL_CONNECTING : +// if (WiFi.status() == WL_CONNECTED) { +// IPAddress deviceIP = WiFi.localIP(); +// BLINKER_LOG(BLINKER_F("WiFi connected")); +// BLINKER_LOG(BLINKER_F("IP address: ")); +// BLINKER_LOG(deviceIP); +// BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + +// _status = BWL_CONNECTED_CHECK; +// return true; +// } +// else if (WiFi.status() != WL_CONNECTED) { +// return false; +// } +// case BWL_CONNECTED_CHECK : +// // if (WiFi.status() != WL_CONNECTED) +// // _status = BWL_DISCONNECTED; +// if (WiFi.status() == WL_CONNECTED) +// { +// return true; +// } +// else +// { +// _status = BWL_DISCONNECTED; +// return false; +// } +// case BWL_RESET : +// return false; +// default : +// if (WiFi.status() == WL_CONNECTED) { +// IPAddress deviceIP = WiFi.localIP(); +// BLINKER_LOG(BLINKER_F("WiFi connected")); +// BLINKER_LOG(BLINKER_F("IP address: ")); +// BLINKER_LOG(deviceIP); +// BLINKER_LOG(BLINKER_F("SSID: "), WiFi.SSID(), BLINKER_F(" PSWD: "), WiFi.psk()); + +// _status = BWL_CONNECTED_CHECK; +// return true; +// } +// return false; +// } +// return false; +// } + +// void BlinkerWlan::disconnect() { +// WiFi.disconnect(); +// delay(100); +// _status = BWL_DISCONNECTED; +// BLINKER_LOG(BLINKER_F("WiFi disconnected")); +// } + +// void BlinkerWlan::reset() { +// disconnect(); +// _status = BWL_RESET; +// } + +// void BlinkerWlan::softAPinit() { +// // _server = new WiFiServer(80); + +// WiFi.mode(WIFI_AP); +// String softAP_ssid = STRING_format(_deviceType) + "_" + macDeviceName(); + +// #if defined(ESP8266) +// WiFi.hostname(softAP_ssid); +// #elif defined(ESP32) +// WiFi.setHostname(softAP_ssid.c_str()); +// #endif + +// #if defined(ESP8266) +// WiFi.softAPConfig(apIP, apIP, netMsk); +// #elif defined(ESP32) +// WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); +// #endif + +// WiFi.softAP(softAP_ssid.c_str(), NULL); +// delay(100); + +// // _server->begin(); +// // BLINKER_LOG(BLINKER_F("AP IP address: "), WiFi.softAPIP()); +// // BLINKER_LOG(BLINKER_F("HTTP _server started")); +// // BLINKER_LOG(String("URL: http://" + WiFi.softAPIP())); + +// _status = BWL_APCONFIG_BEGIN; + +// BLINKER_LOG(BLINKER_F("Wait for APConfig")); +// } + +// void BlinkerWlan::serverClient() +// { +// // if (!_client) +// // { +// // _client = _server->available(); +// // } +// // else +// // { +// // // if (_client.status() == CLOSED) +// // if (!_client.connected()) +// // { +// // _client.stop(); +// // BLINKER_LOG(BLINKER_F("Connection closed on _client")); +// // } +// // else +// // { +// // if (_client.available()) +// // { +// // String data = _client.readStringUntil('\r'); + +// // // data = data.substring(4, data.length() - 9); +// // _client.flush(); + +// // // BLINKER_LOG("clientData: ", data); + +// // if (STRING_contains_string(data, "ssid") && STRING_contains_string(data, "pswd")) { + +// // String msg = BLINKER_F("{\"hello\":\"world\"}"); + +// // String s= BLINKER_F("HTTP/1.1 200 OK\r\nContent-Type: application/json;charset=utf-8\r\n"); +// // s += BLINKER_F("Content-Length: "); +// // s += String(msg.length()); +// // s += BLINKER_F("\r\nConnection: Keep Alive\r\n\r\n"); +// // s += msg; +// // s += BLINKER_F("\r\n"); + +// // _client.print(s); + +// // _client.stop(); + +// // parseUrl(data); +// // } +// // } +// // } +// // } +// } + +// void BlinkerWlan::parseUrl(String data) +// { +// BLINKER_LOG(BLINKER_F("APCONFIG data: "), data); +// // DynamicJsonBuffer jsonBuffer; +// // JsonObject& wifi_data = jsonBuffer.parseObject(data); +// DynamicJsonDocument jsonBuffer(1024); +// DeserializationError error = deserializeJson(jsonBuffer, data); +// JsonObject wifi_data = jsonBuffer.as(); + +// // if (!wifi_data.success()) +// if (error) +// { +// return; +// } + +// String _ssid = wifi_data["ssid"]; +// String _pswd = wifi_data["pswd"]; + +// BLINKER_LOG(BLINKER_F("ssid: "), _ssid); +// BLINKER_LOG(BLINKER_F("pswd: "), _pswd); + +// // free(_server); + +// SSID = (char*)malloc(BLINKER_SSID_SIZE*sizeof(char)); +// PSWD = (char*)malloc(BLINKER_PSWD_SIZE*sizeof(char)); + +// strcpy(SSID, _ssid.c_str()); +// strcpy(PSWD, _pswd.c_str()); +// connectWiFi(_ssid, _pswd); +// connectTime = millis(); +// _status = BWL_APCONFIG_DONE; + +// BLINKER_LOG(BLINKER_F("APConfig Success")); +// } + +// void BlinkerWlan::connectWiFi(String _ssid, String _pswd) +// { +// connectWiFi(_ssid.c_str(), _pswd.c_str()); +// } + +// void BlinkerWlan::connectWiFi(const char* _ssid, const char* _pswd) +// { +// uint32_t connectTime = millis(); + +// BLINKER_LOG(BLINKER_F("Connecting to "), _ssid); + +// WiFi.mode(WIFI_STA); +// String _hostname = STRING_format(_deviceType) + "_" + macDeviceName(); + +// #if defined(ESP8266) +// WiFi.hostname(_hostname); +// #elif defined(ESP32) +// WiFi.setHostname(_hostname.c_str()); +// #endif + +// if (_pswd && strlen(_pswd)) { +// WiFi.begin(_ssid, _pswd); +// } +// else { +// WiFi.begin(_ssid); +// } + +// // while (WiFi.status() != WL_CONNECTED) { +// // ::delay(50); + +// // if (millis() - connectTime > BLINKER_CONNECT_TIMEOUT_MS && WiFi.status() != WL_CONNECTED) { +// // connectTime = millis(); +// // BLINKER_LOG(("WiFi connect timeout, please check ssid and pswd!")); +// // BLINKER_LOG(("Retring WiFi connect again!")); +// // } +// // } +// // BLINKER_LOG(("Connected")); + +// // IPAddress myip = WiFi.localIP(); +// // BLINKER_LOG(("Your IP is: "), myip); + +// // mDNSInit(); +// } + +// bool BlinkerWlan::run() +// { +// // if (millis() - debugStatusTime > 10000) { +// // debugStatusTime = millis(); + +// // BLINKER_LOG_ALL("WLAN status: ", _status); +// // } + +// switch (_status) { +// case BWL_CONFIG_CKECK : +// checkConfig(); +// break; +// case BWL_CONFIG_FAIL : +// #if defined(BLINKER_ESP_SMARTCONFIG) +// smartconfigBegin(); +// #elif defined(BLINKER_APCONFIG) +// softAPinit(); +// #endif +// break; +// case BWL_CONFIG_SUCCESS : +// connect(); +// break; +// case BWL_CONNECTING : +// return connected(); +// break; +// case BWL_CONNECTED : +// return connected(); +// break; +// case BWL_DISCONNECTED : +// connect(); +// break; +// case BWL_SMARTCONFIG_BEGIN : +// smartconfigDone(); +// break; +// case BWL_SMARTCONFIG_DONE : +// return connected(); +// break; +// case BWL_SMARTCONFIG_TIMEOUT : +// _status = BWL_CONFIG_FAIL; +// break; +// case BWL_STACONFIG_BEGIN : +// connect(); +// break; +// case BWL_APCONFIG_BEGIN : +// serverClient(); +// break; +// case BWL_APCONFIG_DONE : +// return connected(); +// break; +// case BWL_APCONFIG_TIMEOUT : +// _status = BWL_CONFIG_FAIL; +// break; +// case BWL_CONNECTED_CHECK : +// return connected(); +// break; +// case BWL_RESET: +// break; +// default : +// break; +// } +// return false; +// } + +// // #endif +// #endif + +// #endif diff --git a/blinker-library/src/Server/.pydio b/blinker-library/src/Server/.pydio new file mode 100644 index 0000000..4977de3 --- /dev/null +++ b/blinker-library/src/Server/.pydio @@ -0,0 +1 @@ +2b45d946-74ce-4a5d-a658-5cedd92058b8 \ No newline at end of file diff --git a/blinker-library/src/Server/BlinkerServer.h b/blinker-library/src/Server/BlinkerServer.h new file mode 100644 index 0000000..cfc430c --- /dev/null +++ b/blinker-library/src/Server/BlinkerServer.h @@ -0,0 +1,16 @@ +#ifndef BLINKER_SERVER_H +#define BLINKER_SERVER_H + +#ifndef BLINKER_SERVER_HTTPS + #ifndef BLINKER_WITHOUT_SSL + #define BLINKER_SERVER_HTTPS "https://iot.diandeng.tech" + #else + #define BLINKER_SERVER_HTTPS "http://iot.diandeng.tech" + #endif +#endif + +#ifndef BLINKER_SERVER_HOST + #define BLINKER_SERVER_HOST "iot.diandeng.tech" +#endif + +#endif \ No newline at end of file diff --git a/blinker-library/src/modules/.pydio b/blinker-library/src/modules/.pydio new file mode 100644 index 0000000..2f1d851 --- /dev/null +++ b/blinker-library/src/modules/.pydio @@ -0,0 +1 @@ +10d16335-5b4c-4235-8a96-e7a1507de2b0 \ No newline at end of file diff --git a/blinker-library/src/modules/ArduinoJson/.pydio b/blinker-library/src/modules/ArduinoJson/.pydio new file mode 100644 index 0000000..2a8aab1 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/.pydio @@ -0,0 +1 @@ +60867012-a186-4a18-923d-c6dbdc4d9071 \ No newline at end of file diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson.h b/blinker-library/src/modules/ArduinoJson/ArduinoJson.h new file mode 100644 index 0000000..3e29f39 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson.h @@ -0,0 +1,17 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#ifdef __cplusplus + +#include "ArduinoJson.hpp" + +using namespace ArduinoJson; + +#else + +#error ArduinoJson requires a C++ compiler, please change file extension to .cc or .cpp + +#endif diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson.hpp new file mode 100644 index 0000000..cb3704e --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson.hpp @@ -0,0 +1,69 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#ifndef ARDUINOJSON_DEBUG +#ifdef __clang__ +#pragma clang system_header +#elif defined __GNUC__ +#pragma GCC system_header +#endif +#endif + +#include "ArduinoJson/Namespace.hpp" + +#include "ArduinoJson/Array/ArrayRef.hpp" +#include "ArduinoJson/Object/ObjectRef.hpp" +#include "ArduinoJson/Variant/VariantRef.hpp" + +#include "ArduinoJson/Document/DynamicJsonDocument.hpp" +#include "ArduinoJson/Document/StaticJsonDocument.hpp" + +#include "ArduinoJson/Array/ArrayImpl.hpp" +#include "ArduinoJson/Array/ElementProxy.hpp" +#include "ArduinoJson/Array/Utilities.hpp" +#include "ArduinoJson/Collection/CollectionImpl.hpp" +#include "ArduinoJson/Object/MemberProxy.hpp" +#include "ArduinoJson/Object/ObjectImpl.hpp" +#include "ArduinoJson/Variant/VariantAsImpl.hpp" +#include "ArduinoJson/Variant/VariantImpl.hpp" + +#include "ArduinoJson/Json/JsonDeserializer.hpp" +#include "ArduinoJson/Json/JsonSerializer.hpp" +#include "ArduinoJson/Json/PrettyJsonSerializer.hpp" +#include "ArduinoJson/MsgPack/MsgPackDeserializer.hpp" +#include "ArduinoJson/MsgPack/MsgPackSerializer.hpp" + +#include "ArduinoJson/compatibility.hpp" + +namespace ArduinoJson { +typedef ARDUINOJSON_NAMESPACE::ArrayConstRef JsonArrayConst; +typedef ARDUINOJSON_NAMESPACE::ArrayRef JsonArray; +typedef ARDUINOJSON_NAMESPACE::Float JsonFloat; +typedef ARDUINOJSON_NAMESPACE::Integer JsonInteger; +typedef ARDUINOJSON_NAMESPACE::ObjectConstRef JsonObjectConst; +typedef ARDUINOJSON_NAMESPACE::ObjectRef JsonObject; +typedef ARDUINOJSON_NAMESPACE::Pair JsonPair; +typedef ARDUINOJSON_NAMESPACE::String JsonString; +typedef ARDUINOJSON_NAMESPACE::UInt JsonUInt; +typedef ARDUINOJSON_NAMESPACE::VariantConstRef JsonVariantConst; +typedef ARDUINOJSON_NAMESPACE::VariantRef JsonVariant; +using ARDUINOJSON_NAMESPACE::BasicJsonDocument; +using ARDUINOJSON_NAMESPACE::copyArray; +using ARDUINOJSON_NAMESPACE::DeserializationError; +using ARDUINOJSON_NAMESPACE::deserializeJson; +using ARDUINOJSON_NAMESPACE::deserializeMsgPack; +using ARDUINOJSON_NAMESPACE::DynamicJsonDocument; +using ARDUINOJSON_NAMESPACE::JsonDocument; +using ARDUINOJSON_NAMESPACE::serialized; +using ARDUINOJSON_NAMESPACE::serializeJson; +using ARDUINOJSON_NAMESPACE::serializeJsonPretty; +using ARDUINOJSON_NAMESPACE::serializeMsgPack; +using ARDUINOJSON_NAMESPACE::StaticJsonDocument; + +namespace DeserializationOption { +using ARDUINOJSON_NAMESPACE::NestingLimit; +} +} // namespace ArduinoJson diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/.pydio b/blinker-library/src/modules/ArduinoJson/ArduinoJson/.pydio new file mode 100644 index 0000000..2ce9b04 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/.pydio @@ -0,0 +1 @@ +9519f033-d8fd-4b4f-aef2-ad6fc6cfa55c \ No newline at end of file diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/.pydio b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/.pydio new file mode 100644 index 0000000..bd06bcb --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/.pydio @@ -0,0 +1 @@ +71ca3e24-cc40-44db-83aa-86e929afd91e \ No newline at end of file diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayFunctions.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayFunctions.hpp new file mode 100644 index 0000000..ec0dedd --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayFunctions.hpp @@ -0,0 +1,29 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#include "../Collection/CollectionData.hpp" + +namespace ARDUINOJSON_NAMESPACE { + +inline VariantData *arrayAdd(CollectionData *arr, MemoryPool *pool) { + return arr ? arr->add(pool) : 0; +} + +template +inline void arrayAccept(const CollectionData *arr, Visitor &visitor) { + if (arr) + visitor.visitArray(*arr); + else + visitor.visitNull(); +} + +inline bool arrayEquals(const CollectionData *lhs, const CollectionData *rhs) { + if (lhs == rhs) return true; + if (!lhs || !rhs) return false; + + return lhs->equalsArray(*rhs); +} +} // namespace ARDUINOJSON_NAMESPACE diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayImpl.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayImpl.hpp new file mode 100644 index 0000000..df01492 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayImpl.hpp @@ -0,0 +1,22 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#include "../Object/ObjectRef.hpp" +#include "ArrayRef.hpp" + +namespace ARDUINOJSON_NAMESPACE { + +template +inline ArrayRef ArrayShortcuts::createNestedArray() const { + return impl()->addElement().template to(); +} + +template +inline ObjectRef ArrayShortcuts::createNestedObject() const { + return impl()->addElement().template to(); +} + +} // namespace ARDUINOJSON_NAMESPACE diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayIterator.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayIterator.hpp new file mode 100644 index 0000000..c1d6096 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayIterator.hpp @@ -0,0 +1,121 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#include "../Variant/SlotFunctions.hpp" +#include "../Variant/VariantRef.hpp" + +namespace ARDUINOJSON_NAMESPACE { + +class VariantPtr { + public: + VariantPtr(MemoryPool *pool, VariantData *data) : _variant(pool, data) {} + + VariantRef *operator->() { + return &_variant; + } + + VariantRef &operator*() { + return _variant; + } + + private: + VariantRef _variant; +}; + +class ArrayIterator { + public: + ArrayIterator() : _slot(0) {} + explicit ArrayIterator(MemoryPool *pool, VariantSlot *slot) + : _pool(pool), _slot(slot) {} + + VariantRef operator*() const { + return VariantRef(_pool, _slot->data()); + } + VariantPtr operator->() { + return VariantPtr(_pool, _slot->data()); + } + + bool operator==(const ArrayIterator &other) const { + return _slot == other._slot; + } + + bool operator!=(const ArrayIterator &other) const { + return _slot != other._slot; + } + + ArrayIterator &operator++() { + _slot = _slot->next(); + return *this; + } + + ArrayIterator &operator+=(size_t distance) { + _slot = _slot->next(distance); + return *this; + } + + VariantSlot *internal() { + return _slot; + } + + private: + MemoryPool *_pool; + VariantSlot *_slot; +}; + +class VariantConstPtr { + public: + VariantConstPtr(const VariantData *data) : _variant(data) {} + + VariantConstRef *operator->() { + return &_variant; + } + + VariantConstRef &operator*() { + return _variant; + } + + private: + VariantConstRef _variant; +}; + +class ArrayConstRefIterator { + public: + ArrayConstRefIterator() : _slot(0) {} + explicit ArrayConstRefIterator(const VariantSlot *slot) : _slot(slot) {} + + VariantConstRef operator*() const { + return VariantConstRef(_slot->data()); + } + VariantConstPtr operator->() { + return VariantConstPtr(_slot->data()); + } + + bool operator==(const ArrayConstRefIterator &other) const { + return _slot == other._slot; + } + + bool operator!=(const ArrayConstRefIterator &other) const { + return _slot != other._slot; + } + + ArrayConstRefIterator &operator++() { + _slot = _slot->next(); + return *this; + } + + ArrayConstRefIterator &operator+=(size_t distance) { + _slot = _slot->next(distance); + return *this; + } + + const VariantSlot *internal() { + return _slot; + } + + private: + const VariantSlot *_slot; +}; +} // namespace ARDUINOJSON_NAMESPACE diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayRef.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayRef.hpp new file mode 100644 index 0000000..e34b623 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayRef.hpp @@ -0,0 +1,153 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#include "../Variant/VariantData.hpp" +#include "ArrayFunctions.hpp" +#include "ArrayIterator.hpp" + +// Returns the size (in bytes) of an array with n elements. +// Can be very handy to determine the size of a StaticMemoryPool. +#define JSON_ARRAY_SIZE(NUMBER_OF_ELEMENTS) \ + ((NUMBER_OF_ELEMENTS) * sizeof(ARDUINOJSON_NAMESPACE::VariantSlot)) + +namespace ARDUINOJSON_NAMESPACE { + +class ObjectRef; +template +class ElementProxy; + +template +class ArrayRefBase { + public: + operator VariantConstRef() const { + const void* data = _data; // prevent warning cast-align + return VariantConstRef(reinterpret_cast(data)); + } + + template + FORCE_INLINE void accept(Visitor& visitor) const { + arrayAccept(_data, visitor); + } + + FORCE_INLINE bool isNull() const { + return _data == 0; + } + + FORCE_INLINE size_t memoryUsage() const { + return _data ? _data->memoryUsage() : 0; + } + + FORCE_INLINE size_t nesting() const { + return _data ? _data->nesting() : 0; + } + + FORCE_INLINE size_t size() const { + return _data ? _data->size() : 0; + } + + protected: + ArrayRefBase(TData* data) : _data(data) {} + TData* _data; +}; + +class ArrayConstRef : public ArrayRefBase, + public Visitable { + friend class ArrayRef; + typedef ArrayRefBase base_type; + + public: + typedef ArrayConstRefIterator iterator; + + FORCE_INLINE iterator begin() const { + if (!_data) return iterator(); + return iterator(_data->head()); + } + + FORCE_INLINE iterator end() const { + return iterator(); + } + + FORCE_INLINE ArrayConstRef() : base_type(0) {} + FORCE_INLINE ArrayConstRef(const CollectionData* data) : base_type(data) {} + + FORCE_INLINE bool operator==(ArrayConstRef rhs) const { + return arrayEquals(_data, rhs._data); + } + + FORCE_INLINE VariantConstRef operator[](size_t index) const { + return getElement(index); + } + + FORCE_INLINE VariantConstRef getElement(size_t index) const { + return VariantConstRef(_data ? _data->get(index) : 0); + } +}; + +class ArrayRef : public ArrayRefBase, + public ArrayShortcuts, + public Visitable { + typedef ArrayRefBase base_type; + + public: + typedef ArrayIterator iterator; + + FORCE_INLINE ArrayRef() : base_type(0), _pool(0) {} + FORCE_INLINE ArrayRef(MemoryPool* pool, CollectionData* data) + : base_type(data), _pool(pool) {} + + operator VariantRef() { + void* data = _data; // prevent warning cast-align + return VariantRef(_pool, reinterpret_cast(data)); + } + + operator ArrayConstRef() const { + return ArrayConstRef(_data); + } + + VariantRef addElement() const { + return VariantRef(_pool, arrayAdd(_data, _pool)); + } + + FORCE_INLINE iterator begin() const { + if (!_data) return iterator(); + return iterator(_pool, _data->head()); + } + + FORCE_INLINE iterator end() const { + return iterator(); + } + + // Copy a ArrayRef + FORCE_INLINE bool set(ArrayConstRef src) const { + if (!_data || !src._data) return false; + return _data->copyFrom(*src._data, _pool); + } + + FORCE_INLINE bool operator==(ArrayRef rhs) const { + return arrayEquals(_data, rhs._data); + } + + // Gets the value at the specified index. + FORCE_INLINE VariantRef getElement(size_t index) const { + return VariantRef(_pool, _data ? _data->get(index) : 0); + } + + // Removes element at specified position. + FORCE_INLINE void remove(iterator it) const { + if (!_data) return; + _data->remove(it.internal()); + } + + // Removes element at specified index. + FORCE_INLINE void remove(size_t index) const { + if (!_data) return; + _data->remove(index); + } + + private: + MemoryPool* _pool; +}; +} // namespace ARDUINOJSON_NAMESPACE diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayShortcuts.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayShortcuts.hpp new file mode 100644 index 0000000..221f3fd --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ArrayShortcuts.hpp @@ -0,0 +1,47 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#include "../Polyfills/attributes.hpp" +#include "../Polyfills/type_traits.hpp" + +namespace ARDUINOJSON_NAMESPACE { +// Forward declarations. +template +class ElementProxy; + +template +class ArrayShortcuts { + public: + // Returns the element at specified index if the variant is an array. + FORCE_INLINE ElementProxy operator[](size_t index) const; + + FORCE_INLINE ObjectRef createNestedObject() const; + + FORCE_INLINE ArrayRef createNestedArray() const; + + // Adds the specified value at the end of the array. + // + // bool add(TValue); + // TValue = bool, long, int, short, float, double, serialized, VariantRef, + // std::string, String, ObjectRef + template + FORCE_INLINE bool add(const T &value) const { + return impl()->addElement().set(value); + } + // + // bool add(TValue); + // TValue = char*, const char*, const __FlashStringHelper* + template + FORCE_INLINE bool add(T *value) const { + return impl()->addElement().set(value); + } + + private: + const TArray *impl() const { + return static_cast(this); + } +}; +} // namespace ARDUINOJSON_NAMESPACE diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ElementProxy.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ElementProxy.hpp new file mode 100644 index 0000000..e1c784a --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/ElementProxy.hpp @@ -0,0 +1,165 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#include "../Configuration.hpp" +#include "../Operators/VariantOperators.hpp" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4522) +#endif + +namespace ARDUINOJSON_NAMESPACE { + +template +class ElementProxy : public VariantOperators >, + public Visitable { + typedef ElementProxy this_type; + + public: + FORCE_INLINE ElementProxy(TArray array, size_t index) + : _array(array), _index(index) {} + + FORCE_INLINE this_type& operator=(const this_type& src) { + getUpstreamElement().set(src.as()); + return *this; + } + + // Replaces the value + // + // operator=(const TValue&) + // TValue = bool, long, int, short, float, double, serialized, VariantRef, + // std::string, String, ArrayRef, ObjectRef + template + FORCE_INLINE this_type& operator=(const T& src) { + getUpstreamElement().set(src); + return *this; + } + // + // operator=(TValue) + // TValue = char*, const char*, const __FlashStringHelper* + template + FORCE_INLINE this_type& operator=(T* src) { + getUpstreamElement().set(src); + return *this; + } + + FORCE_INLINE void clear() const { + getUpstreamElement().clear(); + } + + FORCE_INLINE bool isNull() const { + return getUpstreamElement().isNull(); + } + + template + FORCE_INLINE typename VariantAs::type as() const { + return getUpstreamElement().template as(); + } + + template + FORCE_INLINE bool is() const { + return getUpstreamElement().template is(); + } + + template + FORCE_INLINE typename VariantTo::type to() const { + return getUpstreamElement().template to(); + } + + // Replaces the value + // + // bool set(const TValue&) + // TValue = bool, long, int, short, float, double, serialized, VariantRef, + // std::string, String, ArrayRef, ObjectRef + template + FORCE_INLINE bool set(const TValue& value) const { + return getUpstreamElement().set(value); + } + // + // bool set(TValue) + // TValue = char*, const char*, const __FlashStringHelper* + template + FORCE_INLINE bool set(TValue* value) const { + return getUpstreamElement().set(value); + } + + template + void accept(Visitor& visitor) const { + return getUpstreamElement().accept(visitor); + } + + FORCE_INLINE size_t size() const { + return getUpstreamElement().size(); + } + + template + VariantRef getMember(TNestedKey* key) const { + return getUpstreamElement().getMember(key); + } + + template + VariantRef getMember(const TNestedKey& key) const { + return getUpstreamElement().getMember(key); + } + + template + VariantRef getOrAddMember(TNestedKey* key) const { + return getUpstreamElement().getOrAddMember(key); + } + + template + VariantRef getOrAddMember(const TNestedKey& key) const { + return getUpstreamElement().getOrAddMember(key); + } + + VariantRef addElement() const { + return getUpstreamElement().addElement(); + } + + VariantRef getElement(size_t index) const { + return getUpstreamElement().getElement(index); + } + + FORCE_INLINE void remove(size_t index) const { + getUpstreamElement().remove(index); + } + // remove(char*) const + // remove(const char*) const + // remove(const __FlashStringHelper*) const + template + FORCE_INLINE typename enable_if::value>::type remove( + TChar* key) const { + getUpstreamElement().remove(key); + } + // remove(const std::string&) const + // remove(const String&) const + template + FORCE_INLINE typename enable_if::value>::type remove( + const TString& key) const { + getUpstreamElement().remove(key); + } + + private: + FORCE_INLINE VariantRef getUpstreamElement() const { + return _array.getElement(_index); + } + + TArray _array; + const size_t _index; +}; + +template +inline ElementProxy ArrayShortcuts::operator[]( + size_t index) const { + return ElementProxy(*impl(), index); +} + +} // namespace ARDUINOJSON_NAMESPACE + +#ifdef _MSC_VER +#pragma warning(pop) +#endif diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/Utilities.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/Utilities.hpp new file mode 100644 index 0000000..4959916 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Array/Utilities.hpp @@ -0,0 +1,66 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#include "ArrayRef.hpp" + +namespace ARDUINOJSON_NAMESPACE { + +// Copy a 1D array to a JsonArray +template +inline bool copyArray(T (&src)[N], ArrayRef dst) { + return copyArray(src, N, dst); +} + +// Copy a 1D array to a JsonArray +template +inline bool copyArray(T* src, size_t len, ArrayRef dst) { + bool ok = true; + for (size_t i = 0; i < len; i++) { + ok &= dst.add(src[i]); + } + return ok; +} + +// Copy a 2D array to a JsonArray +template +inline bool copyArray(T (&src)[N1][N2], ArrayRef dst) { + bool ok = true; + for (size_t i = 0; i < N1; i++) { + ArrayRef nestedArray = dst.createNestedArray(); + for (size_t j = 0; j < N2; j++) { + ok &= nestedArray.add(src[i][j]); + } + } + return ok; +} + +// Copy a JsonArray to a 1D array +template +inline size_t copyArray(ArrayConstRef src, T (&dst)[N]) { + return copyArray(src, dst, N); +} + +// Copy a JsonArray to a 1D array +template +inline size_t copyArray(ArrayConstRef src, T* dst, size_t len) { + size_t i = 0; + for (ArrayConstRef::iterator it = src.begin(); it != src.end() && i < len; + ++it) + dst[i++] = *it; + return i; +} + +// Copy a JsonArray to a 2D array +template +inline void copyArray(ArrayConstRef src, T (&dst)[N1][N2]) { + size_t i = 0; + for (ArrayConstRef::iterator it = src.begin(); it != src.end() && i < N1; + ++it) { + copyArray(it->as(), dst[i++]); + } +} + +} // namespace ARDUINOJSON_NAMESPACE diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Collection/.pydio b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Collection/.pydio new file mode 100644 index 0000000..50a79b8 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Collection/.pydio @@ -0,0 +1 @@ +ad121d44-a065-47e3-92b5-2744bc068616 \ No newline at end of file diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Collection/CollectionData.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Collection/CollectionData.hpp new file mode 100644 index 0000000..6b37d53 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Collection/CollectionData.hpp @@ -0,0 +1,70 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +namespace ARDUINOJSON_NAMESPACE { + +class MemoryPool; +class VariantData; +class VariantSlot; + +class CollectionData { + VariantSlot *_head; + VariantSlot *_tail; + + public: + // Must be a POD! + // - no constructor + // - no destructor + // - no virtual + // - no inheritance + VariantSlot *addSlot(MemoryPool *); + + VariantData *add(MemoryPool *pool); + + template + VariantData *add(TAdaptedString key, MemoryPool *pool); + + void clear(); + + template + bool containsKey(const TAdaptedString &key) const; + + bool copyFrom(const CollectionData &src, MemoryPool *pool); + + bool equalsArray(const CollectionData &other) const; + bool equalsObject(const CollectionData &other) const; + + VariantData *get(size_t index) const; + + template + VariantData *get(TAdaptedString key) const; + + VariantSlot *head() const { + return _head; + } + + void remove(size_t index); + + template + void remove(TAdaptedString key) { + remove(getSlot(key)); + } + + void remove(VariantSlot *slot); + + size_t memoryUsage() const; + size_t nesting() const; + size_t size() const; + + private: + VariantSlot *getSlot(size_t index) const; + + template + VariantSlot *getSlot(TAdaptedString key) const; + + VariantSlot *getPreviousSlot(VariantSlot *) const; +}; +} // namespace ARDUINOJSON_NAMESPACE diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Collection/CollectionImpl.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Collection/CollectionImpl.hpp new file mode 100644 index 0000000..c6097e4 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Collection/CollectionImpl.hpp @@ -0,0 +1,163 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#include "../Variant/VariantData.hpp" +#include "CollectionData.hpp" + +namespace ARDUINOJSON_NAMESPACE { + +inline VariantSlot* CollectionData::addSlot(MemoryPool* pool) { + VariantSlot* slot = pool->allocVariant(); + if (!slot) return 0; + + if (_tail) { + _tail->setNextNotNull(slot); + _tail = slot; + } else { + _head = slot; + _tail = slot; + } + + slot->clear(); + return slot; +} + +inline VariantData* CollectionData::add(MemoryPool* pool) { + return slotData(addSlot(pool)); +} + +template +inline VariantData* CollectionData::add(TAdaptedString key, MemoryPool* pool) { + VariantSlot* slot = addSlot(pool); + if (!slotSetKey(slot, key, pool)) return 0; + return slot->data(); +} + +inline void CollectionData::clear() { + _head = 0; + _tail = 0; +} + +template +inline bool CollectionData::containsKey(const TAdaptedString& key) const { + return getSlot(key) != 0; +} + +inline bool CollectionData::copyFrom(const CollectionData& src, + MemoryPool* pool) { + clear(); + for (VariantSlot* s = src._head; s; s = s->next()) { + VariantData* var; + if (s->key() != 0) { + if (s->ownsKey()) + var = add(RamStringAdapter(s->key()), pool); + else + var = add(ConstRamStringAdapter(s->key()), pool); + } else { + var = add(pool); + } + if (!var) return false; + if (!var->copyFrom(*s->data(), pool)) return false; + } + return true; +} + +inline bool CollectionData::equalsObject(const CollectionData& other) const { + size_t count = 0; + for (VariantSlot* slot = _head; slot; slot = slot->next()) { + VariantData* v1 = slot->data(); + VariantData* v2 = other.get(adaptString(slot->key())); + if (!variantEquals(v1, v2)) return false; + count++; + } + return count == other.size(); +} + +inline bool CollectionData::equalsArray(const CollectionData& other) const { + VariantSlot* s1 = _head; + VariantSlot* s2 = other._head; + for (;;) { + if (s1 == s2) return true; + if (!s1 || !s2) return false; + if (!variantEquals(s1->data(), s2->data())) return false; + s1 = s1->next(); + s2 = s2->next(); + } +} + +template +inline VariantSlot* CollectionData::getSlot(TAdaptedString key) const { + VariantSlot* slot = _head; + while (slot) { + if (key.equals(slot->key())) break; + slot = slot->next(); + } + return slot; +} + +inline VariantSlot* CollectionData::getSlot(size_t index) const { + return _head->next(index); +} + +inline VariantSlot* CollectionData::getPreviousSlot(VariantSlot* target) const { + VariantSlot* current = _head; + while (current) { + VariantSlot* next = current->next(); + if (next == target) return current; + current = next; + } + return 0; +} + +template +inline VariantData* CollectionData::get(TAdaptedString key) const { + VariantSlot* slot = getSlot(key); + return slot ? slot->data() : 0; +} + +inline VariantData* CollectionData::get(size_t index) const { + VariantSlot* slot = getSlot(index); + return slot ? slot->data() : 0; +} + +inline void CollectionData::remove(VariantSlot* slot) { + if (!slot) return; + VariantSlot* prev = getPreviousSlot(slot); + VariantSlot* next = slot->next(); + if (prev) + prev->setNext(next); + else + _head = next; + if (!next) _tail = prev; +} + +inline void CollectionData::remove(size_t index) { + remove(getSlot(index)); +} + +inline size_t CollectionData::memoryUsage() const { + size_t total = 0; + for (VariantSlot* s = _head; s; s = s->next()) { + total += sizeof(VariantSlot) + s->data()->memoryUsage(); + if (s->ownsKey()) total += strlen(s->key()) + 1; + } + return total; +} + +inline size_t CollectionData::nesting() const { + size_t maxChildNesting = 0; + for (VariantSlot* s = _head; s; s = s->next()) { + size_t childNesting = s->data()->nesting(); + if (childNesting > maxChildNesting) maxChildNesting = childNesting; + } + return maxChildNesting + 1; +} + +inline size_t CollectionData::size() const { + return slotSize(_head); +} + +} // namespace ARDUINOJSON_NAMESPACE diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Configuration.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Configuration.hpp new file mode 100644 index 0000000..6e97b15 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Configuration.hpp @@ -0,0 +1,173 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#if defined(_MSC_VER) +#define ARDUINOJSON_HAS_INT64 1 +#else +#define ARDUINOJSON_HAS_INT64 0 +#endif + +#if __cplusplus >= 201103L +#define ARDUINOJSON_HAS_LONG_LONG 1 +#define ARDUINOJSON_HAS_NULLPTR 1 +#else +#define ARDUINOJSON_HAS_LONG_LONG 0 +#define ARDUINOJSON_HAS_NULLPTR 0 +#endif + +// Small or big machine? +#ifndef ARDUINOJSON_EMBEDDED_MODE +#if defined(ARDUINO) || defined(__IAR_SYSTEMS_ICC__) || defined(__XC) || \ + defined(__ARMCC_VERSION) +#define ARDUINOJSON_EMBEDDED_MODE 1 +#else +#define ARDUINOJSON_EMBEDDED_MODE 0 +#endif +#endif + +#if ARDUINOJSON_EMBEDDED_MODE + +// Store floats by default to reduce the memory usage (issue #134) +#ifndef ARDUINOJSON_USE_DOUBLE +#define ARDUINOJSON_USE_DOUBLE 0 +#endif + +// Store longs by default, because they usually match the size of a float. +#ifndef ARDUINOJSON_USE_LONG_LONG +#define ARDUINOJSON_USE_LONG_LONG 0 +#endif + +// Embedded systems usually don't have std::string +#ifndef ARDUINOJSON_ENABLE_STD_STRING +#define ARDUINOJSON_ENABLE_STD_STRING 0 +#endif + +// Embedded systems usually don't have std::stream +#ifndef ARDUINOJSON_ENABLE_STD_STREAM +#define ARDUINOJSON_ENABLE_STD_STREAM 0 +#endif + +// Limit nesting as the stack is likely to be small +#ifndef ARDUINOJSON_DEFAULT_NESTING_LIMIT +#define ARDUINOJSON_DEFAULT_NESTING_LIMIT 10 +#endif + +#else // ARDUINOJSON_EMBEDDED_MODE + +// On a computer we have plenty of memory so we can use doubles +#ifndef ARDUINOJSON_USE_DOUBLE +#define ARDUINOJSON_USE_DOUBLE 1 +#endif + +// Use long long when available +#ifndef ARDUINOJSON_USE_LONG_LONG +#if ARDUINOJSON_HAS_LONG_LONG || ARDUINOJSON_HAS_INT64 +#define ARDUINOJSON_USE_LONG_LONG 1 +#else +#define ARDUINOJSON_USE_LONG_LONG 0 +#endif +#endif + +// On a computer, we can use std::string +#ifndef ARDUINOJSON_ENABLE_STD_STRING +#define ARDUINOJSON_ENABLE_STD_STRING 1 +#endif + +// On a computer, we can assume std::stream +#ifndef ARDUINOJSON_ENABLE_STD_STREAM +#define ARDUINOJSON_ENABLE_STD_STREAM 1 +#endif + +// On a computer, the stack is large so we can increase nesting limit +#ifndef ARDUINOJSON_DEFAULT_NESTING_LIMIT +#define ARDUINOJSON_DEFAULT_NESTING_LIMIT 50 +#endif + +#endif // ARDUINOJSON_EMBEDDED_MODE + +#ifdef ARDUINO + +// Enable support for Arduino's String class +#ifndef ARDUINOJSON_ENABLE_ARDUINO_STRING +#define ARDUINOJSON_ENABLE_ARDUINO_STRING 1 +#endif + +// Enable support for Arduino's Stream class +#ifndef ARDUINOJSON_ENABLE_ARDUINO_STREAM +#define ARDUINOJSON_ENABLE_ARDUINO_STREAM 1 +#endif + +// Enable support for Arduino's Print class +#ifndef ARDUINOJSON_ENABLE_ARDUINO_PRINT +#define ARDUINOJSON_ENABLE_ARDUINO_PRINT 1 +#endif + +#else // ARDUINO + +// Enable support for Arduino's String class +#ifndef ARDUINOJSON_ENABLE_ARDUINO_STRING +#define ARDUINOJSON_ENABLE_ARDUINO_STRING 0 +#endif + +// Enable support for Arduino's Stream class +#ifndef ARDUINOJSON_ENABLE_ARDUINO_STREAM +#define ARDUINOJSON_ENABLE_ARDUINO_STREAM 0 +#endif + +// Enable support for Arduino's Print class +#ifndef ARDUINOJSON_ENABLE_ARDUINO_PRINT +#define ARDUINOJSON_ENABLE_ARDUINO_PRINT 0 +#endif + +#endif // ARDUINO + +#ifndef ARDUINOJSON_ENABLE_PROGMEM +#ifdef PROGMEM +#define ARDUINOJSON_ENABLE_PROGMEM 1 +#else +#define ARDUINOJSON_ENABLE_PROGMEM 0 +#endif +#endif + +// Convert unicode escape sequence (\u0123) to UTF-8 +#ifndef ARDUINOJSON_DECODE_UNICODE +#define ARDUINOJSON_DECODE_UNICODE 0 +#endif + +// Support NaN in JSON +#ifndef ARDUINOJSON_ENABLE_NAN +#define ARDUINOJSON_ENABLE_NAN 0 +#endif + +// Support Infinity in JSON +#ifndef ARDUINOJSON_ENABLE_INFINITY +#define ARDUINOJSON_ENABLE_INFINITY 0 +#endif + +// Control the exponentiation threshold for big numbers +// CAUTION: cannot be more that 1e9 !!!! +#ifndef ARDUINOJSON_POSITIVE_EXPONENTIATION_THRESHOLD +#define ARDUINOJSON_POSITIVE_EXPONENTIATION_THRESHOLD 1e7 +#endif + +// Control the exponentiation threshold for small numbers +#ifndef ARDUINOJSON_NEGATIVE_EXPONENTIATION_THRESHOLD +#define ARDUINOJSON_NEGATIVE_EXPONENTIATION_THRESHOLD 1e-5 +#endif + +#ifndef ARDUINOJSON_LITTLE_ENDIAN +#if defined(_MSC_VER) || \ + (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || \ + defined(__LITTLE_ENDIAN__) || defined(__i386) || defined(__x86_64) +#define ARDUINOJSON_LITTLE_ENDIAN 1 +#else +#define ARDUINOJSON_LITTLE_ENDIAN 0 +#endif +#endif + +#ifndef ARDUINOJSON_TAB +#define ARDUINOJSON_TAB " " +#endif diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/.pydio b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/.pydio new file mode 100644 index 0000000..7c06e1a --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/.pydio @@ -0,0 +1 @@ +a7314719-130d-4293-a623-0c2d97d12b6c \ No newline at end of file diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/ArduinoStreamReader.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/ArduinoStreamReader.hpp new file mode 100644 index 0000000..0551bd4 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/ArduinoStreamReader.hpp @@ -0,0 +1,31 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#if ARDUINOJSON_ENABLE_ARDUINO_STREAM + +#include + +namespace ARDUINOJSON_NAMESPACE { + +struct ArduinoStreamReader { + Stream& _stream; + + public: + explicit ArduinoStreamReader(Stream& stream) : _stream(stream) {} + + int read() { + // don't use _stream.read() as it ignores the timeout + uint8_t c; + return _stream.readBytes(&c, 1) ? c : -1; + } +}; + +inline ArduinoStreamReader makeReader(Stream& input) { + return ArduinoStreamReader(input); +} +} // namespace ARDUINOJSON_NAMESPACE + +#endif diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/CharPointerReader.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/CharPointerReader.hpp new file mode 100644 index 0000000..2de68d1 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/CharPointerReader.hpp @@ -0,0 +1,67 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +namespace ARDUINOJSON_NAMESPACE { + +template +struct IsCharOrVoid { + static const bool value = + is_same::value || is_same::value || + is_same::value || is_same::value; +}; + +template +struct IsCharOrVoid : IsCharOrVoid {}; + +class UnsafeCharPointerReader { + const char* _ptr; + + public: + explicit UnsafeCharPointerReader(const char* ptr) + : _ptr(ptr ? ptr : reinterpret_cast("")) {} + + int read() { + return static_cast(*_ptr++); + } +}; + +class SafeCharPointerReader { + const char* _ptr; + const char* _end; + + public: + explicit SafeCharPointerReader(const char* ptr, size_t len) + : _ptr(ptr ? ptr : reinterpret_cast("")), _end(_ptr + len) {} + + int read() { + if (_ptr < _end) + return static_cast(*_ptr++); + else + return -1; + } +}; + +template +inline typename enable_if::value, + UnsafeCharPointerReader>::type +makeReader(TChar* input) { + return UnsafeCharPointerReader(reinterpret_cast(input)); +} + +template +inline + typename enable_if::value, SafeCharPointerReader>::type + makeReader(TChar* input, size_t n) { + return SafeCharPointerReader(reinterpret_cast(input), n); +} + +#if ARDUINOJSON_ENABLE_ARDUINO_STRING +inline SafeCharPointerReader makeReader(const ::String& input) { + return SafeCharPointerReader(input.c_str(), input.length()); +} +#endif + +} // namespace ARDUINOJSON_NAMESPACE diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/DeserializationError.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/DeserializationError.hpp new file mode 100644 index 0000000..8707b3b --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/DeserializationError.hpp @@ -0,0 +1,113 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#if ARDUINOJSON_ENABLE_STD_STREAM +#include +#endif + +namespace ARDUINOJSON_NAMESPACE { + +class DeserializationError { + // safe bool idiom + typedef void (DeserializationError::*bool_type)() const; + void safeBoolHelper() const {} + + public: + enum Code { + Ok, + IncompleteInput, + InvalidInput, + NoMemory, + NotSupported, + TooDeep + }; + + DeserializationError() {} + DeserializationError(Code c) : _code(c) {} + + // Compare with DeserializationError + friend bool operator==(const DeserializationError& lhs, + const DeserializationError& rhs) { + return lhs._code == rhs._code; + } + friend bool operator!=(const DeserializationError& lhs, + const DeserializationError& rhs) { + return lhs._code != rhs._code; + } + + // Compare with Code + friend bool operator==(const DeserializationError& lhs, Code rhs) { + return lhs._code == rhs; + } + friend bool operator==(Code lhs, const DeserializationError& rhs) { + return lhs == rhs._code; + } + friend bool operator!=(const DeserializationError& lhs, Code rhs) { + return lhs._code != rhs; + } + friend bool operator!=(Code lhs, const DeserializationError& rhs) { + return lhs != rhs._code; + } + + // Behaves like a bool + operator bool_type() const { + return _code != Ok ? &DeserializationError::safeBoolHelper : 0; + } + friend bool operator==(bool value, const DeserializationError& err) { + return static_cast(err) == value; + } + friend bool operator==(const DeserializationError& err, bool value) { + return static_cast(err) == value; + } + friend bool operator!=(bool value, const DeserializationError& err) { + return static_cast(err) != value; + } + friend bool operator!=(const DeserializationError& err, bool value) { + return static_cast(err) != value; + } + + // Returns internal enum, useful for switch statement + Code code() const { + return _code; + } + + const char* c_str() const { + switch (_code) { + case Ok: + return "Ok"; + case TooDeep: + return "TooDeep"; + case NoMemory: + return "NoMemory"; + case InvalidInput: + return "InvalidInput"; + case IncompleteInput: + return "IncompleteInput"; + case NotSupported: + return "NotSupported"; + default: + return "???"; + } + } + + private: + Code _code; +}; + +#if ARDUINOJSON_ENABLE_STD_STREAM +inline std::ostream& operator<<(std::ostream& s, + const DeserializationError& e) { + s << e.c_str(); + return s; +} + +inline std::ostream& operator<<(std::ostream& s, DeserializationError::Code c) { + s << DeserializationError(c).c_str(); + return s; +} +#endif + +} // namespace ARDUINOJSON_NAMESPACE diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/FlashStringReader.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/FlashStringReader.hpp new file mode 100644 index 0000000..e8066ef --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/FlashStringReader.hpp @@ -0,0 +1,48 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#if ARDUINOJSON_ENABLE_PROGMEM + +namespace ARDUINOJSON_NAMESPACE { +class UnsafeFlashStringReader { + const char* _ptr; + + public: + explicit UnsafeFlashStringReader(const __FlashStringHelper* ptr) + : _ptr(reinterpret_cast(ptr)) {} + + int read() { + return pgm_read_byte_near(_ptr++); + } +}; + +class SafeFlashStringReader { + const char* _ptr; + const char* _end; + + public: + explicit SafeFlashStringReader(const __FlashStringHelper* ptr, size_t size) + : _ptr(reinterpret_cast(ptr)), _end(_ptr + size) {} + + int read() { + if (_ptr < _end) + return pgm_read_byte_near(_ptr++); + else + return -1; + } +}; + +inline UnsafeFlashStringReader makeReader(const __FlashStringHelper* input) { + return UnsafeFlashStringReader(input); +} + +inline SafeFlashStringReader makeReader(const __FlashStringHelper* input, + size_t size) { + return SafeFlashStringReader(input, size); +} +} // namespace ARDUINOJSON_NAMESPACE + +#endif diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/IteratorReader.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/IteratorReader.hpp new file mode 100644 index 0000000..f2605e4 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/IteratorReader.hpp @@ -0,0 +1,31 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +namespace ARDUINOJSON_NAMESPACE { + +template +class IteratorReader { + TIterator _ptr, _end; + + public: + explicit IteratorReader(TIterator begin, TIterator end) + : _ptr(begin), _end(end) {} + + int read() { + if (_ptr < _end) + return static_cast(*_ptr++); + else + return -1; + } +}; + +template +inline IteratorReader makeReader( + const TInput& input) { + return IteratorReader(input.begin(), + input.end()); +} +} // namespace ARDUINOJSON_NAMESPACE diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/NestingLimit.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/NestingLimit.hpp new file mode 100644 index 0000000..f1f4a5b --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/NestingLimit.hpp @@ -0,0 +1,17 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#include "../Configuration.hpp" + +namespace ARDUINOJSON_NAMESPACE { + +struct NestingLimit { + NestingLimit() : value(ARDUINOJSON_DEFAULT_NESTING_LIMIT) {} + explicit NestingLimit(uint8_t n) : value(n) {} + + uint8_t value; +}; +} // namespace ARDUINOJSON_NAMESPACE diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/StdStreamReader.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/StdStreamReader.hpp new file mode 100644 index 0000000..8996a77 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/StdStreamReader.hpp @@ -0,0 +1,34 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#if ARDUINOJSON_ENABLE_STD_STREAM + +#include + +namespace ARDUINOJSON_NAMESPACE { + +class StdStreamReader { + std::istream& _stream; + char _current; + + public: + explicit StdStreamReader(std::istream& stream) + : _stream(stream), _current(0) {} + + int read() { + return _stream.get(); + } + + private: + StdStreamReader& operator=(const StdStreamReader&); // Visual Studio C4512 +}; + +inline StdStreamReader makeReader(std::istream& input) { + return StdStreamReader(input); +} +} // namespace ARDUINOJSON_NAMESPACE + +#endif diff --git a/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/deserialize.hpp b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/deserialize.hpp new file mode 100644 index 0000000..112d082 --- /dev/null +++ b/blinker-library/src/modules/ArduinoJson/ArduinoJson/Deserialization/deserialize.hpp @@ -0,0 +1,76 @@ +// ArduinoJson - arduinojson.org +// Copyright Benoit Blanchon 2014-2019 +// MIT License + +#pragma once + +#include "../StringStorage/StringStorage.hpp" +#include "ArduinoStreamReader.hpp" +#include "CharPointerReader.hpp" +#include "DeserializationError.hpp" +#include "FlashStringReader.hpp" +#include "IteratorReader.hpp" +#include "NestingLimit.hpp" +#include "StdStreamReader.hpp" + +namespace ARDUINOJSON_NAMESPACE { + +template