adventcalenderさくらインターネットのapiを叩いてネットワークチャレンジ【2019/12/13 分として投稿】


2020/02/08

こんにちは、コロナです

今回はさくらインターネットapiをつかって、ビューワー（アプリ）開発をしました


今回の更新内容

使ったapi
クラウドサーバ一覧を取得
https://developer.sakura.ad.jp/cloud/api/1.1/server/#get_server

# アプリの設計

  サーバのインスタンス毎に、起動するようにしておく
  ![スクリーンショット 2021-06-15 020705.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/45396/013ab389-8fd4-2faf-85fd-a8d6221064e3.png)

   今回は、基地風に２つのリージョンで場所を分けてみました

![スクリーンショット 2021-06-15 021650.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/45396/d2474986-2505-abb1-fec2-5670d4777865.png)

# 開発チャレンジ

## サーバ一覧取得

### 第１東京

```HQL
https://secure.sakura.ad.jp/cloud/zone/tk1a/api/cloud/1.1/server
```

### 第2東京

```HQL
https://secure.sakura.ad.jp/cloud/zone/tk1a/api/cloud/1.1/server
```

### 取得結果
今回は、以下のServerキーを使います

```jsonc
{"From":0,"Count":1,"Total":1,"Servers":[{"Index":0,"ID":"113301066111","Name":"\u30cd\u30eb\u30d5","HostName":"localhost","Description":"","Availability":"available","ServiceClass":"cloud\/plan\/1core-1gb","InterfaceDriver":"virtio","CreatedAt":"2021-06-08T20:10:56+09:00","ModifiedAt":"2021-06-08T20:11:46+09:00","Icon":null,"ServerPlan":{"ID":100001001,"Name":"\u30d7\u30e9\u30f3\/1Core-1GB","CPU":1,"MemoryMB":1024,"Commitment":"standard","Generation":100,"ServiceClass":"cloud\/plan\/1core-1gb"},"Zone":{"ID":21002,"DisplayOrder":20021002,"Name":"tk1b","Description":"\u6771\u4eac\u7b2c2\u30be\u30fc\u30f3","IsDummy":false,"VNCProxy":{"HostName":"sac-tk1b-vnc.cloud.sakura.ad.jp","IPAddress":"61.211.224.155"},"FTPServer":{"HostName":"sac-tk1b-ftp.cloud.sakura.ad.jp","IPAddress":"163.43.143.247"},"Settings":{"SelectableGenerations":[100],"DefaultGeneration":100,"Subnet":{"Plan":{"Member":[28,27,26],"Staff":[28,27,26,25,24,23,22,21,20,19,18]}},"DisablePassport":false,"DisablePrivateHost":false,"SuspendPrivateHost":false},"Region":{"ID":210,"Name":"\u6771\u4eac","Description":"\u6771\u4eac","NameServers":["210.188.224.10","210.188.224.11"]}},"Instance":{"Server":{"ID":"113301066111"},"Status":"up","BeforeStatus":"down","Warnings":"none","WarningsValue":0,"StatusChangedAt":"2021-06-08T20:11:56+09:00","MigrationProgress":null,"MigrationSchedule":null,"MigrationAllowed":null,"ModifiedAt":"2021-06-08T20:11:56+09:00","Host":{"Name":"sac-tk1b-sv010","InfoURL":"","Class":"dynamic","Commitment":"standard","ForPrivate":false,"Generation":100,"Version":303,"SystemVersion":"SAKURA Internet [CLOUD SERVICE 3.3]","PrivateHost":null},"CDROM":null},"Disks":[{"ID":"113301066113","Name":"\u30cd\u30eb\u30d5","Connection":"virtio","ConnectionOrder":1,"ReinstallCount":0,"ToBeInitialized":false,"Availability":"available","SizeMB":20480,"Plan":{"ID":4},"Storage":{"ID":2100294002,"Generation":100,"MountIndex":2100294002,"Class":"iscsi1204"},"BundleInfo":null}],"Interfaces":[{"ID":"113301066112","MACAddress":"9C:A3:BA:32:C0:5B","IPAddress":"163.43.128.235","UserIPAddress":null,"HostName":null,"Switch":{"ID":"113201227923","Name":"\u30b9\u30a4\u30c3\u30c1","Scope":"shared","Subnet":{"ID":null,"NetworkAddress":"163.43.128.0","NetworkMaskLen":24,"DefaultRoute":"163.43.128.1","Internet":{"BandWidthMbps":100}},"UserSubnet":{"DefaultRoute":null,"NetworkMaskLen":12}},"PacketFilter":null}],"Appliance":null,"PrivateHost":null,"Tags":[]}],"is_ok":true}
```

## アプリ側

### 定期的に地形情報を更新

```csharp
     if (currentTime > span)
        {
            Debug.LogFormat("{0}秒経過", span);
            Debug.LogFormat("第2新東京検査開始");
            StartCoroutine(NetWorkManager.instance.CloudServerGetRequest("tk1a", SetThirdRoboData));
            Debug.LogFormat("第3新東京検査開始");
            StartCoroutine(NetWorkManager.instance.CloudServerGetRequest("tk1b", SetSecondRoboData));
            // issue 第3新東京と石狩も作る
            currentTime = 0f;
        }

```

サーバ情報を取得して、存在する限りオブジェクトのSetActiveをtrueにする

```csharp
 public void SetThirdRoboData(CloudServerInfo[] servers)
    {
        int i = 0;
        DateTime now = System.DateTime.Now;

       
        foreach (GameObject robo in ThirdRobos)
        {
            robo.SetActive(i < servers.Length);
            i++;
            // issue カッコイイパラメータをなんか入れる
        }
    }
```


サーバ情報を変換するモデルデータ

```csharp
using System.Collections;
using UnityEngine.Networking;
using UnityEngine.UI;
using UnityEngine;
using System;
using System.Collections.Generic;

namespace BaseCampResponseData
{


    [Serializable]
    public class CloudServerResponse
    {
        [SerializeField]
        public int From;
        [SerializeField]
        public int Count;
        [SerializeField]
        public int Total;
        [SerializeField]
        public CloudServerInfo[] Servers;
    }

    [Serializable]
    public class CloudServerInfo
    {
        [SerializeField]
        public String ID;
        [SerializeField]
        public String NAME;

    }

}


```


# 実行動画

さくらサーバとデジタルワールドがリンクしているのをみることができます。

<p data-height="565" data-theme-id="0" data-slug-hash="rNyoBqQ" data-default-tab="js,result" data-user="tomoasleep" data-embed-version="2" data-pen-title="dJgNLK" class="codepen">See the Pen <a href="https://codepen.io/sakuriver/pen/rNyoBqQ
">サーバチャレンジ</a> by Tomoya Chiba (<a href="https://codepen.io/tomoasleep">@tomoasleep</a>) on <a href="https://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>


2021/06/15 実際の開発に合わせて記事の内容を更新


利用元アセット

カッコイイサーバ（デジタル物理)
https://booth.pm/ja/items/3026322

土地のモデルファイル
https://www.geospatial.jp/ckan/dataset/plateau-tokyo23ku-fbx-2020

### 感想

次回以降のネットワーク学習などで、学習を兼ねてリッチにしたいなと思います