Ed Tanous | 70ee8cb | 2019-10-03 11:36:05 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | |
| 3 | # Example of streaming sensor values from openbmc using the /subscribe api |
| 4 | # requires websockets package to be installed |
| 5 | |
| 6 | import asyncio |
Ed Tanous | 9b243a4 | 2018-08-03 14:33:10 -0700 | [diff] [blame] | 7 | import ssl |
Ed Tanous | 70ee8cb | 2019-10-03 11:36:05 -0700 | [diff] [blame] | 8 | import websockets |
| 9 | import base64 |
| 10 | import json |
| 11 | import argparse |
Ed Tanous | 9b243a4 | 2018-08-03 14:33:10 -0700 | [diff] [blame] | 12 | |
Ed Tanous | 70ee8cb | 2019-10-03 11:36:05 -0700 | [diff] [blame] | 13 | parser = argparse.ArgumentParser() |
| 14 | parser.add_argument("--host", help="Host to connect to", required=True) |
| 15 | parser.add_argument( |
| 16 | "--username", help="Username to connect with", default="root") |
| 17 | parser.add_argument("--password", help="Password to use", default="0penBmc") |
Ed Tanous | 9b243a4 | 2018-08-03 14:33:10 -0700 | [diff] [blame] | 18 | |
Ed Tanous | 70ee8cb | 2019-10-03 11:36:05 -0700 | [diff] [blame] | 19 | args = parser.parse_args() |
Ed Tanous | 9b243a4 | 2018-08-03 14:33:10 -0700 | [diff] [blame] | 20 | |
Ed Tanous | 70ee8cb | 2019-10-03 11:36:05 -0700 | [diff] [blame] | 21 | sensor_type_map = { |
| 22 | "voltage": "Volts", |
| 23 | "power": "Watts", |
| 24 | "fan": "RPM", |
| 25 | "fan_tach": "RPM", |
| 26 | "temperature": "Degrees C", |
| 27 | "altitude": "Meters", |
| 28 | "current": "Amps", |
| 29 | "energy": "Joules", |
| 30 | "cfm": "CFM" |
| 31 | } |
| 32 | |
| 33 | |
| 34 | async def hello(): |
| 35 | uri = 'wss://{}/subscribe'.format(args.host) |
| 36 | ssl_context = ssl.SSLContext() |
| 37 | authbytes = "{}:{}".format(args.username, args.password).encode('ascii') |
| 38 | auth = "Basic {}".format(base64.b64encode(authbytes).decode('ascii')) |
| 39 | headers = {"Authorization": auth} |
Ed Tanous | f395daa | 2021-08-02 08:56:24 -0700 | [diff] [blame] | 40 | async with \ |
| 41 | websockets.connect(uri, ssl=ssl_context, extra_headers=headers) \ |
| 42 | as websocket: |
Ed Tanous | 70ee8cb | 2019-10-03 11:36:05 -0700 | [diff] [blame] | 43 | request = json.dumps({ |
| 44 | "paths": ["/xyz/openbmc_project/sensors"], |
| 45 | "interfaces": ["xyz.openbmc_project.Sensor.Value"] |
| 46 | }) |
| 47 | await websocket.send(request) |
| 48 | |
| 49 | while True: |
| 50 | payload = await websocket.recv() |
| 51 | j = json.loads(payload) |
| 52 | path = j.get("path", "unknown/unknown") |
| 53 | name = path.split("/")[-1] |
| 54 | sensor_type = path.split("/")[-2] |
| 55 | units = sensor_type_map.get(sensor_type, "") |
| 56 | properties = j.get("properties", []) |
| 57 | value = properties.get("Value", None) |
| 58 | if value is None: |
| 59 | continue |
| 60 | print(f"{name:<20} {value:4.02f} {units}") |
| 61 | |
| 62 | asyncio.get_event_loop().run_until_complete(hello()) |