润开鸿HH-SCDAYU800A开发板(四)

(六)基于润开鸿HH-SCDAYU800A开发板开发的在线温湿度互动屏

润开鸿HH-SCDAYU800A开发板

项目目的

本项目旨在通过调用互联网调用相关天气接口和显示环境温湿度数据,为用户提供直观的环境信息,并结合触摸交互功能,实现个性化实时反馈。同时探索物联网设备互联与协同应用,验证开发板的性能与功能,推动OpenHarmony生态建设,最终提升用户体验并为相关教育与培训提供实践案例。

项目目标

本项目致力于构建一个基于OpenHarmony系统的环境信息交互系统,通过调用互联网天气接口以及采集环境温湿度数据,为用户提供清晰直观的环境信息展示。系统将集成触摸交互功能,根据用户的操作实现个性化实时反馈,满足用户对环境信息的多样化需求。同时,本项目将探索物联网设备之间的互联与协同应用模式,验证开发板在实际项目中的性能与功能表现,为OpenHarmony生态建设提供实践案例和技术支持。最终,通过本项目的实施,旨在提升用户对环境信息获取的便捷性和满意度,为相关教育与培训领域提供具有参考价值的实践案例,推动OpenHarmony技术在智能环境监测领域的应用与发展。

项目准备

获取中国气象数据网API接口

