Weather Service

Last Updated on : 2024-05-11 03:23:35download

This topic describes how to use the MCU SDK to get the weather data for your product. The weather service is an important feature for smart devices, allowing the MCU to request weather data through the Wi-Fi or Wi-Fi and Bluetooth combo module.

Scenario

After the module is connected to the cloud, the MCU can send the module a command to enable access to weather data. This way, the module will send weather data to the MCU on a regular basis.

The weather location depends on the latitude and longitude where a mobile phone is located.

Commands

The commands used in the weather service.

Command Description
0x20 Enable weather data
0x21 Send weather data
0x34 (subcommand: 0x03) Request weather data

Enable weather data (0x20)

After the initialization, the MCU can call this command to enable weather data. The module returns the result.

The MCU sends the following data.

Field Bytes Description
Header 2 0x55aa
Version 1 0x03
Command 1 0x20
Data length 2 N((L+K)+(L+K)…)
Data n
  • L: a 1-byte value, representing the length of K.
  • K: the name of the request parameter. For more information about the supported parameter, see Appendix 1.
Example of parameters that can be forecast:
  • L: 0x0A K: w.humidity
  • L: 0x08 K: w.date.7
Example of parameters that cannot be forecast: L: 0x06 K: w.pm25
Checksum 1 Start from the header, add up all the bytes, and then divide the sum by 256 to get the remainder.

Example: If the request parameters are w.temp and w.pm25, the payload will be L:0x06 K:w.temp and L:0x06 K:w.pm25.

55 aa 03 20 00 0e 06 77 2e 74 65 6d 70 06 77 2e 70 6d 32 35 80

  • To get the weather data that can be forecast, you must specify the number of days for which the API returns forecast data (up to 7 days).

    Example:

    • w.humidity, w.date.1: Get the humidity for today.
    • w.humidity, w.date.7: Get the humidity for the next 7 days starting from the current day.
  • To get the weather data that cannot be forecast, you must not specify the number of days for which the API returns forecast data.

    Example: w.pm2.5

  • To get the time-dependent weather data, you must use the t.unix or t.local parameter to request data in GMT or local time.

    Example:

    • L: 0x0b K: w.sunRise
    • L: 0x0b K: w.date.7
    • L: 0x06 K: t.unix
  • The module returns the sunrise time in GMT. The time takes the format of Year-Month-Date Hour: Minute.

The module returns the following data.

Field Bytes Description
Header 2 0x55aa
Version 1 0x00
Command 1 0x20
Data length 2 0x0002
Data 2
  • Data[0]:
    • 0x00: Failure. See Data[1] for the error code.
    • 0x01: Success.
  • Data[1]:
    • 0x00: No error.
    • 0x01: Invalid data format.
    • 0x02: Exception.
Checksum 1 Start from the header, add up all the bytes, and then divide the sum by 256 to get the remainder.

Example: 55 aa 00 20 00 02 01 00 22

Send weather data (0x21)

With weather data enabled, the module will regularly send weather data to the MCU after connecting to the cloud. The module sends weather data as soon as weather data is enabled and then every 30 minutes thereafter.

The module sends the following data.

Field Bytes Description
Header 2 0x55aa
Version 1 0x00
Command 1 0x21
Data length 2 N((LKTLV)+(LKTLV)+…)
Data Data
  • 0x00: Failure.
  • 0x01: Access denied. Check whether you have subscribed to the weather service, or enabled it through the command 0x20.
  • 0x01: Success.
  • L: The length of the parameter name.
  • K: The parameter name.
  • T: 0x00 for integer and 0x01 for string.
  • L: The length of the field name.
  • V: The value of the field.
Checksum 1 Start from the header, add up all the bytes, and then divide the sum by 256 to get the remainder.

Example: w.temp: 15, w.humidity: 23, w.pm25: 27, w.conditionNum: 120

Weather service Hexadecimal Return value Hexadecimal
w.temp 77 2E 74 65 6D 70 15 00 00 00 0F
w.humidity 77 2E 68 75 6D 69 64 69 74 79 23 00 00 00 17
w.pm25 77 2E 70 6D 32 35 27 00 00 00 1B
w.conditionNum 77 2E 63 6F 6E 64 69 74 69 6F 6E 4E 75 6D 120 31 32 30

