api: use record instead of tuple to pass around State

This commit is contained in:
Bart Van Der Meerssche 2010-03-14 13:47:28 +00:00
parent cf79030ec1
commit 4a5e939acc
1 changed files with 11 additions and 6 deletions

View File

@ -7,38 +7,43 @@
-include_lib("webmachine/include/webmachine.hrl"). -include_lib("webmachine/include/webmachine.hrl").
-record(state,
{rrdSensor,
rrdTime,
rrdFactor}).
init([]) -> init([]) ->
{ok, undefined}. {ok, undefined}.
allowed_methods(ReqData, State) -> allowed_methods(ReqData, State) ->
{['GET'], ReqData, State}. {['GET'], ReqData, State}.
malformed_request(ReqData, State) -> malformed_request(ReqData, _) ->
{RrdSensor, ValidSensor} = rrd_sensor(wrq:path_info(sensor, ReqData)), {RrdSensor, ValidSensor} = rrd_sensor(wrq:path_info(sensor, ReqData)),
{RrdTime, ValidInterval} = rrd_time(wrq:get_qs_value("interval", ReqData)), {RrdTime, ValidInterval} = rrd_time(wrq:get_qs_value("interval", ReqData)),
{RrdFactor, ValidUnit} = rrd_factor(wrq:get_qs_value("unit", ReqData)), {RrdFactor, ValidUnit} = rrd_factor(wrq:get_qs_value("unit", ReqData)),
State = #state{rrdSensor = RrdSensor, rrdTime = RrdTime, rrdFactor = RrdFactor},
{case {ValidSensor, ValidInterval, ValidUnit} of {case {ValidSensor, ValidInterval, ValidUnit} of
{true, true, true} -> false; {true, true, true} -> false;
_ -> true _ -> true
end, end,
ReqData, {RrdSensor , RrdTime, RrdFactor}}. ReqData, State}.
content_types_provided(ReqData, State) -> content_types_provided(ReqData, State) ->
{[{"application/json", to_json}], ReqData, State}. {[{"application/json", to_json}], ReqData, State}.
to_json(ReqData, State) -> to_json(ReqData, State) ->
{RrdSensor , RrdTime, RrdFactor} = State,
case wrq:path_info(interval, ReqData) of case wrq:path_info(interval, ReqData) of
"night" -> Path = "var/data/night/"; "night" -> Path = "var/data/night/";
_Interval -> Path = "var/data/base/" _Interval -> Path = "var/data/base/"
end, end,
case erlrrd:fetch(erlrrd:c([[Path, [RrdSensor|".rrd"]], "AVERAGE", ["-s",RrdTime]])) of case erlrrd:fetch(erlrrd:c([[Path, [State#state.rrdSensor|".rrd"]], "AVERAGE", ["-s",State#state.rrdTime]])) of
{ok, Response} -> {ok, Response} ->
Filtered = [re:split(X, "[:][ ]", [{return,list}]) || [X] <- Response, string:str(X, ":") == 11], Filtered = [re:split(X, "[:][ ]", [{return,list}]) || [X] <- Response, string:str(X, ":") == 11],
Datapoints = [[list_to_integer(X), round(list_to_float(Y) * RrdFactor)] || [X, Y] <- Filtered, string:len(Y) /= 3], Datapoints = [[list_to_integer(X), round(list_to_float(Y) * State#state.rrdFactor)] || [X, Y] <- Filtered, string:len(Y) /= 3],
Nans = [[list_to_integer(X), list_to_binary(Y)] || [X, Y] <- Filtered, string:len(Y) == 3], Nans = [[list_to_integer(X), list_to_binary(Y)] || [X, Y] <- Filtered, string:len(Y) == 3],
Final = lists:merge(Datapoints, Nans), Final = lists:merge(Datapoints, Nans),
{mochijson2:encode(Final), ReqData, State}; {mochijson2:encode(Final), ReqData, State};