Skip to content

Commit

Permalink
initial fix of control type, using REST
Browse files Browse the repository at this point in the history
  • Loading branch information
maartendamen committed Mar 29, 2012
1 parent 3f355db commit 28c699f
Show file tree
Hide file tree
Showing 5 changed files with 101 additions and 32 deletions.
4 changes: 3 additions & 1 deletion houseagent/core/coordinator.py
Expand Up @@ -270,7 +270,9 @@ def send_command(self, plugin_id, content):
if p:
return self.broker.send_rpc(p.routing_info, content)
else:
return None
d = defer.Deferred()
d.callback("fail")
return d

def send_crud_update(self, type, action, parameters):
'''
Expand Down
14 changes: 12 additions & 2 deletions houseagent/core/database.py
Expand Up @@ -101,6 +101,7 @@ def _updatedb(self, txn, dbversion):
# history_periods table
txn.execute("CREATE TABLE history_periods(id integer PRIMARY KEY AUTOINCREMENT NOT NULL,\
name varchar(20), secs integer NOT NULL, sysflag CHAR(1) NOT NULL DEFAULT '0');")

# default values for history_periods table
txn.execute("INSERT INTO history_periods VALUES(1,'Disabled',0,'1');")
txn.execute("INSERT INTO history_periods VALUES(2,'5 min',300,'1');")
Expand All @@ -115,6 +116,7 @@ def _updatedb(self, txn, dbversion):
# history_types table
txn.execute("CREATE TABLE history_types (id integer PRIMARY KEY AUTOINCREMENT NOT NULL, \
name varchar(50));")

# default values for history_types table
txn.execute("INSERT INTO history_types VALUES (NULL, 'GAUGE');")
txn.execute("INSERT INTO history_types VALUES (NULL, 'COUNTER');")
Expand All @@ -127,6 +129,7 @@ def _updatedb(self, txn, dbversion):
txn.execute("INSERT INTO current_values_tmp \
SELECT id, name, value, device_id, lastupdate, history, \
history_type_id, control_type_id FROM current_values;")

# create new current_values scheme (old data are purged)
txn.execute("DROP TABLE current_values;")
txn.execute("CREATE TABLE current_values(id integer PRIMARY KEY AUTOINCREMENT NOT NULL, \
Expand All @@ -136,6 +139,7 @@ def _updatedb(self, txn, dbversion):
FOREIGN KEY (history_period_id) REFERENCES history_periods(id), \
FOREIGN KEY (history_type_id) REFERENCES history_types(id), \
FOREIGN KEY (device_id) REFERENCES devices(id));")

# current_values indexes
txn.execute("CREATE INDEX 'current_values.fk_current_values_control_types1' \
ON current_values (control_type_id);")
Expand All @@ -145,6 +149,7 @@ def _updatedb(self, txn, dbversion):
ON current_values (history_type_id);")
txn.execute("CREATE INDEX 'current_values.fk_values_devices1' \
ON current_values (device_id);")

# fill new current_values table
txn.execute("INSERT INTO current_values \
SELECT id, name, value, device_id, lastupdate, 1, 1, control_type_id \
Expand All @@ -160,6 +165,11 @@ def _updatedb(self, txn, dbversion):
ON history_values (created_at);")
txn.execute("CREATE INDEX 'history_values.idx_history_values_value_id1' \
ON history_values (value_id);")

# Control types fix
txn.execute("INSERT into control_types VALUES(0, 'Not controllable');")
txn.execute("UPDATE control_types SET name='Switch (On/off)' WHERE id=1;")
txn.execute("UPDATE control_types SET name='Thermostat (Setpoint)' WHERE id=2;")

self.log.info("Successfully upgraded database schema")
except:
Expand Down Expand Up @@ -495,7 +505,7 @@ def query_locations(self):
def query_values(self):
return self.dbpool.runQuery("SELECT current_values.name, current_values.value, devices.name, " +
"current_values.lastupdate, plugins.name, devices.address, locations.name, current_values.id" +
", control_types.name, control_types.id, history_types.name, history_periods.name FROM current_values INNER " +
", control_types.name, control_types.id, history_types.name, history_periods.name, plugins.id FROM current_values INNER " +
"JOIN devices ON (current_values.device_id = devices.id) INNER JOIN plugins ON (devices.plugin_id = plugins.id) " +
"LEFT OUTER JOIN locations ON (devices.location_id = locations.id) " +
"LEFT OUTER JOIN control_types ON (current_values.control_type_id = control_types.id) " +
Expand Down Expand Up @@ -565,7 +575,7 @@ def query_controllable_devices(self):
"INNER JOIN devices ON (current_values.device_id = devices.id) " +
"INNER JOIN plugins ON (devices.plugin_id = plugins.id) " +
"INNER JOIN control_types ON (current_values.control_type_id = control_types.id) " +
"WHERE current_values.control_type_id != ''")
"WHERE current_values.control_type_id != 0")

def query_action_types_by_device_id(self, device_id):
return self.dbpool.runQuery("SELECT current_values.id, current_values.name, control_types.name FROM current_values " +
Expand Down
98 changes: 71 additions & 27 deletions houseagent/core/web.py
Expand Up @@ -60,10 +60,11 @@ def __init__(self, log, host, port, backlog, coordinator, eventengine, database)
root.putChild('devices_view', Devices_view())

# Value management
root.putChild('values', Values(self.db))
root.putChild('values', Values(self.db, self.coordinator))
root.putChild('values_view', Values_view())
root.putChild('history_types', HistoryTypes(self.db))
root.putChild('history_periods', HistoryPeriods(self.db))
root.putChild('history_periods', HistoryPeriods(self.db))
root.putChild('control_types', ControlTypes(self.db))

root.putChild("device_add", Device_add(self.db))
root.putChild("device_save", Device_save(self.db))
Expand All @@ -72,7 +73,6 @@ def __init__(self, log, host, port, backlog, coordinator, eventengine, database)
root.putChild("device_del", Device_del(self.db))
root.putChild("device_edit", Device_edit(self.db))
root.putChild("history", History(self.db))
root.putChild("control_type", Control_type(self.db))

# Events
root.putChild("event_create", Event_create(self.db))
Expand Down Expand Up @@ -403,6 +403,7 @@ def _add(self, parameters):
@inlineCallbacks
def _edit(self, parameters):
yield self.db.set_history(parameters['id'][0], parameters['history_period'][0], parameters['history_type'][0])
yield self.db.set_controltype(parameters['id'][0], parameters['control_type'][0])
self._reload()
self._done()

Expand All @@ -423,7 +424,7 @@ class Value(Resource):
'''
This object represents a Value.
'''
def __init__(self, id, name, value, device, device_address, location, plugin, lastupdate, history_type, history_period, control_type):
def __init__(self, id, name, value, device, device_address, location, plugin, lastupdate, history_type, history_period, control_type, plugin_id):
Resource.__init__(self)
self.id = id
self.name = name
Expand All @@ -436,11 +437,12 @@ def __init__(self, id, name, value, device, device_address, location, plugin, la
self.history_type = history_type
self.history_period = history_period
self.control_type = control_type
self.plugin_id = plugin_id

def json(self):
return {'id': self.id, 'name': self.name, 'value': self.value, 'device': self.device, 'device_address': self.device_address,
'location': self.location, 'plugin': self.plugin, 'lastupdate': self.lastupdate, 'history_type': self.history_type,
'control_type': self.control_type, 'history_period': self.history_period}
'control_type': self.control_type, 'history_period': self.history_period, 'plugin_id': self.plugin_id}

def render_GET(self, request):
return json.dumps(self.json())
Expand All @@ -452,6 +454,10 @@ def render_DELETE(self, request):

class Values(HouseAgentREST):

def __init__(self, db, coordinator):
HouseAgentREST.__init__(self, db)
self.coordinator = coordinator

def render_GET(self, request):
self._objects = []
self._load().addCallback(self.done)
Expand All @@ -478,7 +484,7 @@ def _load(self):
value_query = yield self.db.query_values()

for value in value_query:
val = Value(value[7], value[0], value[1], value[2], value[5], value[6], value[4], value[3], value[10], value[11], value[8])
val = Value(value[7], value[0], value[1], value[2], value[5], value[6], value[4], value[3], value[10], value[11], value[8], value[12])
self._objects.append(val)

@inlineCallbacks
Expand All @@ -499,6 +505,35 @@ def delete(self, obj):
yield self.db.del_device(int(obj.id))
self._objects.remove(obj)
obj.request.finish()

def getChild(self, name, request):

try:
action = request.args['action'][0]
except KeyError:
action = None

if not action:
for obj in self._objects:
if name == str(obj.id):
return obj

return NoResource(message="The resource %s was not found" % request.URLPath())
else:
for obj in self._objects:
if name == str(obj.id):
device_address = obj.device_address
plugin_id = obj.plugin_id

def control_result(result):
request.write(str(result))
request.finish()

if action == 'poweron':
print self.coordinator
self.coordinator.send_poweron(plugin_id, device_address).addCallback(control_result)

return NOT_DONE_YET

class Values_view(Resource):

Expand Down Expand Up @@ -568,6 +603,35 @@ def _load(self):
hist = HistoryPeriod(period[0], period[1], period[2], period[3])
self._objects.append(hist)

class ControlType(Resource):
'''
This object represents a ControlType.
'''
def __init__(self, id, name):
Resource.__init__(self)
self.id = id
self.name = name

def json(self):
return {"id": self.id, "name": self.name}

def render_GET(self, request):
return json.dumps(self.json())

class ControlTypes(HouseAgentREST):

@inlineCallbacks
def _load(self):
'''
Load control types from the database.
'''
self._objects = []
control_type_query = yield self.db.query_controltypes()

for control_type in control_type_query:
hist = ControlType(control_type[0], control_type[1])
self._objects.append(hist)

class Plugin_add(Resource):
'''
Template that adds a plugin to the database.
Expand Down Expand Up @@ -1072,27 +1136,7 @@ def render_POST(self, request):
print "history=", history

