This commit is contained in:
anlicheng 2024-08-30 14:57:44 +08:00
parent 24c16d12f5
commit dabb9aee2f
3 changed files with 36 additions and 19 deletions

5
apps/iot/priv/env.config Normal file
View File

@ -0,0 +1,5 @@
[
{super_device_uuids, [
{name, <<"test">>}
]}
].

View File

@ -81,7 +81,8 @@ write_data(Measurement, Tags, FieldsList, Timestamp) when is_binary(Measurement)
-spec get_bucket(DeviceUUID :: binary()) -> binary(). -spec get_bucket(DeviceUUID :: binary()) -> binary().
get_bucket(DeviceUUID) when is_binary(DeviceUUID) -> get_bucket(DeviceUUID) when is_binary(DeviceUUID) ->
case iot_env:exists(DeviceUUID) of SuperDeviceUUIDs = iot_env:get_value(super_device_uuids, []),
case lists:member(DeviceUUID, SuperDeviceUUIDs) of
true -> true ->
<<"metric_", DeviceUUID/binary>>; <<"metric_", DeviceUUID/binary>>;
false -> false ->

View File

@ -9,39 +9,50 @@
-module(iot_env). -module(iot_env).
-author("anlicheng"). -author("anlicheng").
%%
-record(env, {
key,
val
}).
%% API %% API
-export([new/0, reload/0]). -export([new/0, reload/0, get_value/1, get_value/2]).
-export([exists/1]).
-spec new() -> ok. -spec new() -> ok.
new() -> new() ->
ets:new(iot_env, [public, set, named_table, {read_concurrency, true}]), ets:new(iot_env, [public, set, named_table, {read_concurrency, true}, {keypos, 2}]),
DeviceUUIDs = load_env(), Envs = load_env(),
true = ets:insert(iot_env, {device_uuids, DeviceUUIDs}), [ets:insert(iot_env, #env{key = Key, val = Val}) || {Key, Val} <- Envs],
ok. ok.
-spec reload() -> ok. -spec reload() -> ok.
reload() -> reload() ->
DeviceUUIDs = load_env(), Envs = load_env(),
true = ets:insert(iot_env, {device_uuids, DeviceUUIDs}), [ets:insert(iot_env, #env{key = Key, val = Val}) || {Key, Val} <- Envs],
ok. ok.
-spec exists(DeviceUUID :: binary()) -> boolean(). -spec get_value(Key :: atom()) -> any().
exists(DeviceUUID) when is_binary(DeviceUUID) -> get_value(Key) when is_atom(Key) ->
case ets:lookup(iot_env, device_uuids) of get_value(Key, undefined).
-spec get_value(Key :: atom(), Default :: any()) -> any().
get_value(Key, Default) when is_atom(Key) ->
case ets:lookup(iot_env, Key) of
[] -> [] ->
false; Default;
[{device_uuids, DeviceUUIDs}|_] -> [#env{val = Val}|_] ->
lists:member(DeviceUUID, DeviceUUIDs) Val
end. end.
-spec load_env() -> [binary()]. -spec load_env() -> [binary()].
load_env() -> load_env() ->
RootDir = code:root_dir(), Dir = code:priv_dir(iot),
EnvFile = RootDir ++ "/.env", EnvFile = Dir ++ "/env.config",
case file:read_file(EnvFile) of case file:read_file(EnvFile) of
{ok, Content} -> {ok, Content} ->
binary:split(string:trim(Content), <<"\n">>, [global, trim]); {ok, Tokens, _} = erl_scan:string(binary_to_list(Content)),
{ok, Forms} = erl_parse:parse_term(Tokens),
Forms;
{error, Reason} -> {error, Reason} ->
lager:warning("[iot] read .env file: ~p, get error: ~p", [EnvFile, Reason]), lager:warning("[iot] read .env file: ~p, get error: ~p", [EnvFile, Reason]),
[] []