SatDump 2.0.0-alpha-520736c72
Loading...
Searching...
No Matches
test_http_client.h
1#pragma once
2
3#include "../base/remote_handler_backend.h"
4#include "core/exception.h"
5#include "logger.h"
6#include "nlohmann/json.hpp"
7#include "utils/http.h"
8#include <cstddef>
9#include <cstdint>
10#include <exception>
11#include <functional>
12#include <memory>
13#include <mutex>
14#include <string>
15
16#include <nng/nng.h>
17#include <nng/protocol/bus0/bus.h>
18#include <nng/protocol/pair0/pair.h>
19#include <nng/supplemental/http/http.h>
20#include <nng/supplemental/util/platform.h>
21#include <thread>
22
23namespace satdump
24{
25 namespace handlers
26 {
27 class TestHttpClientBackend : public RemoteHandlerBackend
28 {
29 private:
30 nng_socket socket;
31 nng_dialer dialer;
32
33 bool thread_should_run = true;
34 std::thread rx_th;
35
36 const std::string address = "0.0.0.0:8080";
37 // const std::string address = "192.168.10.96:8080";
38 const std::string ws_add = "ws://" + address + "/ws";
39 const std::string ht_add = "http://" + address + "";
40
41 public:
42 TestHttpClientBackend()
43 {
44 {
45 int rv = 0;
46 if (rv = nng_bus0_open(&socket); rv != 0)
47 {
48 printf("pair open error\n");
49 }
50
51 if (rv = nng_dial(socket, ws_add.c_str(), &dialer, 0); rv != 0)
52 {
53 printf("server listen error\n");
54 }
55 }
56
57 rx_th = std::thread(&TestHttpClientBackend::rxThread, this);
58 }
59
60 ~TestHttpClientBackend()
61 {
62 thread_should_run = false;
63 if (rx_th.joinable())
64 rx_th.join();
65 }
66
67 void rxThread()
68 {
69 while (thread_should_run)
70 {
71 void *ptr;
72 size_t sz = 0;
73 nng_recv(socket, &ptr, &sz, NNG_FLAG_ALLOC | NNG_FLAG_NONBLOCK);
74
75 if (ptr != NULL && sz > 0)
76 {
77 uint8_t *dat = (uint8_t *)ptr;
78 std::string id((char *)dat + 1, dat[0]);
79 uint8_t *payload = dat + 1 + (int)dat[0];
80 size_t psize = payload[0] << 24 | payload[1] << 16 | payload[2] << 8 | payload[3];
81 payload += 4;
82 // logger->info("Payload %s %d", id.c_str(), psize);
83
84 push_stream_data(id, payload, psize);
85
86 nng_free(ptr, sz);
87 }
88 }
89 }
90
91 nlohmann::ordered_json _get_cfg_list()
92 {
93 std::string res;
94 perform_http_request(ht_add + "/list", res);
95 return nlohmann::ordered_json::parse(res);
96 }
97
98 nlohmann::ordered_json _get_cfg(std::string key)
99 {
100 std::string res;
101 perform_http_request_post(ht_add + "/get", res, key);
102 return nlohmann::ordered_json::parse(res);
103 }
104
105 cfg_res_t _set_cfg(std::string key, nlohmann::ordered_json v)
106 {
107 std::string res;
108 nlohmann::json vs;
109 vs[key] = v;
110 perform_http_request_post(ht_add + "/set", res, vs.dump());
111 return nlohmann::ordered_json::parse(res)["res"];
112 }
113 };
114 } // namespace handlers
115} // namespace satdump
HTTP Get/Post functions and others.