BLE 导入(用例)
阅读并按照此示例导入蓝牙低能耗 (BLE) 资产,并使用 Python 脚本和 API 为其指定有用的描述性名称。
当您使用瞻博网络 Mist 资产可见性设置并激活基于位置的服务时,像您这样的管理员可以看到所有 BLE 客户端和资产。您还可以在室内平面图或地图上查看它们的精确位置。
对于使用 BLE 资产标签的网站,可以通过为这些设备提供一些上下文的易读名称来跟踪这些设备非常方便。您可以在瞻博网络 Mist 门户中单独添加和显示这些名称,但如果需要管理大量资产,则逐个进行作可能会非常耗时。执行此作的更简单方法是运行脚本来导入 BLE 资源并为它们批量分配名称。
对于此用例,您需要:
-
在每个站点的站点设置中启用资产可见性。
-
确保您拥有有效的资产可见性许可证。
-
请确保在平面图上放置了兼容的接入点。
此用例涉及两个脚本: main.py 和 mist-client.py。第三个文件是名为 assets.csv的 CSV 文件,其中包含 BLE 资源及其相应的名称。
以下是需要导入 BLE 资源时遵循的步骤顺序:
-
首先,使用 Mist API 令牌、Mist 站点通用唯一标识符 (UUID) 和组织托管所在的区域(或云)更新 main.py 脚本。
-
接下来,在文件中 assets.csv 添加、删除或检查 BLE 设备及其名称。
-
运行脚本 main.py ,该脚本将使用 CSV 内容在瞻博网络 Mist 中创建资产。
Main.py 脚本
剧本的 main.py 幕后发生了很多事情。该脚本从 CSV 文件导入数据并将数据转换为 JSON 格式。然后,脚本会为每个设备创建一个 BLE 资产并触发脚本 mist-client.py 。此 mist-client.py 脚本负责对瞻博网络 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.
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-host}/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 脚本的功能类似于用于与瞻博网络 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.pymain.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。您可以探索以下其他选项以实现自动化。