self.db.set_history(int(id), history).addCallback(self.history_set)
return NOT_DONE_YET

class Control_type(Resource):
'''
This sets the control type for a value.
'''
def __init__(self, database):
Resource.__init__(self)
self.db = database

def control_type_set(self, result):
self.request.write(str("done!"))
self.request.finish()

def render_POST(self, request):
self.request = request
id = request.args['id'][0]
control_type = request.args['type'][0]

self.db.set_controltype(int(id), int(control_type)).addCallback(self.control_type_set)
return NOT_DONE_YET
return NOT_DONE_YET

class Location_edited(Resource):
def __init__(self, database):
Expand Down
2 changes: 1 addition & 1 deletion houseagent/templates/control.html
Expand Up @@ -74,7 +74,7 @@
<td id='status${device[5]}'>${device[4]}</td>
<td>

% if device[6] == "CONTROL_TYPE_ON_OFF":
% if device[6] == "Switch (On/off)":
<button onclick='javascript:control("${device[3]}", "${device[1]}", "1", "status${device[3]}");' class="ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all">
<span class="ui-button-text">On</span>
</button>
Expand Down
15 changes: 14 additions & 1 deletion houseagent/templates/values.html
Expand Up @@ -31,6 +31,18 @@
history_periods_list += ";" + item.id + ":" + item.name;
}
});

