Packages

A few sentences (a paragraph) describing the project.

Current section

Files

Jump to
cwikla_pollution lib pollution_value_collector_gen_statem.erl
Raw

lib/pollution_value_collector_gen_statem.erl

%%%-------------------------------------------------------------------
%%% @author Arkadiusz
%%% @copyright (C) 2021, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 16. maj 2021 10:34
%%%-------------------------------------------------------------------
-module(pollution_value_collector_gen_statem).
-author("Arkadiusz").
-behaviour(gen_statem).
-export([start_link/0, stop/0]).
-export([init/1, terminate/3, callback_mode/0, set_station/1, add_value/3, store_data/0, idle/3, collecting/3]).
-record(stash, {nameOrCoords, measurements}).
-define(SERVER, ?MODULE).
start_link() ->
gen_statem:start_link({local, ?SERVER}, ?MODULE, [], []).
set_station(NameOrCoords) ->
gen_statem:cast(?MODULE, {set_station, NameOrCoords}).
add_value(Date, Type, Value) ->
gen_statem:cast(?MODULE, {add_value, Type, Value, Date}).
store_data() ->
gen_statem:cast(?MODULE, store_data).
init([]) ->
{ok, idle, []}.
callback_mode() ->
state_functions.
idle(_EventType, {set_station, NameOrCoords}, _) ->
io:format("~p ~n", ["IDLE"]),
{next_state, collecting, #stash{nameOrCoords = NameOrCoords, measurements = []}}.
collecting(_EventType, {add_value, Type, Value, Date}, Stash) ->
io:format("~p ~n", ["COLLECTING"]),
NewStash = #stash
{
nameOrCoords = Stash#stash.nameOrCoords,
measurements = [{Type, Value, Date} | Stash#stash.measurements]
},
{next_state, collecting, NewStash};
collecting(_EventType, store_data, Stash) ->
io:format("~p ~n", ["STASHING"]),
NameOrCoords = Stash#stash.nameOrCoords,
io:format("~s ~n ~w ~n", ["Data", Stash#stash.measurements]),
Results = [
pollution_gen_server:addValue(NameOrCoords, Date, Type, Value) || {Type, Value, Date} <-Stash#stash.measurements
],
io:format("~s ~n ~w ~n", ["Results", Results]),
checkIfError(lists:member(error, Results)),
{next_state, idle, []}.
terminate(_Reason, _StateName, _Monitor) ->
ok.
stop() ->
gen_statem:stop(?MODULE).
checkIfError(true) -> throw("Bad station name ot coordinates");
checkIfError(false) -> ok
.