55 AA 00 21 00 40 01 06 77 2E 74 65 6D 70 00 04 00 00 00 0F 0A 77 2E 68 75 6D 69 64 69 74 79 00 04 00 00 00 17 06 77 2E 70 6D 32 35 00 04 00 00 00 1B 0E 77 2E 63 6F 6E 64 69 74 69 6F 6E 4E 75 6D 01 03 31 32 30 5B

The MCU returns the following data.

Field Bytes Description
Header 2 0x55aa
Version 1 0x03
Command 1 0x21
Data length 2 0x0000
Data 0 None
Checksum 1 Start from the header, add up all the bytes, and then divide the sum by 256 to get the remainder.

Example: 55 aa 00 21 00 00 20

Request weather data (0x34 & 0x03)

Besides passively receiving weather data from the module, the MCU can proactively request weather data using this command.

  • The minimum request interval is 20 minutes. If the MCU sends multiple requests within 20 minutes, the request is only processed once.
  • The module only uses this command to confirm a request and sends weather data still through the command 0x21.

The MCU sends the following data.

Field Length Description
Header 2 0x55aa
Version 1 0x03
Command 1 0x34
Data length 2 0x0001
Data 1 0x03 (subcommand)
Checksum 1 Start from the header, add up all the bytes, and then divide the sum by 256 to get the remainder.

Example: 55 aa 03 34 00 01 03 3a

The module returns the following data.

Field Bytes Description
Header 2 0x55aa
Version 1 0x00
Command 1 0x34
Data length 2 0x0002
Data 1 0x03 (subcommand)
1 Result:
  • 0x00: Success
  • 0x01: Failure.
Checksum 1 Start from the header, add up all the bytes, and then divide the sum by 256 to get the remainder.

Example: 55 aa 00 34 00 02 03 00 38

Example

The examples are based on the MCU SDK.

Enable weather service

Enable WEATHER_ENABLE to turn on the weather service.

#define         WEATHER_ENABLE                  //Enable the weather service.

Configure the weather parameters and forecasts as needed.

/******************************************************************************
                    Specify whether to enable the weather service
To use the weather service, you must enable this macro and implement the code for data display on the mobile app in the functions `weather_open_return_handle` and `weather_data_user_handle` in the `protocol.c` file.
Remember to delete the `#err` message after you edit these functions.
When you enable the weather service, the serial data buffer must be increased accordingly.
******************************************************************************/
//#define         WEATHER_ENABLE                  //Enable the weather service.
#ifdef          WEATHER_ENABLE
/* You can set the weather data parameters in the `weather_choose` array in the `protocol.c` and write the number of weather data types to this macro. */
#define         WEATHER_CHOOSE_CNT              4   //Specify the number of weather data parameters.
/* When you enable the weather service, you can set this macro to specify the number of days for which the API returns forecast data. The valid value ranges from 1 to 7. Setting to `1` returns the weather of the current day, without a forecast. */
#define         WEATHER_FORECAST_DAYS_NUM       1   //Specify the number of days for which the API returns forecast data.
#endif

Enable weather data

mcu_open_weather() in protocol.c is used for the MCU to request to enable weather data.

