added almost every API method

improved usability and error handling
This commit is contained in:
Simon Stürz 2014-11-06 20:47:21 +01:00 committed by Michael Zanetti
parent cc772678ec
commit 646a1cad8f

View File

@ -7,30 +7,33 @@ HOST='localhost'
PORT=1234
commandId=0
methods = {'List supported Vendors': 'list_vendors',
'List supported Devices': 'list_deviceClasses',
'List configured Devices': 'list_configured_devices',
'Add Device': 'add_device',
'Remove a device': 'remove_device',
'List supported Devices by vendor': 'list_deviceClasses_by_vendor',
'Execute an action': 'execute_action',
'See a device`s states': 'list_device_states',
'Add a rule': 'add_rule',
'List rules': 'list_rules',
'Remove rule': 'remove_rule'}
methods = {'-> List supported vendors': 'list_vendors',
'-> List supported devices': 'list_deviceClasses',
'-> List configured devices': 'list_configured_devices',
'-> List configured device params': 'list_configured_device_params',
'-> Add device': 'add_device',
'-> Remove a device': 'remove_device',
'-> List supported devices by vendor': 'list_deviceClasses_by_vendor',
'-> Execute an action': 'execute_action',
'-> List device states': 'list_device_states',
'-> Add a rule': 'add_rule',
'-> List rules': 'list_rules',
'-> List rule details': 'list_rule_detail',
'-> List rules containing a certain device' : 'list_rules_containig_deviceId',
'-> Remove a rule': 'remove_rule'}
def get_selection(title, options):
print "\n\n", title
for i in range(0,len(options)):
print "%i: %s" % (i, options[i])
print "%5i: %s" % (i, options[i])
selection = raw_input("Enter selection: ")
if not selection:
print "-> error in selection"
print "\n -> error in selection"
return None
return int(selection)
def send_command(method, params = None):
global commandId
commandObj = {}
@ -47,9 +50,11 @@ def send_command(method, params = None):
print "JSON error happened: %s" % response
return response
def get_vendors():
return send_command("Devices.GetSupportedVendors")
def list_vendors():
response = get_vendors();
print "=== Vendors ==="
@ -57,8 +62,12 @@ def list_vendors():
print "%40s %s" % (vendor['name'], vendor['id'])
print "=== Vendors ==="
def select_vendor():
vendors = get_vendors()['params']['vendors']
if not vendors:
print "\n No vendors found. Please install guh-plugins and restart guhd."
return ""
vendorList = []
vendorIdList = []
for i in range(0,len(vendors)):
@ -75,6 +84,17 @@ def get_deviceClasses(vendorId = None):
params['vendorId'] = vendorId
return send_command("Devices.GetSupportedDevices", params)['params']['deviceClasses']
def list_configured_device_params():
deviceId = select_configured_device()
device = get_device(deviceId)
deviceParams = device['params']
print "\nParams of the device with the id ", deviceId, "\n"
print "=== Params ==="
for i in range(len(deviceParams)):
print "%20s: %s" % (deviceParams[i]['name'], deviceParams[i]['value'])
print "=== Params ==="
def list_deviceClasses(vendorId = None):
response = get_deviceClasses(vendorId)
print "=== DeviceClasses ==="
@ -82,11 +102,12 @@ def list_deviceClasses(vendorId = None):
print "%40s %s" % (deviceClass['name'], deviceClass['id'])
print "=== DeviceClasses ==="
def select_deviceClass():
vendorId = select_vendor()
deviceClasses = get_deviceClasses(vendorId)
if len(deviceClasses) == 0:
print "No supported devices for this vendor"
print " No supported devices for this vendor"
return ""
deviceClassList = []
deviceClassIdList = []
@ -97,6 +118,7 @@ def select_deviceClass():
if selection != None:
return deviceClassIdList[selection]
def select_configured_device():
devices = get_configured_devices()
deviceList = []
@ -107,24 +129,30 @@ def select_configured_device():
selection = get_selection("Please select a device: ", deviceList)
if selection != None:
return deviceIdList[selection]
return None
def get_action_types(deviceClassId):
params = {}
params['deviceClassId'] = deviceClassId
return send_command("Devices.GetActionTypes", params)['params']['actionTypes']
def get_eventTypes(deviceClassId):
params = {}
params['deviceClassId'] = deviceClassId
return send_command("Devices.GetEventTypes", params)['params']['eventTypes']
def list_deviceClasses_by_vendor():
vendorId = select_vendor()
list_deviceClasses(vendorId)
def get_configured_devices():
return send_command("Devices.GetConfiguredDevices")['params']['devices']
def list_configured_devices():
deviceList = get_configured_devices()
print "=== Configured Devices ==="
@ -148,7 +176,7 @@ def read_params(paramTypes):
param['name'] = paramType['name']
param['value'] = paramValue
params.append(param)
print "got params:", params
#print "got params:", params
return params
@ -157,6 +185,7 @@ def select_valueOperator():
selection = get_selection("Please select an operator to compare this parameter: ", valueOperators)
if selection != None:
return valueOperators[selection]
return None
def select_stateOperator():
@ -164,7 +193,8 @@ def select_stateOperator():
selection = get_selection("Please select an operator to compare this state: ", stateOperators)
if selection != None:
return stateOperators[selection]
return None
def read_paramDescriptors(paramTypes):
params = []
@ -175,7 +205,6 @@ def read_paramDescriptors(paramTypes):
param['name'] = paramType['name']
param['value'] = paramValue
param['operator'] = operator
# param[paramType['name']] = paramValue
params.append(param)
print "got params:", params
return params
@ -204,14 +233,15 @@ def discover_device(deviceClassId = None):
if selection != None:
return deviceDescriptorIdList[selection]
def get_deviceClass(deviceClassId):
deviceClasses = get_deviceClasses()
for deviceClass in deviceClasses:
# print "got deviceclass", deviceClass
if deviceClass['id'] == deviceClassId:
return deviceClass
return None
def get_device(deviceId):
devices = get_configured_devices()
for device in devices:
@ -219,11 +249,11 @@ def get_device(deviceId):
return device
return None
def get_actionType(actionTypeId):
params = {}
params['actionTypeId'] = actionTypeId
response = send_command("Actions.GetActionType", params)
print "got actionType", response
return response['params']['actionType']
@ -239,10 +269,8 @@ def add_configured_device(deviceClassId):
print "adddevice command params:", params
response = send_command("Devices.AddConfiguredDevice", params)
if response['status'] != "success":
print "Error executing method: ", response
return
print "Added device: %s" % response['params']['deviceId']
print_device_error_code(response['params']['deviceError'])
def add_discovered_device(deviceClassId, deviceDescriptorId):
params = {}
@ -282,7 +310,7 @@ def add_discovered_device(deviceClassId, deviceDescriptorId):
def add_device():
deviceClassId = select_deviceClass()
if deviceClassId == "":
print "Empty deviceClass. Can't continue"
print " Empty deviceClass. Can't continue"
return
deviceClass = get_deviceClass(deviceClassId)
print "createmethods are", deviceClass['createMethods']
@ -294,6 +322,7 @@ def add_device():
elif "CreateMethodAuto" in deviceClass['createMethods']:
print "Can't create this device manually. It'll be created automatically when hardware is discovered."
def select_device():
devices = get_configured_devices()
deviceList = []
@ -305,19 +334,20 @@ def select_device():
if selection != None:
return deviceIdList[selection]
def remove_device():
deviceId = select_device()
print "should remove device", deviceId
params = {}
params['deviceId'] = deviceId
response = send_command("Devices.RemoveConfiguredDevice", params)
if response['status'] == "success":
print "Successfully deleted device"
else:
print "Error deleting device: %s" % response['params']['deviceError']
print_device_error_code(response['params']['deviceError'])
def select_actionType(deviceClassId):
actions = get_action_types(deviceClassId)
if not actions:
return ""
actionList = []
print "got actions", actions
for i in range(len(actions)):
@ -329,27 +359,97 @@ def select_actionType(deviceClassId):
def select_eventType(deviceClassId):
eventTypes = get_eventTypes(deviceClassId)
if not eventTypes:
return ""
eventTypeList = []
for i in range(len(eventTypes)):
eventTypeList.append(eventTypes[i]['name'])
selection = get_selection("Please select an action type:", eventTypeList)
if selection != None:
return eventTypes[selection]
selection = get_selection("Please select an event type:", eventTypeList)
return eventTypes[selection]
def execute_action():
deviceId = select_device()
device = get_device(deviceId)
actionTypeId = select_actionType(device['deviceClassId'])['id']
actionType = select_actionType(device['deviceClassId'])
if actionType == "":
print "\n This device has no actions"
return
actionTypeId = actionType['id']
params = {}
params['actionTypeId'] = actionTypeId
params['deviceId'] = deviceId
# send_command("Actions.ExecuteAction", params)
actionType = get_actionType(actionTypeId)
actionParams = read_params(actionType['paramTypes'])
params['params'] = actionParams
response = send_command("Actions.ExecuteAction", params)
print "execute action response", response
print_device_error_code(response['params']['deviceError'])
def print_device_error_code(deviceError):
if deviceError == "DeviceErrorNoError":
print "\nSuccess!"
elif deviceError == "DeviceErrorPluginNotFound":
print "\nERROR: the plugin could not be found."
elif deviceError == "DeviceErrorDeviceNotFound":
print "\nERROR: the device could not be found."
elif deviceError == "DeviceErrorDeviceClassNotFound":
print "\nERROR: the deviceClass could not be found."
elif deviceError == "DeviceErrorActionTypeNotFound":
print "\nERROR: the actionType could not be found."
elif deviceError == "DeviceErrorStateTypeNotFound":
print "\nERROR: the stateType could not be found."
elif deviceError == "DeviceErrorEventTypeNotFound":
print "\nERROR: the eventType could not be found."
elif deviceError == "DeviceErrorDeviceDescriptorNotFound":
print "\nERROR: the deviceDescriptor could not be found."
elif deviceError == "DeviceErrorMissingParameter":
print "\nERROR: some parameters are missing."
elif deviceError == "DeviceErrorInvalidParameter":
print "\nERROR: invalid parameter."
elif deviceError == "DeviceErrorSetupFailed":
print "\nERROR: setup failed."
elif deviceError == "DeviceErrorDuplicateUuid":
print "\nERROR: uuid allready exists."
elif deviceError == "DeviceErrorCreationMethodNotSupported":
print "\nERROR: the selected CreationMethod is not supported for this device."
elif deviceError == "DeviceErrorSetupMethodNotSupported":
print "\nERROR: the selected SetupMethod is not supported for this device."
elif deviceError == "DeviceErrorHardwareNotAvailable":
print "\nERROR: the hardware is not available."
elif deviceError == "DeviceErrorHardwareFailure":
print "\nERROR: hardware failure. Something went wrong with the hardware."
elif deviceError == "DeviceErrorAsync":
print "\nINFO: the response will need some time. (asynchronous)"
elif deviceError == "DeviceErrorDeviceInUse":
print "\nERROR: the device is currently in use. Try again later."
elif deviceError == "DeviceErrorPairingTransactionIdNotFound":
print "\nERROR: the pairingTransactionId could not be found."
else:
print "\nERROR: Unknown error code: ", deviceError, "Please take a look at the newest API version."
def print_rule_error_code(ruleError):
if ruleError == "RuleErrorNoError":
print "\nSuccess!"
elif ruleError == "RuleErrorInvalidRuleId":
print "\nERROR: the ruleId is not valid."
elif ruleError == "RuleErrorRuleNotFound":
print "\nERROR: the rule could not be found."
elif ruleError == "RuleErrorDeviceNotFound":
print "\nERROR: the device could not be found for this rule."
elif ruleError == "RuleErrorEventTypeNotFound":
print "\nERROR: the eventType could not be found for this rule."
elif ruleError == "RuleErrorActionTypeNotFound":
print "\nERROR: the actionType could not be found for this rule."
elif ruleError == "RuleErrorInvalidParameter":
print "\nERROR: invalid parameter in this rule."
elif ruleError == "RuleErrorMissingParameter":
print "\nERROR: missing parameter in this rule."
else:
print "\nERROR: Unknown error code: ", ruleError, "Please take a look at the newest API version."
def list_device_states():
deviceId = select_device()
@ -362,16 +462,16 @@ def list_device_states():
params['stateTypeId'] = deviceClass['stateTypes'][i]['id']
response = send_command("Devices.GetStateValue", params)
print_device_error_code(response['params']['deviceError'])
print "%s: %s" % (deviceClass['stateTypes'][i]['name'], response['params']['value'])
print "=== States ==="
def create_eventDescriptors():
enough = False
eventDescriptors = []
while not enough:
print "Creating EventDescriptor:"
print "\nCreating EventDescriptor:"
deviceId = select_configured_device()
device = get_device(deviceId)
eventType = select_eventType(device['deviceClassId']);
@ -391,11 +491,27 @@ def create_eventDescriptors():
return eventDescriptors
def create_eventDescriptor():
print "\nCreating EventDescriptor:"
deviceId = select_configured_device()
device = get_device(deviceId)
eventType = select_eventType(device['deviceClassId']);
params = read_paramDescriptors(eventType['paramTypes'])
eventDescriptor = {}
eventDescriptor['deviceId'] = deviceId
eventDescriptor['eventTypeId'] = eventType['id']
if len(params) > 0:
eventDescriptor['paramDescriptors'] = params
print "got eventDescriptors:", eventDescriptor
return eventDescriptor
def create_actions():
enough = False
actions = []
while not enough:
print "Creating Action:"
print "\nCreating Action:"
deviceId = select_configured_device()
device = get_device(deviceId)
actionType = select_actionType(device['deviceClassId'])
@ -411,30 +527,128 @@ def create_actions():
input = raw_input("Do you want to add another action? (y/N): ")
if not input == "y":
enough = True
print "got actions:", actions
#print "got actions:", actions
return actions
def add_rule():
params = {}
params['eventDescriptorList'] = create_eventDescriptors()
params['actions'] = create_actions()
print "adding rule:", params
result = send_command("Rules.AddRule", params)
print "AddRule result:", result
ruleType = select_rule_type()
if ruleType == "EventBasedRule":
params = {}
#params['name'] = raw_input("Please enter the name of the rule: ")
params['eventDescriptor'] = create_eventDescriptor()
params['actions'] = create_actions()
print "adding rule with params:", params
response = send_command("Rules.AddRule", params)
print_rule_error_code(response['params']['ruleError'])
elif ruleType == "StateBasedRule":
params = {}
params['eventDescriptorList'] = create_eventDescriptors()
if len(params['eventDescriptorList']) > 1:
params['stateEvaluator'] = select_stateOperator()
params['actions'] = create_actions()
print "adding rule with params:", params
response = send_command("Rules.AddRule", params)
print_rule_error_code(response['params']['ruleError'])
elif ruleType == "MixedRule":
print "not implemented yet in this script...comming soon ;)"
else:
print " No rule added";
def select_rule_type():
ruleTypes = ["EventBasedRule", "StateBasedRule", "MixedRule"]
selection = get_selection("Please select a rule type: ", ruleTypes)
return ruleTypes[selection]
def list_rules():
result = send_command("Rules.GetRules", {})
print "got rules", result
response = send_command("Rules.GetRules", {})
if not response['params']['ruleIds']:
print "\n No rules found."
return
print "\nRules found:"
for i in range(len(response['params']['ruleIds'])):
print response['params']['ruleIds'][i]
def list_rule_detail():
ruleId = select_rule()
if ruleId == "":
print "\n No rules found"
return
params = {}
params['ruleId'] = ruleId
response = send_command("Rules.GetRuleDetails", params)
#print response
print "\nThe rule", ruleId, "depends on following EventDescriptors:\n"
print "Events:"
for i in range(len(response['params']['rule']['eventDescriptors'])):
eventDescriptor = response['params']['rule']['eventDescriptors'][i]
#print eventDescriptor
device = get_device(eventDescriptor['deviceId'])
paramDescriptors = eventDescriptor['paramDescriptors']
print "%5s. -> %40s -> eventTypeId: %10s: " %(i, device['name'], eventDescriptor['eventTypeId'])
#print paramDescriptors
for i in range(len(paramDescriptors)):
print "%58s %s %s" %(paramDescriptors[i]['name'], get_valueOperator_symbol(paramDescriptors[i]['operator']), paramDescriptors[i]['value'])
print ""
print "\nActions:"
for i in range(len(response['params']['rule']['actions'])):
action = response['params']['rule']['actions'][i]
device = get_device(eventDescriptor['deviceId'])
actionType = get_actionType(response['params']['rule']['actions'][i]['actionTypeId'])
actionParams = response['params']['rule']['actions'][i]['params']
print "%5s. -> %40s -> action: %s" %(i, device['name'], actionType['name'])
for i in range(len(actionParams)):
print "%61s: %s" %(actionParams[i]['name'], actionParams[i]['value'])
print ""
def get_valueOperator_symbol(valueOperator):
if valueOperator == "ValueOperatorEquals":
return "="
elif valueOperator == "ValueOperatorNotEquals":
return "!="
elif valueOperator == "ValueOperatorLess":
return "<"
elif valueOperator == "ValueOperatorGreater":
return ">"
elif valueOperator == "ValueOperatorLessOrEqual":
return "<="
elif valueOperator == "ValueOperatorGreaterOrEqual":
return ">="
else:
return "<unknown value operator>"
def list_rules_containig_deviceId():
deviceId = select_configured_device()
device = get_device(deviceId)
params = {}
params['deviceId'] = deviceId
response = send_command("Rules.FindRules", params)
if not response['params']['ruleIds']:
print "\nThere is no rule containig this device."
return
print "\nFollowing rules contain this device"
for i in range(len(response['params']['ruleIds'])):
print "Device ", deviceId, "found in rule", response['params']['ruleIds'][i]
def select_rule():
ruleIds = send_command("Rules.GetRules", {})['params']['ruleIds']
if not ruleIds:
return ""
selection = get_selection("Please select rule:", ruleIds)
if selection != None:
return ruleIds[selection]
def remove_rule():
ruleId = select_rule()
if ruleId == "":
print "\nNo rules found"
return
params = {}
params['ruleId'] = ruleId
response = send_command("Rules.RemoveRule", params)