ndi_interface.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. #include "core/basic_obj_types.hpp"
  2. #include "core/small_obj.hpp"
  3. #include "utility/config_utility.hpp"
  4. #include "utility/coro_worker.hpp"
  5. #include "utility/coro_worker_helper_func.hpp"
  6. #include "utility/debug_utility.hpp"
  7. #include "utility/name_translator.hpp"
  8. #include "utility/variable_helper.hpp"
  9. #include "utility/versatile_buffer2.hpp"
  10. #include "utility/string_map.hpp"
  11. #include "third_party/static_block.hpp"
  12. #include <boost/algorithm/hex.hpp>
  13. #include <boost/asio/experimental/awaitable_operators.hpp>
  14. #include <boost/asio/experimental/channel.hpp>
  15. #include <boost/asio/ip/address.hpp>
  16. #include <boost/asio/ip/tcp.hpp>
  17. #include <boost/asio/buffers_iterator.hpp>
  18. #include <boost/asio/co_spawn.hpp>
  19. #include <boost/asio/detached.hpp>
  20. #include <boost/asio/read_until.hpp>
  21. #include <boost/asio/serial_port.hpp>
  22. #include <boost/asio/streambuf.hpp>
  23. #include <boost/asio/use_awaitable.hpp>
  24. #include <boost/crc.hpp>
  25. #include <boost/iostreams/device/mapped_file.hpp>
  26. #include <boost/lexical_cast.hpp>
  27. #include <boost/smart_ptr/scoped_ptr.hpp>
  28. #include <boost/system/error_code.hpp>
  29. #ifdef BOOST_OS_WINDOWS_AVAILABLE
  30. #include <winbase.h> // for sending serial break
  31. #endif // BOOST_OS_WINDOWS_AVAILABLE
  32. #include <fmt/format.h>
  33. #include <spdlog/spdlog.h>
  34. #include <chrono>
  35. #include <functional>
  36. #include <vector>
  37. #include <unordered_map>
  38. DEFAULT_TRISTATE_OBJ_DEF(ndi_interface)
  39. namespace sophiar {
  40. using boost::asio::async_read;
  41. using boost::asio::async_read_until;
  42. using boost::asio::async_write;
  43. using boost::asio::awaitable;
  44. using boost::asio::basic_streambuf;
  45. using boost::asio::buffer;
  46. using boost::asio::buffers_begin;
  47. using boost::asio::buffers_end;
  48. using boost::asio::co_spawn;
  49. using boost::asio::detached;
  50. using boost::asio::experimental::channel;
  51. using boost::algorithm::hex;
  52. using boost::algorithm::unhex;
  53. using boost::asio::serial_port;
  54. using boost::asio::use_awaitable;
  55. using boost::iostreams::mapped_file;
  56. using boost::lexical_cast;
  57. using boost::scoped_ptr;
  58. using boost::system::error_code;
  59. using namespace boost::asio::experimental::awaitable_operators;
  60. using namespace boost::asio::ip;
  61. using namespace std::string_view_literals;
  62. enum class ndi_address_type {
  63. ethernet,
  64. serial,
  65. };
  66. name_translator<ndi_address_type> ndi_address_type_translator;
  67. static_block {
  68. ndi_address_type_translator.register_item("ethernet", ndi_address_type::ethernet);
  69. ndi_address_type_translator.register_item("serial", ndi_address_type::serial);
  70. }
  71. struct ndi_interface::impl {
  72. using tool_info_index_type = uint8_t;
  73. using port_handle_type = uint8_t;
  74. static constexpr port_handle_type invalid_port_handle = ~(port_handle_type) 0;
  75. struct tool_info {
  76. port_handle_type port_handle = invalid_port_handle; // assigned by NDI
  77. variable_index_type transform_var_index = invalid_variable_index;
  78. variable_index_type rms_var_index = invalid_variable_index;
  79. uint32_t last_frame_number = 0;
  80. std::string rom_path;
  81. };
  82. using tool_info_pool_type = std::vector<tool_info>;
  83. using port_handle_map_type = std::unordered_map<port_handle_type, tool_info_index_type>;
  84. tool_info_pool_type tool_info_pool;
  85. port_handle_map_type port_handle_map;
  86. static constexpr auto default_tracking_interval = std::chrono::milliseconds(17); // 60Hz
  87. static constexpr uint16_t default_ndi_port = 8765;
  88. static constexpr auto ndi_endian = boost::endian::order::little;
  89. static constexpr uint16_t binary_reply_header_magic = 0xA5C4;
  90. static constexpr uint16_t extended_binary_reply_header_magic = 0xA5C8;
  91. static constexpr uint16_t streaming_header_magic = 0xB5D4;
  92. using crc_checker_type = boost::crc_16_type;
  93. ndi_interface *q_this = nullptr;
  94. using reply_queue_type = channel<void(error_code, dynamic_memory::pointer)>;
  95. using reply_queue_ptr_type = scoped_ptr<reply_queue_type>;
  96. reply_queue_ptr_type command_reply_queue;
  97. using reply_callback_type = std::function<void(dynamic_memory::pointer &&)>;
  98. string_map<reply_callback_type> stream_reply_callback_pool;
  99. ndi_address_type address_type;
  100. // If address type is ethernet
  101. using ip_address_type = boost::asio::ip::address;
  102. ip_address_type ndi_ip;
  103. uint16_t ndi_port = default_ndi_port;
  104. scoped_ptr<tcp::socket> ndi_tcp_socket;
  105. // If address type is serial
  106. std::string com_port_name;
  107. scoped_ptr<serial_port> ndi_com_socket;
  108. int ndi_api_major_version = 0;
  109. bool accept_unreliable_transform = true;
  110. bool prefer_stream_tracking = true;
  111. bool using_stream_tracking = false;
  112. coro_worker::pointer receive_reply_worker;
  113. coro_worker::pointer tracking_tools_worker;
  114. void load_init_config(const nlohmann::json &config) {
  115. // load connection info
  116. address_type = ndi_address_type_translator.translate(LOAD_STRING_ITEM("address_type"));
  117. if (address_type == ndi_address_type::ethernet) {
  118. ndi_ip = make_address(LOAD_STRING_ITEM("ip"));
  119. if (config.contains("tcp_port")) {
  120. ndi_port = LOAD_UINT_ITEM("tcp_port");
  121. } else { // use default value
  122. ndi_port = default_ndi_port;
  123. }
  124. } else if (address_type == ndi_address_type::serial) {
  125. com_port_name = LOAD_STRING_ITEM("com_port");
  126. }
  127. // load tool info
  128. assert(tool_info_pool.empty());
  129. ENSURE_ARRAY("tool_list")
  130. for (auto &tool_config: config["tool_list"]) {
  131. auto rom_path = LOAD_STRING_ITEM2(tool_config, "rom_path");
  132. assert(tool_config.contains("outputs"));
  133. auto &output_config = tool_config["outputs"];
  134. auto transform_var_index = TRY_LOAD_VARIABLE_INDEX2(output_config, transform_obj, "transform");
  135. auto rms_var_index = TRY_LOAD_VARIABLE_INDEX2(output_config, double_obj, "marker_uncertainty");
  136. tool_info_pool.push_back(
  137. {
  138. .port_handle = invalid_port_handle,
  139. .transform_var_index = transform_var_index,
  140. .rms_var_index = rms_var_index,
  141. .rom_path = std::move(rom_path)
  142. });
  143. }
  144. }
  145. void load_start_config(const nlohmann::json &config) {
  146. // P.55 Polaris Spectra-Vicra API Guide
  147. accept_unreliable_transform = TRY_LOAD_BOOL_ITEM("allow_unreliable", false);
  148. prefer_stream_tracking = TRY_LOAD_BOOL_ITEM("prefer_stream_tracking", true);
  149. }
  150. template<typename T>
  151. std::enable_if_t<std::is_arithmetic_v<T>, awaitable<T>>
  152. ndi_async_read_value() {
  153. if (address_type == ndi_address_type::serial) {
  154. return async_read_value<ndi_endian, T>(*ndi_com_socket);
  155. } else if (address_type == ndi_address_type::ethernet) {
  156. return async_read_value<ndi_endian, T>(*ndi_tcp_socket);
  157. }
  158. assert(false);
  159. __builtin_unreachable();
  160. }
  161. template<WriteableMemory MemoryType>
  162. auto ndi_async_fill_memory(MemoryType &mem) {
  163. if (address_type == ndi_address_type::serial) {
  164. return async_fill_memory_from(*ndi_com_socket, mem);
  165. } else if (address_type == ndi_address_type::ethernet) {
  166. return async_fill_memory_from(*ndi_tcp_socket, mem);
  167. }
  168. assert(false);
  169. __builtin_unreachable();
  170. }
  171. awaitable<dynamic_memory::pointer> read_binary_reply(uint16_t header_magic) {
  172. // read length and crc
  173. auto header_buf = static_memory<4>{};
  174. co_await ndi_async_fill_memory(header_buf);
  175. auto header_reader = versatile_reader<ndi_endian>(header_buf);
  176. uint16_t reply_length, header_crc16;
  177. header_reader >> reply_length >> header_crc16;
  178. // check header crc
  179. crc_checker_type crc_checker;
  180. uint16_t header_magic_ndi = header_magic;
  181. swap_net_loc_endian<ndi_endian>(header_magic_ndi);
  182. crc_checker.process_bytes(&header_magic_ndi, 2); // header magic
  183. crc_checker.process_bytes(header_buf.data(), 2); // reply size
  184. if (crc_checker.checksum() != header_crc16) {
  185. // TODO show log
  186. }
  187. // read reply content
  188. auto reply_buf = dynamic_memory::new_instance(reply_length + 2);
  189. co_await ndi_async_fill_memory(*reply_buf);
  190. // check reply crc
  191. crc_checker.reset();
  192. crc_checker.process_bytes(reply_buf->data(), reply_length);
  193. auto reply_crc = read_binary_value<ndi_endian, uint16_t>(reply_buf->data() + reply_length);
  194. if (crc_checker.checksum() != reply_crc) {
  195. // TODO show log
  196. }
  197. reply_buf->increase_size(-2); // strip the crc
  198. co_return std::move(reply_buf);
  199. }
  200. awaitable<dynamic_memory::pointer> read_extended_binary_reply() {
  201. auto reply_length = co_await ndi_async_read_value<uint32_t>();
  202. auto reply_buf = dynamic_memory::new_instance(reply_length);
  203. co_await ndi_async_fill_memory(*reply_buf);
  204. co_return std::move(reply_buf);
  205. }
  206. awaitable<void> read_and_handle_streaming_reply(uint16_t header_magic) {
  207. // read stream id
  208. auto stream_id_length = co_await ndi_async_read_value<uint16_t>();
  209. auto stream_id_buf = dynamic_memory::new_instance(stream_id_length + 2);
  210. co_await ndi_async_fill_memory(*stream_id_buf);
  211. // check header crc
  212. crc_checker_type crc_checker;
  213. uint16_t header_magic_ndi = header_magic;
  214. swap_net_loc_endian<ndi_endian>(header_magic_ndi);
  215. crc_checker.process_bytes(&header_magic_ndi, 2); // header magic
  216. uint16_t stream_id_length_ndi = stream_id_length;
  217. swap_net_loc_endian<ndi_endian>(stream_id_length_ndi);
  218. crc_checker.process_bytes(&stream_id_length_ndi, 2); // stream id length
  219. crc_checker.process_bytes(stream_id_buf->data(), stream_id_length); // stream id
  220. auto header_crc16 = read_binary_value<ndi_endian, uint16_t>(stream_id_buf->data() + stream_id_length);
  221. if (crc_checker.checksum() != header_crc16) {
  222. // TODO show log
  223. }
  224. // read the real content
  225. header_magic = co_await ndi_async_read_value<uint16_t>();
  226. dynamic_memory::pointer reply_buf;
  227. switch (header_magic) {
  228. case binary_reply_header_magic: {
  229. reply_buf = co_await read_binary_reply(header_magic);
  230. break;
  231. }
  232. case extended_binary_reply_header_magic: {
  233. reply_buf = co_await read_extended_binary_reply();
  234. break;
  235. }
  236. default: { // ascii reply
  237. reply_buf = co_await read_ascii_reply(header_magic);
  238. break;
  239. }
  240. }
  241. auto stream_id = std::string_view{stream_id_buf->data(), stream_id_length};
  242. assert(stream_reply_callback_pool.contains(stream_id));
  243. auto &callback = stream_reply_callback_pool.query(stream_id);
  244. callback(std::move(reply_buf));
  245. co_return;
  246. }
  247. // header_magic is also part of the reply
  248. awaitable<dynamic_memory::pointer> read_ascii_reply(uint16_t header_magic) {
  249. static constexpr char cr_ascii = '\r';
  250. using streambuf_type = basic_streambuf<DYNAMIC_ALLOCATOR(char) >;
  251. streambuf_type ascii_buf;
  252. // read the rest ascii reply
  253. if (address_type == ndi_address_type::serial) {
  254. co_await async_read_until(*ndi_com_socket, ascii_buf, cr_ascii, use_awaitable);
  255. } else if (address_type == ndi_address_type::ethernet) {
  256. co_await async_read_until(*ndi_tcp_socket, ascii_buf, cr_ascii, use_awaitable);
  257. }
  258. auto start_iter = buffers_begin(ascii_buf.data());
  259. auto end_iter = buffers_end(ascii_buf.data());
  260. // locate the cr character
  261. auto cr_iter = start_iter;
  262. while (cr_iter != end_iter && *cr_iter != cr_ascii)
  263. ++cr_iter;
  264. assert(cr_iter != end_iter);
  265. // get the crc value
  266. auto crc_iter = cr_iter - 4;
  267. uint16_t reply_crc16;
  268. try {
  269. unhex(crc_iter, cr_iter, &reply_crc16);
  270. } catch (boost::algorithm::non_hex_input &e) {
  271. // TODO show log
  272. co_return nullptr;
  273. }
  274. // create a string as reply
  275. auto reply_content_length = crc_iter - start_iter + 2;
  276. auto reply_buf = dynamic_memory::new_instance(reply_content_length);
  277. // insert the header_magic back to the head of the ascii reply
  278. write_binary_value<ndi_endian>(reply_buf->data(), header_magic);
  279. // insert the rest reply part
  280. std::copy(start_iter, crc_iter, reply_buf->data() + 2);
  281. // check crc value
  282. crc_checker_type crc_checker;
  283. crc_checker.process_bytes(reply_buf->data(), reply_content_length);
  284. if (crc_checker.checksum() != reply_crc16) {
  285. // TODO show log
  286. }
  287. co_return std::move(reply_buf);
  288. }
  289. // 读取并分发 "一份" 来自 NDI 的回复消息
  290. awaitable<bool> read_and_dispatch_reply() {
  291. auto header_magic = co_await ndi_async_read_value<uint16_t>();
  292. if (header_magic == streaming_header_magic) {
  293. co_await read_and_handle_streaming_reply(header_magic);
  294. co_return true;
  295. }
  296. dynamic_memory::pointer reply_buf;
  297. switch (header_magic) {
  298. case binary_reply_header_magic: {
  299. reply_buf = co_await read_binary_reply(header_magic);
  300. break;
  301. }
  302. case extended_binary_reply_header_magic: {
  303. reply_buf = co_await read_extended_binary_reply();
  304. break;
  305. }
  306. default: { // ascii reply
  307. reply_buf = co_await read_ascii_reply(header_magic);
  308. break;
  309. }
  310. }
  311. assert(reply_buf != nullptr);
  312. co_await command_reply_queue->async_send(error_code{}, std::move(reply_buf), use_awaitable);
  313. co_return true;
  314. }
  315. void start_receive_reply() {
  316. assert(receive_reply_worker == nullptr);
  317. auto worker_func = [this]() -> awaitable<bool> {
  318. co_await read_and_dispatch_reply();
  319. co_return true;
  320. };
  321. auto error_handler = [](std::exception &e) {
  322. // TODO show error
  323. };
  324. auto noexcept_worker_func = make_noexcept_func(
  325. [this]() { return read_and_dispatch_reply(); },
  326. std::move(error_handler));
  327. auto exit_func = reset_on_exit_func(q_this);
  328. receive_reply_worker = make_infinite_coro_worker(std::move(noexcept_worker_func),
  329. std::move(exit_func));
  330. receive_reply_worker->run();
  331. }
  332. auto send_command(std::string_view cmd) {
  333. if (address_type == ndi_address_type::serial) {
  334. assert(ndi_com_socket->is_open());
  335. return async_write(*ndi_com_socket, buffer(cmd.data(), cmd.size()), use_awaitable);
  336. } else if (address_type == ndi_address_type::ethernet) {
  337. assert(ndi_tcp_socket->is_open());
  338. return async_write(*ndi_tcp_socket, buffer(cmd.data(), cmd.size()), use_awaitable);
  339. }
  340. assert(false);
  341. __builtin_unreachable();
  342. }
  343. template<typename T, typename OutputIterator>
  344. std::enable_if_t<std::is_integral_v<T>, OutputIterator>
  345. static write_number_as_hex(T val, OutputIterator out) {
  346. swap_net_loc_endian<boost::endian::order::big>(val);
  347. auto val_ptr = reinterpret_cast<uint8_t *>(&val);
  348. auto old_out = out;
  349. out = hex(val_ptr, val_ptr + sizeof(T), out);
  350. assert(out - old_out == sizeof(T) << 1);
  351. return out;
  352. }
  353. template<typename T, typename InputIterator>
  354. std::enable_if_t<std::is_integral_v<T>, T>
  355. static read_number_as_hex(InputIterator in) {
  356. T val;
  357. auto ret_ptr = unhex(in, in + (sizeof(T) << 1), &val);
  358. assert(ret_ptr - &val == 1);
  359. return val;
  360. }
  361. static int get_error_warning_code(std::string_view reply_str) {
  362. static constexpr auto error_prefix = "ERROR"sv;
  363. static constexpr auto warning_prefix = "WARNING"sv;
  364. try {
  365. if (reply_str.starts_with(error_prefix)) { // error
  366. auto error_code = read_number_as_hex<uint8_t>(reply_str.data() + error_prefix.size());
  367. return -error_code;
  368. } else if (reply_str.starts_with(warning_prefix)) { // warning
  369. auto warning_code = read_number_as_hex<uint8_t>(reply_str.data() + warning_prefix.size());
  370. return warning_code;
  371. }
  372. } catch (boost::bad_lexical_cast &e) {
  373. // TODO show log
  374. auto fatal_error_code = std::numeric_limits<int16_t>::min();
  375. return fatal_error_code;
  376. }
  377. return 0; // no error
  378. }
  379. awaitable<bool> simple_cmd_helper(std::string_view cmd) {
  380. co_await send_command(cmd);
  381. auto reply = co_await command_reply_queue->async_receive(use_awaitable);
  382. auto reply_str = reply->as_string_view();
  383. auto reply_code = get_error_warning_code(reply_str);
  384. if (reply_code < 0) { // error
  385. // TODO show error
  386. co_return false;
  387. } else if (reply_code > 0) { // warning
  388. // TODO show warning
  389. } else { // normal
  390. assert(reply_str == "OKAY");
  391. }
  392. co_return true;
  393. }
  394. // 对串口进行配置
  395. awaitable<bool> setup_com_socket() {
  396. assert(address_type == ndi_address_type::serial);
  397. assert(ndi_com_socket->is_open());
  398. // load default config
  399. ndi_com_socket->set_option(serial_port::baud_rate(9600));
  400. ndi_com_socket->set_option(serial_port::character_size(8));
  401. ndi_com_socket->set_option(serial_port::parity(serial_port::parity::none));
  402. ndi_com_socket->set_option(serial_port::stop_bits(serial_port::stop_bits::one));
  403. ndi_com_socket->set_option(serial_port::flow_control(serial_port::flow_control::none));
  404. #ifdef BOOST_OS_WINDOWS_AVAILABLE // boost asio cannot send serial break under windows
  405. using namespace std::chrono_literals;
  406. auto handle = ndi_com_socket->native_handle();
  407. ENSURE_CO(SetCommBreak(handle));
  408. co_await coro_sleep(250ms); // hold serial break for 250ms
  409. ENSURE_CO(ClearCommBreak(handle));
  410. #else // BOOST_OS_WINDOWS_AVAILABLE
  411. ndi_com_socket->send_break(); // cause the system to reset
  412. #endif // BOOST_OS_WINDOWS_AVAILABLE
  413. // wait the RESET to be sent from ndi
  414. auto reset_reply = co_await command_reply_queue->async_receive(use_awaitable);
  415. auto reset_reply_str = reset_reply->as_string_view();
  416. auto reply_code = get_error_warning_code(reset_reply_str);
  417. if (reply_code < 0) {
  418. // TODO show log
  419. co_return false;
  420. }
  421. assert(reset_reply_str == "RESET");
  422. // change the serial config of NDI
  423. CO_ENSURE(simple_cmd_helper("COMM 70001\r"sv))
  424. // load advanced config
  425. ndi_com_socket->set_option(serial_port::baud_rate(19200));
  426. ndi_com_socket->set_option(serial_port::flow_control(serial_port::flow_control::hardware));
  427. co_return true;
  428. }
  429. awaitable<int> get_api_major_version() {
  430. co_await send_command("APIREV \r"sv);
  431. auto reply = co_await command_reply_queue->async_receive(use_awaitable);
  432. auto reply_code = get_error_warning_code(reply->as_string_view());
  433. if (reply_code < 0) {
  434. assert(false);
  435. co_return 0;
  436. }
  437. SPDLOG_INFO("NDI api version is {}.", reply->as_string_view());
  438. auto major_version = lexical_cast<int>(reply->data() + 2, 3); // Like G.001.004A0C0
  439. co_return major_version;
  440. }
  441. awaitable<bool> initialize_ndi() {
  442. return simple_cmd_helper("INIT \r"sv);
  443. }
  444. awaitable<port_handle_type> request_port_handle() {
  445. co_await send_command("PHRQ *********100**\r"sv);
  446. auto reply = co_await command_reply_queue->async_receive(use_awaitable);
  447. auto reply_code = get_error_warning_code(reply->as_string_view());
  448. if (reply_code < 0) {
  449. // TODO show log
  450. co_return -1;
  451. }
  452. auto port_handle = read_number_as_hex<port_handle_type>(reply->data());
  453. co_return port_handle;
  454. }
  455. awaitable<bool> upload_rom(port_handle_type port_handle, const std::string &rom_path) {
  456. static constexpr auto cmd_prefix = "PVWR "sv;
  457. static constexpr auto chunk_size = 64;
  458. static constexpr auto cmd_length = cmd_prefix.size()
  459. + 2 // port handle
  460. + 4 // start address
  461. + chunk_size * 2 // tool definition
  462. + 1; // cr
  463. // setup cmd prefix
  464. auto cmd_buf = static_memory<cmd_length>{};
  465. cmd_prefix.copy(cmd_buf.data(), cmd_prefix.size());
  466. auto cur_buf = cmd_buf.data() + cmd_prefix.size();
  467. // setup port handle
  468. assert(is_valid_id(port_handle));
  469. cur_buf = write_number_as_hex(port_handle, cur_buf);
  470. auto address_buf = cur_buf;
  471. auto data_buf = address_buf + 4;
  472. auto cr_buf = data_buf + chunk_size * 2;
  473. *cr_buf = '\r';
  474. assert(cr_buf + 1 == cmd_buf.data() + cmd_length);
  475. auto rom_file = mapped_file();
  476. try {
  477. rom_file.open(rom_path, boost::iostreams::mapped_file::readonly);
  478. assert(rom_file.is_open());
  479. } catch (std::exception &e) {
  480. // TODO show log
  481. co_return false;
  482. }
  483. auto file_data = rom_file.const_data();
  484. size_t cur_pos = 0, end_pos = rom_file.size();
  485. while (cur_pos != end_pos) {
  486. // write the address
  487. using real_address_type = uint16_t;
  488. assert(cur_pos < std::numeric_limits<real_address_type>::max());
  489. auto cur_address = static_cast<real_address_type >(cur_pos);
  490. write_number_as_hex(cur_address, address_buf);
  491. // write cur chunk
  492. auto chunk_end_pos = std::min(cur_pos + chunk_size, end_pos);
  493. auto ret_buf = hex(file_data + cur_pos, file_data + chunk_end_pos, data_buf);
  494. // padding
  495. if (ret_buf != cr_buf) {
  496. assert(chunk_end_pos - cur_pos < chunk_size);
  497. while (ret_buf != cr_buf) {
  498. *ret_buf++ = '0';
  499. }
  500. }
  501. // send command
  502. CO_ENSURE(simple_cmd_helper(cmd_buf.as_string_view()))
  503. cur_pos = chunk_end_pos;
  504. }
  505. co_return true;
  506. }
  507. awaitable<bool> initialize_port_handle(port_handle_type port_handle) {
  508. static constexpr auto pinit_cmd_template = "PINIT 00\r"sv;
  509. static constexpr auto pinit_cmd_length = pinit_cmd_template.size();
  510. static constexpr ptrdiff_t port_handle_offset = 6;
  511. auto pinit_cmd_buf = static_memory<pinit_cmd_length>();
  512. // fill the template
  513. assert(is_valid_id(port_handle));
  514. pinit_cmd_template.copy(pinit_cmd_buf.data(), pinit_cmd_length);
  515. write_number_as_hex(port_handle, pinit_cmd_buf.data() + port_handle_offset);
  516. auto ok = co_await simple_cmd_helper(pinit_cmd_buf.as_string_view());
  517. co_return ok;
  518. }
  519. awaitable<bool> enable_port_handle(port_handle_type port_handle) {
  520. static constexpr auto pena_cmd_template = "PENA 00D\r"sv;
  521. static constexpr auto pena_cmd_length = pena_cmd_template.size();
  522. static constexpr ptrdiff_t port_handle_offset = 5;
  523. auto pena_cmd_buf = static_memory<pena_cmd_length>();
  524. // fill the template
  525. assert(is_valid_id(port_handle));
  526. pena_cmd_template.copy(pena_cmd_buf.data(), pena_cmd_length);
  527. write_number_as_hex(port_handle, pena_cmd_buf.data() + port_handle_offset);
  528. auto ok = co_await simple_cmd_helper(pena_cmd_buf.as_string_view());
  529. co_return ok;
  530. }
  531. awaitable<bool> config_tools() {
  532. assert(port_handle_map.empty());
  533. for (size_t index = 0; index < tool_info_pool.size(); ++index) {
  534. auto &info = tool_info_pool[index];
  535. auto port_handle = co_await request_port_handle();
  536. if (!is_valid_id(port_handle)) {
  537. // TODO show log
  538. co_return false;
  539. }
  540. info.port_handle = port_handle;
  541. port_handle_map[port_handle] = index;
  542. // config port handle
  543. assert(!info.rom_path.empty());
  544. CO_ENSURE(upload_rom(port_handle, info.rom_path))
  545. CO_ENSURE(initialize_port_handle(port_handle))
  546. CO_ENSURE(enable_port_handle(port_handle))
  547. }
  548. co_return true;
  549. }
  550. awaitable<bool> start_ndi_tracking() {
  551. return simple_cmd_helper("TSTART 80\r"sv);
  552. }
  553. awaitable<bool> stop_ndi_tracking() {
  554. return simple_cmd_helper("TSTOP \r"sv);
  555. }
  556. void handle_bx_reply(dynamic_memory::pointer &&reply_buf) {
  557. auto reader = versatile_reader<ndi_endian>(*reply_buf);
  558. auto num_handle = reader.read_value<uint8_t>();
  559. auto ts = current_timestamp();
  560. for (uint8_t i = 0; i < num_handle; ++i) {
  561. auto port_handle = reader.read_value<port_handle_type>();
  562. assert(port_handle_map.contains(port_handle));
  563. auto tool_index = port_handle_map[port_handle];
  564. assert(tool_index < tool_info_pool.size());
  565. auto &info = tool_info_pool[tool_index];
  566. auto handle_status = reader.read_value<uint8_t>();
  567. uint32_t port_status, frame_number;
  568. if (handle_status != 0x01) { // not invalid
  569. reader >> port_status >> frame_number;
  570. try_update_variable<transform_obj>(info.transform_var_index, nullptr, ts);
  571. try_update_variable<double_obj>(info.rms_var_index, nullptr, ts);
  572. continue;
  573. }
  574. // normal reply
  575. float q0, qx, qy, qz, tx, ty, tz, rms;
  576. static_assert(sizeof(float) == 4);
  577. reader >> q0 >> qx >> qy >> qz;
  578. reader >> tx >> ty >> tz >> rms;
  579. reader >> port_status >> frame_number;
  580. // check frame number
  581. if (frame_number == info.last_frame_number) continue;
  582. info.last_frame_number = frame_number;
  583. auto new_trans = transform_obj::new_instance();
  584. new_trans->value = Eigen::Translation3d(tx, ty, tz) * Eigen::Quaterniond(q0, qx, qy, qz);
  585. try_update_variable<transform_obj>(info.transform_var_index, std::move(new_trans), ts);
  586. try_update_variable_value<double_obj>(info.rms_var_index, rms, ts);
  587. // TODO show log for abnormal value in port_status
  588. }
  589. auto system_status = reader.read_value<uint16_t>();
  590. // TODO show log for abnormal value in system_status
  591. }
  592. // consider unreliable transform
  593. std::string_view get_suitable_bx() const {
  594. static constexpr auto bx_cmd_reliable = "BX 0001\r"sv;
  595. static constexpr auto bx_cmd_unreliable = "BX 0801\r"sv;
  596. return accept_unreliable_transform ? bx_cmd_unreliable : bx_cmd_reliable;
  597. }
  598. // 通过 BX 指令追踪并更新 transform
  599. awaitable<bool> track_once_bx() {
  600. co_await send_command(get_suitable_bx());
  601. auto reply = co_await command_reply_queue->async_receive(use_awaitable);
  602. auto error_code = get_error_warning_code(reply->as_string_view());
  603. if (error_code != 0) {
  604. assert(error_code < 0);
  605. // TODO show error log
  606. co_return false; // ascii reply indicate error
  607. }
  608. handle_bx_reply(std::move(reply));
  609. co_return true;
  610. }
  611. awaitable<bool> start_stream(std::string_view cmd) {
  612. auto stream_cmd = fmt::format("STREAM {}\r", cmd);
  613. auto ok = co_await simple_cmd_helper(stream_cmd);
  614. co_return ok;
  615. }
  616. awaitable<bool> stop_stream(std::string_view cmd) {
  617. auto ustream_cmd = fmt::format("USTREAM {}\r", cmd);
  618. auto ok = co_await simple_cmd_helper(ustream_cmd);
  619. co_return ok;
  620. }
  621. awaitable<bool> on_init_impl() {
  622. // establish connection
  623. if (address_type == ndi_address_type::ethernet) {
  624. ndi_tcp_socket.reset(new tcp::socket(*global_context));
  625. co_await ndi_tcp_socket->async_connect({ndi_ip, ndi_port}, use_awaitable);
  626. // decrease delay
  627. tcp::no_delay no_delay_option(true);
  628. ndi_tcp_socket->set_option(no_delay_option);
  629. } else if (address_type == ndi_address_type::serial) {
  630. ndi_com_socket.reset(new serial_port(*global_context));
  631. ndi_com_socket->open(com_port_name); // will throw error if failed
  632. assert(ndi_com_socket->is_open());
  633. }
  634. // start the receiving reply coroutine
  635. assert(command_reply_queue == nullptr);
  636. command_reply_queue.reset(new reply_queue_type{*global_context});
  637. start_receive_reply();
  638. // extra config is needed for serial port
  639. if (address_type == ndi_address_type::serial) {
  640. CO_ENSURE(setup_com_socket())
  641. }
  642. ndi_api_major_version = co_await get_api_major_version();
  643. // TODO increase Param.Tracking.IlluminatorRate to 60 for Polaris Spectra device
  644. CO_ENSURE(initialize_ndi())
  645. CO_ENSURE(config_tools())
  646. co_return true;
  647. }
  648. awaitable<bool> on_start_impl() {
  649. CO_ENSURE(start_ndi_tracking())
  650. if (prefer_stream_tracking && ndi_api_major_version >= 3) { // use streaming
  651. using_stream_tracking = true;
  652. auto stream_cmd = get_suitable_bx();
  653. reply_callback_type callback = [this](dynamic_memory::pointer &&mem) {
  654. handle_bx_reply(std::move(mem));
  655. };
  656. auto stream_cmd_id = stream_cmd.substr(0, stream_cmd.size() - 1); // strip the '\r'
  657. stream_reply_callback_pool.insert(stream_cmd_id, std::move(callback));
  658. CO_ENSURE(start_stream(stream_cmd))
  659. } else { // use interval streaming
  660. assert(tracking_tools_worker == nullptr);
  661. using_stream_tracking = false;
  662. auto error_handler = [](std::exception &e) {
  663. // TODO show error
  664. };
  665. auto noexcept_worker_func = make_noexcept_func(
  666. [this]() { return track_once_bx(); },
  667. std::move(error_handler));
  668. tracking_tools_worker = make_interval_coro_worker(default_tracking_interval,
  669. std::move(noexcept_worker_func));
  670. tracking_tools_worker->run();
  671. }
  672. co_return true;
  673. }
  674. awaitable<void> on_stop_impl() {
  675. // stop tracking and streaming
  676. try {
  677. if (using_stream_tracking) {
  678. co_await stop_stream(get_suitable_bx());
  679. stream_reply_callback_pool.clear();
  680. } else {
  681. SAFE_RESET_WORKER(tracking_tools_worker)
  682. }
  683. co_await stop_ndi_tracking();
  684. } catch (std::exception &e) {
  685. // do nothing
  686. }
  687. co_return;
  688. }
  689. awaitable<void> on_reset_impl() {
  690. // stop receiving reply
  691. SAFE_RESET_WORKER(receive_reply_worker)
  692. // delete connections
  693. ndi_tcp_socket.reset(nullptr);
  694. ndi_com_socket.reset(nullptr);
  695. // clear tool info
  696. tool_info_pool.clear();
  697. port_handle_map.clear();
  698. co_return;
  699. }
  700. };
  701. ndi_interface::ndi_interface()
  702. : pimpl(std::make_unique<impl>()) {
  703. pimpl->q_this = this;
  704. }
  705. boost::asio::awaitable<bool> ndi_interface::on_init(const nlohmann::json &config) noexcept {
  706. pimpl->load_init_config(config);
  707. try {
  708. CO_ENSURE(pimpl->on_init_impl())
  709. } catch (std::exception &e) {
  710. SPDLOG_ERROR("Failed to initialize ndi: {}", e.what());
  711. co_return false;
  712. }
  713. CO_ENSURE(tristate_obj::on_init(config))
  714. co_return true;
  715. }
  716. boost::asio::awaitable<bool> ndi_interface::on_start(const nlohmann::json &config) noexcept {
  717. pimpl->load_start_config(config);
  718. try {
  719. CO_ENSURE(pimpl->on_start_impl())
  720. } catch (std::exception &e) {
  721. // TODO show log
  722. co_return false;
  723. }
  724. CO_ENSURE(tristate_obj::on_start(config))
  725. co_return true;
  726. }
  727. boost::asio::awaitable<void> ndi_interface::on_stop() noexcept {
  728. co_await pimpl->on_stop_impl();
  729. co_await tristate_obj::on_stop();
  730. co_return;
  731. }
  732. boost::asio::awaitable<void> ndi_interface::on_reset() noexcept {
  733. co_await pimpl->on_reset_impl();
  734. co_await tristate_obj::on_reset();
  735. co_return;
  736. }
  737. ndi_interface::~ndi_interface() = default;
  738. }