Current section
Files
Jump to
Current section
Files
src/bt_engine/blackboard/bt_blackboard.erl
-module(bt_blackboard).
-export([
get_bb_key/2,
is_set/2,
%% not exporting read since eval is enough. otherwise its easy to make mistakes
% read/2,
write/3,
clear_namespace/2,
eval/2
]).
-record(bb_key, {
namespace :: list(string()),
key :: string()
}).
get_bb_key(Namespace, Key) ->
#bb_key{namespace = Namespace, key = Key}.
is_set(BBKey, Blackboard) when is_record(BBKey, bb_key) ->
case maps:get(BBKey, Blackboard) of
null -> false;
{value, _} -> true
end;
%% is not a key, hence set
is_set(_NotKey, _Blackboard) ->
true.
read(BBKey, Blackboard) when is_record(BBKey, bb_key)->
case maps:get(BBKey, Blackboard) of
null ->
ErrorReason = lists:flatten(io_lib:format("Trying to read uninitalized key '~p'~n", [BBKey])),
erlang:error(ErrorReason);
{value, Val} -> Val;
ErrorVal ->
ErrorReason = lists:flatten(io_lib:format("Incorrect value stored for key '~p' as '~p'~n", [BBKey, ErrorVal])),
erlang:error(ErrorReason)
end;
%% is not a key, so return it.
read(NotKey, _Blackboard) ->
NotKey.
write(BBKey, Value, Blackboard) when is_record(BBKey, bb_key)->
maps:put(BBKey, {value, Value}, Blackboard);
write(NotKey, _Value, _Blackboard) ->
ErrorReason = lists:flatten(io_lib:format("Trying to write to ~p which is not a bb key~n", [NotKey])),
erlang:error(ErrorReason).
%% set all keys within this namespace to null
clear_namespace(Namespace, Blackboard) ->
BBAsProplist = maps:to_list(Blackboard),
%% find stuff that is prefix of namespace and set value to null
NewBBProplist = lists:map(
fun({BBKey, BBVal}) ->
BBNS = BBKey#bb_key.namespace,
case lists:prefix(Namespace, BBNS) of
true -> {BBKey, null};
false -> {BBKey, BBVal}
end
end,
BBAsProplist
),
maps:from_list(NewBBProplist).
%% evaluation function!
%% input can be key, array of keys, tuple of keys, non-key
eval(BBKey, Blackboard) when is_record(BBKey, bb_key) ->
read(BBKey, Blackboard);
eval(ListOfVals, Blackboard) when is_list(ListOfVals) ->
[eval(X, Blackboard) || X <- ListOfVals];
eval(TupleOfVals, Blackboard) when is_tuple(TupleOfVals) ->
L = tuple_to_list(TupleOfVals),
eval(L, Blackboard);
eval(Native, _Blackboard) ->
Native.