Prechádzať zdrojové kódy

#1 add settings & web-deamon

Signed-off-by: wlxuz <myxuan475@126.com>
wlxuz 9 mesiacov pred
rodič
commit
ad20ee893a
57 zmenil súbory, kde vykonal 1874 pridanie a 2531 odobranie
  1. 14 3
      CMakeLists.txt
  2. 0 21
      apps/CMakeLists.txt
  3. 0 55
      apps/Makefile
  4. 0 35
      apps/app.json
  5. 0 906
      apps/apps.c
  6. 0 155
      apps/common.c
  7. 0 21
      apps/common.h
  8. BIN
      apps/device_db.db
  9. 0 426
      apps/sql_api.c
  10. 0 26
      apps/sql_api.h
  11. 0 1
      dist/index.html
  12. 0 0
      dist/static/css/app.3d8d24b268d0726c1919f7c7f329e2d4.css
  13. 0 0
      dist/static/css/app.3d8d24b268d0726c1919f7c7f329e2d4.css.map
  14. BIN
      dist/static/fonts/element-icons.535877f.woff
  15. BIN
      dist/static/fonts/element-icons.732389d.ttf
  16. BIN
      dist/static/img/logo_bg.b20eb92.png
  17. 0 0
      dist/static/js/app.6f0ac4c14391b3e0c8fe.js
  18. 0 0
      dist/static/js/app.6f0ac4c14391b3e0c8fe.js.map
  19. 0 2
      dist/static/js/manifest.2ae2e69a05c33dfc65f8.js
  20. 0 0
      dist/static/js/manifest.2ae2e69a05c33dfc65f8.js.map
  21. 0 14
      dist/static/js/vendor.3ce127c54cf2044ee291.js
  22. 0 0
      dist/static/js/vendor.3ce127c54cf2044ee291.js.map
  23. 0 41
      http/CMakeLists.txt
  24. 0 86
      http/Makefile
  25. 0 11
      http/add_device.c
  26. 0 346
      http/command.c
  27. 0 73
      http/command.h
  28. 0 14
      http/common.c
  29. 0 13
      http/common.h
  30. 0 1
      http/cookie/cookied.json
  31. 0 11
      http/del_device.c
  32. 0 11
      http/get_device.c
  33. 0 10
      http/get_platform.c
  34. 0 9
      http/get_system.c
  35. 0 10
      http/get_user.c
  36. 0 170
      http/login.c
  37. 0 38
      http/logout.c
  38. 0 11
      http/set_device.c
  39. 0 11
      http/set_platform.c
  40. 14 0
      settings/CMakeLists.txt
  41. 17 0
      settings/basic_config.xml
  42. 135 0
      settings/config_parser.cpp
  43. 45 0
      settings/config_parser.h
  44. 494 0
      settings/sysinfo.cpp
  45. 82 0
      settings/sysinfo.h
  46. 115 0
      settings/system_settings.cpp
  47. 57 0
      settings/system_settings.h
  48. 83 0
      settings/xmlconfig.cpp
  49. 35 0
      settings/xmlconfig.h
  50. 20 0
      web-deamon/CMakeLists.txt
  51. 88 0
      web-deamon/ajax_handler.cpp
  52. 21 0
      web-deamon/ajax_handler.h
  53. 22 0
      web-deamon/web_deamon.cpp
  54. 351 0
      web-deamon/web_handler.cpp
  55. 28 0
      web-deamon/web_handler.h
  56. 219 0
      web-deamon/web_vendor.cpp
  57. 34 0
      web-deamon/web_vendor.h

+ 14 - 3
CMakeLists.txt

@@ -1,7 +1,18 @@
-add_subdirectory(apps)
-add_subdirectory(http)
+# add_subdirectory(apps)
+# add_subdirectory(http)
 
