BLEインポート(ユースケース)
Bluetooth Low Energy(BLE)アセットをインポートし、Python スクリプトと API を使用してわかりやすい名前を付けるには、この例に従ってください。
Juniper Mistアセットの可視化を利用して位置情報サービスをセットアップして有効化すると、管理者のようなユーザーはすべてのBLEクライアントとアセットを見ることができます。また、屋内の間取り図や地図上で正確な位置を確認することもできます。
BLEアセットタグを使用しているサイトでは、コンテキストを示す読みやすい名前を付けて、デバイスを追跡するのが便利です。これらの名前は Juniper Mist ポータル内で個別に追加して表示できますが、管理するアセットがたくさんある場合は、1 つずつ行うとかなり時間がかかる場合があります。これを行う簡単な方法は、スクリプトを実行してBLEアセットをインポートし、それらに名前を一括で割り当てることです。
このユースケースでは、次のことを行う必要があります。
-
各サイトのサイト設定でアセットの可視性を有効にします。
-
Asset Visibilityの有効なライセンスがあることを確認します。
-
互換性のある AP がフロア プランに配置されていることを確認します。
このユースケースには、 main.py と mist-client.pyの2つのスクリプトが含まれます。3番目のファイル、 assets.csvと呼ばれるCSVファイルには、BLEアセットとそれに対応する名前が含まれています。
BLEアセットをインポートする必要がある場合の手順の順序は次のとおりです。
-
まず、Mist API トークン、Mist サイトのユニバーサル 意の (UUID)、および組織がホストされているリージョン (またはクラウド) を使用して、 main.py スクリプトを更新します。
-
次に、 assets.csv ファイル内でBLEデバイスとその名前を追加、削除、または検査します。
-
CSV コンテンツを使用して Juniper Mist でアセットを作成する main.py スクリプトを実行します。
Main.py スクリプト
main.py脚本の舞台裏では多くのことが起こっています。このスクリプトは、CSVファイルからデータをインポートし、データをJSON形式に変換します。次に、デバイスごとに、スクリプトによってBLEアセットが作成され、mist-client.pyスクリプトがトリガーされます。この mist-client.py スクリプトは、Juniper Mist API に対して必要なすべての呼び出しを行う作業を行います。
#!/usr/bin/python
#
# main.py
#
# Update main.py with your Mist API Token and Juniper Mist site UUID.
#
# Inspect the "assets.csv" file to update the assets being created, then run this exercise to automatically create BLE assets from CSV.
import sys, csv, json, re
from mist_client import Admin # Import the Juniper Mist client
mist_api_token = '' # Your Juniper Mist API token goes here. Documentation: https://api.mist.com/api/v1/docs/Auth#api-token
site_id = '' # Your Site ID goes here
csv_file = 'assets.csv'
# Convert CSV file to JSON object.
def csv_to_json(file):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
csv_rows.extend([ {title[i]: row[title[i]] for i in range(len(title))} ])
return csv_rows
# Creates BLE assets using the given CSV file and the Juniper Mist API
def create_assets(admin, data):
for d in data:
try:
mac = re.sub(r'[^0-9a-fA-F]', '', d.get('MAC', '')).lower()
assert len(mac) == 12
assert mac.isalnum()
except:
print('Invalid MAC {}, skipping this Asset.'.format(d.get('MAC', '(none)')))
continue
# Build the asset payload
payload = {'name': d['Name'].strip(), 'mac': mac}
# Create the BLE Asset and note the targeted region (or cloud)
api_url = 'https://api.mist.com/api/v1/sites/{}/assets'.format(site_id)
(success, result) = admin.post(api_url, payload)
# Add the new BLE Asset to the return list
if result == None:
print('Failed to create BLE Asset {}'.format(mac))
else:
if success:
print('Created BLE Asset \"{}\" ({})'.format(result.get('name', '(unnamed)'), result['mac']))
else:
print('BLE Asset \"{}\" already exists with MAC Address {}'.format(d.get('Name', '(unnamed)'), mac))
# Main function
if __name__ == '__main__':
# Check for required variables
if mist_api_token == '':
print('Please provide your Mist API token as mist_api_token')
sys.exit(1)
elif site_id == '':
print('Please provide your Mist Site UUID as site_id')
sys.exit(1)
# Create Mist client
admin = Admin(mist_api_token)
print()
print('Converting file {} to JSON...\n'.format(csv_file))
# Convert CSV to valid JSON
data = csv_to_json(csv_file)
if data == None or data == []:
print('Failed to convert CSV file to JSON. Exiting script.')
sys.exit(2)
print(json.dumps(data, indent=4, sort_keys=True))
print('\n=====\n')
# Create the BLE Assets from CSV file
print('Creating BLE Assets...\n')
create_assets(admin, data)
print()
Mist_client.py スクリプト
mist_client.py スクリプトは、Juniper Mist API と対話するための通常の RESTful クライアントのように機能します。このスクリプトは、CSVファイルからの入力とmain.pyスクリプトの出力に基づいて API 呼び出しを行います。また、mist-client.py スクリプトは API からの HTTP 応答をエラーチェックし、次のように出力を表示します。
#!/usr/bin/python
#
# mist_client.py
#
# Mist API client session.
import json, requests
# Mist CRUD operations
class Admin(object):
def __init__(self, token=''):
self.session = requests.Session()
self.headers = {
'Content-Type': 'application/json',
'Authorization': 'Token ' + token
}
def get(self, url):
session = self.session
headers = self.headers
print('GET {}'.format(url))
response = session.get(url, headers=headers)
if response.status_code != 200:
print('Failed to GET')
print('\tURL: {}'.format(url))
print('\tResponse: {} ({})'.format(response.text, response.status_code))
return False
return json.loads(response.text)
def post(self, url, payload, timeout=60):
session = self.session
headers = self.headers
#print('POST {}'.format(url))
response = session.post(url, headers=headers, json=payload)
if response.status_code == 400:
return (False, response.text)
elif response.status_code != 200:
'''
print('Failed to POST')
print('\tURL: {}'.format(url))
print('\tPayload: {}'.format(payload))
print('\tResponse: {} ({})'.format(response.text, response.status_code))
'''
return (False, None)
return (True, json.loads(response.text))
Assets.csv
この例では、 assets.csv ファイルは、 mist_client.py および main.py ファイルと同じディレクトリにあります。次の例は、BLEアセットの名前とそれに関連するMACアドレスでCSVファイルをフォーマットする方法を示しています。
Name,MAC Amber Badge,aa:bb:cc:dd:ee:ff Mark Badge,11-22-33-44-55-66 Invalid MAC,xx.yy.zz.xx.yy.zz
自動化は、RESTful APIとPythonを使用するだけではありません。WebSocket や Webhook API などの他のオプションを使用できます。自動化の目的で、これらの他のオプションを調べることができます。