The process is as follows:

  1. The MCU calls mcu_open_weather() to enable weather data.

  2. The MCU gets the enablement result from data_handle() and calls weather_open_return_handle() to proceed with the next operation.

    /**
    * @brief The MCU enables the weather service.
    * @param Null
    * @return Null
    */
    void mcu_open_weather(void)
    {
        int i = 0;
    char buffer[13] = {0};
        unsigned char weather_len = 0;
        unsigned short send_len = 0;
    
        weather_len = sizeof(weather_choose) / sizeof(weather_choose[0]);
    
        for(i=0;i<weather_len;i++) {
            buffer[0] = sprintf(buffer+1,"w.%s",weather_choose[i]);
            send_len = set_wifi_uart_buffer(send_len, (unsigned char *)buffer, buffer[0]+1);
        }
    
        #error "Complete the code and delete this row"
        /*
    // When you request time-dependent parameters such as sunrise and sunset, use t.unix or t.local. Specify the time service you prefer.
        buffer[0] = sprintf(buffer+1,"t.unix"); // GMT or buffer[0] = sprintf(buffer+1,"t.local"); // Local time
    send_len = set_wifi_uart_buffer(send_len, (unsigned char *)buffer, buffer[0]+1);
        */
    
        buffer[0] = sprintf(buffer+1,"w.date.%d",WEATHER_FORECAST_DAYS_NUM);
        send_len = set_wifi_uart_buffer(send_len, (unsigned char *)buffer, buffer[0]+1);
    
        wifi_uart_write_frame(WEATHER_OPEN_CMD, MCU_TX_VER, send_len);
    }
    
    void data_handle(unsigned short offset)
        {
        ......
        case WEATHER_OPEN_CMD:                                  // Enable the weather service.
            weather_open_return_handle(wifi_data_process_buf[offset + DATA_START], wifi_data_process_buf[offset + DATA_START + 1]);
            break;
        ......
    }
    
  3. weather_open_return_handle in protocol.c needs to be implemented by you.

    /**
    * @brief Return the result of enabling the weather service.
    * @param[in] {res} The result of enabling the weather service.
    * @ref       0: Failure
    * @ref       1: Success
    * @param[in] {err} Error code.
    * @return Null
    * @note   To be implemented by the developer.
    */
    void weather_open_return_handle(unsigned char res, unsigned char err)
    {
        #error "Complete the return value and delete this row"
        unsigned char err_num = 0;
    
        if(res == 1) {
            // Success
        }else if(res == 0) {
            // Failure
            // Get the error code.
            err_num = err;
        }
    }
    
  4. If you have enabled the Wi-Fi module self-processing mode with WIFI_CONTROL_SELF_MODE, the module will automatically enable weather data after connected. The related functions are in system.c.

            case WIFI_STATE_CMD:                         //Wi-Fi status
                wifi_work_state = wifi_data_process_buf[offset + DATA_START];
                wifi_uart_write_frame(WIFI_STATE_CMD, MCU_TX_VER, 0);
    #ifdef WEATHER_ENABLE
                if(wifi_work_state == WIFI_CONNECTED && isWoSend == 0) { //When Wi-Fi is connected, enable weather data, only once.
                    mcu_open_weather();
                    isWoSend = 1;
                }
    #endif
            break;
    
  5. Module Debugging Assistant

    Weather Service

Send weather data

weather_data_raw_handle() in system.c is used for the MCU to receive weather data from the module.

