%%%------------------------------------------------------------------- %% @doc iot public API %% @end %%%------------------------------------------------------------------- -module(iot_app). -behaviour(application). -include("iot.hrl"). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> io:setopts([{encoding, unicode}]), %% 加速内存的回收 erlang:system_flag(fullsweep_after, 16), %% 启动mnesia数据库 start_mnesia(), start_http_server(), start_tcp_server(), iot_sup:start_link(). stop(_State) -> ok. %% internal functions %% 启动http服务 start_http_server() -> {ok, Props} = application:get_env(iot, http_server), Acceptors = proplists:get_value(acceptors, Props, 50), MaxConnections = proplists:get_value(max_connections, Props, 10240), Backlog = proplists:get_value(backlog, Props, 1024), Port = proplists:get_value(port, Props), Dispatcher = cowboy_router:compile([ {'_', [ {"/host/[...]", http_protocol, [host_handler]}, {"/device/[...]", http_protocol, [device_handler]}, {"/service/[...]", http_protocol, [service_handler]} ]} ]), TransOpts = [ {port, Port}, {num_acceptors, Acceptors}, {backlog, Backlog}, {max_connections, MaxConnections} ], {ok, Pid} = cowboy:start_clear(http_listener, TransOpts, #{env => #{dispatch => Dispatcher}}), lager:debug("[iot_app] the http server start at: ~p, pid is: ~p", [Port, Pid]). %% 启动tcp服务 start_tcp_server() -> {ok, Props} = application:get_env(iot, tcp_server), Acceptors = proplists:get_value(acceptors, Props, 50), MaxConnections = proplists:get_value(max_connections, Props, 10240), Backlog = proplists:get_value(backlog, Props, 1024), Port = proplists:get_value(port, Props), TransOpts = [ {tcp_options, [ binary, {reuseaddr, true}, {active, false}, {packet, 4}, {nodelay, false}, {backlog, Backlog} ]}, {acceptors, Acceptors}, {max_connections, MaxConnections} ], {ok, _} = esockd:open('iot/tcp_server', Port, TransOpts, {tcp_channel, start_link, []}), lager:debug("[iot_app] the tcp server start at: ~p", [Port]). %% 启动内存数据库 start_mnesia() -> %% 启动数据库 ok = mnesia:start(), Tables = mnesia:system_info(tables), lager:debug("[iot_app] tables: ~p", [Tables]), %% 创建数据库表 not lists:member(service_config, Tables) andalso service_config_model:create_table(), ok.