1.在浏览器中打开中国气象数据网(https://data.cma.cn)。

项目准备_1

2.右上角点击“注册”,根据实际情况进行账号注册并通过邮箱激活账号。

项目准备_2

3.点击首页“服务接口”(https://data.cma.cn/market/index.html)。

项目准备_3

4.点击“查看详情”(https://data.cma.cn/Market/marketList.html)。

项目准备_4

5.点击“中国地面气象站定时值观测资料”(https://data.cma.cn/Market/Detail/code/A.0012.0001/type/0.html)。

项目准备_5

6.“台站选择”选择“订制”并选择所在城市,“要素选择”选择“订制”并选择“温度/气温”及“相对湿度”,“服务时长”选择“免费试用7天”,点击“完成选购”。

项目准备_6

API调用说明
http://api.data.cma.cn:8090/api?userId=<帐号>&pwd=<密码>&dataFormat=json&interfaceId=getSurfEleByTimeRangeAndStaID&dataCode=SURF_CHN_MUL_HOR_3H&timeRange=<时间范围>&staIDs=<台站列表>&elements=Station_Id_C,Year,Mon,Day,Hour,<要素列表>
参数名称参数定义
userId、pwd分配给您的帐号和密码,从订单中获取
dataFormat返回的数据格式,目前仅支持json格式
interfaceId此数据的接口ID,值为getSurfEleByTimeRangeAndStaID
dataCode此数据的编码,中国地面气象站逐小时观测资料的编码为SURF_CHN_MUL_HOR_3H
timeRange时间范围,支持最近7天的数据访问,格式为“[YYYYMMDDHHMISS,YYYYMMDDHHMISS]”
staIDs站号,支持1-30个站点,多个站点之间以“,”分隔
elements返回数据字段,多个字段之间使用“,”分隔,其中:Station_Id_C, Year,Mon,Day,Hour为默认字段,Station_Id_C为站号,Year为资料时间的年,Mon为资料时间的月,Day为资料时间的日,Hour为资料时间的时,<要素列表>为您订单中订制的要素

中国地面气象站点清单文档
中国地面气象站要素清单

使用Python验证中国气象数据网API接口调用的有效性

运行下述代码,若输出所在地温度及湿度信息,则中国气象数据网API接口调用准确。

import requests  # 导入requests库,用于发送HTTP请求
import json  # 导入json库,用于处理JSON数据
from datetime import datetime  # 导入datetime模块,用于获取当前时间

# 获取当前时间
current_datetime = datetime.now()
# 提取当前年份,格式为YYYY
year = current_datetime.strftime("%Y")
# 提取当前月和日,格式为MMDD
month_day = current_datetime.strftime("%m%d")
# 提取当前小时,格式为HH
hour = current_datetime.strftime("%H")

# 构造时间范围字符串,格式为[YYYYMMDD000000, YYYYMMDDHH0000]
time_range = f"[{year}{month_day}000000,{year}{month_day}{hour}0000]"

# 定义获取天气数据的函数
def get_weather_data(user_id, password, time_range, station_ids):
    """
    从中国气象局API获取指定时间范围和站点的天气数据
    :param user_id: 用户ID
    :param password: 用户密码
    :param time_range: 时间范围,格式为[开始时间, 结束时间]
    :param station_ids: 气象站点ID
    :return: 返回JSON格式的天气数据或None
    """
    # API URL
    base_url = "http://api.data.cma.cn:8090/api"
    # 构造请求参数
    params = {
        "userId": user_id,  # 用户ID
        "pwd": password,  # 用户密码
        "dataFormat": "json",  # 数据格式为JSON
        "interfaceId": "getSurfEleByTimeRangeAndStaID",  # 接口ID
        "dataCode": "SURF_CHN_MUL_HOR_3H",  # 数据代码,表示3小时一次的地面观测数据
        "timeRange": time_range,  # 时间范围
        "staIDs": station_ids,  # 气象站点ID
        "elements": "Station_Id_C,Year,Mon,Day,Hour,TEM,RHU"  # 请求的气象要素,包括站点ID、年、月、日、小时、温度、相对湿度
    }
    # 发送GET请求
    response = requests.get(base_url, params=params)
    # 检查响应状态码
    if response.status_code == 200:
        # 如果状态码为200,表示请求成功,解析JSON数据并返回
        data = response.json()
        return data
    else:
        # 如果状态码不是200,打印错误信息并返回None
        print(f"ERROR:{response.status_code}")
        return None

# 用户ID和密码,用于访问API
user_id = "USER_ID"
password = "PassWord"
# 气象站点ID
station_ids = "54511"

# 调用函数获取天气数据
weather_data = get_weather_data(user_id, password, time_range, station_ids)

# 如果获取到天气数据
if weather_data:
    # 打印天气数据,格式化为可读的JSON格式
    print(json.dumps(weather_data, ensure_ascii=False, indent=4))

python CMAAPITest.py

项目准备_7

互联网接入环境

在润开鸿HH-SCDAYU800A开发板点击“设置”,选择“WLAN”,选择对应网络输入密码即可连入网络。

项目准备_8

(七)基于润开鸿HH-SCDAYU800A开发板的在线温湿度互动屏后端开发代码实现

Index.ets文件

// index.ets
import http from '@ohos.net.http'; // 导入 HTTP 模块

@Entry
@Component
struct WeatherApp {
  @State weatherData: string = 'Loading weather data...';

  build() {
    Column() {
      Text(this.weatherData)
        .fontSize(20)
        .textAlign(TextAlign.Center)
        .margin({ top: 20 })
    }
    .width('100%')
    .height('100%')
    .backgroundColor(Color.White)
    .onAppear(() => {
      this.fetchWeatherData();
    })
  }

  fetchWeatherData() {
    const user_id = "USER_ID";
    const password = "PassWord";
    const station_ids = '54511';

    const current_datetime = new Date();
    const year = current_datetime.getFullYear().toString();
    const month_day = (current_datetime.getMonth() + 1).toString().padStart(2, '0') + current_datetime.getDate().toString().padStart(2, '0');
    const hour = current_datetime.getHours().toString().padStart(2, '0');
    const time_range = `[${year}${month_day}000000,${year}${month_day}${hour}0000]`;

    const base_url = 'http://api.data.cma.cn:8090/api';
    const params = `userId=${user_id}&pwd=${password}&dataFormat=html&interfaceId=getSurfEleByTimeRangeAndStaID&dataCode=SURF_CHN_MUL_HOR_3H&timeRange=${time_range}&staIDs=${station_ids}&elements=Station_Id_C,Year,Mon,Day,Hour,TEM,RHU`;

    const request = http.createHttp();
    request.request(
      `${base_url}?${params}`,
      {
        method: http.RequestMethod.GET,
        header: {
          'Content-Type': 'text/html; charset=utf-8'
        },
        expectDataType: http.HttpDataType.STRING,
        usingCache: true,
        priority: 1,
        connectTimeout: 600000,
        readTimeout: 600000
      },
      (err, response) => {
        if (err) {
          console.error(`ERROR: ${err.message}`);
          this.weatherData = `ERROR: ${err.message}`;
          request.destroy();
          return;
        }
        console.log(`API Response: ${JSON.stringify(response)}`); // 打印返回的原始数据

        // 检查 response.data 是否存在
        if (response) {
          this.weatherData = JSON.stringify(response); // 直接显示返回的 HTML 内容
        } else {
          this.weatherData = 'ERROR: No data returned';
        }
        request.destroy();
      }
    );
  }
}

Index.ets

build-profile.json5文件

{
  "app": {
    "signingConfigs": [
      {
        "name": "default",
        "type": "HarmonyOS",
        "material": {
          "certpath": "",
          "storePassword": "",
          "keyAlias": "debugKey",
          "keyPassword": "",
          "profile": "",
          "signAlg": "",
          "storeFile": ""
        }
      }
    ],
    "compileSdkVersion": 9,
    "compatibleSdkVersion": 9,
    "products": [
      {
        "name": "default",
        "signingConfig": "default",
      }
    ],
    "buildModeSet": [
      {
        "name": "debug",
      },
      {
        "name": "release"
      }
    ],
  },
  "modules": [
    {
      "name": "entry",
      "srcPath": "./entry",
      "targets": [
        {
          "name": "default",
          "applyToProducts": [
            "default"
          ]
        }
      ]
    }
  ]
}

build-profile.json5

module.json5文件

{
  "module": {
    "name": "entry",
    "type": "entry",
    "description": "$string:module_desc",
    "mainElement": "EntryAbility",
    "deviceTypes": [
      "phone",
      "tablet"
    ],
    "deliveryWithInstall": true,
    "installationFree": false,
    "pages": "$profile:main_pages",
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ts",
        "description": "$string:EntryAbility_desc",
        "icon": "$media:icon",
        "label": "$string:EntryAbility_label",
        "startWindowIcon": "$media:startIcon",
        "startWindowBackground": "$color:start_window_background",
        "exported": true,
        "skills": [
          {
            "entities": [
              "entity.system.home"
            ],
            "actions": [
              "action.system.home"
            ]
          }
        ]
      }
    ],
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]
  }
}

module.json5

运行效果

烧录
运行效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值