The process is as follows:

  1. The MCU gets weather data from data_handle().

  2. data_handle() calls weather_data_raw_handle() to parse the received weather data.

    void data_handle(unsigned short offset)
    {
    ......
        case WEATHER_DATA_CMD:                                  // Send weather data.
                total_len = (wifi_data_process_buf[offset + LENGTH_HIGH] << 8) | wifi_data_process_buf[offset + LENGTH_LOW];
                weather_data_raw_handle((unsigned char *)wifi_data_process_buf + offset + DATA_START, total_len);
            break;
        ......
    }
    
  3. weather_data_raw_handle() in system.c calls weather_data_user_handle() to pass the weather data to your application for processing.

    /**
    * @brief Parse weather data.
    * @param[in] {p_data} The pointer to the received data.
    * @param[in] {data_len} The length of the received data.
    * @return Null
    */
    static void weather_data_raw_handle(const unsigned char p_data[], unsigned short data_len)
    {
        int i = 1;
        int can_len = 0;
        char can[15] = {0};
        char day = 0;
        int type1 = 0;
        unsigned char value_string[100] = {0};
        int val_cnt = 0;
        int val_len = 0;
    
        if(p_data[0] != 1 | | data_len < 1) {
            // Failure.
        }else {
            if(data_len < 4) {
                // Empty data
            }
    
            while (i < data_len) {
                can_len = p_data[i];
    
                my_memset(can, '\0', 15);
                my_memcpy(can, p_data + i + 1, can_len - 2);
    
                day = p_data[i + can_len] - '0';
    
                type1 = p_data[i + 1 + can_len];
                if(type1 != 0 && type1 != 1) {
                    return;
                }
    
                my_memset(value_string, '\0', 100);
                val_cnt = i + 1 + can_len + 1;
                val_len = p_data[val_cnt];
                if (type1 == 0) { //int32
                    weather_data_user_handle(can+2, type1, p_data+val_cnt+1, day);
                }
                else if(type1 == 1) { //string
                    my_memcpy(value_string, p_data + val_cnt + 1, val_len);
                    weather_data_user_handle(can+2, type1, value_string, day);
                }
    
                i += 1 + can_len + 1 + 1 + val_len;
            }
    
            wifi_uart_write_frame(WEATHER_DATA_CMD, 0, 0);
        }
    }
    
  4. weather_data_user_handle() needs to be implemented by you.

    /**
    * @brief User-defined weather data handler.
    * @param[in] {name} The parameter name.
    * @param[in] {type} The parameter type.
    * @ref       0: The integer type.
    * @ref       1: The string type.
    * @param[in] {data} The address of the parameter value.
    * @param[in] {day} The number of days for which the API returns forecast data. The value ranges from 0 to 6 and 0 indicates the current day.
    * @ref       0: Today
    * @ref       1: Tomorrow
    * @return Null
    * @note   To be implemented by the developer.
    */
    void weather_data_user_handle(char *name, unsigned char type, const unsigned char *data, char day)
    {
        #error "Complete the code and delete this row"
        int value_int;
        char value_string[50];//Defaults to 50. You can adjust it based on your defined parameters.
    
        my_memset(value_string, '\0', 50);
    
        //Get the data type.
        if(type == 0) { //The integer type.
            value_int = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3];
        }else if(type == 1) {
            my_strcpy(value_string, data);
        }
    
        //Request the parameter value according to the selected parameters.
        if(my_strcmp(name, "temp") == 0) {
            printf("day:%d temp value is:%d\r\n", day, value_int);          //The integer type.
        }else if(my_strcmp(name, "humidity") == 0) {
            printf("day:%d humidity value is:%d\r\n", day, value_int);      //The integer type.
        }else if(my_strcmp(name, "pm25") == 0) {
            printf("day:%d pm25 value is:%d\r\n", day, value_int);          //The integer type.
        }else if(my_strcmp(name, "condition") == 0) {
            printf("day:%d condition value is:%s\r\n", day, value_string); //The string type.
        }
    }
    
  5. Module Debugging Assistant

    Weather Service

Request weather data

request_weather_serve() in mcu_api.c is used for the MCU to proactively request weather data.

The process is as follows:

  1. Enable MODULE_EXPANDING_SERVICE_ENABLE to turn on extended features.

    #define         MODULE_EXPANDING_SERVICE_ENABLE        // Enable the extended feature.
    
  2. The MCU calls request_weather_serve() to proactively request weather data.

    /**
    * @brief Request weather data.
    * @param Null
    * @return Null
    * @note  To be implemented by the developer.
    */
    void request_weather_serve(void)
    {
        unsigned short send_len = 0;
        send_len = set_wifi_uart_byte(send_len, 0x03);
        wifi_uart_write_frame(MODULE_EXTEND_FUN_CMD, MCU_TX_VER, send_len);
    }
    
  3. The MCU gets the request result from data_handle() and calls open_module_time_serve_result() to proceed with the next operation.

    void data_handle(unsigned short offset)
    {
        ......
        #ifdef MODULE_EXPANDING_SERVICE_ENABLE
            case MODULE_EXTEND_FUN_CMD:                             // The extended feature.
                total_len = (wifi_data_process_buf[offset + LENGTH_HIGH] << 8) | wifi_data_process_buf[offset + LENGTH_LOW];
                open_module_time_serve_result((unsigned char *)(wifi_data_process_buf + offset + DATA_START), total_len);
            break;
        #endif
        ......
        }
    
  4. open_module_time_serve_result() in protocol.c needs to be implemented by you.

    /**
    * @brief The result of enabling the time service.
    * @param[in] {value} The buffer.
    * @param[in] {length} The data length.
    * @return Null
    * @note   To be implemented by the developer.
    */
    void open_module_time_serve_result(const unsigned char value[], unsigned short length)
    {
        ......
        case 0x03: { //Subcommand. Request weather service data.
                if(0x02 != length) {
                    // Data length error.
                    return;
                }
    
                if(value[1] == 0) {
                    //Success
                }else {
                    //Failure
                }
            }
            break;
            ......
    }
    
  5. Module Debugging Assistant

    Weather Service

