%%%-------------------------------------------------------------------
%%% @author licheng5
%%% @copyright (C) 2023, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 14. 2月 2023 20:32
%%%-------------------------------------------------------------------
-module(iot_mock).
-author("licheng5").
-include("iot.hrl").

%% API
-export([rsa_encode/1]).
-export([test_influxdb/0]).

test_influxdb() ->
    UUID = <<"device123123">>,

    lists:foreach(fun(Id) ->
        Point = influx_point:new(<<"shui_biao">>,
            [{<<"uuid">>, UUID}, {<<"service_name">>, <<"shui_biao">>}],
            [{<<"cost">>, Id}],
            iot_util:timestamp()),

        poolboy:transaction(influx_pool, fun(Pid) ->
           influx_client:write(Pid, <<"iot">>, <<"iot">>, [Point])
                                         end)
                  end, lists:seq(1, 100)).

rsa_encode(Data) when is_binary(Data) ->
    %% 读取相关配置
    PublicPemFile = "/tmp/keys/public.pem",

    %% 私钥保存解析后的
    {ok, PubBin} = file:read_file(PublicPemFile),
    logger:debug("pub bin is: ~p", [PubBin]),
    [Pub] = public_key:pem_decode(PubBin),
    logger:debug("pub pem bin is: ~p", [Pub]),
    PubKey = public_key:pem_entry_decode(Pub),
    logger:debug("the public key is: ~p", [PubKey]),

    EncData = public_key:encrypt_public(Data, PubKey),
    logger:debug("enc data is: ~p", [EncData]),

    rsa_decode(EncData),

    ok.

rsa_decode(EncData) when is_binary(EncData) ->
    %% 读取相关配置
    PublicPemFile = "/tmp/keys/pri.pem",

    %% 私钥保存解析后的
    {ok, PubBin} = file:read_file(PublicPemFile),
    logger:debug("pub bin is: ~p", [PubBin]),
    [Pub] = public_key:pem_decode(PubBin),
    logger:debug("pub pem bin is: ~p", [Pub]),
    PubKey = public_key:pem_entry_decode(Pub),
    logger:debug("the public key is: ~p", [PubKey]),

    PlainData = public_key:decrypt_private(EncData, PubKey),
    logger:debug("plain data is: ~p", [PlainData]),

    ok.
