[Huawei's cloud technology to share best practices]] [IoT devices to obtain real-time weather DEMO Code Interpretation

Abstract Before, we worked on how to achieve your device real-time access to weather information, this article will provide you with real-time weather interpret the DEMO application logic from the code level.

Paper undertake [best practices] IoT devices get real-time weather information , for your interpretation of the code logic weather DEMO to help you develop your own real-time weather applications.

Business logic

Before looking at the code, let us first understand this device to obtain real-time weather application business logic.

1577259798263576.png

1. First, the application platform of things need to first subscribe to device data change notification, the platform will push data to applications such equipment when reporting data.

2-3. Then, the device needs to report the data to the city code comprising a platform, the platform will be pushed to the application.

After 4-5. Applications received data contains the city code, according to city code name lookup the city name, then check the corresponding city weather information is cached.

6-8. If the query cache miss or weather information in the cache has cached more than an hour, the application for the latest weather information to the meteorological platform and write caching.

9 to 10. The application of weather information sent by the internet to the device under things.

Code

Let's look at how to use the DEMO JAVA business logic to achieve this.

First check the Main function as an application portal.

. 1  public  static  void main (String [] args) throws Exception {
 2     // ----------------------- change subscription data call interfaces ---------------- --- 
. 3     SubscribeDataChange.subscribe ();
 . 4     . the System OUT .println ( " being set up message receiving server. " );
 5     // ------------ start report data receiving server --- ---------------- 
. 6     SpringApplication.run (the Main. class );
 . 7     . the System OUT .println ( " message server receives the completed structures. " );
 8 }

Main function of this total has done two things, one is called Internet of Things platform subscription excuse subscribed device data change, the second is to accept the start of a news server (based SpringBoot framework).

When the subscription device data changes, Main function calls the subscribe method SubscribeDataChange class:

 1 public static void subscribe() throws Exception{
 2    /**---------------------initialize northApiClient------------------------*/
 3    NorthApiClient northApiClient = AuthUtil.initApiClient();
 4    SubscriptionManagement subscriptionManagement = new SubscriptionManagement(northApiClient);
 5    /**---------------------get accessToken at first------------------------*/
 6    Authentication authentication = new Authentication(northApiClient);
 7    AuthOutDTO authOutDTO = authentication.getAuthToken();
 8    String accessToken = authOutDTO.getAccessToken();
 9    /**---------------------sub deviceAdded notification------------------------*/
10    //note: 10.X.X.X is a LAN IP, not a public IP, so subscription callbackUrl's IP cannot be 10.X.X.X
11    String callbackUrl = PropertyUtil.getProperty("subscription_CallbackUrl");//this is a test callbackUrl
12    SubscriptionDTO subDTO = subDeviceData(subscriptionManagement, "deviceDataChanged", callbackUrl, accessToken);
13 }private static SubscriptionDTO subDeviceData(SubscriptionManagement subscriptionManagement, String notifyType, String callbackUrl, String accessToken) {
14        SubDeviceDataInDTO sddInDTO = new SubDeviceDataInDTO();
15        sddInDTO.setNotifyType(notifyType);
16        sddInDTO.setCallbackUrl(callbackUrl);       try {
17           SubscriptionDTO subDTO = subscriptionManagement.subDeviceData(sddInDTO, null, accessToken);
18           System.out.println("上报数据订阅成功"+subDTO.toString());          return subDTO;
19        } The catch (NorthApiException E) {
 20 is            the System. OUT .println ( " subscribe interface is used, if the recurring subscription ignore " + e.toString ());
 21 is        }
 22 is        return  null ;
 23 is }

The method by north Huawei cloud application device management services SDK completed subscription access authentication and device data change notification of Things platform.

Main function after executing the application in a state of waiting for the call, wait for the platform to push up device data.

When the application receives the device data platform push, calls handleDeviceDataChanged method, which is defined by the device management service north to the application SDK, we need to rewrite it to achieve our business logic.

 1 @Overridepublic void handleDeviceDataChanged(NotifyDeviceDataChangedDTO body) {
 2    String cityCode = body.getService().getData().get("areaCode").asText();
 3    //------------查询天气-------------------
 4    Map<String,Object>  apiBody = null;   try {
 5       apiBody = WeatherUtil.getApiBody(cityCode);
 6    } catch (IOException e) {
 7       e.printStackTrace();
 8    } catch (ParseException e) {
 9       e.printStackTrace ();
 10     } the try {
 . 11        . the System OUT .println ( " is a command issued to the device. " );
 12        // send command ------------ Call Interface - ----------------- 
13 is        InvokeDeviceService.invocation (apiBody);
 14     } the catch (Exception E) {
 15        e.printStackTrace ();
 16     }
 . 17     . the System OUT .println ( " issued the command has been completed. " );
 18 }

In this method, the application first check the weather by city code, and then send a query to the weather equipment issued by the command mode. Issued orders and subscriptions as are applied to the interface of the SDK, this will not expand the device management service by calling the North, let us look at the application launched by the city code query weather specific processes.

1 public static Map<String,Object> getApiBody(String cityCode) throws IOException, ParseException {
2     Map<String, String> cityCodeName = new HashMap<String, String>();
3     cityCodeName.put("755", "深圳");
4     cityCodeName.put("20", "广州");
5     cityCodeName.put("10", "北京");
6     cityCodeName.put(" 21 " , " Shanghai " );
 . 7      . String cityName = cityCodeName GET (cityCode);
 . 8      . The System OUT .println ( " receives the data reported by the device, the device reported cityCode is " + cityCode + " , corresponding to the city name is " + + cityName " . " );

First, the application queries the name of the city according to city code. In this DEMO, we constructed a scene cityCodeName and written correspondence between the city code and city name in several major cities, but in practical applications, this table should be maintained in a persistent database, the database from here It can read.

. 1 File File = new new File ( " Cache / " + + cityName " dateTime " + " .txt " );
 2 Boolean = isWeatherCur to false ; IF (! File.Exists ()) {
 . 3      . The System OUT .println ( " cache does weather data is being called weather query interface to obtain weather information. " );
 4      SimpleDateFormat SDF = new new SimpleDateFormat ( " YY / mM / dd HH: mm: SS " );
 5      String str = sdf.format ( new new a Date ());
 6     ReadWrTxt.writeFile(cityName+"dateTime",str);
 7 }else{
 8     String fileDateTime = ReadWrTxt.readFile(cityName+"dateTime");
 9     SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
10     String nowTime=format.format(new Date());
11     Date d1 = format.parse(nowTime);
12     Date d2 = format.parse(fileDateTime);    long diff = d1.getTime() - d2.getTime();    long= TimeUnit.MILLISECONDS.toMinutes diffMinutes (the diff);     IF (diffMinutes <= 60 && diffMinutes> = 0 ) {
 13 is          the System. OUT .println ( " Read Cache weather data successfully. " );
 14          isWeatherCur = to true ;
 15      } the else {
 16          System. OUT .println ( " weather data cache more than one hour has expired, the weather is calling query interface to obtain weather information. " );
 17          SimpleDateFormat SDF = new new SimpleDateFormat ( " YY / mM / dd HH: mm: SS ");        String str=sdf.format(new Date());        ReadWrTxt.writeFile(cityName+"dateTime",str);    }}

Then applied to determine whether the cached weather data for the city, and whether the cache when more than one hour. Here we use a relatively simple approach, the cache is txt file, the file name directly, including city names, weather information and cache each time a file is saved. Txt file program by determining whether there is time to determine whether the cache cached weather information, then read to determine whether the cache file cache timeout time. When you develop your own application, it is recommended not to use as a txt file cache, use redis for caching database.

. 1 File weatherFile = new new File ( " Cache / " + + cityName " Weather " + " .txt " );
 2 the Map <String, Object> apiBodySave = null ; IF (!! WeatherFile.exists () || isWeatherCur) {
 . 3      / / ------------ call the weather query interface, where the use of Huawei SDK ------------------- APIG 
4      apiBodySave = Weather.getApiBody (cityName);
 . 5      String apiBodyStr = apiBodySave.toString ();
 . 6      ReadWrTxt.writeFile (cityName + " Weather ",apiBodyStr);
 7 }
 8 String fileApiBodyStr = ReadWrTxt.readFile(cityName+"weather");
 9 fileApiBodyStr = fileApiBodyStr.replace("{","");
10 fileApiBodyStr = fileApiBodyStr.replace("}","");
11 fileApiBodyStr = fileApiBodyStr.replaceAll(" ","");
12 String[] afterSplit = fileApiBodyStr.split(",");
13 Map<String, Object> apiBody = new HashMap<String, Object>();for (String ele: afterSplit) {
14     String[] keyVal = ele.split("=");
15     keyVal[1]=keyVal[1].trim();
16     apiBody.put(keyVal[0], keyVal[1]);
17 }return apiBody;}

If no cached weather information of the city or the cache has expired, by Huawei's cloud platform APIG calls weather meteorological query excuse, and caches weather information. Ruoyi cached and weather information is not expired, then skip this step, weather information directly read cache and returns.

Thus, get real-time weather equipment business logic has been opened up, the rest of this article will not explain some of the implementation details, if you are interested, you can refer to on a blog to download DEMO study the code.

Author: Huawei's cloud experts I was spiced corned egg

Guess you like

Origin www.cnblogs.com/huaweicloud/p/12525874.html