2011-03-23 09:16:02 +00:00
|
|
|
%% @author Bart Van Der Meerssche <bart.vandermeerssche@flukso.net>
|
|
|
|
%% @copyright (C) 2009-2011 Bart Van Der Meerssche
|
|
|
|
%%%
|
|
|
|
%%% This program is free software: you can redistribute it and/or modify
|
|
|
|
%%% it under the terms of the GNU General Public License as published by
|
|
|
|
%%% the Free Software Foundation, either version 3 of the License, or
|
|
|
|
%%% (at your option) any later version.
|
|
|
|
%%%
|
|
|
|
%%% This program is distributed in the hope that it will be useful,
|
|
|
|
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
%%% GNU General Public License for more details.
|
|
|
|
%%%
|
|
|
|
%%% You should have received a copy of the GNU General Public License
|
|
|
|
%%% along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
%%%
|
|
|
|
%% @doc Flukso API: /sensor/xyz resource specification
|
2010-02-25 17:45:11 +00:00
|
|
|
|
2011-03-04 18:30:58 +00:00
|
|
|
-module(flukso_sensor_xyz).
|
2011-03-23 09:16:02 +00:00
|
|
|
-author('Bart Van Der Meerssche <bart.vandermeerssche@flukso.net>').
|
|
|
|
|
2011-03-04 18:30:58 +00:00
|
|
|
-export([init/1,
|
|
|
|
allowed_methods/2,
|
|
|
|
malformed_request/2,
|
|
|
|
is_authorized/2,
|
|
|
|
content_types_provided/2,
|
|
|
|
to_json/2,
|
|
|
|
process_post/2]).
|
2010-02-25 17:45:11 +00:00
|
|
|
|
|
|
|
-include_lib("webmachine/include/webmachine.hrl").
|
2011-03-23 17:40:28 +00:00
|
|
|
-include("flukso.hrl").
|
2010-03-14 13:47:28 +00:00
|
|
|
|
2010-02-25 17:45:11 +00:00
|
|
|
init([]) ->
|
|
|
|
{ok, undefined}.
|
|
|
|
|
2011-03-04 18:30:58 +00:00
|
|
|
% debugging
|
|
|
|
%init(Config) ->
|
|
|
|
% {{trace, "/tmp"}, Config}.
|
|
|
|
|
2010-02-25 17:45:11 +00:00
|
|
|
allowed_methods(ReqData, State) ->
|
2011-03-04 18:30:58 +00:00
|
|
|
{['POST', 'GET'], ReqData, State}.
|
|
|
|
|
|
|
|
malformed_request(ReqData, State) ->
|
|
|
|
case wrq:method(ReqData) of
|
|
|
|
'POST' -> malformed_POST(ReqData, State);
|
|
|
|
'GET' -> malformed_GET(ReqData, State)
|
|
|
|
end.
|
|
|
|
|
|
|
|
malformed_POST(ReqData, _State) ->
|
2011-03-26 22:47:42 +00:00
|
|
|
{_Version, ValidVersion} = check_version(wrq:get_req_header("X-Version", ReqData)),
|
2011-03-04 18:30:58 +00:00
|
|
|
{RrdSensor, ValidSensor} = check_sensor(wrq:path_info(sensor, ReqData)),
|
2011-03-26 22:47:42 +00:00
|
|
|
{Digest, ValidDigest} = check_digest(wrq:get_req_header("X-Digest", ReqData)),
|
2011-03-04 18:30:58 +00:00
|
|
|
|
2011-03-26 22:47:42 +00:00
|
|
|
State = #state{rrdSensor = RrdSensor,
|
|
|
|
digest = Digest},
|
2011-03-04 18:30:58 +00:00
|
|
|
|
2011-03-27 11:22:34 +00:00
|
|
|
{case {ValidVersion, ValidSensor, ValidDigest} of
|
|
|
|
{true, true, true} -> false;
|
2011-03-04 18:30:58 +00:00
|
|
|
_ -> true
|
|
|
|
end,
|
|
|
|
ReqData, State}.
|
2010-02-25 17:45:11 +00:00
|
|
|
|
2011-03-04 18:30:58 +00:00
|
|
|
malformed_GET(ReqData, _State) ->
|
2010-04-27 22:08:41 +00:00
|
|
|
{_Version, ValidVersion} = check_version(wrq:get_req_header("X-Version", ReqData), wrq:get_qs_value("version", ReqData)),
|
2010-04-27 21:23:27 +00:00
|
|
|
{RrdSensor, ValidSensor} = check_sensor(wrq:path_info(sensor, ReqData)),
|
2010-05-22 11:21:31 +00:00
|
|
|
{RrdStart, RrdEnd, RrdResolution, ValidTime} = check_time(wrq:get_qs_value("interval", ReqData), wrq:get_qs_value("start", ReqData), wrq:get_qs_value("end", ReqData), wrq:get_qs_value("resolution", ReqData)),
|
2010-04-27 21:47:01 +00:00
|
|
|
{RrdFactor, ValidUnit} = check_unit(wrq:get_qs_value("unit", ReqData)),
|
2010-04-27 21:23:27 +00:00
|
|
|
{Token, ValidToken} = check_token(wrq:get_req_header("X-Token", ReqData), wrq:get_qs_value("token", ReqData)),
|
|
|
|
{JsonpCallback, ValidJsonpCallback} = check_jsonp_callback(wrq:get_qs_value("jsonp_callback", ReqData)),
|
2010-02-25 17:45:11 +00:00
|
|
|
|
2010-05-22 11:21:31 +00:00
|
|
|
State = #state{rrdSensor = RrdSensor,
|
|
|
|
rrdStart = RrdStart,
|
|
|
|
rrdEnd = RrdEnd,
|
|
|
|
rrdResolution = RrdResolution,
|
|
|
|
rrdFactor = RrdFactor,
|
|
|
|
token = Token,
|
|
|
|
jsonpCallback = JsonpCallback},
|
2010-03-14 13:47:28 +00:00
|
|
|
|
2010-05-21 14:25:01 +00:00
|
|
|
{case {ValidVersion, ValidSensor, ValidTime, ValidUnit, ValidToken, ValidJsonpCallback} of
|
2010-04-27 22:08:41 +00:00
|
|
|
{true, true, true, true, true, true} -> false;
|
2010-02-25 17:45:11 +00:00
|
|
|
_ -> true
|
|
|
|
end,
|
2010-03-14 13:47:28 +00:00
|
|
|
ReqData, State}.
|
2010-02-25 17:45:11 +00:00
|
|
|
|
2011-03-04 18:30:58 +00:00
|
|
|
is_authorized(ReqData, State) ->
|
|
|
|
case wrq:method(ReqData) of
|
|
|
|
'POST' -> is_auth_POST(ReqData, State);
|
|
|
|
'GET' -> is_auth_GET(ReqData, State)
|
|
|
|
end.
|
|
|
|
|
2011-03-27 11:19:58 +00:00
|
|
|
is_auth_POST(ReqData, #state{rrdSensor = Sensor, digest = ClientDigest} = State) ->
|
2011-04-16 21:52:19 +00:00
|
|
|
{data, Result} = mysql:execute(pool, sensor_key, [Sensor]),
|
2011-03-30 09:29:01 +00:00
|
|
|
|
|
|
|
case mysql:get_result_rows(Result) of
|
|
|
|
[[Key]] ->
|
|
|
|
Data = wrq:req_body(ReqData),
|
|
|
|
<<X:160/big-unsigned-integer>> = crypto:sha_mac(Key, Data),
|
|
|
|
ServerDigest = lists:flatten(io_lib:format("~40.16.0b", [X])),
|
|
|
|
|
|
|
|
{case ServerDigest of
|
|
|
|
ClientDigest -> true;
|
|
|
|
_WrongDigest -> "Incorrect digest"
|
|
|
|
end,
|
|
|
|
ReqData, State};
|
|
|
|
|
|
|
|
_NoKey ->
|
2011-04-08 18:49:41 +00:00
|
|
|
{"No proper provisioning for this sensor", ReqData, State}
|
2011-03-30 09:29:01 +00:00
|
|
|
end.
|
2011-03-04 18:30:58 +00:00
|
|
|
|
|
|
|
is_auth_GET(ReqData, #state{rrdSensor = RrdSensor, token = Token} = State) ->
|
2010-03-14 20:31:10 +00:00
|
|
|
{data, Result} = mysql:execute(pool, permissions, [RrdSensor, Token]),
|
|
|
|
|
|
|
|
{case mysql:get_result_rows(Result) of
|
|
|
|
[[62]] -> true;
|
2011-03-30 09:29:01 +00:00
|
|
|
_Permission -> "Access refused"
|
2010-03-14 20:31:10 +00:00
|
|
|
end,
|
|
|
|
ReqData, State}.
|
|
|
|
|
2010-02-25 17:45:11 +00:00
|
|
|
content_types_provided(ReqData, State) ->
|
2011-03-04 18:30:58 +00:00
|
|
|
{[{"application/json", to_json}], ReqData, State}.
|
2010-02-25 17:45:11 +00:00
|
|
|
|
2010-05-22 11:21:31 +00:00
|
|
|
to_json(ReqData, #state{rrdSensor = RrdSensor, rrdStart = RrdStart, rrdEnd = RrdEnd, rrdResolution = RrdResolution, rrdFactor = RrdFactor, jsonpCallback = JsonpCallback} = State) ->
|
2010-04-27 12:22:25 +00:00
|
|
|
case wrq:get_qs_value("interval", ReqData) of
|
2011-03-28 20:21:38 +00:00
|
|
|
"night" -> Path = ?NIGHT_PATH;
|
|
|
|
_Interval -> Path = ?BASE_PATH
|
2010-02-25 17:45:11 +00:00
|
|
|
end,
|
|
|
|
|
2010-05-22 11:21:31 +00:00
|
|
|
%% debugging: io:format("~s~n", [erlrrd:c([[Path, [RrdSensor|".rrd"]], "AVERAGE", ["-s ", RrdStart], ["-e ", RrdEnd], ["-r ", RrdResolution]])]),
|
2010-05-21 14:25:01 +00:00
|
|
|
|
2011-03-29 08:08:09 +00:00
|
|
|
case rrd_fetch(Path, RrdSensor, RrdStart, RrdEnd, RrdResolution) of
|
2010-02-25 17:45:11 +00:00
|
|
|
{ok, Response} ->
|
|
|
|
Filtered = [re:split(X, "[:][ ]", [{return,list}]) || [X] <- Response, string:str(X, ":") == 11],
|
2010-03-14 14:12:35 +00:00
|
|
|
Datapoints = [[list_to_integer(X), round(list_to_float(Y) * RrdFactor)] || [X, Y] <- Filtered, string:len(Y) /= 3],
|
2010-02-25 17:45:11 +00:00
|
|
|
Nans = [[list_to_integer(X), list_to_binary(Y)] || [X, Y] <- Filtered, string:len(Y) == 3],
|
2010-04-23 23:20:47 +00:00
|
|
|
Final = mochijson2:encode(lists:merge(Datapoints, Nans)),
|
|
|
|
{case JsonpCallback of
|
|
|
|
undefined -> Final;
|
|
|
|
_ -> [JsonpCallback, "(", Final, ");"]
|
|
|
|
end,
|
|
|
|
ReqData, State};
|
2010-02-25 17:45:11 +00:00
|
|
|
|
2010-03-14 20:31:10 +00:00
|
|
|
{error, _Reason} ->
|
2010-02-25 17:45:11 +00:00
|
|
|
{{halt, 404}, ReqData, State}
|
|
|
|
end.
|
|
|
|
|
2011-04-25 16:52:27 +00:00
|
|
|
|
|
|
|
process_post(ReqData, State) ->
|
|
|
|
{struct, JsonData} = mochijson2:decode(wrq:req_body(ReqData)),
|
|
|
|
Payload = {proplists:get_value(<<"measurements">>, JsonData),
|
|
|
|
proplists:get_value(<<"config">>, JsonData)},
|
|
|
|
|
|
|
|
case Payload of
|
|
|
|
{undefined, undefined} ->
|
|
|
|
{false, ReqData, State};
|
|
|
|
{Measurements, undefined} ->
|
|
|
|
process_measurements(Measurements, ReqData, State);
|
|
|
|
{undefined, Config} ->
|
|
|
|
process_config(Config, ReqData, State);
|
|
|
|
{_Measurements, _Config} ->
|
|
|
|
{false, ReqData, State}
|
|
|
|
end.
|
|
|
|
|
|
|
|
% JSON: {"config":{"type":"electricity","enable":0,"class":"analog","current":50,"voltage":230}}
|
|
|
|
% Mochijson2: {struct,[{<<"config">>, {struct,[{<<"type">>,<<"electricity">>}, {<<"enable">>,0}, ... ]} }]}
|
|
|
|
process_config({struct, Params}, ReqData, #state{rrdSensor = Sensor} = State) ->
|
|
|
|
Args = [proplists:get_value(<<"class">>, Params),
|
|
|
|
proplists:get_value(<<"type">>, Params),
|
|
|
|
proplists:get_value(<<"function">>, Params),
|
|
|
|
proplists:get_value(<<"voltage">>, Params),
|
|
|
|
proplists:get_value(<<"current">>, Params),
|
2011-04-26 08:26:24 +00:00
|
|
|
proplists:get_value(<<"phase">>, Params),
|
2011-04-25 16:52:27 +00:00
|
|
|
proplists:get_value(<<"constant">>, Params),
|
|
|
|
proplists:get_value(<<"enable">>, Params),
|
|
|
|
Sensor],
|
|
|
|
|
|
|
|
{updated, _Result} = mysql:execute(pool, sensor_config, Args),
|
|
|
|
|
|
|
|
{true, ReqData, State}.
|
|
|
|
|
2011-03-27 19:18:13 +00:00
|
|
|
% JSON: {"measurements":[[<TS1>,<VALUE1>],...,[<TSn>,<VALUEn>]]}
|
|
|
|
% Mochijson2: {struct,[{<<"measurements">>,[[<TS1>,<VALUE1>],...,[<TSn>,<VALUEn>]]}]}
|
2011-04-25 16:52:27 +00:00
|
|
|
process_measurements(Measurements, ReqData, #state{rrdSensor = RrdSensor} = State) ->
|
2011-03-26 22:47:42 +00:00
|
|
|
RrdData = [[integer_to_list(Time), ":", integer_to_list(Counter), " "] || [Time, Counter] <- Measurements],
|
2011-03-28 20:21:38 +00:00
|
|
|
[LastTimestamp, LastValue] = lists:last(Measurements),
|
|
|
|
|
|
|
|
{data, Result} = mysql:execute(pool, sensor_props, [RrdSensor]),
|
|
|
|
[[Uid, _Device, Midnight]] = mysql:get_result_rows(Result),
|
2011-03-26 22:47:42 +00:00
|
|
|
|
2011-03-29 08:08:09 +00:00
|
|
|
case rrd_update(?BASE_PATH, RrdSensor, RrdData) of
|
2011-03-28 20:21:38 +00:00
|
|
|
{ok, _RrdResponse} ->
|
|
|
|
RrdResponse = "ok",
|
2011-03-29 07:45:59 +00:00
|
|
|
NewMidnight = update_night(RrdSensor, Uid, Midnight, LastTimestamp, ReqData),
|
2011-03-28 20:21:38 +00:00
|
|
|
mysql:execute(pool, sensor_update, [unix_time(), NewMidnight, LastValue, RrdSensor]);
|
|
|
|
|
|
|
|
{error, RrdResponse} ->
|
2011-03-29 07:45:59 +00:00
|
|
|
logger(Uid, <<"rrdupdate.base">>, list_to_binary(RrdResponse), ?ERROR, ReqData)
|
2011-03-26 22:47:42 +00:00
|
|
|
end,
|
|
|
|
|
|
|
|
JsonResponse = mochijson2:encode({struct, [{<<"response">>, list_to_binary(RrdResponse)}]}),
|
|
|
|
{true , wrq:set_resp_body(JsonResponse, ReqData), State}.
|
2011-03-28 20:21:38 +00:00
|
|
|
|
2011-03-29 07:45:59 +00:00
|
|
|
update_night(RrdSensor, Uid, Midnight, LastTimestamp, ReqData) when LastTimestamp > Midnight + 6 * ?HOUR ->
|
2011-03-28 20:21:38 +00:00
|
|
|
LastMidnight = calculate_midnight(unix_time(), Uid),
|
2011-03-29 08:08:09 +00:00
|
|
|
RrdStart = integer_to_list(LastMidnight + 2 * ?HOUR),
|
|
|
|
RrdEnd = integer_to_list(LastMidnight + 5 * ?HOUR),
|
|
|
|
RrdResolution = integer_to_list(?QUARTER),
|
2011-03-28 20:21:38 +00:00
|
|
|
|
2011-03-29 08:08:09 +00:00
|
|
|
case rrd_fetch(?BASE_PATH, RrdSensor, RrdStart, RrdEnd, RrdResolution) of
|
2011-03-28 20:21:38 +00:00
|
|
|
{ok, Response} ->
|
|
|
|
Filtered = [re:split(X, "[:][ ]", [{return,list}]) || [X] <- Response, string:str(X, ":") == 11],
|
|
|
|
Datapoints = [list_to_float(Y) || [_X, Y] <- Filtered, string:len(Y) /= 3],
|
2011-04-08 13:45:01 +00:00
|
|
|
NightAverage = lists:foldl(fun(X, Sum) -> X / 12 + Sum end, 0.0, Datapoints),
|
2011-03-29 08:08:09 +00:00
|
|
|
RrdData = [integer_to_list(LastMidnight + 5 * ?HOUR), ":", float_to_list(NightAverage)],
|
2011-03-28 20:21:38 +00:00
|
|
|
|
2011-03-29 08:18:49 +00:00
|
|
|
case rrd_update(?NIGHT_PATH, RrdSensor, RrdData) of
|
|
|
|
{ok, _Response} ->
|
|
|
|
logger(Uid, <<"rrdupdate.night">>, <<"Successful update of night rrd.">>, ?INFO, ReqData);
|
|
|
|
|
|
|
|
{error, Reason} ->
|
|
|
|
logger(Uid, <<"rrdupdate.night">>, list_to_binary(Reason), ?ERROR, ReqData)
|
|
|
|
end;
|
|
|
|
|
2011-03-29 07:45:59 +00:00
|
|
|
{error, Reason} ->
|
|
|
|
logger(Uid, <<"rrdupdate.night">>, list_to_binary(Reason), ?ERROR, ReqData)
|
2011-03-28 20:21:38 +00:00
|
|
|
end,
|
|
|
|
|
|
|
|
LastMidnight + ?DAY;
|
2011-03-29 07:45:59 +00:00
|
|
|
update_night(_RrdSensor, _Uid, Midnight, _LastTimestamp, _ReqData) ->
|
2011-03-28 20:21:38 +00:00
|
|
|
Midnight.
|
|
|
|
|
|
|
|
calculate_midnight(Timestamp, Uid) ->
|
|
|
|
{data, Result} = mysql:execute(pool, timezone, [Uid]),
|
2011-04-08 13:43:35 +00:00
|
|
|
|
|
|
|
case mysql:get_result_rows(Result) of
|
|
|
|
[[undefined]] ->
|
|
|
|
Timezone = 0;
|
|
|
|
[[TimezoneChar8]] ->
|
|
|
|
Timezone = list_to_integer(binary_to_list(TimezoneChar8))
|
|
|
|
end,
|
|
|
|
|
2011-03-28 20:21:38 +00:00
|
|
|
closest_midnight(trunc(Timestamp/?DAY + 1) * ?DAY - Timezone, Timestamp).
|
|
|
|
|
|
|
|
closest_midnight(ProposedMidnight, Timestamp) when ProposedMidnight > Timestamp ->
|
|
|
|
closest_midnight(ProposedMidnight - ?DAY, Timestamp);
|
|
|
|
closest_midnight(ProposedMidnight, _Timestamp) ->
|
|
|
|
ProposedMidnight.
|