Issues (158)

doorpi/action/SingleActions/ipsrpc_setvalue.py (2 issues)

1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
import logging
5
logger = logging.getLogger(__name__)
6
logger.debug("%s loaded", __name__)
7
8
import doorpi
9
import requests
10
import json
11
from requests.auth import HTTPBasicAuth
12
from doorpi.action.base import SingleAction
13
14 View Code Duplication
def ips_rpc_create_config():
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
15
    config = {}
16
    config['webservice_url'] = doorpi.DoorPi().config.get('IP-Symcon', 'server')
17
    config['username'] = doorpi.DoorPi().config.get('IP-Symcon', 'username')
18
    config['password'] = doorpi.DoorPi().config.get('IP-Symcon', 'password')
19
    config['jsonrpc'] = doorpi.DoorPi().config.get('IP-Symcon', 'jsonrpc', '2.0')
20
    config['headers'] = {'content-type': 'application/json'}
21
    return config
22
23
def ips_rpc_fire(method, config, *parameters):
24
    payload = {
25
       "method": method,
26
       "params": parameters,
27
       "jsonrpc": config['jsonrpc'],
28
       "id": 0,
29
    }
30
    return requests.post(
31
        config['webservice_url'],
32
        headers = config['headers'],
33
        auth = HTTPBasicAuth(config['username'], config['password']),
34
        data = json.dumps(payload)
35
    )
36
37
def ips_rpc_check_variable_exists(key, config = None):
38
    if config is None: config = ips_rpc_create_config()
39
    response = ips_rpc_fire('IPS_VariableExists', config, key)
40
    return response.json['result']
41
42
def ips_rpc_get_variable_type(key, config = None):
43
    if config is None: config = ips_rpc_create_config()
44
    response = ips_rpc_fire('IPS_GetVariable', config, key)
45
    return response.json['result']['VariableValue']['ValueType']
46
47
def ips_rpc_set_value(key, value, config = None):
48
    try:
49
        if config is None: config = ips_rpc_create_config()
50
        if ips_rpc_check_variable_exists(key, config) is not True: raise Exception("var %s doesn't exist", key)
51
        type = ips_rpc_get_variable_type(key, config)
0 ignored issues
show
Bug Best Practice introduced by Thomas Meissner
This seems to re-define the built-in type.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
52
        if type is None: raise Exception("type of var %s couldn't find", key)
53
        # http://www.ip-symcon.de/service/dokumentation/befehlsreferenz/variablenverwaltung/ips-getvariable/
54
        # Variablentyp (0: Boolean, 1: Integer, 2: Float, 3: String)
55
        elif type == 0:
56
            if value.lower() in ['true', 'yes', '1']: value = True
57
            else: value = False
58
        elif type == 1: value = int(value)
59
        elif type == 2: value = float(value)
60
        elif type == 3: value = str(value)
61
        else: value = str(value)
62
        ips_rpc_fire('SetValue', config, key, value)
63
    except Exception as ex:
64
        logger.exception("couldn't send IpsRpc (%s)", ex)
65
        return False
66
    return True
67
68
def get(parameters):
69
    parameter_list = parameters.split(',')
70
    if len(parameter_list) is not 2: return None
71
72
    key = int(parameter_list[0])
73
    value = parameter_list[1]
74
75
    return IpsRpcSetValueAction(ips_rpc_set_value, key, value)
76
77
class IpsRpcSetValueAction(SingleAction):
78
    pass