Appendix

Appendix 1: Weather data in ASCII

Parameter Meaning
Mainland China Other countries/regions Weather forecast Length Hexadecimal value
w.temp Atmospheric temperature in °C Supported Supported 7-day forecast (except for mainland China) 6 77 2e 74 65 6d 70
w.humidity Air humidity Supported Supported 7-day forecast 10 77 2e 68 75 6d 69 64 69 74 79
w.conditionNum Weather condition No. Supported Supported 7-day forecast 14 77 2e 63 6f 6e 64 69 74 69 6f 6e 4e 75 6d
w.pressure Atmospheric pressure in mbar Supported Supported 7-day forecast (except for mainland China) 10 77 2e 70 72 65 73 73 75 72 65
w.realFeel Apparent temperature Supported Supported N/A 10 77 2e 72 65 61 6c 46 65 65 6c
w.uvi Ultraviolet index Supported Supported 7-day forecast 5 77 2e 75 76 69
w.sunrise Sunrise Supported Supported 7-day forecast 9 77 2e 73 75 6e 72 69 73 65
w.sunset Sunset Supported Supported 7-day forecast 8 77 2e 73 75 6e 73 65 74
t.unix GMT, used with sunrise (w.sunrise) and sunset (w.sunset) - - - 6 74 2e 75 6e 69 78
t.local Local time, used with sunrise (w.sunrise) and sunset (w.sunset) - - - 7 74 2e 6c 6f 63 61 6c
w.windSpeed Wind speed in m/s Supported Supported 7-day forecast 11 77 2e 77 69 6e 64 53 70 65 65 64
w.windDir Wind direction Supported Supported 7-day forecast 9 77 2e 77 69 6e 64 44 69 72
w.windLevel Wind scale Supported Not supported 7-day forecast 11 77 2e 77 69 6e 64 4c 65 76 65 6c
w.aqi Air quality index, US EPA standard: 0 to 500 Supported Supported Current day only 5 77 2e 61 71 69
w.rank/w.quality AQI details and national ranking Supported Not supported Current day only 6 77 2e 72 61 6e 6b / 77 2e 71 75 61 6c 69 74 79
w.pm10 PM10 (inhalable particulate matter) in µg/m³ Supported Supported Current day only 6 77 2e 70 6d 31 30
w.pm25 PM2.5 (fine particulate matter) in µg/m³ Supported Supported Current day only 6 77 2e 70 6d 32 35
w.o3 Ozone level in µg/m³ Supported Supported Current day only 4 77 2e 6f 33
w.no2 Nitrogen dioxide level in µg/m³ Supported Supported Current day only 5 77 2e 6e 6f 32
w.co Carbon monoxide level in µg/m³ Supported Supported Current day only 4 77 2e 63 6f
w.so2 Sulfur dioxide level in µg/m³ Supported Supported Current day only 5 77 2e 73 6f 32
w.thigh The highest temperature in °C Supported Supported Forecast only 7 77 2e 74 68 69 67 68
w.tlow The lowest temperature in °C Supported Supported Forecast only 6 77 2e 74 6c 6f 77
w.date.n Number of forecast days, represented by n with 1 ≤ n ≤ 7 Supported Supported - 8 77 2e 64 61 74 65 2e 6e
w.currdate Current weather Supported Supported - 10 77 2e 63 75 72 72 64 61 74 65
  • WindDir indicates the wind direction. For more information about the wind direction code, see Appendix 5.
  • w.conditionNum indicates the weather condition code. For more information, see Appendix 4.
  • Atmospheric pressure conversion: 1 mbar = 100 pa = 1 hPa.
  • Support for forecasts: If w.date.n is carried, the return data is the weather forecast.
  • Support for real-time weather data: For weather requests with w.date.n carried, w.currdate can be carried to get the real-time weather data at the same time. For more information, see Examples of weather data request.

Appendix 2: City service data in ASCII

Identifier Description Type Length Hexadecimal value
c.area County or district name String 6 63 2e 61 72 65 61
c.city City name String 6 63 2e 63 69 74 79
c.province Province String 10 63 2e 70 72 6f 76 69 6e 63 65

