Feeling challenged by @PhilipDAth I've attempted to upgrade my script to use asyncio. It's my first attempt at using it, and it seems to work. But I feel there's something off with the numbers, and I can't quite put a finger on it.
If you have any suggestions as to what it could be, let me know.
[Updated Script]
#! /usr/bin/env python3
from datetime import datetime
import asyncio
import meraki
import meraki.aio
def ConvertKbytesToMbytes(p_Kbytes: int) -> float:
"""Convert KB/s to MB/s"""
return p_Kbytes/1000
async def GetWirelessUsageHistory(p_dashboard: meraki.aio.AsyncDashboardAPI,p_network_id,p_Target,p_Ap):
"""https://developer.cisco.com/meraki/api-latest/#!get-network-wireless-usage-history"""
totalKbytes = 0
sentKbytes = 0
receivedKbytes = 0
try:
print(f"Getting usage for AP {p_Ap['name']}")
ApUsageHistory = await p_dashboard.wireless.getNetworkWirelessUsageHistory(
p_network_id,
timespan=p_Target['timespan'],
resolution=p_Target['resolution'],
deviceSerial=p_Ap['serial'],
ssid=p_Target['number']
)
except meraki.AsyncAPIError as e:
print(f"Meraki API error {e}")
return -1
except Exception as e:
print(f"Some other exception {e}")
return -2
print(f"Summing usage history for AP {p_Ap['name']}, over the last {p_Target['timespan']/3600} hours.")
print()
'''Meraki uses wrong notation.
Documentation says output is kilobytes-per-second (KB/s), but response keys use kilobits-per-second (Kbps)'''
for entry in ApUsageHistory:
if entry['totalKbps'] == None:
entry['totalKbps'] = 0
if entry['sentKbps'] == None:
entry['sentKbps'] = 0
if entry['receivedKbps'] == None:
entry['receivedKbps'] = 0
totalKbytes += entry['totalKbps']
sentKbytes += entry['sentKbps']
receivedKbytes += entry['receivedKbps']
return totalKbytes,sentKbytes,receivedKbytes
async def main():
"""Main function routine"""
organization_id = ""
network_id = ""
TargetSsid = {
"name": "Winona Router",
"timespan": 86400, # Spanning over the last 24 hours
"resolution": 300 # 1 hour resolution
}
totalKbytes = 0
sentKbytes = 0
receivedKbytes = 0
dashboard = meraki.DashboardAPI()
AllDevices = dashboard.organizations.getOrganizationInventoryDevices(
organization_id, total_pages='all'
)
print(f"Getting all wireless devices for {network_id} ")
AllWirelessDevices = []
for device in AllDevices:
if device['productType'] == "wireless" and device['networkId'] == network_id:
AllWirelessDevices.append(
{
"name": device['name'],
"serial": device['serial'],
"totalKbytes": 0,
"sentKbytes": 0,
"receivedKbytes": 0,
}
)
TotalNumberOfAps = len(AllWirelessDevices)
print("Finding the SSID number...")
AllSsids = dashboard.wireless.getNetworkWirelessSsids(
network_id,
)
for ssid in AllSsids:
if ssid['name'] == TargetSsid['name']:
TargetSsid['number'] = ssid['number']
break
async with meraki.aio.AsyncDashboardAPI(
maximum_retries=5
) as aiodashboard:
WirelessUsageHistoryTask = [GetWirelessUsageHistory(aiodashboard,network_id,TargetSsid,ap) for ap in AllWirelessDevices]
for task in asyncio.as_completed(WirelessUsageHistoryTask):
[ap_totalKbytes,ap_sentKbytes,ap_receivedKbytes] = await task
totalKbytes += ap_totalKbytes
sentKbytes += ap_sentKbytes
receivedKbytes += ap_receivedKbytes
print()
print(f"Average usage [MB/s] for SSID {TargetSsid['name']} over {TotalNumberOfAps} APs")
print(f"\t Sent: {ConvertKbytesToMbytes(sentKbytes/(TargetSsid['timespan']/TargetSsid['resolution']))} MB/s")
print(f"\t Received: {ConvertKbytesToMbytes(receivedKbytes/(TargetSsid['timespan']/TargetSsid['resolution']))} MB/s")
print(f"\t Total: {ConvertKbytesToMbytes(totalKbytes/(TargetSsid['timespan']/TargetSsid['resolution']))} MB/s")
print(f"Total usage [MB/s] for SSID {TargetSsid['name']} over {TotalNumberOfAps} APs")
print(f"\t Sent: {ConvertKbytesToMbytes(sentKbytes)} MB/s")
print(f"\t Received: {ConvertKbytesToMbytes(receivedKbytes)} MB/s")
print(f"\t Total: {ConvertKbytesToMbytes(totalKbytes)} MB/s")
return 0
if __name__ == "__main__":
ScriptStart = datetime.now()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
print("\n$Time Elapsed:",datetime.now()-ScriptStart)
LinkedIn :::
https://blog.rhbirkelund.dk/Like what you see? - Give a Kudo ## Did it answer your question? - Mark it as a Solution
🙂All code examples are provided as is. Responsibility for Code execution lies solely your own.