|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# vim: set encoding=utf-8 tabstop=4 softtabstop=4 shiftwidth=4 expandtab |
| 3 | +######################################################################### |
| 4 | +# Copyright 2019 Torsten Dreyer torsten (at) t3r (dot) de |
| 5 | +# Copyright 2021 Bernd Meiners Bernd.Meiners@mail.de |
| 6 | +######################################################################### |
| 7 | +# This file is part of SmartHomeNG. |
| 8 | +# https://www.smarthomeNG.de |
| 9 | +# https://knx-user-forum.de/forum/supportforen/smarthome-py |
| 10 | +# |
| 11 | +# SmartHomeNG is free software: you can redistribute it and/or modify |
| 12 | +# it under the terms of the GNU General Public License as published by |
| 13 | +# the Free Software Foundation, either version 3 of the License, or |
| 14 | +# (at your option) any later version. |
| 15 | +# |
| 16 | +# SmartHomeNG is distributed in the hope that it will be useful, |
| 17 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 18 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 19 | +# GNU General Public License for more details. |
| 20 | +# |
| 21 | +# You should have received a copy of the GNU General Public License |
| 22 | +# along with SmartHomeNG. If not, see <http://www.gnu.org/licenses/>. |
| 23 | +# |
| 24 | +######################################################################### |
| 25 | + |
| 26 | +import logging |
| 27 | +import json |
| 28 | +import requests |
| 29 | +from requests_file import FileAdapter |
| 30 | +import pyjq |
| 31 | +from lib.model.smartplugin import SmartPlugin |
| 32 | +from lib.item import Items |
| 33 | +from .webif import WebInterface |
| 34 | + |
| 35 | + |
| 36 | +class JSONREAD(SmartPlugin): |
| 37 | + PLUGIN_VERSION = "1.0.4" |
| 38 | + |
| 39 | + def __init__(self, sh): |
| 40 | + """ |
| 41 | + Initializes the plugin |
| 42 | + @param url: URL of the json data to fetch |
| 43 | + @param cycle: the polling interval in seconds |
| 44 | + """ |
| 45 | + # Call init code of parent class (SmartPlugin) |
| 46 | + super().__init__() |
| 47 | + |
| 48 | + from bin.smarthome import VERSION |
| 49 | + if '.'.join(VERSION.split('.', 2)[:2]) <= '1.5': |
| 50 | + self.logger = logging.getLogger(__name__) |
| 51 | + |
| 52 | + self._url = self.get_parameter_value('url') |
| 53 | + self._cycle = self.get_parameter_value('cycle') |
| 54 | + self._session = requests.Session() |
| 55 | + self._session.mount('file://', FileAdapter()) |
| 56 | + self._items = {} |
| 57 | + self._lastresult = {} |
| 58 | + self._lastresultstr = "" |
| 59 | + self._lastresultjq = "" |
| 60 | + |
| 61 | + # if plugin should start even without web interface |
| 62 | + self.init_webinterface(WebInterface) |
| 63 | + |
| 64 | + |
| 65 | + def run(self): |
| 66 | + """ |
| 67 | + Run method for the plugin |
| 68 | + """ |
| 69 | + self.logger.debug("Run method called") |
| 70 | + self.alive = True |
| 71 | + self.scheduler_add(self.get_fullname(), self.poll_device, cycle=self._cycle) |
| 72 | + |
| 73 | + def stop(self): |
| 74 | + self.logger.debug("Stop method called") |
| 75 | + self.scheduler_remove(self.get_fullname() ) |
| 76 | + self.alive = False |
| 77 | + |
| 78 | + def parse_item(self, item): |
| 79 | + if self.has_iattr(item.conf, 'jsonread_filter'): |
| 80 | + self._items[item] = self.get_iattr_value(item.conf, 'jsonread_filter') |
| 81 | + |
| 82 | + def poll_device(self): |
| 83 | + try: |
| 84 | + response = self._session.get(self._url) |
| 85 | + |
| 86 | + except Exception as ex: |
| 87 | + self.logger.error("Exception when sending GET request for {}: {}".format(self._url,str(ex))) |
| 88 | + return |
| 89 | + |
| 90 | + if response.status_code != 200: |
| 91 | + self.logger.error("Bad response code from GET '{}': {}".format(self._url, response.status_code)) |
| 92 | + return |
| 93 | + |
| 94 | + try: |
| 95 | + json_obj = response.json() |
| 96 | + except Exception as ex: |
| 97 | + self.logger.error("Response from '{}' doesn't look like json '{}'".format(self._url, str(response.content)[:30])) |
| 98 | + return |
| 99 | + |
| 100 | + try: |
| 101 | + self._lastresult = json_obj |
| 102 | + self._lastresultstr = json.dumps(self._lastresult, indent=4, sort_keys=True) |
| 103 | + self._lastresultjq = '\n'.join(str(x) for x in pathes(self._lastresult)) |
| 104 | + except Exception as ex: |
| 105 | + self.logger.error("Could not change '{}' into pretty json string'{}'".format(self._lastresult,self._lastresultstr)) |
| 106 | + self._lastresultstr = "<empty due to failure>" |
| 107 | + |
| 108 | + for k in self._items.keys(): |
| 109 | + try: |
| 110 | + jqres = pyjq.first(self._items[k], json_obj) |
| 111 | + |
| 112 | + except Exception as ex: |
| 113 | + self.logger.error("jq filter failed: {}'".format(str(ex))) |
| 114 | + continue |
| 115 | + |
| 116 | + k(jqres) |
| 117 | + |
| 118 | +# just a helper function |
| 119 | + |
| 120 | +def pathes( d, stem=""): |
| 121 | + #print("Stem:",stem) |
| 122 | + if isinstance(d, dict): |
| 123 | + for key, value in d.items(): |
| 124 | + if isinstance(value, dict): |
| 125 | + for d in pathes(value, "{}.{}".format(stem,key)): |
| 126 | + yield d |
| 127 | + elif isinstance(value, list) or isinstance(value, tuple): |
| 128 | + for v in value: |
| 129 | + for d in pathes(v, "{}.{}".format(stem,key)): |
| 130 | + yield d |
| 131 | + else: |
| 132 | + yield "{}.{} => {}".format(stem,key,value) |
| 133 | + elif isinstance(d, list) or isinstance(d, tuple): |
| 134 | + for value in d: |
| 135 | + if isinstance(value, dict): |
| 136 | + for d in pathes(value, "{}.{}".format(stem,key)): |
| 137 | + yield d |
| 138 | + elif isinstance(value, list) or isinstance(value, tuple): |
| 139 | + for v in value: |
| 140 | + for d in pathes(v, "{}.{}".format(stem,key)): |
| 141 | + yield d |
| 142 | + else: |
| 143 | + yield "{}.{} => {}".format(stem,key,value) |
| 144 | + else: |
| 145 | + yield "{}.{}".format(stem,d) |
0 commit comments