Nghiên cứu phát triển cảm biến trạng thái cửa ứng dụng trong hệ điều khiển của nhà thông minh (smarthome)

74 0 0
Nghiên cứu phát triển cảm biến trạng thái cửa ứng dụng trong hệ điều khiển của nhà thông minh (smarthome)

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

TRƯỜNG ĐẠI HỌC LÂM NGHIÊP VIỆT NAM KHOA CƠ ĐIỆN VÀ CƠNG TRÌNH BỘ MƠN KỸ THUẬT ĐIỆN VÀ TỰ ĐỘNG HÓA BÁO CÁO KHÓA LUẬN TỐT NGHIỆP NGHIÊN CỨU PHÁT TRIỂN CẢM BIẾN TRẠNG THÁI CỬA ỨNG DỤNG TRONG HỆ ĐIỀU KHIỂN CỦA NHÀ THÔNG MINH (SMARTHOME) NGÀNH : CÔNG NGHỆ KỸ THUẬT CƠ ĐIỆN TỬ MÃ SỐ : 7510203 Giáo viên hướng dẫn : TS Hoàng Sơn Sinh viên thực : Trần Quỳnh Trang Mã sinh viên : 1851080456 Lớp : K63 – CNKTCĐT Khóa học : 2018 – 2022 Hà Nội, 2022 LỜI NÓI ĐẦU Sau năm học trường đại học, Đồ án tốt nghiệp môn học cuối đánh dấu kết thúc trình học tập rèn luyện kiến thức bản, đồng thời mở đường thực tế vào sống tương lai Quá trình làm luận văn giúp em thu thập, tổng hợp lại kiến thức học suốt năm qua, qua rèn luyện khả tính tốn giải vấn đề thực tế Trong trình làm đồ án em gặp khơng khó khăn trở ngại vốn kiến thức cịn hạn chế Dù bận rộn nhiều cơng việc thầy cô giành nhiều thời gian tâm huyết việc hướng dẫn em Các thầy cô quan tâm, bảo sửa chữa vấn đề quan trọng giúp em định hướng làm việc theo quan điểm đắn, tận tâm nhiệt huyết thầy giúp cho em có tinh thần, niềm tin khối lượng kiến thức phong phú để đến ngày hôm đồ án tốt nghiệp em hoàn thành Trước hết, với tất lòng biết ơn sâu sắc, em xin chân thành cảm ơn quý thầy, cô khoa Cơ điện Cơng trình Đặc biệt thầy, mơn Kỹ thuật điện Tự động hóa tận tình dạy trang bị cho em kiến thức cần thiết suốt thời gian ngồi ghế giảng đường, làm tảng cho em hồn thành khóa luận Em xin trân trọng cảm ơn thầy Hồng Sơn tận tình giúp đỡ, định hướng cách tư cách làm việc khoa học Đó góp ý q báu khơng q trình thực khóa luận mà hành trang tiếp bước cho em trình học tập lập nghiệp sau Và cuối em xin gửi lời cảm ơn đến gia đình, người thân, bạn bè ln bên cạnh ủng hộ động viện; cảm ơn tập thể lớp K63-CĐT gắn bó học tập, giúp đỡ em suốt thời gian qua, q trình hồn thành đồ án tốt nghiệp Tuy nhiên điều kiện lực thân hạn chế, chun đề khóa luận tốt nghiệp chắn khơng tránh khỏi thiếu sót Kính mong nhận đóng góp ý kiến thầy giáo, bạn bè để khóa luận em hồn thiện Em xin chân thành cảm ơn! Hà Nội, ngày tháng năm 2022 Sinh viên thực (Chữ ký, họ tên) NHẬN XÉT CỦA GIÁO VIÊN HƯỚNG DẪN Họ tên sinh viên: Mã sinh viên: Lớp: Kết luận: Đồng ý/Không đồng ý cho sinh viên…………nộp báo cáo khóa luận tốt nghiệp Hà Nội, ngày……tháng……năm…… GIÁO VIÊN HƯỚNG DẪN (Chữ ký, Họ tên) NHẬN XÉT CỦA GIÁO VIÊN PHẢN BIỆN Họ tên sinh viên: Mã sinh viên: Lớp: GIÁO VIÊN PHẢN BIỆN (Chữ ký, Họ tên) MỤC LỤC LỜI NÓI ĐẦU MỤC LỤC DANH MỤC CÁC TỪ VIẾT TẮT DANH MỤC CÁC BẢNG DANH MỤC CÁC HÌNH PHẦN 1: TỔNG QUAN VỀ VẤN ĐỀ NGHIÊN CỨU 1 Lí chọn đề tài: Mục tiêu nghiên cứu: Đối tượng nghiên cứu: Phạm vi nghiên cứu: .1 Phương pháp nghiên cứu: Kết dự kiến đạt được: PHẦN 2: NỘI DUNG KHÓA LUẬN CHƯƠNG TỔNG QUAN NHÀ THÔNG MINH VÀ CÁC THIẾT BỊ ĐIỀU KHIỂN CỦA NHÀ THÔNG MINH 1.1 Tổng quan thiết bị điều khiển dùng cho nhà thông minh 1.2 Tổng quan cảm biến cửa nhà thông minh .3 1.2.1 Chức năng, công dụng cảm biến cửa 1.2.2 Các loại cảm biến cửa ứng dụng cho nhà thông minh .5 CHƯƠNG MƠ HÌNH HOẠT ĐỘNG CỦA THIẾT BỊ VÀ NGHIÊN CỨU THIẾT KẾ MẠCH PHẦN CỨNG 2.1 Mơ hình hoạt động thiết bị 2.1.1 Thiết bị mơ hình hoạt động 2.1.2 Cloud server mơ hình hoạt động .8 2.2 Sơ đồ khối phần cứng 2.3 Thiết kế mạch .9 2.3.1 Lựa chọn linh kiện cho mạch 2.3.1.1 Lựa chọn linh kiện cho mạch Điều khiển trung tâm (Gateway) 2.3.1.2 Lựa chọn linh kiện cho mạch Cảm biến (Sensor) 14 2.3.2 Thiết kế mạch nguyên lý mạch in .18 2.3.2.1 Thiết kế mạch nguyên lý mạch in cho mạch Điều khiển trung tâm (Gateway) .18 2.3.2.2 Thiết kế mạch nguyên lý mạch in cho mạch Cảm biến (Sensor) 21 CHƯƠNG NGHIÊN CỨU CẤU TRÚC TRUYỀN THƠNG VÀ TRAO ĐỒI TÍN HIỆU 25 3.1 Công nghệ wifi BLE 25 3.1.1 Wifi 25 3.1.2 Bluetooth Low Energy .25 3.1.3 Ứng dụng beacon BLE .27 3.2 Mơ hình truyền thơng liệu 28 3.2.1 Mơ hình Center-Peripheral BLE 28 3.2.2 Mơ hình Client-Server mạng 29 3.3 Giao thức truyền thông MQTT 31 3.4 Giới thiệu cloud server 32 3.4.1 Cloud server 32 3.4.2 Cloud server Thingspeak .33 CHƯƠNG NGHIÊN CỨU THUẬT TOÁN ĐIỀU KHIỂN VÀ PHẦN MỀM 34 4.1 Lưu đồ giải thuật phần mềm 34 4.1.1 Lưu đồ phần mềm mạch cảm biến 34 4.1.2 Lưu đồ phần mềm mạch điều khiển trung tâm 34 4.2 Cài đặt thông số cloud server 35 4.3 Lập trình phần mềm mạch điều khiển trung tâm mạch cảm biến 37 4.3.1 Lâp trình mạch cảm biến .37 4.3.2 Lâp trình mạch điều khiển trung tâm 38 4.4 Tiến hành kiểm thử nghiệm (kết Demo, kết thử nghiệm thực) 39 4.4.1 Sản phầm sau hoàn thiện 39 4.4.2 Kết liệu cloud .40 4.5 Hướng phát triển 40 KẾT LUẬN - TỒN TẠI - KIẾN NGHỊ .41 Kết luận 41 Tồn 41 Kiến nghị 41 PHỤ LỤC DANH MỤC TÀI LIỆU THAM KHẢO DANH MỤC CÁC TỪ VIẾT TẮT Từ viết tắt IoT VPN Từ đầy đủ Nội dung Internet of Things Là liên mạng, thiết bị, phương tiện vận tải, phịng ốc trang thiết bị khác nhúng với phận điện tử, phần mềm, cảm biến, cấu chấp hành với khả kết nối mạng máy tính giúp cho thiết bị thu thập truyền tải liệu Virtual Private Network Là mạng riêng ảo, cho phép người dùng thiết lập mạng riêng ảo với mạng khác Internet HTTP HyperText Transfer Protocol Giao thức truyền tải siêu văn bản, giao thức ứng dụng sử dụng thường xuyên giao thức TCP/IP (gồm nhóm giao thức tảng cho internet) MQTT Message Queuing Telemetry Transport Là giao thức truyền thông điệp (message) theo mơ hình publish/subscribe (cung cấp/th bao), sử dụng cho thiết bị IoT với băng thông thấp, độ tin cậy cao khả sử dụng mạng lưới không ổn định DANH MỤC CÁC BẢNG Bảng 3.1 Hoạt động mơ hình Center-Peripheral: 29 DANH MỤC CÁC HÌNH Hình 1.1: Tổng quan nhà thông minh Hình 1.2: Cảm biến cửa Hình 1.3: Cảm biến cửa với đèn rèm cửa thông minh Hình 1.4: Cảm biến cửa với cảm biến chuyển động camera thơng minh Hình 1.5: Cảm biến cửa với cịi hú thơng minh Hình 2.1: Mơ hình hoạt động thiết bị Hình 2.2: Sơ đồ khối mạch Điều khiển trung tâm mạch Cảm biến Hình 2.3: Module thu phát wifi bluetooth ESP32 .9 Hình 2.4: Sơ đồ chân module thu phát wifi bluetooth ESP32 12 Hình 2.5: IC ổn áp nguồn AMS1117 SMD chân dán 12 Hình 2.6: Cuộn cảm dán 2.2uH 0805 SMD 13 Hình 2.7: Module Bluetooth E73 chip nRF52832 14 Hình 2.8: Sơ đồ chân module bluetooth E73 .16 Hình 2.9: Cơng tắc từ 16 Hình 2.10: Cơng tắc gạt chân 17 Hình 2.11: Sơ đồ nguyên lý mạch Điều khiển trung tâm (Gateway) 18 Hình 2.12: Mơ 2D mạch điều khiển trung tâm 19 Hình 2.13: Mơ 3D mạch điều khiển trung tâm (mặt trước) 19 Hình 2.14: Mơ 3D mạch điều khiển trung tâm (mặt sau) 20 Hình 2.15: Khối chuyển đổi nguồn mạch Điều khiển trung tâm .20 Hình 2.16: Khối vi xử lý mạch Điều khiển trung tâm 21 Hình 2.17: Sơ đồ nguyên lý mạch Cảm biến (Sensor) 21 Hình 2.18: Mơ 2D mạch Cảm biến 22 Hình 2.19: Mô 3D mạch Cảm biến (mặt trước) 22 Hình 2.20: Mơ 3D mạch Cảm biến (mặt sau) 22 Hình 2.21: Khối nguồn mạch Cảm biến (Sensor) 23 Hình 2.22: Khối cảm biến mạch Cảm biến (Sensor) 23 Hình 2.23: Khối xử lý mạch Cảm biến (Sensor) 24 Hình 3.1: Mơ hình Center-Peripheral 28 Hình 3.2: Mơ hình Client-Server 29 Hình 3.3: Giao diện dashboard điều khiển quản lý liệu 33 Hình 4.1: Lưu đồ phần mềm mạch cảm biến .34 Hình 4.2: Lưu đồ hoạt động điều khiển trung tâm .35 Hình 4.3: Cài đặt thơng số đăng nhập cho thiết bị 36 Hình 4.4: Cài đặt thông số để lưu liệu .36 Hình 4.5: Khung truyền beacon 37 Hình 4.6: Xử lí đọc update liệu trạng thái cửa .37 Hình 4.7: Cấu hình kết nối cloud 38 Hình 4.8: Nhận update liệu lên cloud .38 Hình 4.9: Mạch Điều khiển trung tâm - Gateway (mặt trước) 39 Hình 4.10: Mạch Điều khiển trung tâm - Gateway (mặt sau) 39 Hình 4.11: Mạch Cảm biến - Sensor (mặt trước) .39 Hình 4.12: Mạch Cảm biến - Sensor (mặt sau) 40 Hình 4.13: Kết liệu cloud 40 strncpy((char *)ap_config.ap.ssid, (char *)param->softap_ssid.ssid, param>softap_ssid.ssid_len); ap_config.ap.ssid[param->softap_ssid.ssid_len] = '\0'; ap_config.ap.ssid_len = param->softap_ssid.ssid_len; esp_wifi_set_config(WIFI_IF_AP, &ap_config); BLUFI_INFO("Recv SOFTAP SSID %s, ssid len %d\n", ap_config.ap.ssid, ap_config.ap.ssid_len); break; case ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD: strncpy((char *)ap_config.ap.password, (char *)param->softap_passwd.passwd, param->softap_passwd.passwd_len); ap_config.ap.password[param->softap_passwd.passwd_len] = '\0'; esp_wifi_set_config(WIFI_IF_AP, &ap_config); BLUFI_INFO("Recv SOFTAP PASSWORD %s len = %d\n", ap_config.ap.password, param->softap_passwd.passwd_len); break; case ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM: if (param->softap_max_conn_num.max_conn_num > 4) { return; } ap_config.ap.max_connection = param->softap_max_conn_num.max_conn_num; esp_wifi_set_config(WIFI_IF_AP, &ap_config); BLUFI_INFO("Recv SOFTAP MAX CONN NUM %d\n", ap_config.ap.max_connection); break; case ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE: if (param->softap_auth_mode.auth_mode >= WIFI_AUTH_MAX) { return; } ap_config.ap.authmode = param->softap_auth_mode.auth_mode; esp_wifi_set_config(WIFI_IF_AP, &ap_config); BLUFI_INFO("Recv SOFTAP AUTH MODE %d\n", ap_config.ap.authmode); break; case ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL: if (param->softap_channel.channel > 13) { return; } ap_config.ap.channel = param->softap_channel.channel; esp_wifi_set_config(WIFI_IF_AP, &ap_config); BLUFI_INFO("Recv SOFTAP CHANNEL %d\n", ap_config.ap.channel); break; case ESP_BLUFI_EVENT_GET_WIFI_LIST:{ wifi_scan_config_t scanConf = { ssid = NULL, bssid = NULL, channel = 0, show_hidden = false }; esp_wifi_scan_start(&scanConf, true); break; } case ESP_BLUFI_EVENT_RECV_CUSTOM_DATA: BLUFI_INFO("Recv Custom Data %d\n", param->custom_data.data_len); esp_log_buffer_hex("Custom Data", param->custom_data.data, param>custom_data.data_len); break; case ESP_BLUFI_EVENT_RECV_USERNAME: /* Not handle currently */ break; case ESP_BLUFI_EVENT_RECV_CA_CERT: /* Not handle currently */ break; case ESP_BLUFI_EVENT_RECV_CLIENT_CERT: /* Not handle currently */ break; case ESP_BLUFI_EVENT_RECV_SERVER_CERT: /* Not handle currently */ break; case ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY: /* Not handle currently */ break;; case ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY: /* Not handle currently */ break; default: break; } } static void task_main(void *arg) { while(1) { vTaskDelay(1000/portTICK_RATE_MS); printf("heap: %d\n",xPortGetFreeHeapSize()); if(isBlufiRunning && !ble_is_connected) { if(xTaskGetTickCount() > 10000) { esp_blufi_adv_stop(); blufi_security_init(); esp_blufi_deinit(); vTaskDelay(1000/portTICK_RATE_MS); esp_err_t status; //register the scan callback function to the gap module if ((status = esp_ble_gap_register_callback(esp_gap_cb)) != ESP_OK) { BLUFI_INFO( "gap register error: %s", esp_err_to_name(status)); return; } /* set scan parameters */ /* set scan parameters */ #if (IBEACON_MODE == IBEACON_RECEIVER) esp_ble_gap_set_scan_params(&ble_scan_params); #elif (IBEACON_MODE == IBEACON_SENDER) esp_ble_ibeacon_t ibeacon_adv_data; status = esp_ble_config_ibeacon_data (&vendor_config, &ibeacon_adv_data); if (status == ESP_OK){ esp_ble_gap_config_adv_data_raw((uint8_t*)&ibeacon_adv_data, sizeof(ibeacon_adv_data)); } else { ESP_LOGE(DEMO_TAG, "Config iBeacon data failed: %s\n", esp_err_to_name(status)); } #endif } } } vTaskDelete(NULL); } void ble_ibeacon_appRegister(void) { esp_err_t status; ESP_LOGI(DEMO_TAG, "register callback"); //register the scan callback function to the gap module if ((status = esp_ble_gap_register_callback(esp_gap_cb)) != ESP_OK) { ESP_LOGE(DEMO_TAG, "gap register error: %s", esp_err_to_name(status)); return; } } void ble_ibeacon_init(void) { esp_bluedroid_init(); esp_bluedroid_enable(); ble_ibeacon_appRegister(); } void app_main(void) { esp_err_t ret; // Initialize NVS ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_ERROR_CHECK(nvs_flash_erase()); ret = nvs_flash_init(); } ESP_ERROR_CHECK( ret ); mqtt_app_init(); initialise_wifi(); ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_B T)); esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); ret = esp_bt_controller_init(&bt_cfg); if (ret) { BLUFI_ERROR("%s initialize bt controller failed: %s\n", func , esp_err_to_name(ret)); } ret = esp_bt_controller_enable(ESP_BT_MODE_BLE); if (ret) { BLUFI_ERROR("%s enable bt controller failed: %s\n", func , esp_err_to_name(ret)); return; } ret = esp_blufi_host_and_cb_init(&example_callbacks); if (ret) { BLUFI_ERROR("%s initialise failed: %s\n", func , esp_err_to_name(ret)); return; } BLUFI_INFO("BLUFI VERSION %04x\n", esp_blufi_get_version()); xTaskCreate(task_main,"task_main",4096, NULL, 5, NULL); // ESP_ERROR_CHECK(nvs_flash_init()); // ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC _BT)); // esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); // esp_bt_controller_init(&bt_cfg); // esp_bt_controller_enable(ESP_BT_MODE_BLE); // ble_ibeacon_init(); // /* set scan parameters */ // #if (IBEACON_MODE == IBEACON_RECEIVER) // esp_ble_gap_set_scan_params(&ble_scan_params); // #elif (IBEACON_MODE == IBEACON_SENDER) // esp_ble_ibeacon_t ibeacon_adv_data; // esp_err_t status = esp_ble_config_ibeacon_data (&vendor_config, &ibeacon_adv_data); // if (status == ESP_OK){ // esp_ble_gap_config_adv_data_raw((uint8_t*)&ibeacon_adv_data, sizeof(ibeacon_adv_data)); // } // else { // ESP_LOGE(DEMO_TAG, "Config iBeacon data failed: %s\n", esp_err_to_name(status)); // } // #endif } MqttHandle.c #include #include #include #include #include "esp_wifi.h" #include "esp_system.h" #include "nvs_flash.h" #include "esp_event.h" #include "esp_netif.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" #include "freertos/queue.h" #include "lwip/sockets.h" #include "lwip/dns.h" #include "lwip/netdb.h" #include "esp_log.h" #include "mqtt_client.h" static const char *TAG = "MQTT_EXAMPLE"; esp_mqtt_client_handle_t g_client = NULL; static void log_error_if_nonzero(const char *message, int error_code) { if (error_code != 0) { ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code); } } /* * @brief Event handler registered to receive MQTT events * * This function is called by the MQTT client event loop * * @param handler_args user data registered to the event * @param base Event base for the handler(always MQTT Base in this example) * @param event_id The id for the received event * @param event_data The data for the event, esp_mqtt_event_handle_t */ static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) { ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, event_id); esp_mqtt_event_handle_t event = event_data; esp_mqtt_client_handle_t client = event->client; int msg_id; switch ((esp_mqtt_event_id_t)event_id) { case MQTT_EVENT_CONNECTED: ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED"); msg_id = esp_mqtt_client_subscribe(client, "channels/1799759/subscribe", 0); ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id); break; case MQTT_EVENT_DISCONNECTED: ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED"); break; case MQTT_EVENT_SUBSCRIBED: ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id); msg_id = esp_mqtt_client_publish(client, "channels/1799759/publish", "field2=25", 0, 1, 0); ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id); break; case MQTT_EVENT_UNSUBSCRIBED: ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event>msg_id); break; case MQTT_EVENT_PUBLISHED: ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id); break; case MQTT_EVENT_DATA: ESP_LOGI(TAG, "MQTT_EVENT_DATA"); printf("TOPIC=%.*s\r\n", event->topic_len, event->topic); printf("DATA=%.*s\r\n", event->data_len, event->data); break; case MQTT_EVENT_ERROR: ESP_LOGI(TAG, "MQTT_EVENT_ERROR"); if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) { log_error_if_nonzero("reported from esp-tls", event->error_handle>esp_tls_last_esp_err); log_error_if_nonzero("reported from tls stack", event->error_handle>esp_tls_stack_err); log_error_if_nonzero("captured as transport's socket errno", event->error_handle>esp_transport_sock_errno); ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle>esp_transport_sock_errno)); } break; default: ESP_LOGI(TAG, "Other event id:%d", event->event_id); break; } } void mqtt_app_init(void) { esp_mqtt_client_config_t mqtt_cfg = { host = "mqtt3.thingspeak.com", port = 1883, username = "KDAzNh4MND07LhM9JwghGBg", client_id = "KDAzNh4MND07LhM9JwghGBg", password = "r/6VC15l+H/1tDjvhLlVGG/K" }; g_client = esp_mqtt_client_init(&mqtt_cfg); /* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */ esp_mqtt_client_register_event(g_client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL); } void mqtt_publish_doorState(bool state) { char buf[100]; sprintf(buf,"field3=%d",state); int msg_id = esp_mqtt_client_publish(g_client, "channels/1799759/publish",buf , 0, 1, 0); ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id); } void mqtt_app_start(void) { esp_mqtt_client_start(g_client); } Phụ lục 2: Chương trình phần mềm mạch cảm biến Main.c #include #include #include "nordic_common.h" #include "bsp.h" #include "nrf_soc.h" #include "nrf_sdh.h" #include "nrf_sdh_ble.h" #include "ble_advdata.h" #include "app_timer.h" #include "nrf_pwr_mgmt.h" #include "nrf_log.h" #include "nrf_log_ctrl.h" #include "nrf_log_default_backends.h" #include "nrf_delay.h" #include "ble_advertising.h" #define APP_BLE_CONN_CFG_TAG identifying the SoftDevice BLE configuration */ /**< A tag #define NON_CONNECTABLE_ADV_INTERVAL MSEC_TO_UNITS(100, UNIT_0_625_MS) /**< The advertising interval for non-connectable advertisement (100 ms) This value can vary between 100ms to 10.24s) */ #define APP_BEACON_INFO_LENGTH 0x17 /**< Total length of information advertised by the Beacon */ #define APP_ADV_DATA_LENGTH 0x15 /**< Length of manufacturer specific data in the advertisement */ #define APP_DEVICE_TYPE 0x02 /**< 0x02 refers to Beacon */ #define APP_MEASURED_RSSI 0xC3 /**< The Beacon's measured RSSI at meter distance in dBm */ #define APP_COMPANY_IDENTIFIER 0x0059 /**< Company identifier for Nordic Semiconductor ASA as per www.bluetooth.org */ #define APP_MAJOR_VALUE 0x01, 0x02 /**< Major value used to identify Beacons */ #define APP_MINOR_VALUE 0x03, 0x04 /**< Minor value used to identify Beacons */ #define APP_BEACON_UUID 0x01, 0x12, 0x23, 0x34, \ 0x45, 0x56, 0x67, 0x78, \ 0x89, 0x9a, 0xab, 0xbc, \ 0xcd, 0xde, 0xef, 0xf0 /**< Proprietary UUID for Beacon */ #define DEAD_BEEF 0xDEADBEEF /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind */ #if defined(USE_UICR_FOR_MAJ_MIN_VALUES) #define MAJ_VAL_OFFSET_IN_BEACON_INFO 18 /**< Position of the MSB of the Major Value in m_beacon_info array */ #define UICR_ADDRESS 0x10001080 /**< Address of the UICR register used by this example The major and minor versions to be encoded into the advertising data will be picked up from this location */ #endif static ble_gap_adv_params_t m_adv_params; /**< Parameters to be passed to the stack when starting advertising */ static uint8_t m_adv_handle = BLE_GAP_ADV_SET_HANDLE_NOT_SET; /**< Advertising handle used to identify an advertising set */ static uint8_t m_enc_advdata[BLE_GAP_ADV_SET_DATA_SIZE_MAX]; /**< Buffer for storing an encoded advertising set */ /**@brief Struct that contains pointers to the encoded advertising data */ static ble_gap_adv_data_t m_adv_data = { adv_data = { p_data = m_enc_advdata, len = BLE_GAP_ADV_SET_DATA_SIZE_MAX }, scan_rsp_data = { p_data = NULL, len = } }; static uint8_t m_beacon_info[APP_BEACON_INFO_LENGTH] = /**< Information advertised by the Beacon */ { APP_DEVICE_TYPE, // Manufacturer specific information Specifies the device type in this // implementation APP_ADV_DATA_LENGTH, // Manufacturer specific information Specifies the length of the // manufacturer specific data in this implementation APP_BEACON_UUID, // 128 bit UUID value APP_MAJOR_VALUE, // Major arbitrary value that can be used to distinguish between Beacons APP_MINOR_VALUE, // Minor arbitrary value that can be used to distinguish between Beacons APP_MEASURED_RSSI // Manufacturer specific information The Beacon's measured TX power in // this implementation }; /**@brief Callback function for asserts in the SoftDevice * * @details This function will be called in case of an assert in the SoftDevice * * @warning This handler is an example only and does not fit a final product You need to analyze * how your product is supposed to react in case of Assert * @warning On assert from the SoftDevice, the system can only recover on reset * * @param[in] line_num Line number of the failing ASSERT call * @param[in] file_name File name of the failing ASSERT call */ void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name) { app_error_handler(DEAD_BEEF, line_num, p_file_name); } /**@brief Function for initializing the Advertising functionality * * @details Encodes the required advertising data and passes it to the stack * Also builds a structure to be passed to the stack when starting advertising */ static void advertising_init(void) { uint32_t err_code; ble_advdata_t advdata; uint8_t flags = BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED; ble_advdata_manuf_data_t manuf_specific_data; manuf_specific_data.company_identifier = APP_COMPANY_IDENTIFIER; #if defined(USE_UICR_FOR_MAJ_MIN_VALUES) // If USE_UICR_FOR_MAJ_MIN_VALUES is defined, the major and minor values will be read from the // UICR instead of using the default values The major and minor values obtained from the UICR // are encoded into advertising data in big endian order (MSB First) // To set the UICR used by this example to a desired value, write to the address 0x10001080 // using the nrfjprog tool The command to be used is as follows // nrfjprog snr memwr 0x10001080 val // For example, for a major value and minor value of 0xabcd and 0x0102 respectively, the // the following command should be used // nrfjprog snr memwr 0x10001080 val 0xabcd0102 uint16_t major_value = ((*(uint32_t *)UICR_ADDRESS) & 0xFFFF0000) >> 16; uint16_t minor_value = ((*(uint32_t *)UICR_ADDRESS) & 0x0000FFFF); uint8_t index = MAJ_VAL_OFFSET_IN_BEACON_INFO; m_beacon_info[index++] = MSB_16(major_value); m_beacon_info[index++] = LSB_16(major_value); m_beacon_info[index++] = MSB_16(minor_value); m_beacon_info[index++] = LSB_16(minor_value); #endif manuf_specific_data.data.p_data = (uint8_t *) m_beacon_info; manuf_specific_data.data.size = APP_BEACON_INFO_LENGTH; // Build and set advertising data memset(&advdata, 0, sizeof(advdata)); advdata.name_type = BLE_ADVDATA_NO_NAME; advdata.flags = flags; advdata.p_manuf_specific_data = &manuf_specific_data; // Initialize advertising parameters (used when starting advertising) memset(&m_adv_params, 0, sizeof(m_adv_params)); m_adv_params.properties.type = BLE_GAP_ADV_TYPE_NONCONNECTABLE_NONSCANNABLE_UNDIRECTED; m_adv_params.p_peer_addr = NULL; // Undirected advertisement m_adv_params.filter_policy = BLE_GAP_ADV_FP_ANY; m_adv_params.interval = NON_CONNECTABLE_ADV_INTERVAL; m_adv_params.duration = 0; // Never time out err_code = ble_advdata_encode(&advdata, m_adv_data.adv_data.p_data, &m_adv_data.adv_data.len); APP_ERROR_CHECK(err_code); err_code = sd_ble_gap_adv_set_configure(&m_adv_handle, &m_adv_data, &m_adv_params); APP_ERROR_CHECK(err_code); } /**@brief Function for starting advertising */ static void advertising_start(void) { ret_code_t err_code; err_code = sd_ble_gap_adv_start(m_adv_handle, APP_BLE_CONN_CFG_TAG); APP_ERROR_CHECK(err_code); err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING); APP_ERROR_CHECK(err_code); } static void advertising_atop(void) { ret_code_t err_code; err_code = sd_ble_gap_adv_stop(m_adv_handle); APP_ERROR_CHECK(err_code); } /**@brief Function for initializing the BLE stack * * @details Initializes the SoftDevice and the BLE event interrupt */ static void ble_stack_init(void) { ret_code_t err_code; err_code = nrf_sdh_enable_request(); APP_ERROR_CHECK(err_code); // Configure the BLE stack using the default settings // Fetch the start address of the application RAM uint32_t ram_start = 0; err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start); APP_ERROR_CHECK(err_code); // Enable BLE stack err_code = nrf_sdh_ble_enable(&ram_start); APP_ERROR_CHECK(err_code); } /**@brief Function for initializing logging */ static void log_init(void) { ret_code_t err_code = NRF_LOG_INIT(NULL); APP_ERROR_CHECK(err_code); NRF_LOG_DEFAULT_BACKENDS_INIT(); } /**@brief Function for initializing LEDs */ static void leds_init(void) { ret_code_t err_code = bsp_init(BSP_INIT_LEDS, NULL); APP_ERROR_CHECK(err_code); } /**@brief Function for initializing timers */ static void timers_init(void) { ret_code_t err_code = app_timer_init(); APP_ERROR_CHECK(err_code); } /**@brief Function for initializing power management */ static void power_management_init(void) { ret_code_t err_code; err_code = nrf_pwr_mgmt_init(); APP_ERROR_CHECK(err_code); } /**@brief Function for handling the idle state (main loop) * * @details If there is no pending log operation, then sleep until next the next event occurs */ static void idle_state_handle(void) { if (NRF_LOG_PROCESS() == false) { nrf_pwr_mgmt_run(); } } #define PIN_DOOR #define ALARM_LED 24 uint8_t cntLedDelay = 0; void led_turn(bool isOn) { if(!isOn) { nrf_gpio_pin_set(ALARM_LED); } else { nrf_gpio_pin_clear(ALARM_LED); } } bool isDetectDoorOpen = false; uint8_t lastLevel = 0; static bool sensor_getStatusDoor() { NRF_LOG_INFO("pin door: %d\n", nrf_gpio_pin_read(PIN_DOOR)); //led_turn(false); if( nrf_gpio_pin_read(PIN_DOOR) == && lastLevel == 0) { NRF_LOG_INFO("open door:"); isDetectDoorOpen = true; cntLedDelay = 6; led_turn(true); } else if( nrf_gpio_pin_read(PIN_DOOR) == && lastLevel == 1) { NRF_LOG_INFO("close door:"); } lastLevel = nrf_gpio_pin_read(PIN_DOOR); } static void sensor_updateData() { sensor_getStatusDoor(); m_beacon_info[APP_BEACON_INFO_LENGTH - 3] = 0; m_beacon_info[APP_BEACON_INFO_LENGTH - 2] = nrf_gpio_pin_read(PIN_DOOR); advertising_init(); advertising_start(); } /** * @brief Function for application main entry */ void gpio_init() { nrf_gpio_cfg_output(ALARM_LED); nrf_gpio_cfg_input(PIN_DOOR,NRF_GPIO_PIN_PULLUP); } int main(void) { bool ledTgl = false; // Initialize gpio_init(); log_init(); timers_init(); leds_init(); power_management_init(); ble_stack_init(); advertising_init(); // Start execution NRF_LOG_INFO("Beacon example started."); advertising_start(); // Enter main loop for (;; ) { idle_state_handle(); advertising_atop(); // m_beacon_info[APP_BEACON_INFO_LENGTH - 2]++; // advertising_init(); // advertising_start(); sensor_updateData(); // led_turn(ledTgl); //ledTgl = !ledTgl; nrf_delay_ms(500); if(cntLedDelay) { if( cntLedDelay == 0) { led_turn(false); } } //ble_advertising_advdata_update(); } } /** * @} */ DANH MỤC TÀI LIỆU THAM KHẢO Tiếng việt Hồng Minh Sơn (2007), Giáo trình “Mạng truyền thơng cơng nghiệp”, NXB Khoa học kỹ thuật Hoàng Sơn, Đinh Hải Lĩnh (2020), Bài giảng kỹ thuật điện tử, NXB Đại học Lâm Nghiệp Website https://lcsc.com https://thingspeak.com https://ch.mathworks.com https://www.123doc.net

Ngày đăng: 11/10/2023, 00:24

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan