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