-install(DIRECTORY dist
+# add_subdirectory(web-deamon)
+add_subdirectory(settings)
+
+install(FILES dist/index.html
+        DESTINATION webconfig
+)
+install(DIRECTORY dist/static
         DESTINATION webconfig/
         FILES_MATCHING PATTERN "*"
+)
+
+install(DIRECTORY config
+        DESTINATION ./
+        FILES_MATCHING PATTERN "*"
 )

+ 0 - 21
apps/CMakeLists.txt

@@ -1,21 +0,0 @@
-# 子模块参考模版
-include(${ROOT_DIR}/buildtools/cmake/toolchain_common.cmake)
-
-# 模块名称
-set(MODULE apps)
-
-aux_source_directory(. DIRSRCS)
-include_directories(./)
-
-build_subdirectory(thirdparty/mosquitto)
-build_subdirectory(thirdparty/SQLiteCpp include thirdparty/SQLiteCpp/sqlite3)
-build_subdirectory(thirdparty/json-c define STDC_HEADERS)
-
-message("current dir: ${CMAKE_CURRENT_SOURCE_DIR}")
-
-add_library(${MODULE} ${DIRSRCS})
-target_link_libraries(${MODULE} sqlite3 json-c rt pthread m)
-
-install(TARGETS ${MODULE} DESTINATION webconfig)
-install(FILES app.json DESTINATION webconfig)
-install(FILES device_db.db DESTINATION webconfig)

+ 0 - 55
apps/Makefile

@@ -1,55 +0,0 @@
-### Application-specific constants
-APP_NAME = apps
-### Environment constants 
-#ARCH := arm
-#CROSS_COMPILE :=  ../../buildroot-at91-2018.02-at91/output/host/bin/arm-linux-
-#CROSS_COMPILE := /home/logan/EmbeddedProject/RTU/buildroot/buildroot-at91-2018.02-at91/output/host/bin/arm-linux-
-#CROSS_COMPILE := /home/logan/iot/EdgeGateway/a40_src/out/sun8iw11p1/linux/common/buildroot/host/opt/ext-toolchain/bin/arm-linux-gnueabi-
-
-OBJDIR = obj
-INCLUDES = $(wildcard inc/*.h)
-
-### External constant definitions
-# must get library build option to know if mpsse must be linked or not
-
-### Constant symbols
-
-CC := $(CROSS_COMPILE)gcc
-AR := $(CROSS_COMPILE)ar
-#CC := gcc
-#AR := ar
-
-CFLAGS := -O2 -Wall -Wextra  -Iinc -I.
-##CFLAGS := -O2 -Wall -Wextra -I.
-
-# List the library sub-modules that are used by the application
-
-### Linking options
-
-#LIBS := -lmosquitto -lcrypto -lsqlite3 -ljson-c -lrt -lpthread -lm
-#LIBS := -lmosquitto -lcrypto -lsqlite3 -ljson-c -lrt -lpthread -lm -Wl,-rpath=../../buildroot-at91-2018.02-at91/output/target/usr/lib
-LIBS := -lmosquitto  -lsqlite3 -ljson-c -lrt -lpthread -lm
-
-### General build targets
-
-all: $(APP_NAME)
-
-clean:
-	rm -f *.o
-	rm -f $(APP_NAME)
-
-### Sub-modules compilation
-%.o: %.c
-	$(CC) $(CFLAGS) -c  $< -o $@
-
-$(APP_NAME):apps.o  sql_api.o common.o
-	$(CC)  $^ -o $@ $(LIBS)
-
-#sql_api: command.o sql_api.o common.o
-#	$(CC)   $^ -o $@ $(LIBS)
-
-install:
-	echo "install"
-
-### EOF
-

+ 0 - 35
apps/app.json

@@ -1,35 +0,0 @@
-{
-    "system":{
-        "uuid":"0102030405060708",
-        "boot_time":"2023-12-14 21:41:52",
-        "product_name":"LoRa Gateway",
-        "product_model":"M1001_For_Modbus",
-        "hw_version":"M1000_hardware_V1.0.1",
-        "sw_version":"M1000_firmware_V1.0.1",
-        "total_memory":"1000",
-        "used_memory":"200",
-        "total_flash":"1000",
-        "used_flash":"1000",
-        "ethernet_wan":"connected",
-        "wan_mac":"C2:96:78:2C:CE:D3",
-        "ethernet_lan":"disconnected",
-        "lan_mac":"C2:96:78:2C:CE:D3",
-        "lte_status":"disconnected",
-        "lte_mac":"C2:96:78:2C:CE:D3"
-    },
-
-    "user":{
-        "user":"admin",
-        "passwd":"leo2023"
-    },
-
-    "platform":{
-        "platform_proto":"modbus",
-        "platform_server":"123.60.64.212",
-        "platform_port":"9401",
-        "platform_id":"1"
-    }
-
-}
-
-

+ 0 - 906
apps/apps.c

@@ -1,906 +0,0 @@
-#include "common.h"
-#include <arpa/inet.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <json-c/json.h>
-#include <json-c/json_object.h>
-#include <json-c/json_util.h>
-#include <mosquitto.h>
-#include <netdb.h>
-#include <netinet/in.h>
-#include <netinet/ip.h>
-#include <netinet/tcp.h>
-#include <pthread.h>
-#include <signal.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <termios.h>
-#include <time.h>
-#include <unistd.h>
-
-#define MAX_VCOM 4
-
-#define ETH_0_NAME "eth0"
-#define ETH_1_NAME "eth1"
-
-#define GET_LAN_IP "ifconfig eth0 | grep 'inet addr' | awk -F'[ :]+' '{print $4}'"
-#define GET_LAN_NETMASK "ifconfig eth0 | grep 'inet addr' | awk -F'[ :]+' '{print $8}'"
-#define GET_LAN_GATEWAY "ifconfig eth0 | grep 'inet addr' | awk -F'[ :]+' '{print $6}'"
-#define GET_LAN_MACADDR "ifconfig eth0 | grep 'HWaddr' | awk -F' ' '{print $5}'"
-#define GET_LAN_STATE "cat /sys/class/net/eth0/operstate"
-
-#define GET_WAN_IP "ifconfig eth1 | grep 'inet addr' | awk -F'[ :]+' '{print $4}'"
-#define GET_WAN_NETMASK "ifconfig eth1 | grep 'inet addr' | awk -F'[ :]+' '{print $8}'"
-#define GET_WAN_GATEWAY "ifconfig eth1 | grep 'inet addr' | awk -F'[ :]+' '{print $6}'"
-#define GET_WAN_MACADDR "ifconfig eth1 | grep 'HWaddr' | awk -F' ' '{print $5}'"
-#define GET_WAN_STATE "cat /sys/class/net/eth1/operstate"
-
-#define GET_LTE_IP "ifconfig usb0 | grep 'inet addr' | awk -F'[ :]+' '{print $4}'"
-#define GET_LTE_NETMASK "ifconfig usb0 | grep 'inet addr' | awk -F'[ :]+' '{print $8}'"
-#define GET_LTE_GATEWAY "ifconfig usb0 | grep 'inet addr' | awk -F'[ :]+' '{print $6}'"
-#define GET_LTE_MACADDR "ifconfig usb0 | grep 'HWaddr' | awk -F' ' '{print $5}'"
-#define GET_LTE_STATE "cat /sys/class/net/usb0/operstate"
-
-#define GET_WLAN_IP "ifconfig wlan0 | grep 'inet addr' | awk -F'[ :]+' '{print $4}'"
-#define GET_WLAN_NETMASK "ifconfig wlan0 | grep 'inet addr' | awk -F'[ :]+' '{print $8}'"
-#define GET_WLAN_GATEWAY "ifconfig wlan0 | grep 'inet addr' | awk -F'[ :]+' '{print $6}'"
-#define GET_WLAN_MACADDR "ifconfig wlan0 | grep 'HWaddr' | awk -F' ' '{print $5}'"
-#define GET_WLAN_STATE "cat /sys/class/net/wlan0/operstate"
-
-#define GET_TOTAL_MEM "free -m | grep 'Mem:' | awk -F' ' '{print $2}'"
-#define GET_USED_MEM "free -m | grep 'Mem:' | awk -F' ' '{print $3}'"
-
-#define GET_TOTAL_FLASH "4096"
-#define GET_USED_FLASH "362"
-
-#define GET_NOWTIME "date +'%Y-%m-%d %H:%M.%S'"
-
-int vcom_fd[MAX_VCOM];
-struct mosquitto* mosq_up_mqtt[MAX_VCOM];
-struct mosquitto* mosq_dw_mqtt[MAX_VCOM];
-
-volatile bool exit_sig = false;
-volatile bool quit_sig = false;
-int net_sock = 0;
-
-struct json_object* root_obj = NULL;
-
-pthread_mutex_t mx_db = PTHREAD_MUTEX_INITIALIZER;
-pthread_mutex_t root_lock;
-
-struct mosquitto* mosq_http;
-
-static uint16_t CRC16(const uint8_t* p_data, uint32_t len, uint16_t* p_crc)
-{
-    uint32_t i;
-    uint16_t crc = 0xffff;
-    if (NULL == p_data || NULL == p_crc || 0 == len) {
-        return -1;
-    }
-    for (i = 0; i < len; i++) {
-        crc = (unsigned char)(crc >> 8) | (crc << 8);
-        crc ^= p_data[i];
-        crc ^= (unsigned char)(crc & 0xff) >> 4;
-        crc ^= (crc << 8) << 4;
-        crc ^= ((crc & 0xff) << 4) << 1;
-    }
-    *p_crc = crc;
-    return 0;
-}
-
-void exec_cmd(char* cmd, char* buf)
-{
-    FILE* fp = NULL;
-
-    if ((fp = popen(cmd, "r")) == NULL) {
-        printf("error: popen failed!\r\n");
-        exit(1);
-    }
-
-    while (fgets(buf, 199, fp) != NULL) {
-        if (buf[strlen(buf) - 1] == '\n')
-            buf[strlen(buf) - 1] = '\0';
-    }
-
-    pclose(fp);
-}
-
-static void sig_handler(int sigio)
-{
-    if (sigio == SIGQUIT) {
-        quit_sig = true;
-    } else if ((sigio == SIGINT) || (sigio == SIGTERM)) {
-        exit_sig = true;
-    }
-
-    return;
-}
-
-/*
-
-modbus  ---> json
-{
- "reg_0001":23,
- "reg_0002":24
-}
-
-
-*/
-int dwlink_packet_process(uint8_t* device_id_str,
-                          uint8_t* dw_buffer,
-                          uint8_t* dw_buffer_len,
-                          uint8_t* attr_addr_str,
-                          uint8_t* attr_value_str)
-{
-    struct json_object* dw_obj = NULL;
-
-    dw_obj = json_object_new_object();
-    if (dw_obj == NULL) {
-        printf("dw_obj is null\r\n");
-        return NULL;
-    }
-
-    json_object_object_add(dw_obj, attr_addr_str, json_object_new_string(attr_value_str));
-    if (strlen(json_object_to_json_string(dw_obj)) < 255) {
-        memcpy(dw_buffer, json_object_to_json_string(dw_obj), strlen(json_object_to_json_string(dw_obj)));
-        *dw_buffer_len = strlen(json_object_to_json_string(dw_obj));
-    }
-
-    json_object_put(dw_obj);
-}
-
-void config_init()
-{
-    root_obj = json_object_from_file("./app.json");
-    if (root_obj == NULL) {
-        return 0;
-    }
-}
-
-void mosq_http_connect_callback(struct mosquitto* mosq, void* obj, int rc)
-{
-    printf("http_json_connect_callback set\r\n");
-}
-
-void mosq_http_disconnect_callback(struct mosquitto* mosq, void* obj, int result)
-{
-    printf("http_json_disconnect_callback set\r\n");
-}
-
-struct json_object* get_system_json()
-{
-    struct json_object *rsp_obj = NULL, *system_obj = NULL;
-
-    rsp_obj = json_object_new_object();
-    if (rsp_obj == NULL) {
-        printf("rsp_obj is null\r\n");
-        return NULL;
-    }
-
-    json_object_object_get_ex(root_obj, "system", &system_obj);
-    json_object_object_add(rsp_obj, "system", system_obj);
-    json_object_get(system_obj);
-    json_object_object_add(rsp_obj, "state", json_object_new_string("success"));
-
-    return rsp_obj;
-}
-
-struct json_object* get_platform_json()
-{
-    struct json_object *rsp_obj = NULL, *platform_obj = NULL;
-
-    rsp_obj = json_object_new_object();
-    if (rsp_obj == NULL) {
-        printf("rsp_obj is null\r\n");
-        return NULL;
-    }
-
-    json_object_object_get_ex(root_obj, "platform", &platform_obj);
-    json_object_object_add(rsp_obj, "platform", platform_obj);
-    json_object_get(platform_obj);
-    json_object_object_add(rsp_obj, "state", json_object_new_string("success"));
-
-    return rsp_obj;
-}
-
-struct json_object* get_user_json()
-{
-    struct json_object *rsp_obj = NULL, *user_obj = NULL;
-
-    rsp_obj = json_object_new_object();
-    if (rsp_obj == NULL) {
-        printf("rsp_obj is null\r\n");
-        return NULL;
-    }
-    json_object_object_get_ex(root_obj, "user", &user_obj);
-    json_object_object_add(rsp_obj, "user", user_obj);
-    json_object_get(user_obj);
-    json_object_object_add(rsp_obj, "state", json_object_new_string("success"));
-
-    return rsp_obj;
-}
-
-struct json_object* get_devices_json()
-{
-    struct json_object* rsp_obj = NULL;
-
-    select_all_device(&rsp_obj);
-
-    return rsp_obj;
-}
-
-struct json_object* set_devices_json(char* payload)
-{
-    struct json_object *payload_obj = NULL, *item_obj = NULL, *devices_obj = NULL, *device_id_obj = NULL,
-                       *device_name_obj = NULL, *device_addr_obj = NULL, *application_id_obj = NULL;
-    char *device_id_str = NULL, *device_name_str = NULL, *device_addr_str = NULL, *application_id_str = NULL;
-    int len = 0, index = 0;
-
-    payload_obj = json_tokener_parse(payload);
-    if (payload_obj == NULL) {
-        printf("payload is null\r\n");
-        return NULL;
-    }
-
-    json_object_object_get_ex(payload_obj, "devices", &devices_obj);
-    len = json_object_array_length(devices_obj);
-    for (index = 0; index < len; index++) {
-        item_obj = json_object_array_get_idx(devices_obj, index);
-        json_object_object_get_ex(item_obj, "device_id", &device_id_obj);
-        device_id_str = json_object_get_string(device_id_obj);
-        json_object_object_get_ex(item_obj, "device_name", &device_name_obj);
-        device_name_str = json_object_get_string(device_name_obj);
-        json_object_object_get_ex(item_obj, "device_addr", &device_addr_obj);
-        device_addr_str = json_object_get_string(device_addr_obj);
-        json_object_object_get_ex(item_obj, "application_id", &application_id_obj);
-        application_id_str = json_object_get_string(application_id_obj);
-
-        pthread_mutex_lock(&mx_db);
-        update_device_by_device_id(tolower(device_id_str), tolower(device_name_str), atoi(device_addr_str),
-                                   tolower(application_id_str));
-        pthread_mutex_unlock(&mx_db);
-    }
-
-    json_object_object_add(payload_obj, "state", json_object_new_string("success"));
-
-    return payload_obj;
-}
-
-struct json_object* set_platform_json(char* payload)
-{
-    struct json_object *payload_obj = NULL, *platform_obj = NULL;
-
-    payload_obj = json_tokener_parse(payload);
-    if (payload_obj == NULL) {
-        printf("payload is null\r\n");
-        return NULL;
-    }
-
-    json_object_object_get_ex(payload_obj, "platform", &platform_obj);
-    json_object_object_add(root_obj, "platform", platform_obj);
-    json_object_get(platform_obj);
-    json_object_to_file_ext("./app.json", root_obj, JSON_C_TO_STRING_PRETTY);
-    sync();
-    json_object_object_add(payload_obj, "state", json_object_new_string("success"));
-
-    return payload_obj;
-}
-
-struct json_object* del_devices_json(char* payload)
-{
-    struct json_object *payload_obj = NULL, *item_obj = NULL, *devices_obj = NULL, *device_id_obj = NULL,
-                       *device_name_obj = NULL, *device_addr_obj = NULL, *module_id_obj = NULL;
-    char *device_id_str = NULL, *device_name_str = NULL, *device_addr_str = NULL, *module_id_str = NULL;
-    int len = 0, index = 0;
-
-    payload_obj = json_tokener_parse(payload);
-    if (payload_obj == NULL) {
-        printf("payload is null\r\n");
-        return NULL;
-    }
-
-    json_object_object_get_ex(payload_obj, "devices", &devices_obj);
-    len = json_object_array_length(devices_obj);
-    for (index = 0; index < len; index++) {
-        item_obj = json_object_array_get_idx(devices_obj, index);
-        json_object_object_get_ex(item_obj, "device_id", &device_id_obj);
-        device_id_str = json_object_get_string(device_id_obj);
-
-        pthread_mutex_lock(&mx_db);
-        delete_device_by_device_id(device_id_str);
-        pthread_mutex_unlock(&mx_db);
-    }
-
-    json_object_object_add(payload_obj, "state", json_object_new_string("success"));
-
-    return payload_obj;
-}
-
-struct json_object* add_devices_json(char* payload)
-{
-    struct json_object *payload_obj = NULL, *item_obj = NULL, *devices_obj = NULL, *device_id_obj = NULL,
-                       *device_name_obj = NULL, *device_addr_obj = NULL, *application_id_obj = NULL;
-    char *device_id_str = NULL, *device_name_str = NULL, *device_addr_str = NULL, *application_id_str = NULL;
-    int len = 0, index = 0;
-    int ret = 0;
-
-    payload_obj = json_tokener_parse(payload);
-    if (payload_obj == NULL) {
-        printf("payload is null\r\n");
-        return NULL;
-    }
-
-    json_object_object_get_ex(payload_obj, "devices", &devices_obj);
-    len = json_object_array_length(devices_obj);
-    for (index = 0; index < len; index++) {
-        item_obj = json_object_array_get_idx(devices_obj, index);
-        json_object_object_get_ex(item_obj, "device_id", &device_id_obj);
-        device_id_str = json_object_get_string(device_id_obj);
-        json_object_object_get_ex(item_obj, "device_name", &device_name_obj);
-        device_name_str = json_object_get_string(device_name_obj);
-        json_object_object_get_ex(item_obj, "device_addr", &device_addr_obj);
-        device_addr_str = json_object_get_string(device_addr_obj);
-        json_object_object_get_ex(item_obj, "application_id", &application_id_obj);
-        application_id_str = json_object_get_string(application_id_obj);
-
-        pthread_mutex_lock(&mx_db);
-        ret = insert_device_item(tolower(device_id_str), tolower(device_name_str), atoi(device_addr_str),
-                                 tolower(application_id_str));
-        pthread_mutex_unlock(&mx_db);
-    }
-
-    if (ret == 0)
-        json_object_object_add(payload_obj, "state", json_object_new_string("success"));
-    else
-        json_object_object_add(payload_obj, "state", json_object_new_string("fail"));
-
-    return payload_obj;
-}
-
-// req:get/devices/none/http
-// rsp:ack/get/device/none/http
-void mosq_http_json_message_callback(struct mosquitto* mosq, void* obj, const struct mosquitto_message* msg)
-{
-    struct json_object* rsp_obj = NULL;
-    char** topics;
-    int topic_count;
-    char pub_topic[200];
-
-    mosquitto_sub_topic_tokenise(msg->topic, &topics, &topic_count);
-    if (strncmp(topics[0], "get", STR_MAX_LEN(topics[0], "get")) == 0) {
-        if (strncmp(topics[1], "system", STR_MAX_LEN(topics[1], "system")) == 0) {
-            pthread_mutex_lock(&root_lock);
-            rsp_obj = get_system_json();
-            pthread_mutex_unlock(&root_lock);
-
-            if (rsp_obj != NULL) {
-                printf("get system rsp_obj:%s\r\n", json_object_to_json_string(rsp_obj));
-            }
-
-        } else if (strncmp(topics[1], "platform", STR_MAX_LEN(topics[1], "platform")) == 0) {
-            pthread_mutex_lock(&root_lock);
-            rsp_obj = get_platform_json();
-            pthread_mutex_unlock(&root_lock);
-
-            if (rsp_obj != NULL) {
-                printf("get platform rsp_obj:%s\r\n", json_object_to_json_string(rsp_obj));
-            }
-        } else if (strncmp(topics[1], "user", STR_MAX_LEN(topics[1], "user")) == 0) {
-            pthread_mutex_lock(&root_lock);
-            rsp_obj = get_user_json();
-            pthread_mutex_unlock(&root_lock);
-
-            if (rsp_obj != NULL) {
-                printf("get user rsp_obj:%s\r\n", json_object_to_json_string(rsp_obj));
-            }
-        } else if (strncmp(topics[1], "devices", STR_MAX_LEN(topics[1], "devices")) == 0) {
-            pthread_mutex_lock(&root_lock);
-            rsp_obj = get_devices_json();
-            pthread_mutex_unlock(&root_lock);
-
-            if (rsp_obj != NULL) {
-                printf("get devices rsp_obj:%s\r\n", json_object_to_json_string(rsp_obj));
-            }
-        }
-    } else if (strncmp(topics[0], "set", STR_MAX_LEN(topics[0], "set")) == 0) {
-        if (strncmp(topics[1], "platform", STR_MAX_LEN(topics[1], "platform")) == 0) {
-            pthread_mutex_lock(&root_lock);
-            rsp_obj = set_platform_json(msg->payload);
-            pthread_mutex_unlock(&root_lock);
-
-            if (rsp_obj != NULL) {
-                printf("set platform rsp_obj:%s\r\n", json_object_to_json_string(rsp_obj));
-            }
-        } else if (strncmp(topics[1], "devices", STR_MAX_LEN(topics[1], "devices")) == 0) {
-            pthread_mutex_lock(&root_lock);
-            rsp_obj = set_devices_json(msg->payload);
-            pthread_mutex_unlock(&root_lock);
-
-            if (rsp_obj != NULL) {
-                printf("set devices rsp_obj:%s\r\n", json_object_to_json_string(rsp_obj));
-            }
-        }
-    } else if (strncmp(topics[0], "del", STR_MAX_LEN(topics[0], "del")) == 0) {
-        if (strncmp(topics[1], "devices", STR_MAX_LEN(topics[1], "devices")) == 0) {
-            pthread_mutex_lock(&root_lock);
-            rsp_obj = del_devices_json(msg->payload);
-            pthread_mutex_unlock(&root_lock);
-
-            if (rsp_obj != NULL) {
-                printf("del devices rsp_obj:%s\r\n", json_object_to_json_string(rsp_obj));
-            }
-        }
-    } else if (strncmp(topics[0], "add", STR_MAX_LEN(topics[0], "add")) == 0) {
-        if (strncmp(topics[1], "devices", STR_MAX_LEN(topics[1], "devices")) == 0) {
-            pthread_mutex_lock(&root_lock);
-            rsp_obj = add_devices_json(msg->payload);
-            pthread_mutex_unlock(&root_lock);
-            if (rsp_obj != NULL) {
-                printf("add devices rsp_obj:%s\r\n", json_object_to_json_string(rsp_obj));
-            }
-        }
-    }
-
-    if (rsp_obj != NULL) {
-        sprintf(pub_topic, "ack/%s/%s/%s/%s", topics[0], topics[1], topics[2], topics[3]);
-        mosquitto_publish(mosq, NULL, pub_topic, strlen(json_object_to_json_string(rsp_obj)),
-                          json_object_to_json_string(rsp_obj), 1, false);
-        json_object_put(rsp_obj);
-    }
-
-    mosquitto_sub_topic_tokens_free(&topics, topic_count);
-
-    printf("mosq_http_json_message_callback\r\n");
-}
-
-void mosq_http_json_subscribe_callback(struct mosquitto* mosq,
-                                       void* obj,
-                                       int mid,
-                                       int qos_count,
-                                       const int* granted_qos)
-{
-    printf("http_json_subscribe_callback set\r\n");
-}
-
-// req:get/devices/none/http
-// rsp:ack/get/device/none/http
-void http_json_process_thread(void)
-{
-    char pub_topic[200];
-    char id[50];
-
-    snprintf(id, 50, "http_json_%d", getpid());
-    mosq_http = mosquitto_new(id, true, NULL);
-    mosquitto_connect_callback_set(mosq_http, mosq_http_connect_callback);
-    mosquitto_disconnect_callback_set(mosq_http, mosq_http_disconnect_callback);
-    mosquitto_message_callback_set(mosq_http, mosq_http_json_message_callback);
-    mosquitto_subscribe_callback_set(mosq_http, mosq_http_json_subscribe_callback);
-    mosquitto_connect(mosq_http, "localhost", 1883, 600);
-    // mosquitto_username_pw_set(mosq_http,"leo_mqtt", "leo_mqtt@");
-    mosquitto_subscribe(mosq_http, NULL, "+/+/+/http", 1);
-
-    while (!exit_sig && !quit_sig) {
-        if (mosquitto_loop(mosq_http, 100, 1)) {
-            mosquitto_reconnect(mosq_http);
-            sleep(10);
-        }
-
-        usleep(500000);
-    }
-
-    printf("http_json_process_thread exit\r\n");
-}
-
-int get_system_status()
-{
-    char buf[200];
-
-    struct json_object* system_obj = NULL;
-
-    json_object_object_get_ex(root_obj, "system", &system_obj);
-
-    memset(buf, '\0', 200);
-    exec_cmd(GET_WAN_MACADDR, buf);
-    // printf("WAN-ADDR:%s\r\n",buf);
-
-    json_object_object_add(system_obj, "wan_mac", json_object_new_string(buf));
-
-    memset(buf, '\0', 200);
-    exec_cmd(GET_WAN_STATE, buf);
-    // printf("WAN-STTE:%s\r\n",buf);
-    if (strncmp(buf, "up", STR_MAX_LEN("up", buf)) == 0) {
-        json_object_object_add(system_obj, "ethernet_wan", json_object_new_string("连接"));
-    } else {
-        json_object_object_add(system_obj, "ethernet_wan", json_object_new_string("断开"));
-    }
-
-    memset(buf, '\0', 200);
-    exec_cmd(GET_LAN_MACADDR, buf);
-    // printf("LAN-ADDR:%s\r\n",buf);
-    json_object_object_add(system_obj, "lan_mac", json_object_new_string(buf));
-
-    memset(buf, '\0', 200);
-    exec_cmd(GET_LAN_STATE, buf);
-    // printf("LAN-STATE:%s\r\n",buf);
-    if (strncmp(buf, "up", STR_MAX_LEN("up", buf)) == 0) {
-        json_object_object_add(system_obj, "ethernet_lan", json_object_new_string("连接"));
-    } else {
-        json_object_object_add(system_obj, "ethernet_lan", json_object_new_string("断开"));
-    }
-
-    memset(buf, '\0', 200);
-    exec_cmd(GET_LTE_MACADDR, buf);
-    // printf("LTE-ADDR:%s\r\n",buf);
-    json_object_object_add(system_obj, "lte_mac", json_object_new_string(buf));
-
-    memset(buf, '\0', 200);
-    exec_cmd(GET_LTE_STATE, buf);
-    // printf("LTE-STATE:%s\r\n",buf);
-    if (strncmp(buf, "up", STR_MAX_LEN("up", buf)) == 0) {
-        json_object_object_add(system_obj, "lte_status", json_object_new_string("连接"));
-    } else {
-        json_object_object_add(system_obj, "lte_status", json_object_new_string("断开"));
-    }
-
-    memset(buf, '\0', 200);
-    exec_cmd(GET_TOTAL_MEM, buf);
-    // printf("TOTAL-MEM:%s\r\n",buf);
-    json_object_object_add(system_obj, "total_memory", json_object_new_string(buf));
-
-    memset(buf, '\0', 200);
-    exec_cmd(GET_USED_MEM, buf);
-    // printf("USED-MEM:%s\r\n",buf);
-    json_object_object_add(system_obj, "used_memory", json_object_new_string(buf));
-
-    memset(buf, '\0', 200);
-    // exec_cmd(GET_TOTAL_FLASH, buf);
-    json_object_object_add(system_obj, "total_flash", json_object_new_string("4096"));
-
-    memset(buf, '\0', 200);
-    // exec_cmd(GET_USED_FLASH, buf);
-    json_object_object_add(system_obj, "used_flash", json_object_new_string("361"));
-
-    memset(buf, '\0', 200);
-    exec_cmd(GET_NOWTIME, buf);
-    json_object_object_add(system_obj, "boot_time", json_object_new_string(buf));
-}
-
-void mosq_up_mqtt_connect_callback(struct mosquitto* mosq, void* obj, int rc)
-{
-    printf("mosq_up_mqtt_connect_callback set\r\n");
-}
-
-void mosq_up_mqtt_disconnect_callback(struct mosquitto* mosq, void* obj, int result)
-{
-    printf("mosq_up_mqtt_disconnect_callback set\r\n");
-}
-
-void mosq_up_mqtt_message_callback(struct mosquitto* mosq, void* obj, const struct mosquitto_message* msg)
-{
-    struct json_object *payload_obj = NULL, *devEUI_obj = NULL, *object_obj = NULL;
-    char* devEUI_str = NULL;
-
-    payload_obj = json_tokener_parse(msg->payload);
-    if (payload_obj == NULL)
-        goto _exit_0;
-
-    json_object_object_get_ex(payload_obj, "devEUI", &devEUI_obj);
-    devEUI_str = json_object_get_string(devEUI_obj);
-    json_object_object_get_ex(payload_obj, "object", &object_obj);
-    if (object_obj == NULL || object_obj == "") {
-        goto _exit_0;
-    }
-
-    json_object_object_foreach(object_obj, key, val)
-    {
-        printf("key:%s --- value:%s   \r\n", key, json_object_to_json_string(val));
-        update_attrtab_item_by_device_id(devEUI_str, key, json_object_to_json_string(val));
-    }
-
-    json_object_put(payload_obj);
-
-_exit_0:
-    printf("mqtt_process_message_callback\r\n");
-}
-
-void mosq_up_mqtt_subscribe_callback(struct mosquitto* mosq, void* obj, int mid, int qos_count, const int* granted_qos)
-{
-    printf("mosq_up_mqtt_subscribe_callback set\r\n");
-}
-
-/*
-uplink topic: application/+/device/+/event/up
-
-{"applicationID":"1","applicationName":"leo","deviceName":"1000000000000001","deviceProfileName":"leo_otaa_c","deviceProfileID":"172bf053-caf5-49d1-8bdb-5d989aef9ec1","devEUI":"1000000000000001","rxInfo":[{"gatewayID":"aa555a0000000000","uplinkID":"312238b9-ffc3-4a4d-914d-e8ace8ffbae1","name":"AA555A0000000000","rssi":-93,"loRaSNR":8.2,"location":{"latitude":0,"longitude":0,"altitude":0}}],"txInfo":{"frequency":476100000,"dr":2},"adr":false,"fCnt":3,"fPort":2,"data":"MTIzNDU2","object":{"reg_0001":49,"reg_0002":50}}
-
-dwlink topic: application/+/device/+/command/down
-*/
-
-void mqtt_modbus_uplink_process_thread(void* argc)
-{
-    char sub_topic[200];
-    char id[50];
-    int mqtt_index = *((int*)argc);
-
-    printf("mqtt_index_uplink:%d \r\n", mqtt_index);
-    snprintf(id, 50, "mqtt_modbus_up_%d", mqtt_index);
-    printf("mqtt_uplink_id:%s\r\n", id);
-    mosq_up_mqtt[mqtt_index] = mosquitto_new(id, true, NULL);
-    mosquitto_connect_callback_set(mosq_up_mqtt[mqtt_index], mosq_up_mqtt_connect_callback);
-    mosquitto_disconnect_callback_set(mosq_up_mqtt[mqtt_index], mosq_up_mqtt_disconnect_callback);
-    mosquitto_message_callback_set(mosq_up_mqtt[mqtt_index], mosq_up_mqtt_message_callback);
-    mosquitto_subscribe_callback_set(mosq_up_mqtt[mqtt_index], mosq_up_mqtt_subscribe_callback);
-    mosquitto_connect(mosq_up_mqtt[mqtt_index], "localhost", 1883, 600);
-    sprintf(sub_topic, "application/%d/device/+/event/up", mqtt_index + 1);
-    mosquitto_username_pw_set(mosq_up_mqtt[mqtt_index], "leo_mqtt", "leo_mqtt@");
-    mosquitto_subscribe(mosq_up_mqtt[mqtt_index], NULL, sub_topic, 0);
-
-    while (!exit_sig && !quit_sig) {
-        if (mosquitto_loop(mosq_up_mqtt[mqtt_index], 100, 1)) {
-            mosquitto_reconnect(mosq_up_mqtt[mqtt_index]);
-            sleep(10);
-        }
-        usleep(500000);
-    }
-
-    mosquitto_disconnect(mosq_up_mqtt[mqtt_index]);
-    mosquitto_destroy(mosq_up_mqtt[mqtt_index]);
-
-    printf("mqtt_modbus_uplink_process_thread exit\r\n");
-}
-
-void mosq_dw_mqtt_connect_callback(struct mosquitto* mosq, void* obj, int rc)
-{
-    printf("mosq_dw_mqtt_connect_callback set\r\n");
-}
-void mosq_dw_mqtt_disconnect_callback(struct mosquitto* mosq, void* obj, int result)
-{
-    printf("mosq_dw_mqtt_disconnect_callback set\r\n");
-}
-void mosq_dw_mqtt_message_callback(struct mosquitto* mosq, void* obj, const struct mosquitto_message* msg)
-{
-    printf("mosq_dw_mqtt_message_callback\r\n");
-}
-void mosq_dw_mqtt_subscribe_callback(struct mosquitto* mosq, void* obj, int mid, int qos_count, const int* granted_qos)
-{
-    printf("mosq_dw_mqtt_subscribe_callback set\r\n");
-}
-
-/*
-dwlink topic: application/+/device/+/command/down
-*/
-void mqtt_modbus_dwlink_process_thread(void* argc)
-{
-    uint8_t rx_buffer[255] = {0};
-    uint8_t tx_buffer[255] = {0};
-    int ret = 0, i = 0, j = 0, rx_buffer_len = 0, tx_buffer_len = 0;
-    char attr_addr_str[9], attr_value_str[5];
-    uint16_t attr_value = 0, attr_num = 0, attr_addr = 0, crc = 0;
-    uint8_t device_addr = 0, device_funcode = 0;
-    uint8_t device_id[17];
-    char pub_topic[200];
-    char id[50];
-
-    uint8_t dw_buffer[255];
-    uint8_t dw_buffer_len = 0;
-
-    int mqtt_index = *((int*)argc);
-
-    printf("dwmqtt_index:%d\r\n", mqtt_index);
-    snprintf(id, 50, "mqtt_modbus_dw_%d", mqtt_index);
-    printf("dwid:%s\r\n", id);
-    mosq_dw_mqtt[mqtt_index] = mosquitto_new(id, true, NULL);
-    mosquitto_connect_callback_set(mosq_dw_mqtt[mqtt_index], mosq_dw_mqtt_connect_callback);
-    mosquitto_disconnect_callback_set(mosq_dw_mqtt[mqtt_index], mosq_dw_mqtt_disconnect_callback);
-    mosquitto_message_callback_set(mosq_dw_mqtt[mqtt_index], mosq_dw_mqtt_message_callback);
-    mosquitto_subscribe_callback_set(mosq_dw_mqtt[mqtt_index], mosq_dw_mqtt_subscribe_callback);
-    mosquitto_username_pw_set(mosq_dw_mqtt[mqtt_index], "leo_mqtt", "leo_mqtt@");
-    mosquitto_connect(mosq_dw_mqtt[mqtt_index], "localhost", 1883, 600);
-
-    while (!exit_sig && !quit_sig) {
-        ret = read(vcom_fd[mqtt_index], rx_buffer, 255);
-        if (ret > 0) {
-            rx_buffer_len = ret;
-            printf("info: rx modbus data -->");
-            for (i = 0; i < rx_buffer_len; i++)
-                printf("0x%x ", rx_buffer[i]);
-            printf("\r\n");
-            crc = App_Crc16(rx_buffer, rx_buffer_len - 2);
-            if (crc != (*(rx_buffer + rx_buffer_len - 2) << 8 | *(rx_buffer + rx_buffer_len - 1))) {
-                printf("rx modbus crc failed \r\n");
-                tcflush(vcom_fd[mqtt_index], TCIOFLUSH);
-                continue;
-            }
-
-            device_addr = rx_buffer[0];
-            device_funcode = rx_buffer[1];
-            tx_buffer[0] = device_addr;
-            tx_buffer[1] = device_funcode;
-
-            switch (device_funcode) {
-                case 0x03: {
-                    attr_addr = rx_buffer[2] << 8 | rx_buffer[3];
-                    attr_num = rx_buffer[4] << 8 | rx_buffer[5];
-                    tx_buffer[2] = attr_num * 2;
-                    for (j = 0; j < attr_num; j++) {
-                        sprintf(attr_addr_str, "reg_%04x", (attr_addr + j));
-                        attr_addr_str[8] = '\0';
-                        pthread_mutex_lock(&mx_db);
-                        printf("attr_id:%s --device_addr:%d --appid:%d\r\n", attr_addr_str, device_addr,
-                               mqtt_index + 1);
-                        select_attr_by_device_addr(&attr_value, device_addr, attr_addr_str, mqtt_index + 1);
-                        pthread_mutex_unlock(&mx_db);
-                        tx_buffer[3 + 2 * j] = (attr_value >> 8 & 0xff);
-                        tx_buffer[3 + 2 * j + 1] = (attr_value >> 0 & 0xff);
-                    }
-
-                    crc = App_Crc16(tx_buffer, 3 + attr_num * 2);
-                    tx_buffer[3 + 2 * attr_num] = (crc >> 8 & 0xff);
-                    tx_buffer[3 + 2 * attr_num + 1] = (crc >> 0 & 0xff);
-                    tx_buffer_len = 3 + 2 * attr_num + 2;
-
-                    break;
-                }
-                case 0x06: {
-                    attr_addr = rx_buffer[2] << 8 | rx_buffer[3];
-                    attr_value = rx_buffer[4] << 8 | rx_buffer[5];
-                    sprintf(attr_addr_str, "reg_%04x", attr_addr);
-                    attr_addr_str[8] = '\0';
-                    sprintf(attr_value_str, "%d", attr_value);
-                    attr_value_str[4] = '\0';
-                    tx_buffer[2] = (attr_addr >> 8 & 0xff);
-                    tx_buffer[3] = (attr_addr >> 0 & 0xff);
-                    tx_buffer[4] = (attr_value >> 8 & 0xff);
-                    tx_buffer[5] = (attr_value >> 0 & 0xff);
-                    crc = App_Crc16(tx_buffer, 6);
-                    tx_buffer[6] = (crc >> 8 & 0xff);
-                    tx_buffer[7] = (crc >> 0 & 0xff);
-                    tx_buffer_len = 8;
-
-                    if (select_device_id_by_device_addr(device_addr, device_id, mqtt_index) == 1) {
-                        printf("attr_addr:%s --- attr-value:%s \r\n", attr_addr_str, attr_value_str);
-
-                        // update sqllite
-                        pthread_mutex_lock(&mx_db);
-                        update_tab_item_by_device_addr(device_addr, attr_addr_str, attr_value_str, mqtt_index);
-                        pthread_mutex_unlock(&mx_db);
-
-                        dwlink_packet_process(device_id, dw_buffer, &dw_buffer_len, attr_addr_str, attr_value_str);
-
-                        // publish dwlink/devices/id/mqtt
-                        sprintf(pub_topic, "application/%d/device/%s/command/down", mqtt_index + 1, device_id);
-                        mosquitto_publish(mosq_dw_mqtt[mqtt_index], NULL, pub_topic, dw_buffer_len, dw_buffer, 1,
-                                          false);
-
-                        printf("publish:\r\n");
-                        for (i = 0; i < dw_buffer_len; i++)
-                            printf("%02x ", dw_buffer[i]);
-                        printf("\r\n");
-                    }
-                    break;
-                }
-                default: {
-                    tx_buffer[0] = device_addr;
-                    tx_buffer[1] = 0x83;
-                    tx_buffer[2] = 0x02;
-                    tx_buffer_len = 3;
-                    break;
-                }
-            }
-
-            write(vcom_fd[mqtt_index], tx_buffer, tx_buffer_len);
-            printf("info: tx modbus data -->");
-            for (i = 0; i < tx_buffer_len; i++)
-                printf("0x%x ", tx_buffer[i]);
-            printf("\r\n");
-
-        } else if (ret < 0) {
-            continue;
-        }
-
-        if (mosquitto_loop(mosq_dw_mqtt[mqtt_index], 100, 1)) {
-            mosquitto_reconnect(mosq_dw_mqtt[mqtt_index]);
-            sleep(10);
-        }
-
-        usleep(500000);
-    }
-
-    mosquitto_disconnect(mosq_dw_mqtt[mqtt_index]);
-    mosquitto_destroy(mosq_dw_mqtt[mqtt_index]);
-
-    printf("mqtt_modbus_dwlink_process_thread exit\r\n");
-}
-
-int vcom_init()
-{
-    char* dev[] = {"/dev/tty10", "/dev/tty12", "/dev/tty14", "/dev/tty16"};
-    int i = 0;
-
-    for (i = 0; i < MAX_VCOM; i++) {
-        vcom_fd[i] = open(dev[i], O_RDWR | O_NOCTTY | O_NDELAY);  // open("/dev/tttyS0",O_RDWR | O_NOCTTY);  //O_NDELAY
-        if (vcom_fd[i] == -1) {
-            printf("can't open :%s \r\n", dev[i]);
-            return -1;
-        }
-    }
-
-    printf("vcom fd open success\r\n");
-
-    return 1;
-}
-
-int main(int argc, char* argv[])
-{
-    pthread_t mqtt_modbus_uplink_tid[MAX_VCOM], mqtt_modbus_dwlink_tid[MAX_VCOM], http_json_tid;
-    int err = 0, i = 0;
-    int thread_index[MAX_VCOM] = {0, 1, 2, 3};
-    struct sigaction sigact;
-
-    mosquitto_lib_init();
-    init_device_db();
-    pthread_mutex_init(&root_lock, NULL);
-
-    config_init();
-
-    vcom_init();
-
-    for (i = 0; i < MAX_VCOM; i++) {
-        printf("mqtt modbus vcom_%d uplink thread\r\n", i);
-        err = pthread_create(&mqtt_modbus_uplink_tid[i], NULL, (void* (*)(void*))mqtt_modbus_uplink_process_thread,
-                             (void*)(&thread_index[i]));
-        if (err != 0) {
-            printf("create mqtt modbus vcom_%d uplink thread failed\r\n", i);
-            exit(EXIT_FAILURE);
-        }
-
-        printf("mqtt modbus vcom_%d dwlink thread\r\n", i);
-        err = pthread_create(&mqtt_modbus_dwlink_tid[i], NULL, (void* (*)(void*))mqtt_modbus_dwlink_process_thread,
-                             (void*)(&thread_index[i]));
-        if (err != 0) {
-            printf("create mqtt modbus vcomd_%d dwlink thread failed\r\n", i);
-            exit(EXIT_FAILURE);
-        }
-    }
-
-    // web
-    printf("http json process thread\r\n");
-    err = pthread_create(&http_json_tid, NULL, (void* (*)(void*))http_json_process_thread, NULL);
-    if (err != 0) {
-        printf("create http json thread failed\r\n");
-        exit(EXIT_FAILURE);
-    }
-
-    sigemptyset(&sigact.sa_mask);
-    sigact.sa_flags = 0;
-    sigact.sa_handler = sig_handler;
-    sigaction(SIGQUIT, &sigact, NULL);
-    sigaction(SIGINT, &sigact, NULL);
-    sigaction(SIGTERM, &sigact, NULL);
-
-    while (!exit_sig && !quit_sig) {
-        pthread_mutex_lock(&root_lock);
-        get_system_status();
-        pthread_mutex_unlock(&root_lock);
-        sleep(120);
-    }
-
-    for (i = 0; i < MAX_VCOM; i++) {
-        pthread_join(mqtt_modbus_uplink_tid[i], NULL);
-        pthread_join(mqtt_modbus_dwlink_tid[i], NULL);
-    }
-
-    pthread_join(http_json_tid, NULL);
-    if (exit_sig || quit_sig) {
-        // shutdown(net_sock, SHUT_RDWR);
-    }
-
-    pthread_mutex_destroy(&root_lock);
-    mosquitto_lib_cleanup();
-    exit(EXIT_SUCCESS);
-}

+ 0 - 155
apps/common.c

@@ -1,155 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdbool.h>
-#include <signal.h>
-#include <unistd.h>
-#include "common.h"
-
-
-static const uint8_t table_crc_hi[] = {
-    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
-    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
-    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
-    0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
-    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
-    0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
-    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
-    0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
-    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
-    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
-    0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
-    0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
-    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
-    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
-    0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
-    0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
-    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
-    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
-    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
-    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
-    0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
-    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
-    0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
-    0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
-    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
-    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
-};
-
-static const uint8_t table_crc_lo[] = {
-    0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
-    0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
-    0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
-    0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
-    0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
-    0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
-    0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
-    0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
-    0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
-    0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
-    0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
-    0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
-    0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
-    0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
-    0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
-    0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
-    0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
-    0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
-    0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
-    0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
-    0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
-    0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
-    0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
-    0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
-    0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
-    0x43, 0x83, 0x41, 0x81, 0x80, 0x40
-};
-
-
-uint16_t App_Crc16(uint8_t *buffer, uint16_t buffer_length)
-{
-    uint8_t crc_hi = 0xFF; 
-    uint8_t crc_lo = 0xFF; 
-    unsigned int i; 
-
-    while (buffer_length--) {
-        i = crc_hi ^ *buffer++;
-        crc_hi = crc_lo ^ table_crc_hi[i];
-        crc_lo = table_crc_lo[i];
-    }
-
-    return (crc_hi << 8 | crc_lo);
-}
-
-
-void timestamp_get(char *timestamp)
-{	
-	time_t t;
-
-	t = time(NULL);  
-	sprintf(timestamp,"%lld",((long long)t)*1000);
-}
-
-
-uint8_t CharToHex(uint8_t ch)
-{
-    uint8_t val = (uint8_t)-1;
-
-    if ((ch >= '0') && (ch <='9')) 
-	{
-        val = ch - '0';
-    }
-    else if ((ch >= 'A') && (ch <='F')) 
-	{
-        val = ch - 'A' + 10;
-    }
-    else if ((ch >= 'a') && (ch <='f')) 
-	{
-        val = ch - 'a' + 10;
-    }
-    return val;
-}
-
-
-
-void HexToString(char *des, uint8_t *src , uint16_t len)
-{
-    uint16_t i;
-    uint8_t *p;
-    char tmp[4];
-
-    p = src;
-    for(i=0; i<len; i++) 
-	{
-        memset((void *)tmp, 0, sizeof(tmp));
-        sprintf(tmp, "%02x", *p++);
-        strcat(des, tmp);
-    }
-}
-
-
-int StringToHex(uint8_t *pbDest, const char *pbSrc, uint16_t srcLen)
-{
-    uint16_t i=0,j=0;
-    uint8_t chl,chh;
-
-    memset(pbDest, 0, srcLen/2);
-    while (i < srcLen) 
-	{
-        if ((i+1) == srcLen) 
-		{  
-            chl = CharToHex(pbSrc[i]);
-            pbDest[j] = chl<<4;
-            j ++;
-        }
-		else
-		{
-            chh = CharToHex(pbSrc[i]);
-            chl = CharToHex(pbSrc[i+1]);
-            pbDest[j] = (chh << 4) | chl;
-            j ++;
-        }
-        i = i+2;
-    }
-    return j;
-}

+ 0 - 21
apps/common.h

@@ -1,21 +0,0 @@
-#ifndef __COMMON_H__
-#define __COMMON_H__
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <signal.h>
-#include <unistd.h>
-#include <sys/types.h>
-
-#define STR_MAX_LEN(str1,str2)	((strlen(str1)>strlen(str2))?strlen(str1):strlen(str2))
-
-void timestamp_get(char *timestamp);
-
-uint16_t App_Crc16(uint8_t *buffer, uint16_t buffer_length);
-
-void HexToString(char *des, uint8_t *src , uint16_t len);
-int StringToHex(uint8_t *pbDest, const char *pbSrc, uint16_t srcLen);
-
-#endif

BIN
apps/device_db.db


+ 0 - 426
apps/sql_api.c

@@ -1,426 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include "sqlite3.h"
-#include "sql_api.h"
-
-int callback_db(void *ptr, int count)
-{
-    usleep(500000);
-    return -1;
-}
-
-int do_cmd_str(char* sql)
-{
-	int rc;
-	sqlite3* db;
-	char *errmsg = NULL;
-
-	rc = sqlite3_open(SQL_NAME, &db);	
-	if ( rc != SQLITE_OK )	
-	{		
-		printf("ERROR: open sqlite %s \r\n",sqlite3_errmsg(db));		
-		sqlite3_close(db);		
-		return -1;
-	}
-	
-	sqlite3_busy_handler(db, callback_db, (void*)db);
-	rc = sqlite3_exec(db,sql,NULL,NULL,&errmsg);
-	if (rc != SQLITE_OK )
-	{
-		printf("ERROR: %s-%s \r\n", sql, errmsg);
-		sqlite3_close(db);
-		return -1;
-	}
-	
-	sqlite3_close(db);
-	return 0;
-}
-
-//初始化设备数据库
-int init_device_db(void)
-{
-	char cmd[MAX_TXET_LEN];
-	sprintf(cmd,"%s","create table if not exists device_db(device_id text primary key , device_name text, device_addr integer unique, application_id text);");
-	if(do_cmd_str(cmd) != 0)
-		return -1;
-	return 0;
-}
-
-//插入设备到数据库
-int insert_device_item(char*device_id,char*device_name,uint8_t device_addr, char* application_id)
-{
-	char cmd[MAX_TXET_LEN];
-	sprintf(cmd,"insert into device_db(device_id,device_name,device_addr,application_id) values('%s','%s',%d,'%s');", device_id,device_name,device_addr,application_id);
-	if(do_cmd_str(cmd)!=0)
-		return -1;
-	return 0;
-}
-
-
-//更新设备到数据库
-int update_device_by_device_id(char*device_id,char*device_name,uint8_t device_addr,char *application_id)
-{
-	char cmd[MAX_TXET_LEN];
-	sprintf(cmd,"update device_db set device_id = '%s',device_name = '%s', device_addr = %d, application_id = '%s' where device_id = '%s';", device_id,device_name,device_addr,application_id,device_id);
-	if(do_cmd_str(cmd)!=0)
-		return -1;
-	return 0;
-}
-
-//删除设备通过设备id
-int delete_device_by_device_id( char*device_id )
-{
-	char cmd[MAX_TXET_LEN];
-	sprintf(cmd,"delete from device_db where device_id = '%s';", device_id);
-	if(do_cmd_str(cmd)!=0)
-		return -1;
-	return 0;
-}
-
-
-int update_attrtab_item_by_device_id(char*device_id, char*attr_id, char*attr_value)
-{
-	char cmd[MAX_TXET_LEN];
-	int rc,nRow,nColumn,i=0;
-	sqlite3* db;
-	char **result=NULL, *errmsg = NULL;
-	
-	
-	rc = sqlite3_open(SQL_NAME, &db);	
-	if ( rc != SQLITE_OK )	
-	{		
-		printf("ERROR:open sqlite %s \r\n",sqlite3_errmsg(db));		
-		sqlite3_close(db);		
-		return -1;
-	}
-	
-	sprintf(cmd,"select * from device_db limit 0;");
-	rc = sqlite3_get_table(db,cmd,&result,&nRow,&nColumn,&errmsg);
-	if (rc != SQLITE_OK)
-	{
-		printf("ERROR: get table %s \r\n", errmsg);
-		sqlite3_close(db);
-		return -1;
-	}
-
-	for(i=0; i<nColumn ;i++)
-	{	
-		if(strcmp(attr_id, result[i])==0)
-			break;
-	}
-	
-	if( i == nColumn)
-	{
-		sprintf(cmd, "alter table device_db add column %s text", attr_id);
-		sqlite3_busy_handler(db, callback_db, (void*)db);
-		sqlite3_exec(db,cmd,NULL,NULL,&errmsg);
-		
-		sprintf(cmd, "update device_db set  %s = '%s' where device_id = '%s';", attr_id,attr_value,device_id);
-		sqlite3_busy_handler(db, callback_db, (void*)db);
-		sqlite3_exec(db,cmd,NULL,NULL,&errmsg);
-	}
-	else
-	{
-		sprintf(cmd, "update device_db set  %s = '%s' where device_id = '%s';", attr_id,attr_value,device_id);
-		sqlite3_busy_handler(db, callback_db, (void*)db);
-		sqlite3_exec(db,cmd,NULL,NULL,&errmsg);
-	}
-	
-	sqlite3_free_table(result);
-	sqlite3_close(db);
-	
-	return 1;	
-}
-
-
-
-//更新数据到数据库通过设备id 
-int update_tab_item_by_device_id(char*device_id,char *attr_id, char *attr_value)
-{
-	char cmd[MAX_TXET_LEN];
-	sprintf(cmd,"update device_db set %s = '%s' where device_id = '%s';", attr_id,attr_value,device_id);
-	if(do_cmd_str(cmd)!=0)
-		return -1;
-	return 0;
-}
-//更新数据到数据库通过设备地址
-int update_tab_item_by_device_addr(uint8_t device_addr,char *attr_id, char *attr_value, uint8_t application_id)
-{
-	char cmd[MAX_TXET_LEN];
-	sprintf(cmd,"update device_db set %s = '%s' where device_addr = %d and application_id = %d;", attr_id,attr_value,device_addr,application_id);
-	if(do_cmd_str(cmd)!=0)
-		return -1;
-	return 0;
-}
-
-//查询设备列表
-int select_all_device(struct json_object **rsp_obj)
-{
-	int rc,nRow,nColumn,i=0;
-	sqlite3* db;
-	char **result=NULL, *errmsg = NULL, cmd[MAX_TXET_LEN]={0};
-	struct json_object *device_obj =NULL, *device_array=NULL;
-	 
-	rc = sqlite3_open(SQL_NAME, &db);	
-	if ( rc != SQLITE_OK )	
-	{		
-		printf("ERROR:open sqlite %s \r\n",sqlite3_errmsg(db));		
-		sqlite3_close(db);		
-		return -1;
-	}
-
-	sprintf(cmd,"select device_id, device_name, device_addr, application_id from device_db;");
-	rc = sqlite3_get_table(db,cmd,&result,&nRow,&nColumn,&errmsg);
-	if (rc != SQLITE_OK)
-	{
-		printf("ERROR: get table %s \r\n", errmsg);
-		sqlite3_close(db);
-		return -1;
-	}
-
-	*rsp_obj = json_object_new_object();
-	if(*rsp_obj == NULL)
-	{
-		sqlite3_free_table(result);
-		sqlite3_close(db);
-		return -1;
-	}
-
-	device_array = json_object_new_array();
-	if(device_array == NULL)
-	{
-		sqlite3_free_table(result);
-		sqlite3_close(db);
-		json_object_put(*rsp_obj);
-		return -1;
-	}
-	
-
-	for(i=1; i<=nRow ;i++)
-	{	
-		device_obj = json_object_new_object();
-		json_object_object_add(device_obj, "device_id", json_object_new_string(result[i*nColumn+0]));
-		json_object_object_add(device_obj, "device_name", json_object_new_string(result[i*nColumn+1]));
-		json_object_object_add(device_obj, "device_addr", json_object_new_string(result[i*nColumn+2]));
-		json_object_object_add(device_obj, "application_id", json_object_new_string(result[i*nColumn+3]));
-		json_object_array_add(device_array, device_obj);
-		
-	}
-
-	json_object_object_add(*rsp_obj, "devices", device_array);
-	json_object_object_add(*rsp_obj, "state", json_object_new_string("success"));
-
-
-	sqlite3_free_table(result);
-	sqlite3_close(db);
-
-	return nRow;
-}
-
-int select_device_id_by_device_addr(uint8_t device_addr,uint8_t *device_id, uint8_t application_id)
-{
-	int rc,nRow,nColumn,i=0;
-	sqlite3* db;
-	char **result=NULL, *errmsg = NULL, cmd[MAX_TXET_LEN]={0};
-	 
-	rc = sqlite3_open(SQL_NAME, &db);	
-	if ( rc != SQLITE_OK )	
-	{		
-		printf("ERROR:open sqlite %s \r\n",sqlite3_errmsg(db));		
-		sqlite3_close(db);		
-		return -1;
-	}
-
-	sprintf(cmd,"select device_id from device_db where device_addr = %d and application_id = %d;", device_addr,application_id);
-	rc = sqlite3_get_table(db,cmd,&result,&nRow,&nColumn,&errmsg);
-	if (rc != SQLITE_OK)
-	{
-		printf("ERROR: get table %s \r\n", errmsg);
-		sqlite3_close(db);
-		return -1;
-	}
-
-
-	if(nRow == 0)
-	{
-		memset(device_id,'\0', 17);
-	}
-	else
-	{
-		memset(device_id,'\0', 17);
-		memcpy(device_id,result[1*nColumn+0],16);
-	}
-
-	sqlite3_free_table(result);
-	sqlite3_close(db);
-
-	return nRow;
-}
-
-//通过设备地址查询设备数据
-int select_attr_by_device_addr(uint16_t *buffer, uint8_t device_addr, char*attr_id, uint8_t application_id)
-{
-	int rc,nRow,nColumn,i=0;
-	sqlite3* db;
-	char **result=NULL, *errmsg = NULL, cmd[MAX_TXET_LEN]={0};
-	uint16_t value =0 ;
-	 
-	rc = sqlite3_open(SQL_NAME, &db);	
-	if ( rc != SQLITE_OK )	
-	{		
-		printf("ERROR:open sqlite %s \r\n",sqlite3_errmsg(db));		
-		sqlite3_close(db);		
-		return -1;
-	}
-
-	sprintf(cmd,"select %s from device_db where device_addr = %d and application_id = %d;", attr_id,device_addr,application_id);
-	rc = sqlite3_get_table(db,cmd,&result,&nRow,&nColumn,&errmsg);
-	if (rc != SQLITE_OK)
-	{
-		*buffer =0;
-		sqlite3_close(db);
-		return -1;
-	}
-
-	if(nRow == 0)
-	{
-	  	*buffer =0;
-	}
-	else
-	{
-		*buffer = atoi(result[1*nColumn+0]);
-	}
-	//sscanf(result[1*nColumn+0],"%04d",&value);
-	//*buffer = value;
-	//strtol(result[1*nColumn+0], buffer, 16);
-
-	sqlite3_free_table(result);
-	sqlite3_close(db);
-
-	return nRow;
-}
-
-#if 0
-//读取数据库
-int get_tab_item(int numofday)
-{
-	int rc,nRow,nColumn,i=0;
-	sqlite3* db;
-	char **result;
-	char *errmsg = NULL;
-	char cmd[512];
-
-	rc = sqlite3_open(SQL_NAME, &db);	
-	if ( rc != SQLITE_OK )	
-	{		
-		printf("ERROR:open sqlite %s \r\n",sqlite3_errmsg(db));		
-		sqlite3_close(db);		
-		return -1;
-	}
-
-	sprintf(cmd,"select * from log_db where date(logtime) between date('now','-%d day','localtime') and date('now','localtime');", numofday);
-
-	rc = sqlite3_get_table(db,cmd,&result,&nRow,&nColumn,&errmsg);
-	if (rc != SQLITE_OK)
-	{
-		printf("ERROR: get table %s \r\n", errmsg);
-		sqlite3_close(db);
-		return -1;
-	}
-
-	for(i=0;i<nRow;i++)
-	{
-		printf("%s %s %s %s %s\r\n",result[i*nColumn],result[i*nColumn+1],result[i*nColumn+2],result[i*nColumn+3],result[i*nColumn+4]);
-		
-	}
-
-	sqlite3_free_table(result);
-	sqlite3_close(db);
-
-	return 0;
-}
-
-#endif
-
-#if 0
-//删除30天前的日志
-int del_30d_item()
-{
-	char cmd[512];
-
-	sprintf(cmd,"%s","delete from log_db where date('now', '-30 day') >= date(logtime);");
-	if(do_cmd_str(cmd)!=0)
-		return -1;
-	return 0;
-}
-
-//用户写日志
-int log_write(char*type,char*level,char *log)
-{
-	insert_tab_item(type,level,log);
-}
-//用户读日志
-void log_read(struct json_object *root)
-{
-	get_tab_item(root);
-}
-
-#endif
-
-#if 0
-int main(void)
-{
-	uint16_t buffer16;
-	uint8_t tmp[5];
-	uint16_t attr_value;
-	uint8_t j=0;
-	uint8_t device_id[17];
-
-	init_device_db();
-	//insert_device_item("0102030405060708","test0",1, "lora");
-	//insert_device_item("0102030405060709","test1",2, "lora");
-	//insert_device_item("010203040506070a","test2",3, "lora");
-	
-	update_tab_item_by_device_id("0102030405060709","0000", "0");
-	update_tab_item_by_device_id("0102030405060709","0001", "1");
-	update_tab_item_by_device_id("0102030405060709","0002", "2");
-	update_tab_item_by_device_id("0102030405060709","0003", "3");
-
-	update_tab_item_by_device_addr(2, "0000", "8");
-	update_tab_item_by_device_addr(2, "0001", "8");
-	update_tab_item_by_device_addr(2, "0002", "8");
-	update_tab_item_by_device_addr(2, "0003", "8");
-
-	update_tab_item_by_device_addr(3, "0000", "8");
-
-	update_tab_item_by_device_addr(4, "0000", "8");
-
-	select_device_id_by_device_addr(4,device_id);
-	printf("addr:%d ---id:0x%s\r\n",4,device_id);
-
-	select_device_id_by_device_addr(2,device_id);
-	printf("addr:%d ---id:0x%s\r\n",2,device_id);
-
-
-	for(j=1; j<4; j++)
-	{ 
-		sprintf(tmp, "%04x",j);	
-		tmp[4]='\0';
-		printf("%s----",tmp);
-		printf("nrow=%d\r\n",select_attr_by_device_addr(&attr_value, 2, tmp));
-		printf("maddr:%d, attrid:%s, buffer16:%d \r\n",2, tmp, attr_value);
-	}
-
-	for(j=1; j<4; j++)
-	{ 
-		sprintf(tmp, "%04x",j);	
-		tmp[4]='\0';
-		printf("%s----",tmp);
-		printf("nrow=%d\r\n",select_attr_by_device_addr(&attr_value, 3, tmp));
-		printf("maddr:%d, attrid:%s, buffer16:%d \r\n",3, tmp, attr_value);
-	}
-	
-}
-#endif
-

+ 0 - 26
apps/sql_api.h

@@ -1,26 +0,0 @@
-#ifndef __SQL_API_H__
-#define __SQL_API_H__
-
-#include "json-c/json.h"
-#include "json-c/json_util.h"
-
-
-#define SQL_NAME	"./device_db.db"
-#define MAX_TXET_LEN	10240
-
-int init_device_db(void);
-int insert_device_item(char*device_id,char*device_name,uint8_t device_addr,char *application_id);
-int delete_device_by_device_id( char*device_id );
-int update_device_by_device_id(char*device_id,char*device_name,uint8_t device_addr,char *application_id);
-int update_tab_item_by_device_id(char*device_id,char *attr_id, char *attr_value);
-//int update_tab_item_by_device_addr(uint8_t device_addr,char *attr_id, char *attr_value);
-int update_tab_item_by_device_addr(uint8_t device_addr,char *attr_id, char *attr_value, uint8_t application_id);
-int select_all_device(struct json_object **rsp_obj);
-//int select_device_id_by_device_addr(uint8_t device_addr,uint8_t *device_id);
-int select_device_id_by_device_addr(uint8_t device_addr,uint8_t *device_id, uint8_t application_id);
-//int select_attr_by_device_addr(uint16_t *buffer, uint8_t device_addr, char*attr_id);
-int select_attr_by_device_addr(uint16_t *buffer, uint8_t device_addr, char*attr_id, uint8_t application_id);
-
-
-
-#endif

+ 0 - 1
dist/index.html

@@ -1 +0,0 @@
-<!DOCTYPE html><html><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><title>rtuweb</title><link href=/static/css/app.3d8d24b268d0726c1919f7c7f329e2d4.css rel=stylesheet></head><body><div id=app></div><script type=text/javascript src=/static/js/manifest.2ae2e69a05c33dfc65f8.js></script><script type=text/javascript src=/static/js/vendor.3ce127c54cf2044ee291.js></script><script type=text/javascript src=/static/js/app.6f0ac4c14391b3e0c8fe.js></script></body></html>

Rozdielové dáta súboru neboli zobrazené, pretože súbor je príliš veľký
+ 0 - 0
dist/static/css/app.3d8d24b268d0726c1919f7c7f329e2d4.css


Rozdielové dáta súboru neboli zobrazené, pretože súbor je príliš veľký
+ 0 - 0
dist/static/css/app.3d8d24b268d0726c1919f7c7f329e2d4.css.map


BIN
dist/static/fonts/element-icons.535877f.woff


BIN
dist/static/fonts/element-icons.732389d.ttf


BIN
dist/static/img/logo_bg.b20eb92.png


Rozdielové dáta súboru neboli zobrazené, pretože súbor je príliš veľký
+ 0 - 0
dist/static/js/app.6f0ac4c14391b3e0c8fe.js


Rozdielové dáta súboru neboli zobrazené, pretože súbor je príliš veľký
+ 0 - 0
dist/static/js/app.6f0ac4c14391b3e0c8fe.js.map


+ 0 - 2
dist/static/js/manifest.2ae2e69a05c33dfc65f8.js

@@ -1,2 +0,0 @@
-!function(r){var n=window.webpackJsonp;window.webpackJsonp=function(e,u,c){for(var f,i,p,a=0,l=[];a<e.length;a++)i=e[a],o[i]&&l.push(o[i][0]),o[i]=0;for(f in u)Object.prototype.hasOwnProperty.call(u,f)&&(r[f]=u[f]);for(n&&n(e,u,c);l.length;)l.shift()();if(c)for(a=0;a<c.length;a++)p=t(t.s=c[a]);return p};var e={},o={2:0};function t(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return r[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=r,t.c=e,t.d=function(r,n,e){t.o(r,n)||Object.defineProperty(r,n,{configurable:!1,enumerable:!0,get:e})},t.n=function(r){var n=r&&r.__esModule?function(){return r.default}:function(){return r};return t.d(n,"a",n),n},t.o=function(r,n){return Object.prototype.hasOwnProperty.call(r,n)},t.p="/",t.oe=function(r){throw console.error(r),r}}([]);
-//# sourceMappingURL=manifest.2ae2e69a05c33dfc65f8.js.map

Rozdielové dáta súboru neboli zobrazené, pretože súbor je príliš veľký
+ 0 - 0
dist/static/js/manifest.2ae2e69a05c33dfc65f8.js.map


Rozdielové dáta súboru neboli zobrazené, pretože súbor je príliš veľký
+ 0 - 14
dist/static/js/vendor.3ce127c54cf2044ee291.js


Rozdielové dáta súboru neboli zobrazené, pretože súbor je príliš veľký
+ 0 - 0
dist/static/js/vendor.3ce127c54cf2044ee291.js.map


+ 0 - 41
http/CMakeLists.txt

@@ -1,41 +0,0 @@
-# 子模块参考模版
-include(${ROOT_DIR}/buildtools/cmake/toolchain_common.cmake)
-
-# 模块名称
-set(MODULE httpConfig)
-
-aux_source_directory(. DIRSRCS)
-include_directories(./)
-
-build_subdirectory(thirdparty/mosquitto)
-build_subdirectory(thirdparty/SQLiteCpp include thirdparty/SQLiteCpp/sqlite3)
-build_subdirectory(thirdparty/json-c define STDC_HEADERS)
-
-# link_libraries(${MODULE} mosquitto sqlite3 json-c rt pthread m)
-
-function(gen_cgi src)
-  set(cgi_name "${src}.cgi")
-  add_library(${cgi_name} ${src}.c common.c command.c)
-  target_link_libraries(${cgi_name} sqlite3 json-c rt pthread m)
-  install(TARGETS ${cgi_name}
-          DESTINATION webconfig/cgi-bin
-          PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ)
-endfunction(gen_cgi src)
-
-
-gen_cgi("get_device")
-gen_cgi("set_device")
-gen_cgi("add_device")
-gen_cgi("del_device")
-gen_cgi("get_system")
-gen_cgi("get_user")
-gen_cgi("get_platform")
-gen_cgi("set_platform")
-gen_cgi("login")
-gen_cgi("logout")
-
-
-install(DIRECTORY cookie
-        DESTINATION webconfig/cgi-bin
-        FILES_MATCHING PATTERN "*"
-)

+ 0 - 86
http/Makefile

@@ -1,86 +0,0 @@
-### Environment constants 
-ARCH := arm
-#CROSS_COMPILE := ../../buildroot-at91-2018.02-at91/output/host/bin/arm-linux-
-#CROSS_COMPILE := /home/logan/EmbeddedProject/RTU/buildroot/buildroot-at91-2018.02-at91/output/host/bin/arm-linux-
-
-OBJDIR = obj
-INCLUDES = $(wildcard inc/*.h)
-
-### External constant definitions
-# must get library build option to know if mpsse must be linked or not
-
-### Constant symbols
-
-#CC := $(CROSS_COMPILE)gcc
-#AR := $(CROSS_COMPILE)ar
-CC := $(CROSS_COMPILE)gcc
-AR := $(CROSS_COMPILE)ar
-RANLIB := $(CROSS_COMPILE)ranlib
-
-CFLAGS := -O2 -Wall -Wextra -std=c99 -Iinc -I.
-# List the library sub-modules that are used by the application
-
-### Linking options
-
-LIBS := -lmosquitto  -lsqlite3 -ljson-c -lrt -lpthread -lm
-### General build targets
-
-all: get_device.cgi set_device.cgi add_device.cgi del_device.cgi get_system.cgi \
-	get_user.cgi get_platform.cgi set_platform.cgi login.cgi logout.cgi
-
-clean:
-	rm -f *.o
-	rm -f get_device.cgi set_device.cgi add_device.cgi del_device.cgi get_system.cgi \
-	get_user.cgi get_platform.cgi set_platform.cgi login.cgi logout.cgi
-		
-
-### Sub-modules compilation
-
-libcgic.a: cgic.o cgic.h
-	rm -f libcgic.a
-	$(AR) rc libcgic.a cgic.o
-	$(RANLIB) libcgic.a
-
-
-%.o: %.c
-	$(CC) $(CFLAGS) -c  $< -o $@
-
-get_device.cgi:get_device.o common.o command.o
-	$(CC)   $^ -o $@ $(LIBS)
-
-set_device.cgi:set_device.o common.o command.o
-	$(CC)   $^ -o $@ $(LIBS)
-
-add_device.cgi:add_device.o common.o command.o
-	$(CC)   $^ -o $@ $(LIBS)
-
-del_device.cgi:del_device.o common.o command.o
-	$(CC)   $^ -o $@ $(LIBS)
-
-get_system.cgi:get_system.o common.o command.o
-	$(CC)   $^ -o $@ $(LIBS)
-
-get_user.cgi:get_user.o common.o command.o
-	$(CC)   $^ -o $@ $(LIBS)
-
-get_platform.cgi:get_platform.o common.o command.o
-	$(CC)   $^ -o $@ $(LIBS)
-
-set_platform.cgi:set_platform.o common.o command.o
-	$(CC)    $^ -o $@ $(LIBS)
-
-login.cgi:login.o common.o command.o
-	$(CC)    $^ -o $@ $(LIBS)
-
-logout.cgi:logout.o common.o command.o
-	$(CC)    $^ -o $@ $(LIBS)
-
-
-install:
-	echo "install"
-	cp -rf ../dist/index.html /var/www/
-	cp -rf ../dist/static /var/www/
-	cp -rf cookie /var/www/cgi-bin/
-	cp *.cgi /var/www/cgi-bin/
-### EOF
-

+ 0 - 11
http/add_device.c

@@ -1,11 +0,0 @@
-#include <stdio.h>
-#include "common.h"
-#include "command.h"
-
-int main(int argc, char *argv[])
-{
-
-	add_configure_by_type(PUB_ADD_DEVICES_NONE_HTTP, SUB_ADD_DEVICES_NONE_HTTP);
-
-	return 0;
-}

+ 0 - 346
http/command.c

@@ -1,346 +0,0 @@
-#include <stdio.h>
-#include <string.h>
-#include <time.h>
-#include <stdbool.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <json-c/json.h>
-#include <json-c/json_util.h>
-#include <json-c/json_object.h>
-#include <mosquitto.h>
-#include "common.h"
-#include "command.h"
-
-static volatile bool run =true;
-
-bool auth_user()
-{
-#if ENABLE_HTTP_COOKIE
-	char*info=NULL;
-	struct json_object *proot=NULL, *cookied_obj =NULL, *resp_obj = NULL;
-	const char *cookied=NULL;
-	const char *resp_string=NULL;
-	char id[100];
-
-	info = getenv("HTTP_COOKIE");
-	if(info == NULL)
-	{
-		printf("%s\n\n","Content-Type:application/json;charset=UTF-8");
-		resp_obj = json_object_new_object();
-		json_object_object_add(resp_obj, "status", json_object_new_string("expired"));
-		resp_string = json_object_to_json_string(resp_obj);
-		printf("%s",resp_string);
-		json_object_put(resp_obj);
-		return false;
-	}
-	else
-	{
-		sscanf(info,"cookied=%s",id);
-		proot = json_object_from_file("./cookie/cookied.json");
-		if(proot == NULL)
-		{
-			printf("%s\n\n","Content-Type:application/json;charset=UTF-8"); 
-			resp_obj = json_object_new_object();
-			json_object_object_add(resp_obj, "status", json_object_new_string("expired"));
-			resp_string = json_object_to_json_string(resp_obj);
-			printf("%s",resp_string);
-			json_object_put(resp_obj);
-			return false;
-		}
-		json_object_object_get_ex(proot, "cookied",&cookied_obj);
-		cookied = json_object_get_string(cookied_obj);
-		if(strncmp(cookied, id, STR_MAX_LEN(cookied, id)) != 0)
-		{
-			json_object_put(proot);
-			printf("%s\n\n","Content-Type:application/json;charset=UTF-8"); 
-			resp_obj = json_object_new_object();
-			json_object_object_add(resp_obj, "status", json_object_new_string("expired"));
-			resp_string = json_object_to_json_string(resp_obj);
-			printf("%s",resp_string);
-			json_object_put(resp_obj);
-			return false;
-		}
-		json_object_put(proot);
-	}
-
-#endif
-	return true;
-
-}
-
-void http_connect_callback(struct mosquitto *mosq, void *obj, int rc)
-{
-	run = true;
-}
-
-void http_disconnect_callback(struct mosquitto *mosq, void *obj, int result)
-{
-	run = false;
-}
-
-void http_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg)
-{
-
-	printf("%s\n\n","Content-Type:application/json;charset=UTF-8"); 
-
-	
-	printf("%s",msg->payload);
-	
-	run =false;
-
-}
-
-void http_subscribe_callback(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos)
-{
-	run = true;
-}
-
-
-void get_configure_by_type(char *pub_topic, char *sub_topic)
-{
-	struct mosquitto *http_mosq;
-	char*info=NULL;
-	int max=0;
-	char id[50];
-
-#if ENABLE_HTTP_COOKIE
-	if (auth_user() ==false)
-		return;
-#endif
-
-	mosquitto_lib_init();
-	snprintf(id, 50, "get_configure_%d", getpid());
-	http_mosq = mosquitto_new(id, true, NULL);
-
-	mosquitto_connect_callback_set(http_mosq, http_connect_callback);
-	mosquitto_disconnect_callback_set(http_mosq, http_disconnect_callback);
-	mosquitto_message_callback_set(http_mosq, http_message_callback);
-	mosquitto_subscribe_callback_set(http_mosq, http_subscribe_callback);
-	mosquitto_connect(http_mosq, "localhost", 1883, 600);
-	mosquitto_subscribe(http_mosq, NULL, sub_topic, 1);
-	mosquitto_publish(http_mosq, NULL, pub_topic, 0, "", 1, false);
-	while(run ==true && max < MAX_TIMEOUT)
-	{
-		mosquitto_loop(http_mosq, 500, 1);
-		max++;
-
-	}
-
-	mosquitto_disconnect(http_mosq);
-	mosquitto_destroy(http_mosq);
-	
-	mosquitto_lib_cleanup();
-
-}
-
-
-void set_configure_by_type(char *pub_topic ,char *sub_topic)
-{
-	char *info=NULL, *p=NULL, *pRequestMethod=NULL, *inputbuffer=NULL;
-	int ContentLength,x,i=0;
-	struct mosquitto *http_mosq;
-	int max=0;
-	char id[50];
-
-#if ENABLE_HTTP_COOKIE
-	if (auth_user() ==false)
-		return;
-#endif
-
-	setvbuf(stdin, NULL , _IONBF, 0);
-	pRequestMethod = getenv("REQUEST_METHOD");
-	if(pRequestMethod == NULL)
-	{
-		printf("<p> request = null </p>");
-		return;
-	}
-	
-	if(strcasecmp(pRequestMethod, "POST") == 0)
-	{
-		p = getenv("CONTENT_LENGTH");
-		if(p!=NULL)
-		{
-			ContentLength =atoi(p);
-		}
-		else
-		{
-			ContentLength = 0;
-		}
-		
-		inputbuffer = (char *)malloc(ContentLength + 1);
-		while(i < ContentLength)
-		{
-			x = fgetc(stdin);
-			if(x == EOF)
-				break;
-			*(inputbuffer+i) =x;
-			i++;
-		}
-		*(inputbuffer+i) = '\0';
-		ContentLength = i;
-
-		mosquitto_lib_init();
-		snprintf(id, 50, "set_configure_%d", getpid());
-		http_mosq = mosquitto_new(id, true, NULL);
-		mosquitto_connect_callback_set(http_mosq, http_connect_callback);
-		mosquitto_disconnect_callback_set(http_mosq, http_disconnect_callback);
-		mosquitto_message_callback_set(http_mosq, http_message_callback);
-		mosquitto_subscribe_callback_set(http_mosq, http_subscribe_callback);
-		mosquitto_connect(http_mosq, "localhost", 1883, 600);
-		mosquitto_subscribe(http_mosq, NULL, sub_topic, 1);
-		mosquitto_publish(http_mosq, NULL, pub_topic, ContentLength, inputbuffer, 1, false);
-		while(run ==true && max < MAX_TIMEOUT)
-		{
-			mosquitto_loop(http_mosq, 500, 1);
-			max++;
-		}
-
-		mosquitto_disconnect(http_mosq);
-		mosquitto_destroy(http_mosq);
-	
-		mosquitto_lib_cleanup();
-		free(inputbuffer);
-	}
-
-}
-
-void del_configure_by_type(char *pub_topic,char *sub_topic)
-{
-	char *info=NULL, *p=NULL, *pRequestMethod=NULL, *inputbuffer=NULL;
-	int ContentLength,x,i=0;
-	struct mosquitto *http_mosq;
-	int max=0;
-	char id[50];
-
-#if ENABLE_HTTP_COOKIE
-	if (auth_user() ==false)
-		return;
-#endif
-
-	setvbuf(stdin, NULL , _IONBF, 0);
-	pRequestMethod = getenv("REQUEST_METHOD");
-	if(pRequestMethod == NULL)
-	{
-		printf("<p> request = null </p>");
-		return;
-	}
-	
-	if(strcasecmp(pRequestMethod, "POST") == 0)
-	{
-		p = getenv("CONTENT_LENGTH");
-		if(p!=NULL)
-		{
-			ContentLength =atoi(p);
-		}
-		else
-		{
-			ContentLength = 0;
-		}
-		
-		inputbuffer = (char *)malloc(ContentLength + 1);
-		while(i < ContentLength)
-		{
-			x = fgetc(stdin);
-			if(x == EOF)
-				break;
-			*(inputbuffer+i) =x;
-			i++;
-		}
-		*(inputbuffer+i) = '\0';
-		ContentLength = i;
-
-		mosquitto_lib_init();
-		snprintf(id, 50, "del_configure_%d", getpid());
-		http_mosq = mosquitto_new(id, true, NULL);
-		mosquitto_connect_callback_set(http_mosq, http_connect_callback);
-		mosquitto_disconnect_callback_set(http_mosq, http_disconnect_callback);
-		mosquitto_message_callback_set(http_mosq, http_message_callback);
-		mosquitto_subscribe_callback_set(http_mosq, http_subscribe_callback);
-		mosquitto_connect(http_mosq, "localhost", 1883, 600);
-		mosquitto_subscribe(http_mosq, NULL, sub_topic, 1);
-		mosquitto_publish(http_mosq, NULL, pub_topic, ContentLength, inputbuffer, 1, false);
-		while(run ==true && max < MAX_TIMEOUT)
-		{
-			mosquitto_loop(http_mosq, 500, 1);
-			max++;
-		}
-
-		mosquitto_disconnect(http_mosq);
-		mosquitto_destroy(http_mosq);
-	
-		mosquitto_lib_cleanup();
-		free(inputbuffer);
-	}
-}
-
-void add_configure_by_type(char *pub_topic , char *sub_topic)
-{
-	char *info=NULL, *p=NULL, *pRequestMethod=NULL, *inputbuffer=NULL;
-	int ContentLength,x,i=0;
-	struct mosquitto *http_mosq;
-	int max =0;
-	char id[50];
-
-#if ENABLE_HTTP_COOKIE
-	if (auth_user() ==false)
-		return;
-#endif
-
-	setvbuf(stdin, NULL , _IONBF, 0);
-	pRequestMethod = getenv("REQUEST_METHOD");
-	if(pRequestMethod == NULL)
-	{
-		printf("<p> request = null </p>");
-		return;
-	}
-	
-	if(strcasecmp(pRequestMethod, "POST") == 0)
-	{
-		p = getenv("CONTENT_LENGTH");
-		if(p!=NULL)
-		{
-			ContentLength =atoi(p);
-		}
-		else
-		{
-			ContentLength = 0;
-		}
-		
-		inputbuffer = (char *)malloc(ContentLength + 1);
-		while(i < ContentLength)
-		{
-			x = fgetc(stdin);
-			if(x == EOF)
-				break;
-			*(inputbuffer+i) =x;
-			i++;
-		}
-		*(inputbuffer+i) = '\0';
-		ContentLength = i;
-
-		mosquitto_lib_init();
-		snprintf(id, 50, "add_configure_%d", getpid());
-		http_mosq = mosquitto_new(id, true, NULL);
-		mosquitto_connect_callback_set(http_mosq, http_connect_callback);
-		mosquitto_disconnect_callback_set(http_mosq, http_disconnect_callback);
-		mosquitto_message_callback_set(http_mosq, http_message_callback);
-		mosquitto_subscribe_callback_set(http_mosq, http_subscribe_callback);
-		mosquitto_connect(http_mosq, "localhost", 1883, 600);
-		mosquitto_subscribe(http_mosq, NULL, sub_topic, 1);
-		mosquitto_publish(http_mosq, NULL, pub_topic, ContentLength, inputbuffer, 1, false);
-		while(run ==true && max < MAX_TIMEOUT)
-		{
-			mosquitto_loop(http_mosq, 500, 1);
-			max++;
-		}
-
-		mosquitto_disconnect(http_mosq);
-		mosquitto_destroy(http_mosq);
-	
-		mosquitto_lib_cleanup();
-		free(inputbuffer);
-	}
-}
-
-
-

+ 0 - 73
http/command.h

@@ -1,73 +0,0 @@
-#ifndef __COMMAND_H__
-#define __COMMAND_H__
-#include<stdio.h>
-#include <time.h>
-#include <stdbool.h>
-
-#define ENABLE_HTTP_COOKIE 1
-
-#define MAX_TIMEOUT 20
-
-//devices.db http 
-#define PUB_GET_DEVICES_NONE_HTTP		"get/devices/none/http"
-#define SUB_GET_DEVICES_NONE_HTTP		"ack/get/devices/none/http"
-
-#define PUB_ADD_DEVICES_NONE_HTTP		"add/devices/none/http"
-#define SUB_ADD_DEVICES_NONE_HTTP		"ack/add/devices/none/http"
-
-#define PUB_SET_DEVICES_NONE_HTTP		"set/devices/none/http"
-#define SUB_SET_DEVICES_NONE_HTTP		"ack/set/devices/none/http"
-
-#define PUB_DEL_DEVICES_NONE_HTTP		"del/devices/none/http"
-#define SUB_DEL_DEVICES_NONE_HTTP		"ack/del/devices/none/http"
-
-//platform.json
-#define PUB_GET_PLATFORM_NONE_HTTP		"get/platform/none/http"
-#define SUB_GET_PLATFORM_NONE_HTTP		"ack/get/platform/none/http"
-
-#define PUB_ADD_PLATFORM_NONE_HTTP		"add/platform/none/http"
-#define SUB_ADD_PLATFORM_NONE_HTTP		"ack/add/platform/none/http"
-
-#define PUB_SET_PLATFORM_NONE_HTTP		"set/platform/none/http"
-#define SUB_SET_PLATFORM_NONE_HTTP		"ack/set/platform/none/http"
-
-#define PUB_DEL_PLATFORM_NONE_HTTP		"del/platform/none/http"
-#define SUB_DEL_PLATFORM_NONE_HTTP		"ack/del/platform/none/http"
-
-//system.json
-#define PUB_GET_SYSTEM_NONE_HTTP		"get/system/none/http"
-#define SUB_GET_SYSTEM_NONE_HTTP		"ack/get/system/none/http"
-
-#define PUB_ADD_SYSTEM_NONE_HTTP		"add/system/none/http"
-#define SUB_ADD_SYSTEM_NONE_HTTP		"ack/add/system/none/http
-
-#define PUB_SET_SYSTEM_NONE_HTTP		"set/system/none/http"
-#define SUB_SET_SYSTEM_NONE_HTTP		"ack/set/system/none/http"
-
-#define PUB_DEL_SYSTEM_NONE_HTTP		"del/system/none/http"
-#define SUB_DEL_SYSTEM_NONE_HTTP		"ack/del/system/none/http"
-
-//user.json
-#define PUB_GET_USER_NONE_HTTP			"get/user/none/http"
-#define SUB_GET_USER_NONE_HTTP			"ack/get/user/none/http"
-
-#define PUB_ADD_SYSTEM_NONE_HTTP		"add/user/none/http"
-#define SUB_ADD_SYSTEM_NONE_HTTP		"ack/add/user/none/http"
-
-#define PUB_SET_SYSTEM_NONE_HTTP		"set/user/none/http"
-#define SUB_SET_SYSTEM_NONE_HTTP		"ack/set/user/none/http"
-
-#define PUB_DEL_SYSTEM_NONE_HTTP		"del/user/none/http"
-#define SUB_DEL_SYSTEM_NONE_HTTP		"ack/del/user/none/http"
-
-
-
-
-bool auth_user();
-
-void get_configure_by_type(char *pub_topic, char *sub_topic);
-void set_configure_by_type(char *pub_topic, char *sub_topic);
-void del_configure_by_type(char *pub_topic, char *sub_topic);
-void add_configure_by_type(char *pub_topic, char *sub_topic);
-
-#endif

+ 0 - 14
http/common.c

@@ -1,14 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdbool.h>
-#include <unistd.h>
-#include <time.h>
-#include "common.h"
-
-void timestamp_get(char *timestamp)
-{	
-	time_t t;
-
-	t = time(NULL);  
-	sprintf(timestamp,"%lld",((long long)t)*1000);
-}

+ 0 - 13
http/common.h

@@ -1,13 +0,0 @@
-#ifndef __COMMON_H__
-#define __COMMON_H__
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdbool.h>
-#include <unistd.h>
-#include <string.h>
-
-#define STR_MAX_LEN(str1,str2)	((strlen(str1)>strlen(str2))?strlen(str1):strlen(str2))
-
-void timestamp_get(char *timestamp);
-
-#endif

+ 0 - 1
http/cookie/cookied.json

@@ -1 +0,0 @@
-{"cookied":""}

+ 0 - 11
http/del_device.c

@@ -1,11 +0,0 @@
-#include <stdio.h>
-#include "common.h"
-#include "command.h"
-
-int main(int argc, char *argv[])
-{
-
-	del_configure_by_type(PUB_DEL_DEVICES_NONE_HTTP, SUB_DEL_DEVICES_NONE_HTTP);
-
-	return 0;
-}

+ 0 - 11
http/get_device.c

@@ -1,11 +0,0 @@
-#include <stdio.h>
-#include "common.h"
-#include "command.h"
-
-int main(int argc, char *argv[])
-{
-
-	get_configure_by_type(PUB_GET_DEVICES_NONE_HTTP, SUB_GET_DEVICES_NONE_HTTP);
-
-	return 0;
-}

+ 0 - 10
http/get_platform.c

@@ -1,10 +0,0 @@
-#include <stdio.h>
-#include "common.h"
-#include "command.h"
-
-int main(int argc, char *argv[])
-{
-
-	get_configure_by_type(PUB_GET_PLATFORM_NONE_HTTP,SUB_GET_PLATFORM_NONE_HTTP);
-	return 0;
-}

+ 0 - 9
http/get_system.c

@@ -1,9 +0,0 @@
-#include <stdio.h>
-#include "common.h"
-#include "command.h"
-
-int main(int argc, char *argv[])
-{
-	get_configure_by_type(PUB_GET_SYSTEM_NONE_HTTP,SUB_GET_SYSTEM_NONE_HTTP);
-	return 0;
-}

+ 0 - 10
http/get_user.c

@@ -1,10 +0,0 @@
-#include <stdio.h>
-#include "common.h"
-#include "command.h"
-
-int main(int argc, char *argv[])
-{
-
-	get_configure_by_type(PUB_GET_USER_NONE_HTTP,SUB_GET_USER_NONE_HTTP);
-	return 0;
-}

+ 0 - 170
http/login.c

@@ -1,170 +0,0 @@
-#include <stdio.h>
-#include <string.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <json-c/json.h>
-#include <json-c/json_util.h>
-#include <json-c/json_object.h>
-#include <mosquitto.h>
-#include "common.h"
-#include "command.h"
-
-
-static volatile bool run =true;
-char *inputbuffer=NULL;
-
-void connect_callback(struct mosquitto *mosq, void *obj, int rc)
-{
-	run = true;
-}
-
-void disconnect_callback(struct mosquitto *mosq, void *obj, int result)
-{
-	run = false;
-}
-
-void message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg)
-{
-	struct json_object *proot=NULL, *payload_obj=NULL, *item_obj=NULL, *user_obj=NULL, *temp_obj=NULL, *cookied_obj=NULL, *rsp_obj=NULL;
-	const char *proot_string=NULL, *rsp_string=NULL;
-	const char *user=NULL;
-	const char *passwd=NULL;
-	const char *load_user=NULL;
-	const char *load_passwd=NULL;
-	char timestamp[100];
-
-	proot = json_tokener_parse(msg->payload);
-	if(proot == NULL)
-	{
-		printf("ERROR: login proot is NULL!\r\n");
-		run =false;
-		return ;
-	}
-	json_object_object_get_ex(proot, "user", &user_obj);
-	json_object_object_get_ex(user_obj, "user", &temp_obj);
-	user = json_object_get_string(temp_obj);
-	json_object_object_get_ex(user_obj, "passwd", &temp_obj);
-	passwd = json_object_get_string(temp_obj);
-
-
-	payload_obj = json_tokener_parse(inputbuffer);
-	if(payload_obj == NULL)
-	{
-		printf("ERROR: inputbuffer is error!\r\n");
-		json_object_put(proot);
-		run =false;
-		return;
-	}
-	json_object_object_get_ex(payload_obj, "user", &temp_obj);
-	load_user = json_object_get_string(temp_obj);
-	json_object_object_get_ex(payload_obj, "passwd", &temp_obj);
-	load_passwd = json_object_get_string(temp_obj);
-	if(strncmp(user,load_user, STR_MAX_LEN(user, load_user)) ==0 &&
-	   strncmp(passwd, load_passwd,STR_MAX_LEN(passwd,load_passwd)) ==0)
-	{
-		rsp_obj = json_object_new_object();
-		json_object_object_add(rsp_obj,"state", json_object_new_string("success"));
-		json_object_object_add(rsp_obj,"user", json_object_new_string(user));
-		json_object_object_add(rsp_obj,"passwd", json_object_new_string(passwd));
-
-		timestamp_get(timestamp);
-		cookied_obj = json_object_new_object();
-		json_object_object_add(cookied_obj, "cookied", json_object_new_string(timestamp));
-		json_object_to_file_ext("./cookie/cookied.json", cookied_obj, JSON_C_TO_STRING_PRETTY);
-		printf("Set-Cookie:cookied=%s;path=/;",timestamp);
-		json_object_put(cookied_obj);
-	}
-	else{
-		rsp_obj = json_object_new_object();
-		json_object_object_add(rsp_obj,"state", json_object_new_string("fail"));
-		json_object_object_add(rsp_obj,"user", json_object_new_string(load_user));
-		json_object_object_add(rsp_obj,"passwd", json_object_new_string(load_passwd));
-
-	}
-
-	printf("%s\n\n","Content-Type:application/json;charset=UTF-8");
-
-	rsp_string = json_object_to_json_string(rsp_obj);
-	printf("%s",rsp_string);
-	json_object_put(proot);
-	json_object_put(payload_obj);
-	json_object_put(rsp_obj);
-
-	run =false;
-
-}
-
-void subscribe_callback(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos)
-{
-	run = true;
-}
-
-
-int main(int argc, char *argv[])
-{
-	char *info=NULL, *p=NULL, *pRequestMethod=NULL;
-	int ContentLength,x,i=0;
-	struct mosquitto *http_mosq=NULL;
-	int max =0;
-	char id[50];
-
-    setvbuf(stdin, NULL , _IONBF, 0);
-	pRequestMethod = getenv("REQUEST_METHOD");
-	if(pRequestMethod == NULL)
-	{
-		printf("<p> request = null </p>");
-		return 0;
-	}
-
-	if(strcasecmp(pRequestMethod, "POST") == 0)
-	{
-		p = getenv("CONTENT_LENGTH");
-		if(p!=NULL)
-		{
-			ContentLength =atoi(p);
-		}
-		else
-		{
-			ContentLength = 0;
-		}
-
-		inputbuffer = (char *)malloc(ContentLength + 1);
-		while(i < ContentLength)
-		{
-			x = fgetc(stdin);
-			if(x == EOF)
-				break;
-			*(inputbuffer+i) =x;
-			i++;
-		}
-		*(inputbuffer+i) = '\0';
-		ContentLength = i;
-
-
-		mosquitto_lib_init();
-		snprintf(id, 50, "login_%d", getpid());
-		http_mosq = mosquitto_new(id, true, NULL);
-		mosquitto_connect_callback_set(http_mosq, connect_callback);
-		mosquitto_disconnect_callback_set(http_mosq, disconnect_callback);
-		mosquitto_message_callback_set(http_mosq, message_callback);
-		mosquitto_subscribe_callback_set(http_mosq, subscribe_callback);
-		mosquitto_connect(http_mosq, "localhost", 1883, 600);
-		mosquitto_subscribe(http_mosq, NULL, SUB_GET_USER_NONE_HTTP, 1);
-		mosquitto_publish(http_mosq, NULL, PUB_GET_USER_NONE_HTTP, 0, "", 1, false);
-		while(run ==true && max < MAX_TIMEOUT)
-		{
-			mosquitto_loop(http_mosq, 500, 1);
-			max++;
-
-		}
-
-		mosquitto_disconnect(http_mosq);
-		mosquitto_destroy(http_mosq);
-		mosquitto_lib_cleanup();
-
-		free(inputbuffer);
-	}
-
-	return 0;
-
-}

+ 0 - 38
http/logout.c

@@ -1,38 +0,0 @@
-#include <stdio.h>
-#include <string.h>
-#include <json-c/json.h>
-#include <json-c/json_util.h>
-#include <json-c/json_object.h>
-#include <mosquitto.h>
-#include "common.h"
-#include "command.h"
-
-int main(int argc, char *argv[])
-{
-	struct json_object *proot=NULL, *resp_obj = NULL;
-	const char *resp_string=NULL;
-	
-#if ENABLE_HTTP_COOKIE
-	if (auth_user() ==false)
-		return 0;
-#endif
-
-	proot = json_object_from_file("./cookie/cookied.json");
-	if(proot == NULL)
-	{
-		printf("Location:/index.html\n\n");
-	}
-	json_object_object_add(proot,"cookied", json_object_new_string(""));
-	json_object_to_file_ext("./cookie/cookied.json", proot,JSON_C_TO_STRING_PRETTY);
-	json_object_put(proot);
-
-
-	printf("%s\n\n","Content-Type:application/json;charset=UTF-8"); 
-	resp_obj = json_object_new_object();
-	json_object_object_add(resp_obj, "state", json_object_new_string("success"));
-	resp_string = json_object_to_json_string(resp_obj);
-	printf("%s",resp_string);
-	json_object_put(resp_obj);
-	
-	return 0;
-}

+ 0 - 11
http/set_device.c

@@ -1,11 +0,0 @@
-#include <stdio.h>
-#include "common.h"
-#include "command.h"
-
-int main(int argc, char *argv[])
-{
-
-	set_configure_by_type(PUB_SET_DEVICES_NONE_HTTP, SUB_SET_DEVICES_NONE_HTTP);
-
-	return 0;
-}

+ 0 - 11
http/set_platform.c

@@ -1,11 +0,0 @@
-#include <stdio.h>
-#include "common.h"
-#include "command.h"
-
-int main(int argc, char *argv[])
-{
-
-	set_configure_by_type(PUB_SET_PLATFORM_NONE_HTTP,SUB_SET_PLATFORM_NONE_HTTP);
-
-	return 0;
-}

+ 14 - 0
settings/CMakeLists.txt

@@ -0,0 +1,14 @@
+# 模块名称
+set(MODULE settings)
+
+include_directories(${TINYXML2_INCLUDE_DIR})
+find_library(TYNIXML2_LIBRARY tinyxml2 ${TINYXML2_LIBS_DIR} NO_DEFAULT_PATH)
+message("TINYXML2_LIBS_DIR: ${TINYXML2_LIBS_DIR}, TYNIXML2_LIBRARY: ${TYNIXML2_LIBRARY}")
+
+aux_source_directory(.  DIRSRCS)
+add_library(${MODULE} ${DIRSRCS})
+target_link_libraries(${MODULE} ${TYNIXML2_LIBRARY} utils)
+
+install(TARGETS ${MODULE}
+        DESTINATION lib/
+        PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ)

+ 17 - 0
settings/basic_config.xml

@@ -0,0 +1,17 @@
+<globe>
+<id>0000000000000</id>
+<key>1234567890abcdef</key>
+<host>gateway.leotechnology.cn</host>
+<port>8889</port>
+<tls>1</tls>
+<username>admin</username>
+<password>leo2023</password>
+<dbFile>save.db</dbFile>
+<logStoreDuration>120</logStoreDuration>
+<wwwPort>9080</wwwPort>
+<useRemoteServerTime>1</useRemoteServerTime>
+<retry>3</retry>
+<historyPeriod>10000</historyPeriod>
+<portNames>/dev/tty11,/dev/tty13,/dev/tty15,/dev/tty17,,,,,</portNames>
+<net>[{"IPADDR":"192.168.201.1","NETMASK":"255.255.255.0","GATEWAY":"192.168.201.1","dhcp":false},{"dhcp":dhcp,"IPADDR":"192.168.0.230","NETMASK":"255.255.255.0","GATEWAY":"192.168.0.1"}]</net>
+</globe>

+ 135 - 0
settings/config_parser.cpp

@@ -0,0 +1,135 @@
+#include "config_parser.h"
+#include "vendor_global.h"
+#include <map>
+#include <stdlib.h>
+#include <utils/macro.h>
+
+#define CHECK_MAP_KEY(kv, key)                                   \
+    do {                                                         \
+        if (kv.find(#key) == kv.end()) {                         \
+            HTELINK_LOG_ERR("dataCenter config not found" #key); \
+            return;                                              \
+        }                                                        \
+    } while (0)
+
+namespace settings {
+ConfigParser::ConfigParser() : xmlConfig_(new XmlConfig())
+{
+    if (!xmlConfig_->Load(VENDOR_CONFIG_PATH + "/basic_config.xml")) {
+        HTELINK_LOG_ERR("load xml failed");
+    }
+}
+
+ConfigParser::~ConfigParser()
+{
+    delete xmlConfig_;
+}
+
+std::vector<ConfigParser::DataCenter> ConfigParser::GetDataCenter() const
+{
+    std::vector<DataCenter> dataCenters;
+    xmlConfig_->GetElemValue("dataCenter", [&dataCenters](std::map<std::string, std::string> &kv) -> void {
+        DataCenter center;
+        CHECK_MAP_KEY(kv, name);
+        CHECK_MAP_KEY(kv, id);
+        CHECK_MAP_KEY(kv, host);
+        CHECK_MAP_KEY(kv, port);
+        CHECK_MAP_KEY(kv, key);
+        CHECK_MAP_KEY(kv, tls);
+        center.name = kv["name"];
+        center.ID = kv["id"];
+        center.host = kv["host"];
+        center.port = atoi(kv["port"].c_str());
+        center.protoType = 1;
+        center.key = kv["key"];
+        center.isTls = atoi(kv["tls"].c_str()) != 0;
+        center.yunID = 0;
+        dataCenters.push_back(center);
+    });
+    // 兼容老版本格式
+    if (dataCenters.empty()) {
+        DataCenter center;
+        center.ID = xmlConfig_->GetElemValueString("", "id");
+        center.host = xmlConfig_->GetElemValueString("", "host");
+        center.port = xmlConfig_->GetElemValueInt("", "port");
+        center.key = xmlConfig_->GetElemValueString("", "key");
+        center.isTls = xmlConfig_->GetElemValueBool("", "tls");
+        center.protoType = 1;
+        center.yunID = 0;
+        dataCenters.push_back(center);
+    }
+    return dataCenters;
+}
+
+std::vector<ConfigParser::LoginUser> ConfigParser::GetLoginUsers() const
+{
+    std::vector<LoginUser> loginUsers;
+    xmlConfig_->GetElemValue("logUser", [&loginUsers](std::map<std::string, std::string> &kv) -> void {
+        LoginUser user;
+        CHECK_MAP_KEY(kv, username);
+        CHECK_MAP_KEY(kv, host);
+        user.user = kv["username"];
+        user.passwd = kv["password"];
+        loginUsers.push_back(user);
+    });
+    // 兼容老版本格式
+    if (loginUsers.empty()) {
+        LoginUser user;
+        user.user = xmlConfig_->GetElemValueString("", "username");
+        user.passwd = xmlConfig_->GetElemValueString("", "password");
+        loginUsers.push_back(user);
+    }
+    return loginUsers;
+}
+
+int16_t ConfigParser::GetWWWPort() const
+{
+    return xmlConfig_->GetElemValueInt("", "wwwPort");
+}
+
+int32_t ConfigParser::GetRetryTimes()
+{
+    return xmlConfig_->GetElemValueInt("", "retry");
+}
+
+std::unordered_map<std::string, ConfigParser::Channel> ConfigParser::GetChannels() const
+{
+    std::unordered_map<std::string, Channel> channels;
+
+    std::vector<DataCenter> dataCenters;
+    xmlConfig_->GetElemValue("Channel", [&channels](std::map<std::string, std::string> &kv) -> void {
+        for (std::pair<std::string, std::string> chn : kv) {
+            Channel chnn;
+            chnn.devPath = chn.second;
+            if (utils::StartWith(chn.first, "COM")) {
+                chnn.type = CHN_COM;
+            } else if (utils::StartWith(chn.first, "TCP")) {
+                chnn.type = CHN_TCP;
+            } else if (utils::StartWith(chn.first, "UDP")) {
+                chnn.type = CHN_UDP;
+            } else if (utils::StartWith(chn.first, "LORA")) {
+                chnn.type = CHN_LORA;
+            } else {
+                chnn.type = CHN_COM;
+            }
+            channels[chn.first] = chnn;
+        }
+    });
+    // 兼容老版本格式
+    if (channels.empty()) {
+        std::string chanStr = xmlConfig_->GetElemValueString("", "portNames");
+        std::vector<std::string> chanList = utils::Split(chanStr, ",");
+        int32_t index = 1;
+        for (const std::string &chn : chanList) {
+            if (chn.empty()) {
+                continue;
+            }
+            Channel chnn;
+            chnn.devPath = chn;
+            chnn.type = CHN_COM;
+            channels["COM" + index++] = chnn;
+        }
+    }
+    return channels;
+}
+} // namespace settings

+ 45 - 0
settings/config_parser.h

@@ -0,0 +1,45 @@
+#ifndef FOUNDATION_SETTINGS_CONFIG_PARSER_H
+#define FOUNDATION_SETTINGS_CONFIG_PARSER_H
+#include "xmlconfig.h"
+#include <unordered_map>
+#include <vector>
+
+namespace settings {
+class ConfigParser {
+public:
+    ConfigParser();
+    ~ConfigParser();
+
+    struct DataCenter {
+        std::string name;
+        std::string ID;
+        std::string key;
+        std::string host;
+        int32_t port;
+        bool isTls;
+        int32_t protoType;
+        int32_t yunID;
+    };
+
+    struct LoginUser {
+        std::string user;
+        std::string passwd;
+    };
+
+    struct Channel {
+        int32_t type;
+        std::string devPath;
+    };
+
+    enum ChnType { CHN_COM = 0, CHN_TCP, CHN_UDP, CHN_LORA };
+    std::vector<DataCenter> GetDataCenter() const;
+    std::vector<LoginUser> GetLoginUsers() const;
+    int16_t GetWWWPort() const;
+    int32_t GetRetryTimes();
+    std::unordered_map<std::string, Channel> GetChannels() const;
+
+private:
+    XmlConfig *xmlConfig_;
+};
+} // namespace settings
+#endif // FOUNDATION_SETTINGS_CONFIG_PARSER_H

+ 494 - 0
settings/sysinfo.cpp

@@ -0,0 +1,494 @@
+/*************************************************************************
+        > File Name: sysinfo.cpp
+        > Author: xuwenlong
+        > Mail: myxuan475@126.com
+        > Created Time: 2018年07月17日 星期二 16时09分32秒
+ ************************************************************************/
+#include "sysinfo.h"
+#include <arpa/inet.h>
+#include <ctype.h>
+#include <errno.h>
+#include <error.h>
+#include <ifaddrs.h>
+#include <net/if.h>
+#include <net/route.h>
+#include <netinet/in.h>
+#include <resolv.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <utils/logger.h>
+
+namespace settings {
+namespace sysinfo {
+double cal_occupy(CPU_OCCUPY *o, CPU_OCCUPY *n)
+{
+    double od, nd;
+    double id, sd;
+    double scale;
+    od = (double)(o->user + o->nice + o->system + o->idle); // 第一次(用户+优先级+系统+空闲)的时间再赋给od
+    nd = (double)(n->user + n->nice + n->system + n->idle); // 第二次(用户+优先级+系统+空闲)的时间再赋给od
+    scale = 100.0 / (float)(nd - od);     // 100除强制转换(nd-od)之差为float类型再赋给scale这个变量
+    id = (double)(n->user - o->user);     // 用户第一次和第二次的时间之差再赋给id
+    sd = (double)(n->system - o->system); // 系统第一次和第二次的时间之差再赋给sd
+    return ((sd + id) * 100.0) / (nd - od); //((用户+系统)乖100)除(第一次和第二次的时间差)再赋给g_cpu_used
+}
+
+void get_occupy(CPU_OCCUPY *o)
+{
+    FILE *fd;
+    int n;
+    char buff[MAXBUFSIZE];
+    fd = fopen("/proc/stat",
+        "r"); // 这里只读取stat文件的第一行及cpu总信息,如需获取每核cpu的使用情况,请分析stat文件的接下来几行。
+    (void)fgets(buff, sizeof(buff), fd);
+    sscanf(buff, "%s %u %u %u %u", o->name, &o->user, &o->nice, &o->system, &o->idle);
+    fclose(fd);
+}
+
+void get_mem_occupy(MEM_OCCUPY *mem)
+{
+    FILE *fd;
+    char buff[MAXBUFSIZE];
+    fd = fopen("/proc/meminfo", "r");
+    (void)fgets(buff, sizeof(buff), fd);
+    sscanf(buff, "%s %lld", mem->name, &mem->total);
+    (void)fgets(buff, sizeof(buff), fd);
+    sscanf(buff, "%s %lld", mem->name2, &mem->free);
+    fclose(fd);
+}
+
+float get_io_occupy()
+{
+    char cmd[] = "iostat -d -k";
+    char buffer[MAXBUFSIZE];
+    char a[20];
+    float arr[20];
+    FILE *pipe = popen(cmd, "r");
+    if (!pipe)
+        return -1;
+    (void)fgets(buffer, sizeof(buffer), pipe);
+    (void)fgets(buffer, sizeof(buffer), pipe);
+    (void)fgets(buffer, sizeof(buffer), pipe);
+    (void)fgets(buffer, sizeof(buffer), pipe);
+    sscanf(buffer, "%s %f %f %f %f %f %f %f %f %f %f %f %f %f ", a, &arr[0], &arr[1], &arr[2], &arr[3], &arr[4],
+        &arr[5], &arr[6], &arr[7], &arr[8], &arr[9], &arr[10], &arr[11], &arr[12]);
+    // printf("%f\n",arr[12]);
+
+    pclose(pipe);
+    return arr[12];
+}
+void get_disk_occupy(char **reused)
+{
+    char currentDirectoryPath[MAXBUFSIZE];
+    (void)getcwd(currentDirectoryPath, MAXBUFSIZE);
+    // printf("当前目录:%s\n",currentDirectoryPath);
+    char cmd[50] = "df ";
+    strcat(cmd, currentDirectoryPath);
+    // printf("%s\n",cmd);
+
+    char buffer[MAXBUFSIZE];
+    FILE *pipe = popen(cmd, "r");
+    char fileSys[20];
+    char blocks[20];
+    char used[20];
+    char free[20];
+    char percent[10];
+    char moment[20];
+
+    if (!pipe)
+        return;
+    if (fgets(buffer, sizeof(buffer), pipe) != NULL) {
+        sscanf(buffer, "%s %s %s %s %s %s", fileSys, blocks, used, free, percent, moment);
+    }
+    if (fgets(buffer, sizeof(buffer), pipe) != NULL) {
+        sscanf(buffer, "%s %s %s %s %s %s", fileSys, blocks, used, free, percent, moment);
+    }
+    // printf("desk used:%s\n",percent);
+    strcpy(*reused, percent);
+    pclose(pipe);
+    return;
+}
+
+void getCurrentDownloadRates(long int *save_rate)
+{
+    char intface[] = "eth0:"; // 这是网络接口名,根据主机配置
+    // char intface[] = "wlan0:";
+    FILE *net_dev_file;
+    char buffer[1024];
+    size_t bytes_read;
+    char *match;
+    if ((net_dev_file = fopen("/proc/net/dev", "r")) == NULL) {
+        HTELINK_LOG_ERR("open /proc/net/dev error, %s", strerror(errno));
+        //        exit(EXIT_FAILURE);
+        return;
+    }
+
+    int i = 0;
+    while (i++ < 20) {
+        if (fgets(buffer, sizeof(buffer), net_dev_file) != NULL) {
+            if (strstr(buffer, intface) != NULL) {
+                // printf("%d   %s\n",i,buffer);
+                sscanf(buffer, "%s %ld", buffer, save_rate);
+                break;
+            }
+        }
+    }
+    if (i == 20)
+        *save_rate = 0.01;
+    fclose(net_dev_file); // 关闭文件
+    return;
+}
+
+int SetIfAddr(const char *ifname, const char *Ipaddr, const char *mask, const char *gateway)
+{
+    int fd;
+    int rc;
+    struct ifreq ifr;
+    struct sockaddr_in *sin;
+    struct rtentry rt;
+
+    fd = socket(AF_INET, SOCK_DGRAM, 0);
+    if (fd < 0) {
+        HTELINK_LOG_ERR("socket %s,  error, %s", ifname, strerror(errno));
+        return fd;
+    }
+    memset(&ifr, 0, sizeof(ifr));
+    strcpy(ifr.ifr_name, ifname);
+    sin = (struct sockaddr_in *)&ifr.ifr_addr;
+    sin->sin_family = AF_INET;
+
+    // ipaddr
+    if ((rc = inet_aton(Ipaddr, &(sin->sin_addr))) < 0) {
+        HTELINK_LOG_ERR("inet_aton %s, error, %s", ifname, strerror(errno));
+        close(fd);
+        return rc;
+    }
+
+    if ((rc = ioctl(fd, SIOCSIFADDR, &ifr)) < 0) {
+        HTELINK_LOG_ERR("ioctl ifaddr %s, error, %s", ifname, strerror(errno));
+        close(fd);
+        return rc;
+    }
+
+    // netmask
+    if ((rc = inet_aton(mask, &(sin->sin_addr))) < 0) {
+        HTELINK_LOG_ERR("inet_aton %s,  mask error, %s", ifname, strerror(errno));
+        close(fd);
+        return rc;
+    }
+    if ((rc = ioctl(fd, SIOCSIFNETMASK, &ifr)) < 0) {
+        HTELINK_LOG_ERR("ioctl %s, netmask error, %s", ifname, strerror(errno));
+        close(fd);
+        return rc;
+    }
+
+    // gateway
+    memset(&rt, 0, sizeof(struct rtentry));
+    memset(sin, 0, sizeof(struct sockaddr_in));
+    sin->sin_family = AF_INET;
+    sin->sin_port = 0;
+    if ((rc = inet_aton(gateway, &sin->sin_addr)) < 0) {
+        HTELINK_LOG_ERR("inet_aton %s, error, %s", ifname, strerror(errno));
+    }
+    memcpy(&rt.rt_gateway, sin, sizeof(struct sockaddr_in));
+    ((struct sockaddr_in *)&rt.rt_dst)->sin_family = AF_INET;
+    ((struct sockaddr_in *)&rt.rt_genmask)->sin_family = AF_INET;
+    rt.rt_flags = RTF_GATEWAY;
+    if ((rc = ioctl(fd, SIOCADDRT, &rt)) < 0) {
+        HTELINK_LOG_ERR("ioctl(SIOCADDRT)  %s error in set_default_route, %s", ifname, strerror(errno));
+        close(fd);
+        return rc;
+    }
+    close(fd);
+    return 0;
+}
+
+/*
+ * 获取IP
+ */
+int GetIfAddr(const char *iface, char ipaddr[], char mask[], char gateway[])
+{
+    int sockfd;
+    int rc;
+    struct sockaddr_in *sin;
+    struct ifreq ifr_ip;
+    struct rtentry rt;
+
+    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
+        HTELINK_LOG_ERR("%s socket create failse...GetLocalIp! %s", iface, strerror(errno));
+        return sockfd;
+    }
+
+    /* zero struct */
+    memset(&ifr_ip, 0, sizeof(ifr_ip));
+    strncpy(ifr_ip.ifr_name, iface, sizeof(ifr_ip.ifr_name) - 1);
+
+    /* get ip */
+    if ((rc = ioctl(sockfd, SIOCGIFADDR, &ifr_ip)) < 0) {
+        HTELINK_LOG_ERR("ioctl ip %s,  error, %s", iface, strerror(errno));
+        close(sockfd);
+        return rc;
+    }
+    sin = (struct sockaddr_in *)&ifr_ip.ifr_addr;
+    strcpy(ipaddr, inet_ntoa(sin->sin_addr));
+
+    /* get netmask */
+    if ((rc = ioctl(sockfd, SIOCGIFNETMASK, &ifr_ip)) < 0) {
+        HTELINK_LOG_ERR("netmask ioctl %s,  error, %s", iface, strerror(errno));
+        close(sockfd);
+        return rc;
+    }
+    sin = (struct sockaddr_in *)&(ifr_ip.ifr_netmask);
+    strcpy(mask, inet_ntoa(sin->sin_addr));
+
+    /* gateway */
+    if ((rc = ioctl(sockfd, SIOCGIFCONF, &ifr_ip)) < 0) {
+        HTELINK_LOG_ERR("gateway ioctl %s,  error, %s", iface, strerror(errno));
+        close(sockfd);
+        return rc;
+    }
+    sin = (struct sockaddr_in *)&(ifr_ip.ifr_addr);
+    inet_ntop(AF_INET, &sin->sin_addr, gateway, INET_ADDRSTRLEN);
+
+    close(sockfd);
+
+    return rc;
+}
+
+/*
+ * 获取IP
+ */
+bool GetLocalIp(char ipaddr[])
+{
+    return GetLocalIp("eth0", ipaddr);
+}
+
+bool GetLocalIp(const char *iface, char ipaddr[])
+{
+    int sock_get_ip;
+
+    struct sockaddr_in *sin;
+    struct ifreq ifr_ip;
+
+    if ((sock_get_ip = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
+        printf("socket create failse...GetLocalIp!/n");
+        return false;
+    }
+
+    memset(&ifr_ip, 0, sizeof(ifr_ip));
+    strncpy(ifr_ip.ifr_name, iface, sizeof(ifr_ip.ifr_name) - 1);
+
+    if (ioctl(sock_get_ip, SIOCGIFADDR, &ifr_ip) < 0) {
+        return false;
+    }
+    sin = (struct sockaddr_in *)&ifr_ip.ifr_addr;
+    strcpy(ipaddr, inet_ntoa(sin->sin_addr));
+
+    printf("local ip:%s /n", ipaddr);
+    close(sock_get_ip);
+
+    return true;
+}
+
+/*
+ * 修改本机IP地址的函数
+ */
+int SetLocalIp(const char *iface, const char *ipaddr)
+{
+    int sock_set_ip;
+
+    struct sockaddr_in sin_set_ip;
+    struct ifreq ifr_set_ip;
+
+    bzero(&ifr_set_ip, sizeof(ifr_set_ip));
+
+    if (ipaddr == NULL)
+        return -1;
+
+    if (sock_set_ip = socket(AF_INET, SOCK_STREAM, 0) == -1)
+        ;
+    {
+        perror("socket create failse...SetLocalIp!/n");
+        return -1;
+    }
+
+    memset(&sin_set_ip, 0, sizeof(sin_set_ip));
+    strncpy(ifr_set_ip.ifr_name, iface, sizeof(ifr_set_ip.ifr_name) - 1);
+
+    sin_set_ip.sin_family = AF_INET;
+    sin_set_ip.sin_addr.s_addr = inet_addr(ipaddr);
+    memcpy(&ifr_set_ip.ifr_addr, &sin_set_ip, sizeof(sin_set_ip));
+
+    if (ioctl(sock_set_ip, SIOCSIFADDR, &ifr_set_ip) < 0) {
+        perror("Not setup interface/n");
+        return -1;
+    }
+
+    // 设置激活标志
+    ifr_set_ip.ifr_flags |= IFF_UP | IFF_RUNNING;
+
+    // get the status of the device
+    if (ioctl(sock_set_ip, SIOCSIFFLAGS, &ifr_set_ip) < 0) {
+        perror("SIOCSIFFLAGS");
+        return -1;
+    }
+
+    close(sock_set_ip);
+    return 0;
+}
+
+/*
+ *获取子网掩码的函数
+ */
+bool GetLocalNetMask(const char *ifname, char netmask_addr[])
+{
+    int sock_netmask;
+
+    struct ifreq ifr_mask;
+    struct sockaddr_in *net_mask;
+
+    sock_netmask = socket(AF_INET, SOCK_STREAM, 0);
+    if (sock_netmask == -1) {
+        perror("create socket failture...GetLocalNetMask/n");
+        return false;
+    }
+
+    memset(&ifr_mask, 0, sizeof(ifr_mask));
+    strncpy(ifr_mask.ifr_name, ifname, sizeof(ifr_mask.ifr_name) - 1);
+
+    if ((ioctl(sock_netmask, SIOCGIFNETMASK, &ifr_mask)) < 0) {
+        printf("mac ioctl error/n");
+        return false;
+    }
+
+    net_mask = (struct sockaddr_in *)&(ifr_mask.ifr_netmask);
+    strcpy(netmask_addr, inet_ntoa(net_mask->sin_addr));
+
+    printf("local netmask:%s/n", netmask_addr);
+
+    close(sock_netmask);
+    return true;
+}
+
+/*
+ * 修改子NETMASK的函数
+ */
+bool SetLocalNetMask(const char *iface, const char *szNetMask)
+{
+    int sock_netmask;
+    char netmask_addr[32];
+
+    struct ifreq ifr_mask;
+    struct sockaddr_in *sin_net_mask;
+
+    sock_netmask = socket(AF_INET, SOCK_STREAM, 0);
+    if (sock_netmask == -1) {
+        perror("Not create network socket connect/n");
+        return false;
+    }
+
+    memset(&ifr_mask, 0, sizeof(ifr_mask));
+    strncpy(ifr_mask.ifr_name, iface, sizeof(ifr_mask.ifr_name) - 1);
+    sin_net_mask = (struct sockaddr_in *)&ifr_mask.ifr_addr;
+    sin_net_mask->sin_family = AF_INET;
+    inet_pton(AF_INET, szNetMask, &sin_net_mask->sin_addr);
+
+    if (ioctl(sock_netmask, SIOCSIFNETMASK, &ifr_mask) < 0) {
+        printf("sock_netmask ioctl error/n");
+        return false;
+    }
+    return true;
+}
+
+/*
+ * 获去GateWay
+ */
+bool GetGateWay(char gateway[])
+{
+    FILE *fp;
+    char buf[512];
+    char cmd[128];
+
+    strcpy(cmd, "route -n|grep 'UG'");
+    fp = popen(cmd, "r");
+    if (NULL == fp) {
+        perror("popen error");
+        return false;
+    }
+
+    size_t r = fread(buf, 1, sizeof(buf), fp);
+    sscanf(buf, "%*s%s", gateway);
+    pclose(fp);
+
+    return true;
+}
+
+/*
+ * 设置网关
+ */
+int SetGateWay(const char *szGateWay)
+{
+    int ret = 0;
+    char cmd[128];
+    char strGW[50];
+
+    GetGateWay(strGW);
+
+    strcpy(cmd, "route del default gw ");
+    strcat(cmd, strGW);
+    ret = system(cmd);
+    if (ret < 0) {
+        perror("route error");
+        return -1;
+    }
+    strcpy(cmd, "route add default gw ");
+    strcat(cmd, szGateWay);
+
+    ret = system(cmd);
+    if (ret < 0) {
+        perror("route error");
+        return -1;
+    }
+
+    return ret;
+}
+
+/*
+ *获取本机MAC地址函数
+ */
+bool GetLocalMac(const char *eth, char mac_addr[30])
+{
+    int sock_mac;
+    struct ifreq ifr_mac;
+
+    sock_mac = socket(AF_INET, SOCK_STREAM, 0);
+    if (sock_mac == -1) {
+        perror("create socket falise...mac");
+        return false;
+    }
+
+    memset(&ifr_mac, 0, sizeof(ifr_mac));
+    strncpy(ifr_mac.ifr_name, eth, sizeof(ifr_mac.ifr_name) - 1);
+
+    if ((ioctl(sock_mac, SIOCGIFHWADDR, &ifr_mac)) < 0) {
+        printf("mac ioctl error/n");
+        return false;
+    }
+
+    sprintf(mac_addr, "%02X:%02X:%02X:%02X:%02X:%02X", (unsigned char)ifr_mac.ifr_hwaddr.sa_data[0],
+        (unsigned char)ifr_mac.ifr_hwaddr.sa_data[1], (unsigned char)ifr_mac.ifr_hwaddr.sa_data[2],
+        (unsigned char)ifr_mac.ifr_hwaddr.sa_data[3], (unsigned char)ifr_mac.ifr_hwaddr.sa_data[4],
+        (unsigned char)ifr_mac.ifr_hwaddr.sa_data[5]);
+
+    printf("local mac:%s /n", mac_addr);
+
+    close(sock_mac);
+    return true;
+}
+} // namespace sysinfo
+} // namespace settings

+ 82 - 0
settings/sysinfo.h

@@ -0,0 +1,82 @@
+#ifndef FOUNDATION_SETTINGS_SYSINFO_H
+#define FOUNDATION_SETTINGS_SYSINFO_H
+
+namespace settings {
+namespace sysinfo {
+#define MAXBUFSIZE  1024
+#define WAIT_SECOND 3 // 暂停时间,单位为“秒”
+
+typedef struct occupy {
+    char name[20];
+    unsigned int user;
+    unsigned int nice;
+    unsigned int system;
+    unsigned int idle;
+} CPU_OCCUPY;
+
+typedef struct PACKED {
+    char name[20];
+    long total;
+    char name2[20];
+    long free;
+} MEM_OCCUPY;
+
+double cal_occupy(CPU_OCCUPY *o, CPU_OCCUPY *n);
+
+void get_occupy(CPU_OCCUPY *o);
+
+void get_mem_occupy(MEM_OCCUPY *mem);
+
+float get_io_occupy();
+
+void get_disk_occupy(char **reused);
+
+void getCurrentDownloadRates(long int *save_rate);
+
+/**
+ * 设置IP
+ */
+int SetIfAddr(const char *ifname, const char *Ipaddr, const char *mask, const char *gateway);
+
+/*
+ * 获取IP
+ */
+int GetIfAddr(const char *iface, char ipaddr[], char mask[], char gateway[]);
+
+/*
+ * 获取IP
+ */
+bool GetLocalIp(const char *iface, char ipaddr[]);
+
+/*
+ * 修改本机IP地址的函数
+ */
+int SetLocalIp(const char *iface, const char *ipaddr);
+
+/*
+ *获取子网掩码的函数
+ */
+bool GetLocalNetMask(const char *ifname, char netmask_addr[]);
+
+/*
+ * 修改子NETMASK的函数
+ */
+bool SetLocalNetMask(const char *iface, const char *szNetMask);
+
+/*
+ * 获去GateWay
+ */
+bool GetGateWay(char gateway[]);
+
+/*
+ * 设置网关
+ */
+int SetGateWay(const char *szGateWay);
+
+/*
+ *获取本机MAC地址函数
+ */
+bool GetLocalMac(const char *eth, char mac_addr[30]);
+} // namespace sysinfo
+} // namespace settings
+#endif

+ 115 - 0
settings/system_settings.cpp

@@ -0,0 +1,115 @@
+#include "sysinfo.h"
+#include "system_settings.h"
+#include <fstream>
+#include <iostream>
+#include <map>
+#include <net/if.h>
+#include <sstream>
+#include <string>
+#include <sys/ioctl.h>
+#include <sys/statfs.h>
+#include <sys/sysinfo.h>
+#include <sys/utsname.h>
+#include <utils/custom.h>
+#include <vector>
+
+namespace settings {
+
+void SystemSettings::UpdateNetDev()
+{
+    std::ifstream file("/proc/net/dev");
+    std::string line;
+
+    netCards.clear();
+    // 跳过前两行标题
+    std::getline(file, line);
+    std::getline(file, line);
+
+    while (std::getline(file, line)) {
+        std::istringstream iss(line);
+        std::string interface;
+        if (!(iss >> interface)) {
+            continue;
+        }
+
+        interface = interface.substr(0, interface.length() - 1);
+        if (interface == "lo") {
+            continue;
+        }
+        // 跳过冒号后的空白字符
+        char colon;
+        iss >> std::ws >> colon;
+
+        std::string stats_str;
+        std::getline(iss, stats_str); // 读取剩余所有统计信息
+
+        NetCard interface_stats;
+        std::istringstream stats_iss(stats_str);
+        std::string item;
+        unsigned long long value;
+        std::vector<int32_t *> keys = {&interface_stats.rxPackets, &interface_stats.rxBytes, &interface_stats.rxErrs,
+            &interface_stats.rxDrop, &interface_stats.rxFifoErr, &interface_stats.rxFrameErr,
+            &interface_stats.rxCompressed, &interface_stats.rxMulticast, &interface_stats.txPackets,
+            &interface_stats.txBytes, &interface_stats.txErrs, &interface_stats.txDrop, &interface_stats.txFifoErr,
+            &interface_stats.txCollisionErr, &interface_stats.txCarrierErr, &interface_stats.txCompressed};
+
+        interface_stats.ifname = interface;
+        for (const auto &key : keys) {
+            if (stats_iss >> value) { // 尝试从流中读取一个值
+                *key = value;
+                // 如果需要,可以跳过分隔符(这里假设是空格或制表符,由std::istringstream自动处理)
+            }
+        }
+
+        // 获取MAC, IP
+        char ipaddr[64];
+        char macaddr[64];
+        char mask[64];
+        char gateway[64];
+        sysinfo::GetIfAddr(interface_stats.ifname.c_str(), ipaddr, mask, gateway);
+        sysinfo::GetLocalMac(interface_stats.ifname.c_str(), macaddr);
+        interface_stats.ipAddr = ipaddr;
+        interface_stats.mask = mask;
+        interface_stats.MAC = macaddr;
+        interface_stats.gateway = gateway;
+
+        netCards.push_back(interface_stats);
+    }
+}
+
+bool SystemSettings::UpdateSysInfo()
+{
+    // appVer
+    appVer = DAS_VERSION;
+    // sysver
+    struct utsname un;
+    uname(&un);
+    sysVer = std::string(un.sysname) + " " + std::string(un.release) + " " + std::string(un.machine);
+
+    // systime
+    sysTime = utils::nowtostr();
+    return true;
+}
+
+bool SystemSettings::UpdateDiskInfo()
+{
+    struct statfs diskinfo;
+
+    statfs("/", &diskinfo);
+
+    double fused = diskinfo.f_bfree / 1024.0 * diskinfo.f_bsize / 1024.0;
+    double ftotal = diskinfo.f_blocks / 1024.0 * diskinfo.f_bsize / 1024.0;
+    totalDiskSpace = ftotal;
+    freeDiskSpace = fused;
+    return true;
+}
+
+bool SystemSettings::UpdateMemInfo()
+{
+    sysinfo::MEM_OCCUPY mc;
+    sysinfo::get_mem_occupy(&mc);
+    totalMemory = mc.total / 1024.0;
+    freeMemory = mc.free / 1024.0;
+    return true;
+}
+} // namespace settings

+ 57 - 0
settings/system_settings.h

@@ -0,0 +1,57 @@
+#ifndef FOUNDATION_SETTINGS_SYSTEM_SETTINGS_H
+#define FOUNDATION_SETTINGS_SYSTEM_SETTINGS_H
+#include <string>
+#include <vector>
+
+namespace settings {
+class SystemSettings {
+public:
+    SystemSettings() = default;
+    bool UpdateSysInfo();
+
+    /// @brief
+    /// @return
+    bool UpdateDiskInfo();
+    bool UpdateMemInfo();
+    void UpdateNetDev();
+
+    int totalDiskSpace;
+    int freeDiskSpace;
+    int totalMemory;
+    int freeMemory;
+    std::string appVer;
+    std::string sysVer;
+    std::string sysTime;
+    std::string upgradeTime;
+    std::string updateConfigTime;
+
+    struct NetCard {
+        std::string ifname;
+        std::string ipAddr;
+        std::string MAC;
+        std::string mask;
+        std::string gateway;
+
+        int32_t rxPackets;
+        int32_t rxBytes;
+        int32_t rxErrs;
+        int32_t rxDrop;
+        int32_t rxFifoErr;
+        int32_t rxFrameErr;
+        int32_t rxCompressed;
+        int32_t rxMulticast;
+
+        int32_t txPackets;
+        int32_t txBytes;
+        int32_t txErrs;
+        int32_t txDrop;
+        int32_t txFifoErr;
+        int32_t txCollisionErr;
+        int32_t txCompressed;
+        int32_t txCarrierErr;
+    };
+    std::vector<NetCard> netCards;
+};
+} // namespace settings
+
+#endif // FOUNDATION_SETTINGS_SYSTEM_SETTINGS_H

+ 83 - 0
settings/xmlconfig.cpp

@@ -0,0 +1,83 @@
+#include "xmlconfig.h"
+#include <map>
+#include <utils/logger.h>
+
+namespace settings {
+XmlConfig::XmlConfig() {}
+
+XmlConfig::~XmlConfig() {}
+
+bool XmlConfig::Load(const std::string &path)
+{
+    tinyxml2::XMLError err = xmlDocument_.LoadFile(path.c_str());
+    if (err != tinyxml2::XML_SUCCESS) {
+        HTELINK_LOG_ERR("load %s failed, %d", path.c_str(), err);
+        return false;
+    }
+    return true;
+}
+
+void XmlConfig::GetElemValue(const std::string &father, std::function<void(std::map<std::string, std::string> &)> func)
+{
+    xmlRoot_ = xmlDocument_.RootElement();
+    if (!xmlRoot_) {
+        HTELINK_LOG_ERR("XML ROOT is nullptr, %s", father.c_str());
+        return;
+    }
+
+    tinyxml2::XMLElement *fatherEle = xmlRoot_;
+    if (father == "") {
+        fatherEle = xmlRoot_->FirstChildElement(father.c_str());
+        if (!fatherEle) {
+            HTELINK_LOG_ERR("XML ROOT no father element %s", father.c_str());
+            return;
+        }
+    }
+
+    for (tinyxml2::XMLElement *book = xmlRoot_->FirstChildElement(father.c_str()); book != nullptr;
+         book = book->NextSiblingElement(father.c_str())) {
+        std::map<std::string, std::string> kv;
+        for (tinyxml2::XMLElement *elem = book->FirstChildElement(); elem != nullptr;
+             elem = elem->NextSiblingElement()) {
+            kv[elem->Name()] = elem->GetText();
+        }
+        func(kv);
+    }
+}
+
+const std::string XmlConfig::GetElemValueString(const std::string &father, const std::string elem)
+{
+    xmlRoot_ = xmlDocument_.RootElement();
+    if (!xmlRoot_) {
+        HTELINK_LOG_ERR("XML ROOT is nullptr, %s", elem.c_str());
+        return "";
+    }
+
+    tinyxml2::XMLElement *fatherEle = xmlRoot_;
+    if (father != "") {
+        fatherEle = xmlRoot_->FirstChildElement(father.c_str());
+        if (!fatherEle) {
+            HTELINK_LOG_ERR("XML ROOT no father element %s", father.c_str());
+            return "";
+        }
+    }
+    tinyxml2::XMLElement *xmlEle = fatherEle->FirstChildElement(elem.c_str());
+    if (!xmlEle) {
+        HTELINK_LOG_ERR("XML ROOT no child element %s", elem.c_str());
+        return "";
+    }
+    return xmlEle->GetText();
+}
+
+const int32_t XmlConfig::GetElemValueInt(const std::string &father, const std::string elem)
+{
+    std::string result = GetElemValueString(father, elem);
+    return atoi(result.c_str());
+}
+
+const bool XmlConfig::GetElemValueBool(const std::string &father, const std::string elem)
+{
+    std::string result = GetElemValueString(father, elem);
+    return atoi(result.c_str()) != 0;
+}
+} // namespace settings

+ 35 - 0
settings/xmlconfig.h

@@ -0,0 +1,35 @@
+#ifndef FOUNDATION_SETTINGS_XMLCONFIG_H
+#define FOUNDATION_SETTINGS_XMLCONFIG_H
+
+#ifndef __cplusplus
+extern "C" {
+#endif
+
+#include <tinyxml2/tinyxml2.h>
+#ifndef __cplusplus
+}
+#endif
+#include <functional>
+#include <map>
+#include <string>
+#include <utils/logger.h>
+
+namespace settings {
+class XmlConfig {
+public:
+    XmlConfig();
+    ~XmlConfig();
+    bool Load(const std::string &path);
+
+    void GetElemValue(const std::string &father, std::function<void(std::map<std::string, std::string> &)>);
+
+    const std::string GetElemValueString(const std::string &father, const std::string elem);
+    const int32_t GetElemValueInt(const std::string &father, const std::string elem);
+    const bool GetElemValueBool(const std::string &father, const std::string elem);
+
+private:
+    tinyxml2::XMLDocument xmlDocument_;
+    tinyxml2::XMLElement *xmlRoot_;
+};
+} // namespace settings
+#endif // FOUNDATION_WEBCONFIG_XMLCONFIG_H

+ 20 - 0
web-deamon/CMakeLists.txt

@@ -0,0 +1,20 @@
+# 模块名称
+set(MODULE web-deamon)
+
+message("GOAHEAD_INCLUDE: ${GOAHEAD_INCLUDE_DIR}, GOAHEAD_LINK: ${GOAHEAD_LIBS_DIR}")
+
+include_directories(${PRODUCT_ROOT_DIR}/thirdparty/hat-trie/include)
+
+# find_library(LIBEVENT_CORE_LIBRARY event_core ${LIBEVENT_LIBS_DIR} NO_DEFAULT_PATH)
+
+add_executable(${MODULE} web_vendor.cpp web_handler.cpp web_deamon.cpp ajax_handler.cpp)
+target_link_directories(${MODULE} PUBLIC ${GOAHEAD_LIBS_DIR} ${JSONCPP_LIBS_DIR})
+target_include_directories(${MODULE} PUBLIC ./  ../
+        ${GOAHEAD_INCLUDE_DIR}
+        ${JSONCPP_INCLUDE_DIR})
+add_dependencies(${MODULE} vendor)
+target_link_libraries(${MODULE} $<TARGET_OBJECTS:vendor> settings
+        go jsoncpp)
+install(TARGETS ${MODULE}
+        DESTINATION webconfig/
+        PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ)

+ 88 - 0
web-deamon/ajax_handler.cpp

@@ -0,0 +1,88 @@
+#include "ajax_handler.h"
+#include <settings/config_parser.h>
+#include <settings/system_settings.h>
+
+namespace webconfig {
+Json::Value GetJsonDataCenter(const Json::Value &param)
+{
+    settings::ConfigParser configParser;
+    Json::Value baseConfig;
+    std::vector<settings::ConfigParser::DataCenter> dataCenters = configParser.GetDataCenter();
+
+    for (settings::ConfigParser::DataCenter dc : dataCenters) {
+        Json::Value jsonDc;
+        jsonDc["id"] = dc.ID;
+        jsonDc["host"] = dc.host;
+        jsonDc["port"] = dc.port;
+        jsonDc["secretKey"] = dc.key;
+        jsonDc["tls"] = dc.isTls ? 1 : 0;
+        baseConfig.append(jsonDc);
+    }
+    return baseConfig;
+}
+
+Json::Value GetJsonNetworkInfo(const Json::Value &param)
+{
+    settings::SystemSettings sysSettings;
+    sysSettings.UpdateNetDev();
+    Json::Value netJson;
+    for (settings::SystemSettings::NetCard &netCard : sysSettings.netCards) {
+        Json::Value netJ;
+        netJ["ip"] = netCard.ipAddr;
+        netJ["mac"] = netCard.MAC;
+        netJ["name"] = netCard.ifname;
+        netJ["gateway"] = netCard.gateway;
+        netJ["netmask"] = netCard.mask;
+        netJ["model"] = false;
+        netJson.append(netJ);
+    }
+    return netJson;
+}
+
+Json::Value GetJsonDiskInfo(const Json::Value &param)
+{
+    Json::Value diskJson;
+    settings::SystemSettings sysSettings;
+    sysSettings.UpdateDiskInfo();
+    char disk[20], mem[20];
+    sprintf(disk, "%d M/%d M", sysSettings.freeDiskSpace, sysSettings.totalDiskSpace);
+    sprintf(mem, "%d M/%d M", sysSettings.freeMemory, sysSettings.totalMemory);
+    diskJson["free"] = sysSettings.freeDiskSpace;
+    diskJson["total"] = sysSettings.totalDiskSpace;
+    return diskJson;
+}
+
+Json::Value GetJsonMemInfo(const Json::Value &param)
+{
+    settings::SystemSettings sysSettings;
+    sysSettings.UpdateMemInfo();
+    Json::Value memJson;
+    memJson["free"] = sysSettings.freeMemory;
+    memJson["total"] = sysSettings.totalMemory;
+    return memJson;
+}
+
+Json::Value GetJsonSysInfo(const Json::Value &param)
+{
+    settings::SystemSettings sysSettings;
+    sysSettings.UpdateSysInfo();
+    Json::Value sysJson;
+    sysJson["version"] = sysSettings.appVer;
+    sysJson["time"] = sysSettings.sysTime;
+    sysJson["upgradeTime"] = sysSettings.upgradeTime;
+    sysJson["updateConfigTime"] = sysSettings.updateConfigTime;
+    return sysJson;
+}
+
+Json::Value GetJsonGatewayInfo(const Json::Value &param)
+{
+    Json::Value result;
+    result["disk"] = GetJsonDiskInfo();
+    result["memory"] = GetJsonMemInfo();
+
+    result["network"] = GetJsonNetworkInfo();
+    result["system"] = GetJsonSysInfo();
+    return result;
+}
+
+} // namespace webconfig

+ 21 - 0
web-deamon/ajax_handler.h

@@ -0,0 +1,21 @@
+#ifndef FOUNDATION_WEBCONFIG_AJAXHANDLER_H
+#define FOUNDATION_WEBCONFIG_AJAXHANDLER_H
+#include <json/json.h>
+#include <string>
+
+namespace webconfig {
+
+Json::Value GetJsonNetworkInfo(const Json::Value &param = Json::nullValue);
+
+Json::Value GetJsonDiskInfo(const Json::Value &param = Json::nullValue);
+
+Json::Value GetJsonMemInfo(const Json::Value &param = Json::nullValue);
+
+Json::Value GetJsonSysInfo(const Json::Value &param = Json::nullValue);
+
+Json::Value GetJsonDataCenter(const Json::Value &param = Json::nullValue);
+Json::Value GetJsonGatewayInfo(const Json::Value &param = Json::nullValue);
+
+} // namespace webconfig
+
+#endif // FOUNDATION_WEBCONFIG_AJAXHANDLER_H

+ 22 - 0
web-deamon/web_deamon.cpp

@@ -0,0 +1,22 @@
+#include "web_vendor.h"
+
+int main(int argc, char *argv[])
+{
+    printf("enter\n");
+    fflush(stdout);
+    HTELINK_LOG_ENABLE(true);
+
+    HTELINK_LOG_INFO("check env set");
+    if (getenv(VENDOR_RUN_PATH_ENV) == nullptr) {
+        HTELINK_LOG_INFO("execute env not set");
+        std::string exe_dir = utils::get_executable_directory();
+        setenv(VENDOR_RUN_PATH_ENV, exe_dir.c_str(), 1);
+    }
+
+    HTELINK_LOG_INFO("execute directory is %s", getenv(VENDOR_RUN_PATH_ENV));
+    vendor::VendorBase *vdor = new WebVendor();
+    if (vendor::VendorBase::ParseOptionArgs(vdor, argc, argv) != 0) {
+        exit(-1);
+    }
+    return vdor->Exec();
+}

+ 351 - 0
web-deamon/web_handler.cpp

@@ -0,0 +1,351 @@
+#include "ajax_handler.h"
+#include "settings/system_settings.h"
+#include "web_handler.h"
+#include <json/json.h>
+#include <string>
+#include <tsl/htrie_map.h>
+#include <utils/custom.h>
+#include <utils/logger.h>
+/* clang-format */
+#include <goahead.h>
+
+#undef min
+
+using WebsNode = tsl::htrie_map<char, std::function<Json::Value(Webs *, const std::string &)>>;
+
+static const WebsNode AJAX_WEB_NODES = {
+    {"login",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            std::string token = utils::get_rand(32);
+            Json::Value param;
+            Json::Reader jsonReader;
+
+            HTELINK_LOG_DEBUG("input buf = %s", wp->input.buf);
+            if (!jsonReader.parse(wp->input.buf, param, false)) {
+                HTELINK_LOG_ERR("login parse buf error, buf = %s", (char *)wp->input.buf);
+                return Json::nullValue;
+            }
+            HTELINK_LOG_DEBUG("param = %s", param.toStyledString().c_str());
+            const std::string name = param["username"].asString();
+            const std::string passwd = param["password"].asString();
+
+            Json::Value result;
+            result["code"] = 200;
+            result["message"] = "验证成功";
+            Json::Value tokenJson;
+            tokenJson["token"] = token;
+            result["data"] = tokenJson;
+            return result;
+        }                 },
+    {"logout",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            return result;
+        }                 },
+    {"UID",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            return result;
+        }                 },
+    {"download",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            return result;
+        }                 },
+    {"getBaseConfig",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            result["data"] = webconfig::GetJsonDataCenter();
+            result["code"] = 200;
+            result["message"] = "SUCCESS";
+            return result;
+        }                 },
+    {"getGatewayInfo",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            result["data"] = webconfig::GetJsonGatewayInfo();
+            result["code"] = 200;
+            result["message"] = "SUCCESS";
+            return result;
+        }                 },
+    {"getGatewayStatus",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            Json::Value statJson;
+            statJson["status"] = true;
+            result["code"] = 200;
+            result["message"] = u"在线";
+            result["data"] = statJson;
+            return result;
+        }                 },
+    {"getDarcyConfig",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            return result;
+        }                 },
+    {"reset",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            return result;
+        }                 },
+    {"setNetworkConfig",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            return result;
+        }                 },
+    {"restart",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            return result;
+        }                 },
+    {"reboot",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            return result;
+        }                 },
+    {"deviceType",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            return result;
+        }                 },
+    {"commu",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            return result;
+        }                 },
+    {"deviceList",
+     [](Webs *wp,                     const std::string &subID) -> Json::Value {
+            Json::Value result;
+            return result;
+        }                 },
+    {"ctrlParams",       [](Webs *wp, const std::string &subID) -> Json::Value {
+         Json::Value result;
+         return result;
+     }}
+};
+
+/* clang-format off */
+static const WebsNode UID_WEB_NODES = {
+    {"loadChildNodes/dataCenter", [](Webs *wp,const std::string &subID) -> Json::Value {
+        Json::Value result;
+        settings::ConfigParser configParser;
+        std::vector<settings::ConfigParser::DataCenter> dataCenters = configParser.GetDataCenter();
+        int index = 0;
+        for (settings::ConfigParser::DataCenter &dc : dataCenters){
+            char key[64];
+            sprintf(key, "dataCenter/%d", index++);
+            result[key] = dc.name;
+        }
+        return result;
+    }},
+    {"loadChildNodes/communicator", [](Webs *wp, const std::string &subID) -> Json::Value {
+        Json::Value result;
+        return result;
+    }},
+    {"loadChildNodes/d", [](Webs *wp, const std::string &subID) -> Json::Value {
+        Json::Value result;
+        return result;
+    }},
+    {"loadNode/getGatewayInfo", [](Webs *wp, const std::string &subID) -> Json::Value {
+        settings::SystemSettings sysSettings;
+        sysSettings.UpdateSysInfo();
+        char disk[20], mem[20];
+        sprintf(disk, "%d M/%d M", sysSettings.freeDiskSpace, sysSettings.totalDiskSpace);
+        sprintf(mem, "%d M/%d M", sysSettings.freeMemory, sysSettings.totalMemory);
+        Json::Value result;
+        Json::Value diskJson;
+        diskJson["free"] = sysSettings.freeDiskSpace;
+        diskJson["total"] = sysSettings.totalDiskSpace;
+        result["disk"] = diskJson;
+
+        Json::Value memJson;
+        memJson["free"] = sysSettings.freeMemory;
+        memJson["total"] = sysSettings.totalMemory;
+        result["memory"] = memJson;
+
+        sysSettings.UpdateNetDev();
+        Json::Value netJson;
+        for (settings::SystemSettings::NetCard &netCard: sysSettings.netCards) {
+            Json::Value netJ;
+            netJ["ip"] = netCard.ipAddr;
+            netJ["mac"] = netCard.MAC;
+            netJson.append(netJ);
+        }
+        result["network"] = netJson;
+
+        Json::Value sysJson;
+        sysJson["version"] = sysSettings.appVer;
+        sysJson["time"] = sysSettings.sysTime;
+        sysJson["upgradeTime"] = sysSettings.upgradeTime;
+        sysJson["updateConfigTime"] = sysSettings.updateConfigTime;
+        result["system"] = sysJson;
+        Json::Value root;
+        root["data"]  =result;
+        return root;
+    }},
+    {"loadNode/getGatewayStatus", [](Webs *wp, const std::string &subID) -> Json::Value {
+        Json::Value result;
+        Json::Value statJson;
+        statJson["status"] = false;
+        result["code"] = 200;
+        result["message"] = "";
+        result["data"] = statJson;
+        return result;
+    }},
+    {"loadNode/dataCenter", [](Webs *wp, const std::string &subID) -> Json::Value {
+        settings::ConfigParser configParser;
+        std::vector<settings::ConfigParser::DataCenter> dataCenters = configParser.GetDataCenter();
+        Json::Value result;
+        for (settings::ConfigParser::DataCenter &center : dataCenters) {
+            Json::Value centerJson;
+            centerJson["id"] = center.ID;
+            centerJson["type"] = center.protoType;
+            centerJson["ip"] = center.host;
+            centerJson["port"] = center.port;
+            centerJson["isOnline"] = false;
+            centerJson["recv"] = 0;
+
+        }
+        return result;
+    }},
+    {"loadNode/communicator", [](Webs *wp, const std::string &subID) -> Json::Value {
+        Json::Value result;
+        return result;
+    }},
+    {"loadNode/d", [](Webs *wp, const std::string &subID) -> Json::Value {
+        Json::Value result;
+        return result;}},
+    {"loadNode/param", [](Webs *wp, const std::string &subID) -> Json::Value {
+        Json::Value result;
+        return result;
+    }},
+    {"ctrl", [](Webs *wp, const std::string &subID) -> Json::Value {
+        const char* id = websGetVar(wp, "deviceId", "");
+        const char* name = websGetVar(wp, "paramName", "");
+        const char* value = websGetVar(wp, "paramValue", "");
+        return Json::nullValue;
+    }},
+    {"acquire", [](Webs *wp, const std::string &subID) -> Json::Value {
+        Json::Value result;
+        return result;
+    }},
+    {"point", [](Webs *wp, const std::string &subID) -> Json::Value {
+        Json::Value result;
+        return result;
+    }},
+    };
+/* clang-format on */
+
+WebHandler::WebHandler()
+{
+    // WebNode webNode = {"loadChildNodes", {{"dataCenter", {}}, {"communicator", {}}, {"d", {}}}};
+}
+
+WebHandler *WebHandler::instance()
+{
+    static WebHandler *webHandler = nullptr;
+    if (webHandler == nullptr) {
+        webHandler = new WebHandler();
+    }
+    ASSERT(webHandler != nullptr);
+    return webHandler;
+}
+
+bool WebHandler::LoginVerify(Webs *wp)
+{
+    char passbuf[ME_GOAHEAD_LIMIT_PASSWORD * 3 + 3];
+    bool success;
+
+    assert(wp);
+    if (!wp->user && (wp->user = websLookupUser(wp->username)) == 0) {
+        trace(5, "verifyUser: Unknown user \"%s\"", wp->username);
+        return false;
+    }
+    /*
+        Verify the password. If using Digest auth, we compare the digest of the password.
+        Otherwise we encode the plain-text password and compare that
+     */
+
+    if (!wp->encoded) {
+        fmt(passbuf, sizeof(passbuf), "%s:%s:%s", wp->username, "htelink", wp->password);
+        wfree(wp->password);
+        wp->password = websMD5(passbuf);
+        wp->encoded = 1;
+    }
+
+    HTELINK_LOG_DEBUG("encode = %d, username = %s, password = %s, digest = %s, store password = %s", wp->encoded,
+        wp->username, wp->password, wp->digest, wp->user->password);
+    if (wp->digest) {
+        success = smatch(wp->password, wp->digest);
+    } else {
+        success = smatch(wp->password, wp->user->password);
+    }
+    if (success) {
+        trace(5, "User \"%s\" authenticated", wp->username);
+    } else {
+        trace(5, "Password for user \"%s\" failed to authenticate", wp->username);
+    }
+    return success;
+}
+
+Json::Value WebHandler::UidWebResult(Webs *wp, const std::string &node)
+{
+    HTELINK_LOG_DEBUG("web handler, node: %s", node.c_str());
+    std::string longest_prefix = UID_WEB_NODES.longest_prefix(node).key();
+    HTELINK_LOG_DEBUG("longest prefix, key: %s", longest_prefix.c_str());
+    std::function<Json::Value(Webs *, const std::string &)> func = UID_WEB_NODES.longest_prefix(node).value();
+    if (!func) {
+        return Json::nullValue;
+    }
+    const std::string subId = node.substr(longest_prefix.length());
+    HTELINK_LOG_DEBUG("subId = %s", subId.c_str());
+    return func(wp, subId);
+}
+
+Json::Value WebHandler::AjaxWebResult(Webs *wp, const std::string &node)
+{
+    HTELINK_LOG_DEBUG("web handler, node: %s", node.c_str());
+    WebsNode::const_iterator webNode = AJAX_WEB_NODES.longest_prefix(node);
+    if (webNode == AJAX_WEB_NODES.end()) {
+        HTELINK_LOG_ERR("web handler, node: %s not found", node.c_str());
+        return Json::nullValue;
+    }
+    std::string longestPrefix = webNode.key();
+    HTELINK_LOG_DEBUG("longest prefix, key: %s", longestPrefix.c_str());
+    std::function<Json::Value(Webs *, const std::string &)> func = webNode.value();
+    if (!func) {
+        return Json::nullValue;
+    }
+    const std::string subId = node.substr(std::min(node.length(), longestPrefix.length() + 1));
+    HTELINK_LOG_DEBUG("subId = %s", subId.c_str());
+    return func(wp, subId);
+}
+
+bool WebHandler::WebResult(Webs *wp, const std::string &prefix)
+{
+    HTELINK_LOG_DEBUG("webs ajax path: %s, prefix = %s, user = %s, method = %s, protocol = %s",
+        wp->path == nullptr ? "" : wp->path, wp->route->prefix, wp->username, wp->method, wp->protocol);
+    std::string path = wp->path;
+#undef min
+    path = path.substr(std::min(path.length(), prefix.length()));
+    Json::Value result;
+    if (prefix == "/ajax/") {
+        result = AjaxWebResult(wp, path);
+        websSetStatus(wp, 200);
+    } else if (prefix == "/uid/") {
+        result = UidWebResult(wp, path);
+        websSetStatus(wp, 200);
+    } else {
+        websSetStatus(wp, 401);
+    }
+
+    websWriteHeaders(wp, -1, 0);
+    websWriteEndHeaders(wp);
+
+    Json::FastWriter jsonWriter;
+    std::string strJson = jsonWriter.write(result);
+    HTELINK_LOG_DEBUG("response: %s", result.toStyledString().c_str());
+    websWrite(wp, strJson.c_str());
+    websDone(wp);
+    return true;
+}