var control_types = eval($.ajax({url: '/control_types', async: false, success: function(data, result) {if (!result) alert('Failure to retrieve control_types.');}}).responseText);
var control_types_list = "";
var first = true;
$.each(control_types, function(i, item){
if (first) {
first = false;
control_types_list += item.id + ":" + item.name;
} else {
control_types_list += ";" + item.id + ":" + item.name;
}
});

jQuery("#values").jqGrid({
url:'/values',
Expand All @@ -46,7 +58,7 @@
{name:'lastupdate',index:'lastupdate', width:140,align:"center",editable:false,editoptions:{size:20}},
{name:'history_type',index:'history_type', width:70,align:"center",editable:true,edittype: "select", editoptions:{size:20}},
{name:'history_period',index:'history_period',width:90,align:"center",editable:true,edittype: "select", editoptions:{size:20}},
{name:'control_type',index:'control_type', width:100,align:"center",editable:false,editoptions:{size:20}},
{name:'control_type',index:'control_type', width:100,align:"center",editable:true,edittype: "select", editoptions:{size:20}},
],
rowNum:10,
rowList:[10,20,30],
Expand All @@ -68,6 +80,7 @@
loadComplete: function() {
$("#values").setColProp('history_type', { editoptions: { value: history_types_list} });
$("#values").setColProp('history_period', { editoptions: { value: history_periods_list} });
$("#values").setColProp('control_type', { editoptions: { value: control_types_list} });
},
});

Expand Down

0 comments on commit 28c699f

Please sign in to comment.