====== SORACOM API を使う ====== [[https://soracom.jp/services/air/|SORACOM Air]] は、ユーザーコンソールでのブラウザによる制御以外に、REST APIで制御することが可能です。\\ [[https://dev.soracom.io/jp/tools/#ruby|公式SDK]] として Ruby 用が提供されていますが、Python のほうが慣れているので、[[https://github.com/j3tm0t0/soracom-python|Python用SDK]] を拡張してみました。 * リポジトリ : [[https://github.com/centurysys/soracom-python]] \\ ===== 使い方 ===== [[https://github.com/soracom/soracom-sdk-ruby|Ruby用SDK]] をできるだけそのままの形で Python 用に実装しています。 % ipython3 Python 3.4.3 (default, Nov 19 2015, 13:59:03) Type "copyright", "credits" or "license" for more information. IPython 3.2.1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: from soracom import api_client In [2]: api=api_client.SoracomAPI() In [3]: api.list_subscribers() Out[3]: [{'apn': 'soracom.io', 'createdAt': 1448608559047, 'createdTime': 1448608559047, 'expiredAt': None, 'expiryTime': None, 'groupId': 'ffffffff-0000-1111-2222-333344445555', 'imsi': '440000000000000', 'ipAddress': '10.xxx.xxx.xxx', 'lastModifiedAt': 1448845964414, 'lastModifiedTime': 1448845964414, 'moduleType': 'nano', 'msisdn': '810000000000', 'operatorId': 'OPxxxxxxxxxx', 'plan': 0, 'sessionStatus': {'dnsServers': None, 'imei': None, 'lastUpdatedAt': 1448845964414, 'location': None, 'online': False, 'ueIpAddress': None}, 'speedClass': 's1.slow', 'status': 'active', 'tags': {'name': 'SORACOM SIM_1'}, 'terminationEnabled': False, 'type': 's1.slow'}] In [4]: api.get_air_usage("440000000000000") Out[4]: [{'dataTrafficStatsMap': {'s1.slow': {'downloadByteSizeTotal': 90, 'downloadPacketSizeTotal': 1, 'uploadByteSizeTotal': 126, 'uploadPacketSizeTotal': 1}}, 'date': '2015-11-30T01:13:12.487', 'unixtime': 1448845992}] In [5]: api.list_groups() Out[5]: [{'configuration': {}, 'createdAt': 1448608557355, 'createdTime': 1448608557355, 'groupId': 'ffffffff-1111-2222-3333-444455556666', 'lastModifiedAt': 1448608557355, 'lastModifiedTime': 1448608557355, 'operatorId': 'OPxxxxxxxxxx', 'tags': {'name': 'IoT'}}] \\ [[https://dev.soracom.io/jp/tools/|SORACOM SDK for Ruby]] にあるサンプルコードのPython版です。 #! /usr/bin/env python3 # -*- coding: utf-8 -*- from soracom.api_client import SoracomAPI, SpeedClass # SORACOM APIアクセス用クライアントの初期化方法 # 1. client = soracom.api_client.SoracomAPI(email='登録メールアドレス', # password='パスワード') # 2. client = soracom.api_client.SoracomAPI() # (環境変数 SORACOM_EMAIL & SORACOM_PASSWORD を参照) def main(): client = SoracomAPI() # サブスクライバー(SIM)の一覧を取得 sims = client.list_subscribers() print("found {} SIMs.".format(len(sims))) # 操作対象のIMSI配列を用意 imsis = [sim['imsi'] for sim in sims] print("change plan to {}".format(SpeedClass.s1.fast)) # プラン変更のためのAPIをコールする res = client.update_subscriber_speed_class(imsis, SpeedClass.s1.fast) print("done") if __name__ == "__main__": main() \\ 実行例 % python3 changeSpeedClass.py found 1 SIM(s). change plan to s1.fast done