If the weather service API only returns the service city without any content, it indicates the device does not provide its latitude and longitude, so the request failed. To resolve this issue, you should guide users to enable the location on their mobile phone and pair the device with the mobile app again.

Appendix 3: Weather service data

Identifier Description Type Real-time weather Weather forecast
w.temp Temperature Integer Yes Supported (except for mainland China)
w.humidity Humidity Integer Yes Yes
w.conditionNum Weather condition No. String Yes Yes
w.pressure Air pressure Integer Yes Supported (except for mainland China)
w.realFeel Apparent temperature Integer Yes No
w.uvi Ultraviolet index Integer Yes Yes
w.windDir Wind direction String Yes Yes
w.windLevel Wind scale Integer Mainland China only No
w.windSpeed Wind speed String (format example: 1.0; 0.5) Yes Yes
w.sunrise Sunrise time String (format example: 2017-04-24 05:24) Yes Yes
w.sunset Sunset time String (format example: 2017-04-24 18:32) Yes Yes
w.aqi Air quality index Integer Yes No
w.pm25 PM2.5 Integer Yes No
w.so2 Sulfur dioxide level Integer Yes No
w.rank/w.quality Air quality rating String (format example: 447/609) Mainland China only No
w.pm10 PM10 Integer Yes No
w.o3 Ozone (O3) level Integer Yes No
w.no2 Nitrogen dioxide (NO2) level Integer Yes No
w.co Carbon monoxide (CO) level Integer Yes No
w.qualityLevel Air quality rating Integer Yes No
w.thigh The highest temperature Integer No Yes
w.tlow The lowest temperature Integer No Yes
  • The number in the string is rounded to one decimal place. Example: 1.0; 0.9
  • Support for real-time weather data: For weather requests with w.date.n carried, w.currdate can be carried to get the real-time weather data at the same time. For more information, see Examples of weather data request.
  • Support for forecasts: If w.date.n is carried, the return data is the weather forecast.

Appendix 4: Weather data in UTF-8 encoding

ASCII code w.conditionNum Hexadecimal value Weather conditions
120 31 32 30 Sunny
101 31 30 31 Heavy rain
102 31 30 32 Thunderstorm
103 31 30 33 Sandstorm
104 31 30 34 Light snow
105 31 30 35 Snow
106 31 30 36 Freezing fog
107 31 30 37 Rainstorm
108 31 30 38 Isolated shower
109 31 30 39 Dust
110 31 31 30 Thunder and lightning
111 31 31 31 Light shower
112 31 31 32 Rain
113 31 31 33 Sleet
114 31 31 34 Dust devil
115 31 31 35 Ice pellets
116 31 31 36 Strong sandstorm
117 31 31 37 Sand blowing
118 31 31 38 Light to moderate rain
119 31 31 39 Mostly clear
121 31 32 31 Fog
122 31 32 32 Shower
123 31 32 33 Heavy shower
124 31 32 34 Heavy snow
125 31 32 35 Extreme rainstorm
126 31 32 36 Blizzard
127 31 32 37 Hail
128 31 32 38 Light to moderate snow
129 31 32 39 Partly cloudy
130 31 33 30 Light snow shower
131 31 33 31 Moderate snow
132 31 33 32 Overcast
133 31 33 33 Needle ice
134 31 33 34 Downpour
136 31 33 36 Thundershower and hail
137 31 33 37 Freezing rain
138 31 33 38 Snow shower
139 31 33 39 Light rain
140 31 34 30 Haze
141 31 34 31 Moderate rain
142 31 34 32 Cloudy
143 31 34 33 Thundershower
144 31 34 34 Moderate to heavy rain
145 31 34 35 Heavy rain to rainstorm
146 31 34 36 Clear

Appendix 5: Wind direction code

Code (string) Hexadecimal value Description
N 4e North
NNE 4e 4e 45 Northeast by north
NE 4e 45 Northeast
ENE 45 4e 45 Northeast by east
E 45 East
ESE 45 53 45 Southeast by east
SE 53 45 Southeast
SSE 53 53 45 Southeast by south
S 53 South
SSW 53 53 57 Southwest by south
SW 53 57 Southwest
WSW 57 53 57 Southwest by west
W 57 West
WNW 57 4e 57 Northwest by west
NW 4e 57 Northwest
NNW 4e 4e 57 Northwest by north