+ 28 - 0
web-deamon/web_handler.h

@@ -0,0 +1,28 @@
+#ifndef FOUNDATION_WEBCONFIG_H
+#define FOUNDATION_WEBCONFIG_H
+
+#include "settings/config_parser.h"
+#include <functional>
+#include <json/json.h>
+#include <memory>
+#include <stdio.h>
+#include <unordered_map>
+#include <vector>
+
+struct Webs;
+
+class WebHandler {
+public:
+    WebHandler();
+
+    static WebHandler *instance();
+
+    bool LoginVerify(Webs *wp);
+    Json::Value UidWebResult(Webs *wp, const std::string &node);
+    Json::Value AjaxWebResult(Webs *wp, const std::string &node);
+    bool WebResult(Webs *wp, const std::string &prefix);
+
+private:
+};
+
+#endif // FOUNDATION_WEBCONFIG_H

+ 219 - 0
web-deamon/web_vendor.cpp

@@ -0,0 +1,219 @@
+#include "web_handler.h"
+#include "web_vendor.h"
+#include <json/json.h>
+
+/* clang-format */
+#include <goahead.h>
+
+static vendor::MyOpt myOpts_[] = {
+    {"help",     no_argument,       'h', "[options] [documents] [IPaddress][:port]..."       },
+    {"auth",     required_argument, 0,   "User and role configuration"                       },
+    {"debug",    no_argument,       0,   "Run in debug mode"                                 },
+    {"home",     required_argument, 0,   "Change to directory to run"                        },
+    {"log",      required_argument, 0,   "logFile:level, Log to file file at verbosity level"},
+    {"route",    required_argument, 0,   "route file"                                        },
+    {"port",     required_argument, 0,   "set port, default: 8880"                           },
+    {"delay",    required_argument, 0,   "delay secs to quit"                                },
+    {"document", required_argument, 0,   "document"                                          },
+    {"verbose",  required_argument, 0,   "Same as --log stderr:2"                            },
+    {"version",  no_argument,       0,   "version information"                               }
+};
+
+const std::string DAS_WEB_DOCUMENT = ".";
+const int32_t DAS_WEB_PORT = 8880;
+const int32_t DAS_WEB_SSL_PORT = 8881;
+
+WebVendor::WebVendor() : listenPort_(DAS_WEB_PORT), docFile_(DAS_WEB_DOCUMENT), homeDir_(VENDOR_WWW_PATH), duration_(0)
+{
+    routeFile_ = ""; // "route.txt";
+    authFile_ = "";  // "auth.txt";
+    logSetPath(std::string(VENDOR_LOG_PATH).c_str());
+    HTELINK_LOG_INFO("set log path: %s", VENDOR_LOG_PATH.c_str());
+}
+
+WebVendor::~WebVendor()
+{
+    finish_ = 1;
+    websClose();
+}
+
+int WebVendor::ParseCmdline(const std::string &optname, const std::string &optarg)
+{
+    if (optname == "auth") {
+        authFile_ = optarg;
+    } else if (optname == "debug") {
+        websSetDebug(1);
+        debug_ = true;
+    } else if (optname == "home") {
+        homeDir_ = optarg;
+        if (chdir(homeDir_.c_str()) < 0) {
+            HTELINK_LOG_ERR("Cannot change directory to %s", homeDir_.c_str());
+            exit(-1);
+        }
+        HTELINK_LOG_INFO("change to dir: %s", homeDir_.c_str());
+    } else if (optname == "log") {
+        logSetPath(optarg.c_str());
+        HTELINK_LOG_INFO("set log path: %s", optarg.c_str());
+    } else if (optname == "route") {
+        routeFile_ = optarg;
+    } else if (optname == "document") {
+        docFile_ = optarg;
+    } else if (optname == "port") {
+        listenPort_ = atoi(optarg.c_str());
+    } else if (optname == "port") {
+        duration_ = atoi(optarg.c_str());
+    } else if (optname == "verbose") {
+        logSetPath(optarg.c_str());
+        HTELINK_LOG_INFO("set log path: %s", optarg.c_str());
+    } else if (optname == "version") {
+    } else {
+        exit(-1);
+    }
+    return 0;
+}
+
+vendor::MyOpt *WebVendor::GetOpts()
+{
+    return myOpts_;
+}
+
+int WebVendor::GetOptSize()
+{
+    return sizeof(myOpts_) / sizeof(myOpts_[0]);
+}
+
+void sigHandler(int sig)
+{
+    HTELINK_LOG_DEBUG("sigHandler, %d", sig);
+}
+
+int WebVendor::Run()
+{
+    finish_ = 0;
+    signal(SIGTERM, sigHandler);
+    signal(SIGPIPE, SIG_IGN);
+    // _fmode = _O_BINARY;
+
+    if (routeFile_.empty()) {
+        routeFile_ = homeDir_ + "/route.txt";
+    }
+    if (authFile_.empty()) {
+        authFile_ = homeDir_ + "/route.txt";
+    }
+
+    HTELINK_LOG_INFO(
+        "webs Open doc %s, route file %s, auth file %s", docFile_.c_str(), routeFile_.c_str(), authFile_.c_str());
+    if (websOpen(docFile_.empty() ? nullptr : docFile_.c_str(), routeFile_.c_str()) < 0) {
+        HTELINK_LOG_ERR("Cannot initialize server. Exiting.");
+        return -1;
+    }
+    websSetPasswordStoreVerify([](Webs *wp) -> bool {
+        return WebHandler::instance()->LoginVerify(wp);
+    });
+    websSetIndex("index.html");
+    DefineWeb();
+
+    HTELINK_LOG_INFO("webs Load %s", authFile_.c_str());
+    if (websLoad(authFile_.c_str()) < 0) {
+        HTELINK_LOG_ERR("Cannot load %s", authFile_.c_str());
+        return -1;
+    }
+
+    /* clang-format off */
+    std::string listHosts[] = {
+        std::string("http://*:") + std::to_string(listenPort_),
+        // std::string("https://*:") + std::to_string(DAS_WEB_SSL_PORT)
+        };
+    /* clang-format on */
+
+    for (std::string &host : listHosts) {
+        HTELINK_LOG_INFO("webs Listen %s", host.c_str());
+        if (websListen(host.c_str()) < 0) {
+            HTELINK_LOG_ERR("Cannot listen %s", host.c_str());
+            return -1;
+        }
+    }
+
+    DumpWebVendor();
+    if (duration_ > 0) {
+        HTELINK_LOG_INFO("Running for %d secs\n", duration_);
+        websStartEvent(
+            duration_ * 1000,
+            [](void *data, int id) {
+                websStopEvent(id);
+            },
+            &finish_);
+    }
+    websServiceEvents(&finish_);
+    HTELINK_LOG_INFO("webs service exit, err = %s", strerror(errno));
+    return 0;
+}
+
+std::string WebVendor::Name()
+{
+    return "web-deamon";
+}
+
+void WebVendor::Stop(int signal)
+{
+    HTELINK_LOG_INFO("webs exit, signal = %d", signal);
+    finish_ = 1;
+}
+
+void WebVendor::DumpWebVendor(void)
+{
+    char home[ME_GOAHEAD_LIMIT_STRING];
+
+    getcwd(home, sizeof(home));
+    HTELINK_LOG_INFO("Configuration for %s", PRODUCT_NAME);
+    HTELINK_LOG_INFO("---------------------------------------------");
+    HTELINK_LOG_INFO("Version:            %s", DAS_VERSION);
+    HTELINK_LOG_INFO("BuildType:          %s", ME_DEBUG ? "Debug" : "Release");
+    HTELINK_LOG_INFO("CPU:                %s", ME_CPU);
+    HTELINK_LOG_INFO("OS:                 %s", ME_OS);
+    HTELINK_LOG_INFO("Host:               %s", websGetServerUrl());
+    HTELINK_LOG_INFO("Directory:          %s", home);
+    HTELINK_LOG_INFO("Documents:          %s", websGetDocuments());
+    HTELINK_LOG_INFO("Configure:          %s", ME_CONFIG_CMD);
+    HTELINK_LOG_INFO("---------------------------------------------");
+}
+
+void WebVendor::DefineWeb()
+{
+    if (debug_) {
+        websDefineHandler(
+            "debug",
+            [](Webs *wp) -> bool {
+                HTELINK_LOG_DEBUG("webs debug path: %s, prefix = %s, user = %s, password = %s, decode = %d method = "
+                                  "%s, protocol = %s",
+                    wp->path == nullptr ? "" : wp->path, wp->route->prefix, wp->username, wp->password, wp->encoded,
+                    wp->method, wp->protocol);
+                return false;
+            },
+            0, 0, 0);
+    }
+    //
+    websDefineHandler(
+        "uid", 0,
+        [](Webs *wp) -> bool {
+            HTELINK_LOG_DEBUG("webs uid path: %s, prefix = %s, user = %s, method = %s, protocol = %s",
+                wp->path == nullptr ? "" : wp->path, wp->route->prefix, wp->username, wp->method, wp->protocol);
+            return WebHandler::instance()->WebResult(wp, "/uid/");
+        },
+        0, 0);
+    websDefineHandler(
+        "ajax", 0,
+        [](Webs *wp) -> bool {
+            HTELINK_LOG_DEBUG("webs ajax path: %s, prefix = %s, user = %s, method = %s, protocol = %s",
+                wp->path == nullptr ? "" : wp->path, wp->route->prefix, wp->username, wp->method, wp->protocol);
+            return WebHandler::instance()->WebResult(wp, "/ajax/");
+        },
+        0, 0);
+    // "route uri=/ajax handler=ajax\n route uri=%s handler=uid\n route uri=/";
+    websAddRoute("/ajax", "ajax", 0);
+    websAddRoute(std::to_string(getuid()).c_str(), "uid", 0);
+    if (debug_) {
+        websAddRoute("/", "debug", 0);
+    }
+    websAddRoute("/", "file", -1);
+}

+ 34 - 0
web-deamon/web_vendor.h

@@ -0,0 +1,34 @@
+#ifndef FOUNDATION_WEBCONFIG_WEBVENDOR_H
+#define FOUNDATION_WEBCONFIG_WEBVENDOR_H
+
+#include <vendor_global.h>
+
+class WebVendor : public vendor::VendorBase {
+public:
+    WebVendor();
+    virtual ~WebVendor();
+
+    virtual int Run();
+    virtual std::string Name();
+    virtual void Stop(int signal);
+
+protected:
+    virtual int ParseCmdline(const std::string &optname, const std::string &optarg);
+    virtual vendor::MyOpt *GetOpts();
+    virtual int GetOptSize();
+
+private:
+    void DumpWebVendor();
+    void DefineWeb();
+
+private:
+    int32_t listenPort_ = 8880;
+    std::string authFile_;
+    std::string routeFile_;
+    std::string docFile_;
+    std::string homeDir_;
+    bool debug_ = false;
+    int finish_ = 0;
+    int duration_ = 0;
+};
+#endif // FOUNDATION_WEBCONFIG_WEBVENDOR_H

Niektoré súbory nie sú zobrazené, pretože je v týchto rozdielových dátach zmenené mnoho súborov