Created
May 7, 2016 08:35
-
-
Save basilfx/b4a06b0bc51b31501f871f808514e3ba to your computer and use it in GitHub Desktop.
SAJ Solar Inverter query tool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import xmltodict | |
| import requests | |
| import argparse | |
| import urlparse | |
| import sys | |
| __version__ = "1.0.0" | |
| __description__ = "Query tool for SAJ solar inverters" | |
| def parse_arguments(): | |
| """ | |
| Parse commandline arguments. | |
| """ | |
| parser = argparse.ArgumentParser() | |
| # Add options | |
| parser.add_argument( | |
| "--host", action="store", required=True, help="remote host") | |
| parser.add_argument( | |
| "--query", action="store", help="field to query") | |
| # Parse command line | |
| return parser.parse_args(), parser | |
| def main(): | |
| """ | |
| Read a single value, using the first command line argument as query. | |
| """ | |
| # Parse arguments and configure application instance. | |
| arguments, parser = parse_arguments() | |
| # Fix the host URL. | |
| url = arguments.host | |
| if not url.startswith("http://"): | |
| url = "http://" + url | |
| url = urlparse.urljoin(url, "real_time_data.xml") | |
| # Make request to read data. | |
| try: | |
| response = requests.get(url) | |
| except requests.ConnectionError: | |
| sys.stderr.write("Cannot connect to inverter.\n") | |
| sys.exit(1) | |
| # Parse data. | |
| data = xmltodict.parse(response.content) | |
| if arguments.query: | |
| try: | |
| sys.stdout.write("%s\n" % data["real_time_data"][arguments.query]) | |
| except KeyError: | |
| sys.stderr.write("Cannot query field.\n") | |
| sys.exit(2) | |
| else: | |
| for key, value in data["real_time_data"].iteritems(): | |
| sys.stdout.write("%s: %s\n" % (key, value)) | |
| # E.g. `python power.py --host 192.168.2.1 --query ` | |
| if __name__ == "__main__": | |
| sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment