Python json.htm() Examples

The following are code examples for showing how to use json.htm(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: BatteryLevel   Author: 999LV   File: plugin.py    MIT License 6 votes vote down vote up
def DomoticzAPI(APICall):
    resultJson = None
    url = "http://{}:{}/json.htm?{}".format(Parameters["Address"], Parameters["Port"], parse.quote(APICall, safe="&="))
    Domoticz.Debug("Calling domoticz API: {}".format(url))
    try:
        req = request.Request(url)
        if Parameters["Username"] != "":
            Domoticz.Debug("Add authentification for user {}".format(Parameters["Username"]))
            credentials = ('%s:%s' % (Parameters["Username"], Parameters["Password"]))
            encoded_credentials = base64.b64encode(credentials.encode('ascii'))
            req.add_header('Authorization', 'Basic %s' % encoded_credentials.decode("ascii"))

        response = request.urlopen(req)
        if response.status == 200:
            resultJson = json.loads(response.read().decode('utf-8'))
            if resultJson["status"] != "OK":
                Domoticz.Error("Domoticz API returned an error: status = {}".format(resultJson["status"]))
                resultJson = None
        else:
            Domoticz.Error("Domoticz API: http error = {}".format(response.status))
    except:
        Domoticz.Error("Error calling '{}'".format(url))
    return resultJson 
Example 2
Project: SmartVirtualThermostat   Author: 999LV   File: plugin.py    MIT License 6 votes vote down vote up
def DomoticzAPI(APICall):

    resultJson = None
    url = "http://{}:{}/json.htm?{}".format(Parameters["Address"], Parameters["Port"], parse.quote(APICall, safe="&="))
    Domoticz.Debug("Calling domoticz API: {}".format(url))
    try:
        req = request.Request(url)
        if Parameters["Username"] != "":
            Domoticz.Debug("Add authentification for user {}".format(Parameters["Username"]))
            credentials = ('%s:%s' % (Parameters["Username"], Parameters["Password"]))
            encoded_credentials = base64.b64encode(credentials.encode('ascii'))
            req.add_header('Authorization', 'Basic %s' % encoded_credentials.decode("ascii"))

        response = request.urlopen(req)
        if response.status == 200:
            resultJson = json.loads(response.read().decode('utf-8'))
            if resultJson["status"] != "OK":
                Domoticz.Error("Domoticz API returned an error: status = {}".format(resultJson["status"]))
                resultJson = None
        else:
            Domoticz.Error("Domoticz API: http error = {}".format(response.status))
    except:
        Domoticz.Error("Error calling '{}'".format(url))
    return resultJson 
Example 3
Project: domoticz_skill   Author: treussart   File: Domoticz.py    MIT License 6 votes vote down vote up
def switch(self, state, what, where, action):
        """Switch the device in Domoticz."""
        data = []
        data = self.findid(what, where, state)
        idx = data[0]
        result = data[1]
        stype = data[2]
        dlevel = data[3]
        if result is 1:
            cmd = self.findcmd(state, action, dlevel)
            if cmd:
                try:
                    f = urllib.request.urlopen(self.url + "/json.htm?type=command&param=switch" + stype + "&idx=" + str(idx) + "&switchcmd=" + str(cmd))
                    response = f.read()
                    LOGGER.debug(str(response))
                    return response
                except IOError as e:
                    LOGGER.error(str(e) + ' : ' + str(e.read()))
        else:
            LOGGER.debug("no command found")
        return result 
Example 4
Project: Domoticz-Mysensors.org-   Author: BazemanKM   File: mindergas.py    GNU General Public License v2.0 6 votes vote down vote up
def main(argv=None):
    
    parser = ArgumentParser(description='Upload meterstand van Domoticz naar MinderGas.nl')
    parser.add_argument("-a", "--apikey", dest="apikey", help="MinderGas.nl API Key", required=True)
    parser.add_argument("-u", "--url", dest="url", help="URL naar Domoticz, eg: http://192.168.2.3:8080", default='http://localhost:8080')
    parser.add_argument("-d", "--device-id", dest="device", help="Device id voor de P1 Gas Smart Meter", type=int, required=True)

    args = parser.parse_args()
    
    device_data = json.load(urllib2.urlopen("%s/json.htm?type=devices&rid=%s" % (args.url, args.device), timeout=5))
    meterstand = device_data['result'][0]['Counter']

    code = upload_meterstand(meterstand, args.apikey)

    if code == 201:
        return 0
    else:
        return code 
Example 5
Project: Domoticz-Google-Assistant   Author: DewGew   File: trait.py    Apache License 2.0 6 votes vote down vote up
def execute(self, command, params):
        """Execute an OnOff command."""
        domain = self.state.domain
        protected = self.state.protected
        
        if domain != sensorDOMAIN:
            if domain == groupDOMAIN:
                url = DOMOTICZ_URL + '/json.htm?type=command&param=switchscene&idx=' + self.state.id + '&switchcmd=' + ('On' if params['on'] else 'Off')
            else:
                url = DOMOTICZ_URL + '/json.htm?type=command&param=switchlight&idx=' + self.state.id + '&switchcmd=' + ('On' if params['on'] else 'Off')

            if protected:
                url = url + '&passcode=' + configuration['switchProtectionPass']

            r = requests.get(url, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password']))
            if protected:
                status = r.json()
                err = status.get('status')
                if err == 'ERROR':
                    raise SmartHomeError(ERR_WRONG_PIN,
                        'Unable to execute {} for {} check your settings'.format(command, self.state.entity_id)) 
Example 6
Project: Domoticz-Google-Assistant   Author: DewGew   File: trait.py    Apache License 2.0 6 votes vote down vote up
def execute(self, command, params):
        """Execute a scene command."""
        protected = self.state.protected
        
        url = DOMOTICZ_URL + '/json.htm?type=command&param=switchscene&idx=' + self.state.id + '&switchcmd=On'
        
        if protected:
            url = url + '&passcode=' + configuration['switchProtectionPass']
            
        r = requests.get(url, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password']))
        if protected:
            status = r.json()
            err = status.get('status')
            if err == 'ERROR':
                raise SmartHomeError(ERR_WRONG_PIN,
                    'Unable to execute {} for {} check your settings'.format(command, self.state.entity_id)) 
Example 7
Project: Domoticz-Google-Assistant   Author: DewGew   File: trait.py    Apache License 2.0 6 votes vote down vote up
def execute(self, command, params):
        """Execute a brightness command."""
        protected = self.state.protected
                    
        url = DOMOTICZ_URL + '/json.htm?type=command&param=switchlight&idx=' + self.state.id + '&switchcmd=Set%20Level&level=' + str(int(params['brightness'] * self.state.maxdimlevel / 100))
        
        if protected:
            url = url + '&passcode=' + configuration['switchProtectionPass']
            
        r = requests.get(url, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password']))
        if protected:
            status = r.json()
            err = status.get('status')
            if err == 'ERROR':
                raise SmartHomeError(ERR_WRONG_PIN,
                    'Unable to execute {} for {} check your settings'.format(command, self.state.entity_id)) 
Example 8
Project: Domoticz-Google-Assistant   Author: DewGew   File: trait.py    Apache License 2.0 6 votes vote down vote up
def execute(self, command, params):
        """Execute a color setting command."""
        if "temperature" in params["color"]:
            tempRange = self.kelvinTempMax - self.kelvinTempMin
            kelvinTemp = params['color']['temperature']
            setTemp = 100 - (((kelvinTemp - self.kelvinTempMin) / tempRange) * 100)
            
            url = DOMOTICZ_URL + '/json.htm?type=command&param=setkelvinlevel&idx=' + self.state.id + '&kelvin=' + str(round(setTemp))

        elif "spectrumRGB" in params["color"]:      
            #Convert decimal to hex
            setcolor = params['color']
            color_hex = hex(setcolor['spectrumRGB'])[2:]
            lost_zeros=6 - len(color_hex)
            color_hex_str=""
            for x in range(lost_zeros):
            	color_hex_str+="0"
            color_hex_str+= str(color_hex)
            
            url = DOMOTICZ_URL + '/json.htm?type=command&param=setcolbrightnessvalue&idx=' + self.state.id + '&hex=' + color_hex_str
        
        r = requests.get(url, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password'])) 
Example 9
Project: Domoticz-Google-Assistant   Author: DewGew   File: trait.py    Apache License 2.0 6 votes vote down vote up
def execute(self, command, params):
        """Execute an SetModes command."""
        levelName = base64.b64decode(self.state.selectorLevelName).decode('UTF-8').split("|")
        protected = self.state.protected
        for key in params['updateToggleSettings']:
            if key in levelName:
                level = str(levelName.index(key)*10)
            
        url = DOMOTICZ_URL + '/json.htm?type=command&param=switchlight&idx=' + self.state.id + '&switchcmd=Set%20Level&level=' + level

        if protected:
            url = url + '&passcode=' + configuration['switchProtectionPass']

        r = requests.get(url, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password']))
        
        if protected:
            status = r.json()
            err = status.get('status')
            if err == 'ERROR':
                raise SmartHomeError(ERR_WRONG_PIN,
                    'Unable to execute {} for {} check your settings'.format(command, self.state.entity_id)) 
Example 10
Project: domoticz   Author: ericstaal   File: doorbell.py    MIT License 5 votes vote down vote up
def reportBell():
  domoticzrequest("http://" + domoticzserver + "/json.htm?type=command&param=switchlight&idx=" + str(domoticzidx) + "&switchcmd=On")
  time.sleep(mintimebetweenrings)
  domoticzrequest("http://" + domoticzserver + "/json.htm?type=command&param=switchlight&idx=" + str(domoticzidx) + "&switchcmd=Off") 
Example 11
Project: gb160-kodi-addons   Author: gb160   File: default.py    GNU General Public License v2.0 5 votes vote down vote up
def list_scenes(self):
        self.url = 'http://'+ DomoticzIP + ":" + DomoticzPort +'/json.htm?type=scenes'
        array_id = []
        json_object = json.loads(self.load_json(self.url))

        status = -2
        if json_object["status"] == "OK":
            status = -1
            for i, v in enumerate(json_object["result"]):
                item = []

                item.append (json_object["result"][i]["idx"])
                item.append (json_object["result"][i]["Name"])
                item.append (json_object["result"][i]["Type"])

                # Image
                if json_object["result"][i]["Type"] == "Scene":
                    item.append ("http://"+ DomoticzIP + ":" + DomoticzPort +"/images/push48.png")
                elif json_object["result"][i]["Type"] == "Group" and json_object["result"][i]["Status"] == "On":
                    item.append ("http://"+ DomoticzIP + ":" + DomoticzPort +"/images/push48.png")
                elif json_object["result"][i]["Type"] == "Group" and json_object["result"][i]["Status"] == "Off":
                    item.append ("http://"+ DomoticzIP + ":" + DomoticzPort +"/images/pushoff48.png")
                elif json_object["result"][i]["Type"] == "Group" and json_object["result"][i]["Status"] == "Mixed":
                    item.append ("pushmixed48.png")
                else:
                    item.append ("")

                # Status
                if json_object["result"][i]["Status"] == "On":
                    item.append (1)
                if json_object["result"][i]["Status"] == "Off":
                    item.append (0)
                if json_object["result"][i]["Status"] == "Mixed":
                    item.append (2)

                if len(item) > 0:
                    array_id.append (item)
                xbmc.log ("SCENE " + str(item))

            xbmc.log ("ARRAY ID " + str(array_id))
            return array_id 
Example 12
Project: gb160-kodi-addons   Author: gb160   File: default.py    GNU General Public License v2.0 5 votes vote down vote up
def list_customswitches(self, idxs):
        self.url = 'http://'+ DomoticzIP + ":" + DomoticzPort +'/json.htm?type=devices&filter=all&used=true&order=Name'
        array_idx = idxs.split(",")
        array_id = []
        json_object = json.loads(self.load_json(self.url))

        status = -2
        if json_object["status"] == "OK":
            status = -1
            for i, v in enumerate(json_object["result"]):
                item = []
                if json_object["result"][i]["idx"] in array_idx and "Lighting" in json_object["result"][i]["Type"] :
                    item.append (json_object["result"][i]["idx"])
                    item.append (json_object["result"][i]["Name"])
                    item.append (json_object["result"][i]["Type"])

                    # Image
                    if json_object["result"][i]["Status"] == "On":
                        item.append ("http://"+ DomoticzIP + ":" + DomoticzPort +"/images/" + json_object["result"][i]["Image"] + "48_On.png")
                    else:
                        item.append ("http://"+ DomoticzIP + ":" + DomoticzPort +"/images/" + json_object["result"][i]["Image"] + "48_Off.png")

                    # Status
                    if json_object["result"][i]["Status"] == "On":
                        item.append (1)
                    if json_object["result"][i]["Status"] == "Off":
                        item.append (0)
                    if json_object["result"][i]["Status"] == "Mixed":
                        item.append (2)

                if len(item) > 0:
                    array_id.append (item)
            return array_id 
Example 13
Project: gb160-kodi-addons   Author: gb160   File: default.py    GNU General Public License v2.0 5 votes vote down vote up
def get_roomid(self, roomname):
        self.url = 'http://'+ DomoticzIP + ":" + DomoticzPort +'/json.htm?type=plans'
        json_object = json.loads(self.load_json(self.url))
        roomid = 0
        if json_object["status"] == "OK":
            for i, v in enumerate(json_object["result"]):
                if json_object["result"][i]["Name"].lower() == str(roomname).lower() :
                    roomid = json_object["result"][i]["idx"]
        return roomid 
Example 14
Project: gb160-kodi-addons   Author: gb160   File: default.py    GNU General Public License v2.0 5 votes vote down vote up
def set_switchstatus (self, switchid, status):
        update_domoticz = 0
        if status == 1:
            self.url = "http://" + DomoticzIP + ":" + DomoticzPort + "/json.htm?type=command&param=switchlight&idx=" + str(switchid) + "&switchcmd=On&level=0"
            update_domoticz = 1
        if status == 0:
            self.url = "http://" + DomoticzIP + ":" + DomoticzPort + "/json.htm?type=command&param=switchlight&idx=" + str(switchid) + "&switchcmd=Off&level=0"
            update_domoticz = 1

        if update_domoticz:
            request = urllib2.Request(self.url)
            request.add_header("Authorization", "Basic %s" % self.base64string)
            self.response = urllib2.urlopen(request).read() 
Example 15
Project: gb160-kodi-addons   Author: gb160   File: default.py    GNU General Public License v2.0 5 votes vote down vote up
def set_scenestatus (self, switchid, status):
        xbmc.log ("START SETSCENESTATUS : ")
        update_domoticz = 0
        if status == 1:
            self.url = "http://" + DomoticzIP + ":" + DomoticzPort + "/json.htm?type=command&param=switchscene&idx=" + str(switchid) + "&switchcmd=On"
            update_domoticz = 1
        if status == 0:
            self.url = "http://" + DomoticzIP + ":" + DomoticzPort + "/json.htm?type=command&param=switchscene&idx=" + str(switchid) + "&switchcmd=Off"
            update_domoticz = 1

        if update_domoticz:
            request = urllib2.Request(self.url)
            request.add_header("Authorization", "Basic %s" % self.base64string)
            self.response = urllib2.urlopen(request).read()
            xbmc.log ("START SETSCENESTATUS: " + str(response)) 
Example 16
Project: domoticz_skill   Author: treussart   File: Domoticz.py    MIT License 5 votes vote down vote up
def findid(self, what, where, state):
        i = 0
        wht = re.compile(what, re.I)
        whr = re.compile(where, re.I)
        f = urllib.request.urlopen(self.url + "/json.htm?type=devices&filter=all&used=true")
        response = f.read()
        payload = json.loads(response.decode('utf-8'))
        idx = False
        stype = False
        dlevel = False
        while i < len(payload['result']):
            if whr.search(payload['result'][i]['Name']) and wht.search(payload['result'][i]['Name']):
                stype = payload['result'][i]['Type']
                typ = re.compile(stype, re.I)
                dlevel = "100"
                if typ.search("Group") or typ.search("Scene"):
                    stype = "scene"
                elif typ.search("Light/Switch"):
                    stype = "light"
                    dlevel = payload['result'][i]['Level']
                else:
                    stype = "light"
                idx = payload['result'][i]['idx']
                rslt = re.compile(" " + str(state).title(), re.I)
                if rslt.search(" " + payload['result'][i]['Data']):
                    result = 0
                else:
                    result = 1
                break
            elif i is len(payload['result']) - 1:
                result = None
                break
            i += 1
        return [idx, result, stype, dlevel] 
Example 17
Project: domoticz_skill   Author: treussart   File: Domoticz.py    MIT License 5 votes vote down vote up
def get(self, what, where):
        """Get the device's data in Domoticz."""
        try:
            f = urllib.request.urlopen(self.url + "/json.htm?type=devices&filter=all&used=true")
            response = f.read()
            payload = json.loads(response.decode('utf-8'))
            wht = re.compile(what, re.I)
            i = 0
            if where is not None:
                whr = re.compile(where, re.I)
                while i < len(payload['result']):
                    if whr.search(payload['result'][i]['Name']) and wht.search(payload['result'][i]['Name']):
                        break
                    elif i is len(payload['result']) - 1:
                        payload['result'][i]['Data'] = None
                        break
                    i += 1
            elif where is None:
                while i < len(payload['result']):
                    if wht.search(payload['result'][i]['Name']):
                        break
                    elif i is len(payload['result']) - 1:
                        payload['result'][i]['Data'] = None
                        break
                    i += 1
            return payload['result'][i]
        except IOError as e:
            LOGGER.error(str(e) + ' : ' + str(e.read())) 
Example 18
Project: domoticz-hive   Author: imcfarla2003   File: plugin.urllib.py    MIT License 5 votes vote down vote up
def getDomoticzRevision(self):
        Revision = 0
        if 'DomoticzVersion' in Parameters:
            Domoticz.Log("DomoticzVersion Available " + Parameters['DomoticzVersion'])
            Revision = Parameters['DomoticzVersion'].split(".")[1]
        else:
            Domoticz.Log("DomoticzVersion Not Available - Using JSON")
            url = 'http://127.0.0.1:' + Parameters['Mode2'] + '/json.htm?type=command&param=getversion'
            Domoticz.Log("Version URL: " + url)
            req = Request(url)
            try:
                r = urlopen(req).read().decode('utf-8')
                j = json.loads(r)
                Revision = j['Revision']
                Version = j['version']
                Domoticz.Debug("Domoticz Revision: " + str(Revision))
                Domoticz.Debug("Domoticz Version: " + Version + '->' + str(int(Version[-4:])))
                if int(Version[-4:]) > Revision:  # I've managed to create a build that has Version different to Revision so take the highest
                    Revision = int(Version[-4:])
            except HTTPError as e:
                if e.code == 401:
                    Domoticz.Error("Ensure you have 127.0.0.1 in your 'Local Networks' selection")
                else:
                    Domoticz.Error(str(e))
            except Exception as e:
                Domoticz.Error(str(e))
        Domoticz.Debug("Domoticz Revision: " + str(Revision))
        return Revision 
Example 19
Project: Domoticz-Google-Assistant   Author: DewGew   File: trait.py    Apache License 2.0 5 votes vote down vote up
def execute(self, command, params):
        """Execute a OpenClose command."""
        features = self.state.attributes
        protected = self.state.protected
        if features & ATTRS_PERCENTAGE:
            url = DOMOTICZ_URL + '/json.htm?type=command&param=switchlight&idx=' + self.state.id + '&switchcmd=Set%20Level&level=' + str(100-params['openPercent'])
        else:
            p = params.get('openPercent', 50)
            
            url = DOMOTICZ_URL + '/json.htm?type=command&param=switchlight&idx=' + self.state.id + '&switchcmd='
            
            if p == 100:
                #open
                url += 'Off'
            elif p == 0:
                #close
                url += 'On'
            else:
                #stop
                url += 'Stop'
            
        if protected:
            url = url + '&passcode=' + configuration['switchProtectionPass']
            
        r = requests.get(url, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password']))
        if protected:
            status = r.json()
            err = status.get('status')
            if err == 'ERROR':
                raise SmartHomeError(ERR_WRONG_PIN,
                    'Unable to execute {} for {} check your settings'.format(command, self.state.entity_id)) 
Example 20
Project: Domoticz-Google-Assistant   Author: DewGew   File: trait.py    Apache License 2.0 5 votes vote down vote up
def execute(self, command, params):
        """Execute a temperature point or mode command."""
        # All sent in temperatures are always in Celsius
        if command == COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT:
            url = DOMOTICZ_URL + '/json.htm?type=command&param=setsetpoint&idx=' + self.state.id + '&setpoint=' + str(params['thermostatTemperatureSetpoint'])

        r = requests.get(url, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password'])) 
Example 21
Project: Domoticz-Google-Assistant   Author: DewGew   File: trait.py    Apache License 2.0 5 votes vote down vote up
def execute(self, command, params):
        """Execute an ArmDisarm command."""
        state = self.state.state
        seccode = self.state.seccode
       
        if params["arm"]:
            if params["armLevel"] == "Arm Home":
                if state == "Arm Home":
                    raise SmartHomeError(ERR_ALREADY_IN_STATE,
                    'Unable to execute {} for {} '.format(command, self.state.entity_id))
                else:    
                    self.state.state = "Arm Home"
                    url = DOMOTICZ_URL + "/json.htm?type=command&param=setsecstatus&secstatus=1&seccode=" + seccode
            if params["armLevel"] == "Arm Away":
                if state == "Arm Away":
                    raise SmartHomeError(ERR_ALREADY_IN_STATE,
                    'Unable to execute {} for {} '.format(command, self.state.entity_id))
                else:    
                    self.state.state = "Arm Away"
                    url = DOMOTICZ_URL + "/json.htm?type=command&param=setsecstatus&secstatus=2&seccode=" + seccode
        else:
            if state == "Normal":
                raise SmartHomeError(ERR_ALREADY_IN_STATE,
                'Unable to execute {} for {} '.format(command, self.state.entity_id))
            else:  
                self.state.state = "Normal"
                url = DOMOTICZ_URL + "/json.htm?type=command&param=setsecstatus&secstatus=0&seccode=" + seccode
                
        r = requests.get(url, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password'])) 
Example 22
Project: Domoticz-Google-Assistant   Author: DewGew   File: trait.py    Apache License 2.0 5 votes vote down vote up
def _execute_set_volume(self, params):
        level = params['volumeLevel']

        url = DOMOTICZ_URL + '/json.htm?type=command&param=switchlight&idx=' + self.state.id + '&switchcmd=Set%20Level&level=' + str(int(level * self.state.maxdimlevel / 100))
        r = requests.get(url, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password'])) 
Example 23
Project: Domoticz-Google-Assistant   Author: DewGew   File: trait.py    Apache License 2.0 5 votes vote down vote up
def _execute_volume_relative(self, params):
        # This could also support up/down commands using relativeSteps
        relative = params['volumeRelativeLevel']
        current = level = self.state.level

        url = DOMOTICZ_URL + '/json.htm?type=command&param=switchlight&idx=' + self.state.id + '&switchcmd=Set%20Level&level=' + str(int(current + relative * self.state.maxdimlevel / 100))
        r = requests.get(url, auth=(configuration['Domoticz']['username'], configuration['Domoticz']['password'])) 
Example 24
Project: TP-Link-HS110   Author: ajay10000   File: tplink_hs110_py3.py    Apache License 2.0 4 votes vote down vote up
def send_json(self,received_data):
    json_data = json.loads(received_data)
    logger.debug("json_data: {}".format(json_data))
    try:
      if self.read_state:
        # For getting the switch state only
        state = json_data['system']['get_sysinfo']['relay_state']
        full_url = domain + "json.htm?type=command&param=udevice&idx={}&nvalue={}".format(hs110_switch_idx,state)
        logger.debug("URL: {}".format(full_url))
        # Send the json string
        req = urllib.request.Request(full_url)
        with urllib.request.urlopen(req) as response:
          result = response.read()
        logger.debug("Logger response: {}".format(result))
      else:
        voltage = round(float(json_data['emeter']['get_realtime']['voltage_mv']) / 1000,2)
        current = round(float(json_data['emeter']['get_realtime']['current_ma']) / 1000,2)
        power = round(float(json_data['emeter']['get_realtime']['power_mw']) / 1000,2)
        usage = round(float(json_data['emeter']['get_realtime']['total_wh']) / 1000,3)
    
        for i in range(0,len(domoticz_idx)): # range is 0 based
          if i < len(domoticz_idx) - 1:
            logger.debug("IDX: {}, Item: {}, Value: {}".format(domoticz_idx[i],monitor_list[i],eval(monitor_list[i])))
            full_url = base_url + "&idx={}&svalue={}".format(domoticz_idx[i],eval(monitor_list[i]))
          else:
            # virtual sensor with sensor type Electric (Instant+Counter)
            logger.debug("IDX: {}, Items: {}, Values: {};{}".format(domoticz_idx[i],"Power (W), Usage (kWhr)",power,usage))
            full_url = base_url + "&idx={}&svalue={};{}".format(domoticz_idx[i],power,usage * 1000)
          logger.debug("URL: {}".format(full_url))
          # Send the json string
          req = urllib.request.Request(full_url)
          with urllib.request.urlopen(req) as response:
            result = response.read()
          logger.debug("Logger response: {}".format(result))
        
    except urllib.error.HTTPError as e:
      # Error checking to prevent crashing on bad requests
      logger.error("HTTP error({}): {}".format(e.errno, e.strerror))
    except urllib.error.URLError as e:
      logger.error("URL error({}): {}".format(e.errno, e.strerror))
    
    # write out the text file logs if required.  Don't log state.  
    if text_logging and (not self.read_state):      
      out = time.strftime("%Y-%m-%d %H:%M:%S") + "," + str(voltage) + "," + str(current) + "," + str(power) + "," + str(usage) + "\n"
      self.write_file(datafile, "a", out)
      
      if datetime.datetime.now() > self.next_daily_time:
        self.next_daily_time = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=1),datetime.time(23,55,0))
        out = time.strftime("%Y-%m-%d %H:%M:%S") + "," + str(usage) + "\n"
        self.write_file(dailyfile, "a", out)

  # Send command to smart switch and receive reply
  # read_state is a special case for updating Domoticz with state 
Example 25
Project: TP-Link-HS110   Author: ajay10000   File: tplink_hs110.py    Apache License 2.0 4 votes vote down vote up
def send_json(self,received_data):
    json_data = json.loads(received_data)
    try:
      if self.read_state:
        state = json_data['system']['get_sysinfo']['relay_state']
        full_url = domain + "json.htm?type=command&param=udevice&idx={}&nvalue={}".format(hs110_switch_idx,state)
        logger.debug("URL: {}".format(full_url))
        # Send the json string
        urllib2.urlopen(full_url)
      else:
        voltage = round(float(json_data['emeter']['get_realtime']['voltage_mv']) / 1000,2)
        current = round(float(json_data['emeter']['get_realtime']['current_ma']) / 1000,2)
        power = round(float(json_data['emeter']['get_realtime']['power_mw']) / 1000,2)
        usage = round(float(json_data['emeter']['get_realtime']['total_wh']) / 1000,3)
    
        for i in range(0,len(domoticz_idx)): # range is 0 based
          if i < len(domoticz_idx) - 1:
            logger.debug("IDX: {}, Item: {}, Value: {}".format(domoticz_idx[i],monitor_list[i],eval(monitor_list[i])))
            full_url = base_url + "&idx={}&svalue={}".format(domoticz_idx[i],eval(monitor_list[i]))
          else:
            # virtual sensor with sensor type Electric (Instant+Counter)
            logger.debug("IDX: {}, Items: {}, Values: {};{}".format(domoticz_idx[i],"Power (W), Usage (kWhr)",power,usage))
            full_url = base_url + "&idx={}&svalue={};{}".format(domoticz_idx[i],power,usage * 1000)
          logger.debug("URL: {}".format(full_url))
          # Send the json string
          urllib2.urlopen(full_url)
        
    except urllib2.HTTPError as e:
      # Error checking to prevent crashing on bad requests
      logger.error("HTTP error({}): {}".format(e.errno, e.strerror))
    except urllib2.URLError as e:
      logger.error("URL error({}): {}".format(e.errno, e.strerror))
    
    # write out the text file logs if required.  Don't log state.  
    if text_logging and (not self.read_state):      
      out = time.strftime("%Y-%m-%d %H:%M:%S") + "," + str(voltage) + "," + str(current) + "," + str(power) + "," + str(usage) + "\n"
      self.write_file(datafile, "a", out)
      
      if datetime.datetime.now() > self.next_daily_time:
        self.next_daily_time = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=1),datetime.time(23,55,0))
        out = time.strftime("%Y-%m-%d %H:%M:%S") + "," + str(kwhr) + "\n"
        self.write_file(dailyfile, "a", out)

  # Send command to smart switch and receive reply
  # read_state is a special case for updating Domoticz with state