mirror of
https://gitee.com/beecue/fastbee.git
synced 2025-12-19 17:35:54 +08:00
添加智能灯固件代码
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
# The following lines of boilerplate have to be in your project's CMakeLists
|
||||
# in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
# (Not part of the boilerplate)
|
||||
# This example uses an extra component for common functions such as Wi-Fi and Ethernet connection.
|
||||
set(EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/common_components/protocol_examples_common)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
project(sntp)
|
||||
@@ -0,0 +1,11 @@
|
||||
#
|
||||
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
|
||||
# project subdirectory.
|
||||
#
|
||||
|
||||
PROJECT_NAME := sntp
|
||||
|
||||
EXTRA_COMPONENT_DIRS = $(IDF_PATH)/examples/common_components/protocol_examples_common
|
||||
|
||||
include $(IDF_PATH)/make/project.mk
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
| Supported Targets | ESP32 |
|
||||
| ----------------- | ----- |
|
||||
|
||||
# Example: using LwIP SNTP module and time functions
|
||||
|
||||
This example demonstrates the use of LwIP SNTP module to obtain time from Internet servers. See the README.md file in the upper level 'examples' directory for more information about examples.
|
||||
|
||||
## Configuring the Example
|
||||
|
||||
Open the project configuration menu (`idf.py menuconfig`):
|
||||
|
||||
* Configure Wi-Fi or Ethernet under "Example Connection Configuration" menu. See "Establishing Wi-Fi or Ethernet Connection" section in [examples/protocols/README.md](../README.md) for more details.
|
||||
|
||||
* Select one method to synchronize time out of the three available in `CONFIG_SNTP_TIME_SYNC_METHOD` (default `update time immediately when received`).
|
||||
|
||||
* The time synchronization period is defined by `CONFIG_LWIP_SNTP_UPDATE_DELAY`. This option allows you to set the time synchronization period (default is one hour). This option does not affect this example because after synchronization the program goes into deep sleep for 10 seconds. If you modify this example or use the code from this example, keep in mind that this option will trigger time synchronization. You can change it in `Component config-->LWIP-->SNTP-->Request interval to update time (ms)` menu.
|
||||
|
||||
* When using Make build system, set `Default serial port` under `Serial flasher config`.
|
||||
|
||||
## Obtaining time using LwIP SNTP module
|
||||
|
||||
When this example boots first time after ESP32 is reset, it connects to WiFi and obtains time using SNTP.
|
||||
See `initialize_sntp` function for details.
|
||||
|
||||
## Timekeeping
|
||||
|
||||
Once time is synchronized, ESP32 will perform timekeeping using built-in timers.
|
||||
|
||||
- RTC clock is used to maintain accurate time when chip is in deep sleep mode
|
||||
|
||||
- FRC1 timer is used to provide time at microsecond accuracy when ESP32 is running.
|
||||
|
||||
Timekeeping using RTC timer is demonstrated in this example by going into deep sleep mode. After wake up, ESP32 will print current time without connecting to WiFi.
|
||||
|
||||
To use this functionality, make sure "Timers used for gettimeofday function" option in "ESP32-specific config" menu of menuconfig is set to "RTC and FRC1" or "RTC".
|
||||
|
||||
## Working with time
|
||||
|
||||
To get current time, [`gettimeofday`](http://man7.org/linux/man-pages/man2/gettimeofday.2.html) function may be used. Additionally the following [standard C library functions](https://en.cppreference.com/w/cpp/header/ctime) can be used to obtain time and manipulate it:
|
||||
|
||||
gettimeofday
|
||||
time
|
||||
asctime
|
||||
clock
|
||||
ctime
|
||||
difftime
|
||||
gmtime
|
||||
localtime
|
||||
mktime
|
||||
strftime
|
||||
|
||||
To set time, [`settimeofday`](http://man7.org/linux/man-pages/man2/settimeofday.2.html) POSIX function can be used. It is used internally in LwIP SNTP library to set current time when response from NTP server is received.
|
||||
|
||||
## Timezones
|
||||
|
||||
To set local timezone, use [`setenv`](http://man7.org/linux/man-pages/man3/setenv.3.html) and [`tzset`](http://man7.org/linux/man-pages/man3/tzset.3.html) POSIX functions. First, call `setenv` to set `TZ` environment variable to the correct value depending on device location. Format of the time string is described in [libc documentation](https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html). Next, call `tzset` to update C library runtime data for the new time zone. Once these steps are done, `localtime` function will return correct local time, taking time zone offset and daylight saving time into account.
|
||||
|
||||
## Additional options
|
||||
|
||||
This example can use 3 time synchronization method:
|
||||
|
||||
- `update time immediately when received` - update time immediately as received an answer from SNTP server. Allows syncing the time without any additional code from the user side, and use a callback function or getting status for notification of the process of sync.
|
||||
|
||||
- `update time with smooth method (adjtime)` - time synchronization will use the adjtime function to smoothly update the time. Allows syncing the time without any additional code from the user side, and use a callback function or getting status for notification of the process of sync.
|
||||
|
||||
- `custom implementation` - allows replacing the built-in time synchronization functionality. This option redefines `sntp_sync_time()` function.
|
||||
|
||||
## Useful API function:
|
||||
|
||||
- `sntp_set_time_sync_notification_cb()` - use this function to set a callback function to notify about the time synchronization process.
|
||||
- `sntp_get_sync_status()` and `sntp_set_sync_status()` - get/set time synchronization status.
|
||||
- `sntp_get_sync_mode()` and `sntp_set_sync_mode()` - get/set the sync mode. Allowable two mode: `SNTP_SYNC_MODE_IMMED` and `SNTP_SYNC_MODE_SMOOTH`.
|
||||
|
||||
## Mode of update time
|
||||
|
||||
`sntp_set_sync_mode()` - Set the sync mode of the system time. It has two mode:
|
||||
|
||||
* `SNTP_SYNC_MODE_IMMED` - Update system time immediately when receiving a response from the SNTP server.
|
||||
* `SNTP_SYNC_MODE_SMOOTH` - Smooth time updating. Time error is gradually reduced using adjtime function. If the difference between SNTP response time and system time is large (more than 35 minutes) then update immediately. This mode uses `adjtime()` function.
|
||||
|
||||
## Adjtime()
|
||||
`int adjtime(const struct timeval *delta, struct timeval *outdelta)`
|
||||
|
||||
`adjtime()` is a libc function that is called automatically in "smooth" time update mode, but can also be called from custom time synchronization code.
|
||||
If the time error is less than 35 minutes then `adjtime` function will start smooth adjusting otherwise the return value is -1.
|
||||
|
||||
This function speeds up or slows down the system clock in order to make a gradual adjustment. This ensures that the calendar time reported by the system clock is always monotonically increasing, which might not happen if you simply set the clock. If adjusting the system clock by `adjtime()` is already done during the second call `adjtime()`, and the delta of the second call is not NULL, the earlier tuning is stopped, but the already completed part of the adjustment is not canceled.
|
||||
|
||||
The delta argument specifies a relative adjustment to be made to the clock time. If negative, the system clock is slowed down for a while until it has lost this much elapsed time. If positive, the system clock is speeded up for a while.
|
||||
|
||||
If the olddelta argument is not a null pointer, the adjtime function returns information about any previous time adjustment that has not yet completed.
|
||||
|
||||
The return value is 0 on success and -1 on failure.
|
||||
|
||||
To stop the smooth time adjustment, you need to record the current time using the function `settimeofday()`.
|
||||
@@ -0,0 +1,49 @@
|
||||
from __future__ import unicode_literals
|
||||
from tiny_test_fw import Utility
|
||||
import datetime
|
||||
import re
|
||||
import ttfw_idf
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_sntp(env, extra_data):
|
||||
|
||||
dut = env.get_dut('sntp', 'examples/protocols/sntp')
|
||||
dut.start_app()
|
||||
|
||||
dut.expect_all('Time is not set yet. Connecting to WiFi and getting time over NTP.',
|
||||
'Initializing SNTP',
|
||||
'Waiting for system time to be set... (1/10)',
|
||||
'Notification of a time synchronization event',
|
||||
timeout=60)
|
||||
|
||||
TIME_FORMAT = '%a %b %d %H:%M:%S %Y'
|
||||
TIME_FORMAT_REGEX = r'\w+\s+\w+\s+\d{1,2}\s+\d{2}:\d{2}:\d{2} \d{4}'
|
||||
TIME_DIFF = datetime.timedelta(seconds=10 + 2) # cpu spends 10 seconds in deep sleep
|
||||
NY_time = None
|
||||
SH_time = None
|
||||
|
||||
def check_time(prev_NY_time, prev_SH_time):
|
||||
NY_str = dut.expect(re.compile(r'The current date/time in New York is: ({})'.format(TIME_FORMAT_REGEX)))[0]
|
||||
SH_str = dut.expect(re.compile(r'The current date/time in Shanghai is: ({})'.format(TIME_FORMAT_REGEX)))[0]
|
||||
Utility.console_log('New York: "{}"'.format(NY_str))
|
||||
Utility.console_log('Shanghai: "{}"'.format(SH_str))
|
||||
dut.expect('Entering deep sleep for 10 seconds')
|
||||
Utility.console_log('Sleeping...')
|
||||
new_NY_time = datetime.datetime.strptime(NY_str, TIME_FORMAT)
|
||||
new_SH_time = datetime.datetime.strptime(SH_str, TIME_FORMAT)
|
||||
|
||||
# The initial time is not checked because datetime has problems with timezones
|
||||
assert prev_NY_time is None or new_NY_time - prev_NY_time < TIME_DIFF
|
||||
assert prev_SH_time is None or new_SH_time - prev_SH_time < TIME_DIFF
|
||||
|
||||
return (new_NY_time, new_SH_time)
|
||||
|
||||
NY_time, SH_time = check_time(NY_time, SH_time)
|
||||
for i in range(2, 4):
|
||||
dut.expect('example: Boot count: {}'.format(i), timeout=30)
|
||||
NY_time, SH_time = check_time(NY_time, SH_time)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_examples_sntp()
|
||||
@@ -0,0 +1,2 @@
|
||||
idf_component_register(SRCS "sntp_example_main.c"
|
||||
INCLUDE_DIRS ".")
|
||||
@@ -0,0 +1,17 @@
|
||||
menu "Example Configuration"
|
||||
|
||||
choice SNTP_TIME_SYNC_METHOD
|
||||
prompt "Time synchronization method"
|
||||
default SNTP_TIME_SYNC_METHOD_IMMED
|
||||
help
|
||||
Time synchronization method.
|
||||
|
||||
config SNTP_TIME_SYNC_METHOD_IMMED
|
||||
bool "update time immediately when received"
|
||||
config SNTP_TIME_SYNC_METHOD_SMOOTH
|
||||
bool "update time with smooth method (adjtime)"
|
||||
config SNTP_TIME_SYNC_METHOD_CUSTOM
|
||||
bool "custom implementation"
|
||||
endchoice
|
||||
|
||||
endmenu
|
||||
@@ -0,0 +1,4 @@
|
||||
#
|
||||
# "main" pseudo-component makefile.
|
||||
#
|
||||
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
|
||||
@@ -0,0 +1,158 @@
|
||||
/* LwIP SNTP example
|
||||
|
||||
This example code is in the Public Domain (or CC0 licensed, at your option.)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, this
|
||||
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
CONDITIONS OF ANY KIND, either express or implied.
|
||||
*/
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <sys/time.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/event_groups.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_event.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_attr.h"
|
||||
#include "esp_sleep.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "protocol_examples_common.h"
|
||||
#include "esp_sntp.h"
|
||||
|
||||
static const char *TAG = "example";
|
||||
|
||||
/* Variable holding number of times ESP32 restarted since first boot.
|
||||
* It is placed into RTC memory using RTC_DATA_ATTR and
|
||||
* maintains its value when ESP32 wakes from deep sleep.
|
||||
*/
|
||||
RTC_DATA_ATTR static int boot_count = 0;
|
||||
|
||||
static void obtain_time(void);
|
||||
static void initialize_sntp(void);
|
||||
|
||||
#ifdef CONFIG_SNTP_TIME_SYNC_METHOD_CUSTOM
|
||||
void sntp_sync_time(struct timeval *tv)
|
||||
{
|
||||
settimeofday(tv, NULL);
|
||||
ESP_LOGI(TAG, "Time is synchronized from custom code");
|
||||
sntp_set_sync_status(SNTP_SYNC_STATUS_COMPLETED);
|
||||
}
|
||||
#endif
|
||||
|
||||
void time_sync_notification_cb(struct timeval *tv)
|
||||
{
|
||||
ESP_LOGI(TAG, "Notification of a time synchronization event");
|
||||
}
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
++boot_count;
|
||||
ESP_LOGI(TAG, "Boot count: %d", boot_count);
|
||||
|
||||
time_t now;
|
||||
struct tm timeinfo;
|
||||
time(&now);
|
||||
localtime_r(&now, &timeinfo);
|
||||
// Is time set? If not, tm_year will be (1970 - 1900).
|
||||
if (timeinfo.tm_year < (2016 - 1900)) {
|
||||
ESP_LOGI(TAG, "Time is not set yet. Connecting to WiFi and getting time over NTP.");
|
||||
obtain_time();
|
||||
// update 'now' variable with current time
|
||||
time(&now);
|
||||
}
|
||||
#ifdef CONFIG_SNTP_TIME_SYNC_METHOD_SMOOTH
|
||||
else {
|
||||
// add 500 ms error to the current system time.
|
||||
// Only to demonstrate a work of adjusting method!
|
||||
{
|
||||
ESP_LOGI(TAG, "Add a error for test adjtime");
|
||||
struct timeval tv_now;
|
||||
gettimeofday(&tv_now, NULL);
|
||||
int64_t cpu_time = (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec;
|
||||
int64_t error_time = cpu_time + 500 * 1000L;
|
||||
struct timeval tv_error = { .tv_sec = error_time / 1000000L, .tv_usec = error_time % 1000000L };
|
||||
settimeofday(&tv_error, NULL);
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Time was set, now just adjusting it. Use SMOOTH SYNC method.");
|
||||
obtain_time();
|
||||
// update 'now' variable with current time
|
||||
time(&now);
|
||||
}
|
||||
#endif
|
||||
|
||||
char strftime_buf[64];
|
||||
|
||||
// Set timezone to Eastern Standard Time and print local time
|
||||
setenv("TZ", "EST5EDT,M3.2.0/2,M11.1.0", 1);
|
||||
tzset();
|
||||
localtime_r(&now, &timeinfo);
|
||||
strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
|
||||
ESP_LOGI(TAG, "The current date/time in New York is: %s", strftime_buf);
|
||||
|
||||
// Set timezone to China Standard Time
|
||||
setenv("TZ", "CST-8", 1);
|
||||
tzset();
|
||||
localtime_r(&now, &timeinfo);
|
||||
strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
|
||||
ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);
|
||||
|
||||
if (sntp_get_sync_mode() == SNTP_SYNC_MODE_SMOOTH) {
|
||||
struct timeval outdelta;
|
||||
while (sntp_get_sync_status() == SNTP_SYNC_STATUS_IN_PROGRESS) {
|
||||
adjtime(NULL, &outdelta);
|
||||
ESP_LOGI(TAG, "Waiting for adjusting time ... outdelta = %li sec: %li ms: %li us",
|
||||
(long)outdelta.tv_sec,
|
||||
outdelta.tv_usec/1000,
|
||||
outdelta.tv_usec%1000);
|
||||
vTaskDelay(2000 / portTICK_PERIOD_MS);
|
||||
}
|
||||
}
|
||||
|
||||
const int deep_sleep_sec = 10;
|
||||
ESP_LOGI(TAG, "Entering deep sleep for %d seconds", deep_sleep_sec);
|
||||
esp_deep_sleep(1000000LL * deep_sleep_sec);
|
||||
}
|
||||
|
||||
static void obtain_time(void)
|
||||
{
|
||||
ESP_ERROR_CHECK( nvs_flash_init() );
|
||||
ESP_ERROR_CHECK(esp_netif_init());
|
||||
ESP_ERROR_CHECK( esp_event_loop_create_default() );
|
||||
|
||||
/* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
|
||||
* Read "Establishing Wi-Fi or Ethernet Connection" section in
|
||||
* examples/protocols/README.md for more information about this function.
|
||||
*/
|
||||
ESP_ERROR_CHECK(example_connect());
|
||||
|
||||
initialize_sntp();
|
||||
|
||||
// wait for time to be set
|
||||
time_t now = 0;
|
||||
struct tm timeinfo = { 0 };
|
||||
int retry = 0;
|
||||
const int retry_count = 10;
|
||||
while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET && ++retry < retry_count) {
|
||||
ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
|
||||
vTaskDelay(2000 / portTICK_PERIOD_MS);
|
||||
}
|
||||
time(&now);
|
||||
localtime_r(&now, &timeinfo);
|
||||
|
||||
ESP_ERROR_CHECK( example_disconnect() );
|
||||
}
|
||||
|
||||
static void initialize_sntp(void)
|
||||
{
|
||||
ESP_LOGI(TAG, "Initializing SNTP");
|
||||
sntp_setoperatingmode(SNTP_OPMODE_POLL);
|
||||
sntp_setservername(0, "pool.ntp.org");
|
||||
sntp_set_time_sync_notification_cb(time_sync_notification_cb);
|
||||
#ifdef CONFIG_SNTP_TIME_SYNC_METHOD_SMOOTH
|
||||
sntp_set_sync_mode(SNTP_SYNC_MODE_SMOOTH);
|
||||
#endif
|
||||
sntp_init();
|
||||
}
|
||||
Reference in New Issue
Block a user