rpc.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. #include "rpc_i.h"
  2. #include <pb.h>
  3. #include <pb_decode.h>
  4. #include <pb_encode.h>
  5. #include <storage.pb.h>
  6. #include <flipper.pb.h>
  7. #include <portmacro.h>
  8. #include <furi.h>
  9. #include <cli/cli.h>
  10. #include <stdint.h>
  11. #include <stdio.h>
  12. #include <stream_buffer.h>
  13. #include <m-string.h>
  14. #include <m-dict.h>
  15. #define TAG "RpcSrv"
  16. typedef enum {
  17. RpcEvtNewData = (1 << 0),
  18. RpcEvtDisconnect = (1 << 1),
  19. } RpcEvtFlags;
  20. #define RPC_ALL_EVENTS (RpcEvtNewData | RpcEvtDisconnect)
  21. DICT_DEF2(RpcHandlerDict, pb_size_t, M_DEFAULT_OPLIST, RpcHandler, M_POD_OPLIST)
  22. typedef struct {
  23. RpcSystemAlloc alloc;
  24. RpcSystemFree free;
  25. void* context;
  26. } RpcSystemCallbacks;
  27. static RpcSystemCallbacks rpc_systems[] = {
  28. {
  29. .alloc = rpc_system_system_alloc,
  30. .free = NULL,
  31. },
  32. {
  33. .alloc = rpc_system_storage_alloc,
  34. .free = rpc_system_storage_free,
  35. },
  36. {
  37. .alloc = rpc_system_app_alloc,
  38. .free = rpc_system_app_free,
  39. },
  40. {
  41. .alloc = rpc_system_gui_alloc,
  42. .free = rpc_system_gui_free,
  43. },
  44. {
  45. .alloc = rpc_system_gpio_alloc,
  46. .free = NULL,
  47. }};
  48. struct RpcSession {
  49. Rpc* rpc;
  50. FuriThread* thread;
  51. RpcHandlerDict_t handlers;
  52. StreamBufferHandle_t stream;
  53. PB_Main* decoded_message;
  54. bool terminate;
  55. void** system_contexts;
  56. bool decode_error;
  57. FuriMutex* callbacks_mutex;
  58. RpcSendBytesCallback send_bytes_callback;
  59. RpcBufferIsEmptyCallback buffer_is_empty_callback;
  60. RpcSessionClosedCallback closed_callback;
  61. RpcSessionTerminatedCallback terminated_callback;
  62. void* context;
  63. };
  64. struct Rpc {
  65. FuriMutex* busy_mutex;
  66. };
  67. static bool content_callback(pb_istream_t* stream, const pb_field_t* field, void** arg);
  68. static void rpc_close_session_process(const PB_Main* request, void* context) {
  69. furi_assert(request);
  70. RpcSession* session = (RpcSession*)context;
  71. furi_assert(session);
  72. rpc_send_and_release_empty(session, request->command_id, PB_CommandStatus_OK);
  73. furi_mutex_acquire(session->callbacks_mutex, FuriWaitForever);
  74. if(session->closed_callback) {
  75. session->closed_callback(session->context);
  76. } else {
  77. FURI_LOG_W(TAG, "Session stop isn't processed by transport layer");
  78. }
  79. furi_mutex_release(session->callbacks_mutex);
  80. }
  81. static size_t rpc_sprintf_msg_file(
  82. string_t str,
  83. const char* prefix,
  84. const PB_Storage_File* msg_file,
  85. size_t msg_files_size) {
  86. size_t cnt = 0;
  87. for(size_t i = 0; i < msg_files_size; ++i, ++msg_file) {
  88. string_cat_printf(
  89. str,
  90. "%s[%c] size: %5ld",
  91. prefix,
  92. msg_file->type == PB_Storage_File_FileType_DIR ? 'd' : 'f',
  93. msg_file->size);
  94. if(msg_file->name) {
  95. string_cat_printf(str, " \'%s\'", msg_file->name);
  96. }
  97. if(msg_file->data && msg_file->data->size) {
  98. string_cat_printf(
  99. str,
  100. " (%d):\'%.*s%s\'",
  101. msg_file->data->size,
  102. MIN(msg_file->data->size, 30),
  103. msg_file->data->bytes,
  104. msg_file->data->size > 30 ? "..." : "");
  105. }
  106. string_cat_printf(str, "\r\n");
  107. }
  108. return cnt;
  109. }
  110. void rpc_print_data(const char* prefix, uint8_t* buffer, size_t size) {
  111. string_t str;
  112. string_init(str);
  113. string_reserve(str, 100 + size * 5);
  114. string_cat_printf(str, "\r\n%s DEC(%d): {", prefix, size);
  115. for(size_t i = 0; i < size; ++i) {
  116. string_cat_printf(str, "%d, ", buffer[i]);
  117. }
  118. string_cat_printf(str, "}\r\n");
  119. printf("%s", string_get_cstr(str));
  120. string_reset(str);
  121. string_reserve(str, 100 + size * 3);
  122. string_cat_printf(str, "%s HEX(%d): {", prefix, size);
  123. for(size_t i = 0; i < size; ++i) {
  124. string_cat_printf(str, "%02X", buffer[i]);
  125. }
  126. string_cat_printf(str, "}\r\n\r\n");
  127. printf("%s", string_get_cstr(str));
  128. string_clear(str);
  129. }
  130. void rpc_print_message(const PB_Main* message) {
  131. string_t str;
  132. string_init(str);
  133. string_cat_printf(
  134. str,
  135. "PB_Main: {\r\n\tresult: %d cmd_id: %ld (%s)\r\n",
  136. message->command_status,
  137. message->command_id,
  138. message->has_next ? "has_next" : "last");
  139. switch(message->which_content) {
  140. default:
  141. /* not implemented yet */
  142. string_cat_printf(str, "\tNOT_IMPLEMENTED (%d) {\r\n", message->which_content);
  143. break;
  144. case PB_Main_stop_session_tag:
  145. string_cat_printf(str, "\tstop_session {\r\n");
  146. break;
  147. case PB_Main_app_start_request_tag: {
  148. string_cat_printf(str, "\tapp_start {\r\n");
  149. const char* name = message->content.app_start_request.name;
  150. const char* args = message->content.app_start_request.args;
  151. if(name) {
  152. string_cat_printf(str, "\t\tname: %s\r\n", name);
  153. }
  154. if(args) {
  155. string_cat_printf(str, "\t\targs: %s\r\n", args);
  156. }
  157. break;
  158. }
  159. case PB_Main_app_lock_status_request_tag: {
  160. string_cat_printf(str, "\tapp_lock_status_request {\r\n");
  161. break;
  162. }
  163. case PB_Main_app_lock_status_response_tag: {
  164. string_cat_printf(str, "\tapp_lock_status_response {\r\n");
  165. bool lock_status = message->content.app_lock_status_response.locked;
  166. string_cat_printf(str, "\t\tlocked: %s\r\n", lock_status ? "true" : "false");
  167. break;
  168. }
  169. case PB_Main_storage_md5sum_request_tag: {
  170. string_cat_printf(str, "\tmd5sum_request {\r\n");
  171. const char* path = message->content.storage_md5sum_request.path;
  172. if(path) {
  173. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  174. }
  175. break;
  176. }
  177. case PB_Main_storage_md5sum_response_tag: {
  178. string_cat_printf(str, "\tmd5sum_response {\r\n");
  179. const char* path = message->content.storage_md5sum_response.md5sum;
  180. if(path) {
  181. string_cat_printf(str, "\t\tmd5sum: %s\r\n", path);
  182. }
  183. break;
  184. }
  185. case PB_Main_system_ping_request_tag:
  186. string_cat_printf(str, "\tping_request {\r\n");
  187. break;
  188. case PB_Main_system_ping_response_tag:
  189. string_cat_printf(str, "\tping_response {\r\n");
  190. break;
  191. case PB_Main_system_device_info_request_tag:
  192. string_cat_printf(str, "\tdevice_info_request {\r\n");
  193. break;
  194. case PB_Main_system_device_info_response_tag:
  195. string_cat_printf(str, "\tdevice_info_response {\r\n");
  196. string_cat_printf(
  197. str,
  198. "\t\t%s: %s\r\n",
  199. message->content.system_device_info_response.key,
  200. message->content.system_device_info_response.value);
  201. break;
  202. case PB_Main_storage_mkdir_request_tag:
  203. string_cat_printf(str, "\tmkdir {\r\n");
  204. break;
  205. case PB_Main_storage_delete_request_tag: {
  206. string_cat_printf(str, "\tdelete {\r\n");
  207. const char* path = message->content.storage_delete_request.path;
  208. if(path) {
  209. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  210. }
  211. break;
  212. }
  213. case PB_Main_empty_tag:
  214. string_cat_printf(str, "\tempty {\r\n");
  215. break;
  216. case PB_Main_storage_info_request_tag: {
  217. string_cat_printf(str, "\tinfo_request {\r\n");
  218. const char* path = message->content.storage_info_request.path;
  219. if(path) {
  220. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  221. }
  222. break;
  223. }
  224. case PB_Main_storage_info_response_tag: {
  225. string_cat_printf(str, "\tinfo_response {\r\n");
  226. string_cat_printf(
  227. str, "\t\ttotal_space: %lu\r\n", message->content.storage_info_response.total_space);
  228. string_cat_printf(
  229. str, "\t\tfree_space: %lu\r\n", message->content.storage_info_response.free_space);
  230. break;
  231. }
  232. case PB_Main_storage_stat_request_tag: {
  233. string_cat_printf(str, "\tstat_request {\r\n");
  234. const char* path = message->content.storage_stat_request.path;
  235. if(path) {
  236. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  237. }
  238. break;
  239. }
  240. case PB_Main_storage_stat_response_tag: {
  241. string_cat_printf(str, "\tstat_response {\r\n");
  242. if(message->content.storage_stat_response.has_file) {
  243. const PB_Storage_File* msg_file = &message->content.storage_stat_response.file;
  244. rpc_sprintf_msg_file(str, "\t\t\t", msg_file, 1);
  245. }
  246. break;
  247. }
  248. case PB_Main_storage_list_request_tag: {
  249. string_cat_printf(str, "\tlist_request {\r\n");
  250. const char* path = message->content.storage_list_request.path;
  251. if(path) {
  252. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  253. }
  254. break;
  255. }
  256. case PB_Main_storage_read_request_tag: {
  257. string_cat_printf(str, "\tread_request {\r\n");
  258. const char* path = message->content.storage_read_request.path;
  259. if(path) {
  260. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  261. }
  262. break;
  263. }
  264. case PB_Main_storage_write_request_tag: {
  265. string_cat_printf(str, "\twrite_request {\r\n");
  266. const char* path = message->content.storage_write_request.path;
  267. if(path) {
  268. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  269. }
  270. if(message->content.storage_write_request.has_file) {
  271. const PB_Storage_File* msg_file = &message->content.storage_write_request.file;
  272. rpc_sprintf_msg_file(str, "\t\t\t", msg_file, 1);
  273. }
  274. break;
  275. }
  276. case PB_Main_storage_read_response_tag:
  277. string_cat_printf(str, "\tread_response {\r\n");
  278. if(message->content.storage_read_response.has_file) {
  279. const PB_Storage_File* msg_file = &message->content.storage_read_response.file;
  280. rpc_sprintf_msg_file(str, "\t\t\t", msg_file, 1);
  281. }
  282. break;
  283. case PB_Main_storage_list_response_tag: {
  284. const PB_Storage_File* msg_file = message->content.storage_list_response.file;
  285. size_t msg_file_count = message->content.storage_list_response.file_count;
  286. string_cat_printf(str, "\tlist_response {\r\n");
  287. rpc_sprintf_msg_file(str, "\t\t", msg_file, msg_file_count);
  288. break;
  289. }
  290. case PB_Main_storage_rename_request_tag: {
  291. string_cat_printf(str, "\trename_request {\r\n");
  292. string_cat_printf(
  293. str, "\t\told_path: %s\r\n", message->content.storage_rename_request.old_path);
  294. string_cat_printf(
  295. str, "\t\tnew_path: %s\r\n", message->content.storage_rename_request.new_path);
  296. break;
  297. }
  298. case PB_Main_gui_start_screen_stream_request_tag:
  299. string_cat_printf(str, "\tstart_screen_stream {\r\n");
  300. break;
  301. case PB_Main_gui_stop_screen_stream_request_tag:
  302. string_cat_printf(str, "\tstop_screen_stream {\r\n");
  303. break;
  304. case PB_Main_gui_screen_frame_tag:
  305. string_cat_printf(str, "\tscreen_frame {\r\n");
  306. break;
  307. case PB_Main_gui_send_input_event_request_tag:
  308. string_cat_printf(str, "\tsend_input_event {\r\n");
  309. string_cat_printf(
  310. str, "\t\tkey: %d\r\n", message->content.gui_send_input_event_request.key);
  311. string_cat_printf(
  312. str, "\t\type: %d\r\n", message->content.gui_send_input_event_request.type);
  313. break;
  314. case PB_Main_gui_start_virtual_display_request_tag:
  315. string_cat_printf(str, "\tstart_virtual_display {\r\n");
  316. break;
  317. case PB_Main_gui_stop_virtual_display_request_tag:
  318. string_cat_printf(str, "\tstop_virtual_display {\r\n");
  319. break;
  320. }
  321. string_cat_printf(str, "\t}\r\n}\r\n");
  322. printf("%s", string_get_cstr(str));
  323. string_clear(str);
  324. }
  325. void rpc_session_set_context(RpcSession* session, void* context) {
  326. furi_assert(session);
  327. furi_mutex_acquire(session->callbacks_mutex, FuriWaitForever);
  328. session->context = context;
  329. furi_mutex_release(session->callbacks_mutex);
  330. }
  331. void rpc_session_set_close_callback(RpcSession* session, RpcSessionClosedCallback callback) {
  332. furi_assert(session);
  333. furi_mutex_acquire(session->callbacks_mutex, FuriWaitForever);
  334. session->closed_callback = callback;
  335. furi_mutex_release(session->callbacks_mutex);
  336. }
  337. void rpc_session_set_send_bytes_callback(RpcSession* session, RpcSendBytesCallback callback) {
  338. furi_assert(session);
  339. furi_mutex_acquire(session->callbacks_mutex, FuriWaitForever);
  340. session->send_bytes_callback = callback;
  341. furi_mutex_release(session->callbacks_mutex);
  342. }
  343. void rpc_session_set_buffer_is_empty_callback(
  344. RpcSession* session,
  345. RpcBufferIsEmptyCallback callback) {
  346. furi_assert(session);
  347. furi_mutex_acquire(session->callbacks_mutex, FuriWaitForever);
  348. session->buffer_is_empty_callback = callback;
  349. furi_mutex_release(session->callbacks_mutex);
  350. }
  351. void rpc_session_set_terminated_callback(
  352. RpcSession* session,
  353. RpcSessionTerminatedCallback callback) {
  354. furi_assert(session);
  355. furi_mutex_acquire(session->callbacks_mutex, FuriWaitForever);
  356. session->terminated_callback = callback;
  357. furi_mutex_release(session->callbacks_mutex);
  358. }
  359. /* Doesn't forbid using rpc_feed_bytes() after session close - it's safe.
  360. * Because any bytes received in buffer will be flushed before next session.
  361. * If bytes get into stream buffer before it's get epmtified and this
  362. * command is gets processed - it's safe either. But case of it is quite
  363. * odd: client sends close request and sends command after.
  364. */
  365. size_t
  366. rpc_session_feed(RpcSession* session, uint8_t* encoded_bytes, size_t size, TickType_t timeout) {
  367. furi_assert(session);
  368. size_t bytes_sent = xStreamBufferSend(session->stream, encoded_bytes, size, timeout);
  369. furi_thread_flags_set(furi_thread_get_id(session->thread), RpcEvtNewData);
  370. return bytes_sent;
  371. }
  372. size_t rpc_session_get_available_size(RpcSession* session) {
  373. furi_assert(session);
  374. return xStreamBufferSpacesAvailable(session->stream);
  375. }
  376. bool rpc_pb_stream_read(pb_istream_t* istream, pb_byte_t* buf, size_t count) {
  377. RpcSession* session = istream->state;
  378. furi_assert(session);
  379. furi_assert(istream->bytes_left);
  380. uint32_t flags = 0;
  381. size_t bytes_received = 0;
  382. while(1) {
  383. bytes_received +=
  384. xStreamBufferReceive(session->stream, buf + bytes_received, count - bytes_received, 0);
  385. if(xStreamBufferIsEmpty(session->stream)) {
  386. if(session->buffer_is_empty_callback) {
  387. session->buffer_is_empty_callback(session->context);
  388. }
  389. }
  390. if(session->decode_error) {
  391. /* never go out till RPC_EVENT_DISCONNECT come */
  392. bytes_received = 0;
  393. }
  394. if(count == bytes_received) {
  395. break;
  396. } else {
  397. flags = furi_thread_flags_wait(RPC_ALL_EVENTS, FuriFlagWaitAny, FuriWaitForever);
  398. if(flags & RpcEvtDisconnect) {
  399. if(xStreamBufferIsEmpty(session->stream)) {
  400. session->terminate = true;
  401. istream->bytes_left = 0;
  402. bytes_received = 0;
  403. break;
  404. } else {
  405. /* Save disconnect flag and continue reading buffer */
  406. furi_thread_flags_set(furi_thread_get_id(session->thread), RpcEvtDisconnect);
  407. }
  408. } else if(flags & RpcEvtNewData) {
  409. // Just wake thread up
  410. }
  411. }
  412. }
  413. #if SRV_RPC_DEBUG
  414. rpc_print_data("INPUT", buf, bytes_received);
  415. #endif
  416. return (count == bytes_received);
  417. }
  418. static bool content_callback(pb_istream_t* stream, const pb_field_t* field, void** arg) {
  419. furi_assert(stream);
  420. RpcSession* session = stream->state;
  421. furi_assert(session);
  422. RpcHandler* handler = RpcHandlerDict_get(session->handlers, field->tag);
  423. if(handler && handler->decode_submessage) {
  424. handler->decode_submessage(stream, field, arg);
  425. }
  426. return true;
  427. }
  428. static int32_t rpc_session_worker(void* context) {
  429. furi_assert(context);
  430. RpcSession* session = (RpcSession*)context;
  431. Rpc* rpc = session->rpc;
  432. FURI_LOG_D(TAG, "Session started");
  433. while(1) {
  434. pb_istream_t istream = {
  435. .callback = rpc_pb_stream_read,
  436. .state = session,
  437. .errmsg = NULL,
  438. .bytes_left = RPC_MAX_MESSAGE_SIZE, /* max incoming message size */
  439. };
  440. bool message_decode_failed = false;
  441. if(pb_decode_ex(&istream, &PB_Main_msg, session->decoded_message, PB_DECODE_DELIMITED)) {
  442. #if SRV_RPC_DEBUG
  443. FURI_LOG_I(TAG, "INPUT:");
  444. rpc_print_message(session->decoded_message);
  445. #endif
  446. RpcHandler* handler =
  447. RpcHandlerDict_get(session->handlers, session->decoded_message->which_content);
  448. if(handler && handler->message_handler) {
  449. furi_check(furi_mutex_acquire(rpc->busy_mutex, FuriWaitForever) == FuriStatusOk);
  450. handler->message_handler(session->decoded_message, handler->context);
  451. furi_check(furi_mutex_release(rpc->busy_mutex) == FuriStatusOk);
  452. } else if(session->decoded_message->which_content == 0) {
  453. /* Receiving zeroes means message is 0-length, which
  454. * is valid for proto3: all fields are filled with default values.
  455. * 0 - is default value for which_content field.
  456. * Mark it as decode error, because there is no content message
  457. * in Main message with tag 0.
  458. */
  459. message_decode_failed = true;
  460. } else if(!handler && !session->terminate) {
  461. FURI_LOG_E(
  462. TAG,
  463. "Message(%d) decoded, but not implemented",
  464. session->decoded_message->which_content);
  465. rpc_send_and_release_empty(
  466. session,
  467. session->decoded_message->command_id,
  468. PB_CommandStatus_ERROR_NOT_IMPLEMENTED);
  469. }
  470. } else {
  471. message_decode_failed = true;
  472. }
  473. if(message_decode_failed) {
  474. xStreamBufferReset(session->stream);
  475. if(!session->terminate) {
  476. /* Protobuf can't determine start and end of message.
  477. * Handle this by adding varint at beginning
  478. * of a message (PB_ENCODE_DELIMITED). But decoding fail
  479. * means we can't be sure next bytes are varint for next
  480. * message, so the only way to close session.
  481. * RPC itself can't make decision to close session. It has
  482. * to notify:
  483. * 1) down layer (transport)
  484. * 2) other side (companion app)
  485. * Who are responsible to handle RPC session lifecycle.
  486. * Companion receives 2 messages: ERROR_DECODE and session_closed.
  487. */
  488. FURI_LOG_E(TAG, "Decode failed, error: \'%.128s\'", PB_GET_ERROR(&istream));
  489. session->decode_error = true;
  490. rpc_send_and_release_empty(session, 0, PB_CommandStatus_ERROR_DECODE);
  491. furi_mutex_acquire(session->callbacks_mutex, FuriWaitForever);
  492. if(session->closed_callback) {
  493. session->closed_callback(session->context);
  494. }
  495. furi_mutex_release(session->callbacks_mutex);
  496. }
  497. }
  498. pb_release(&PB_Main_msg, session->decoded_message);
  499. if(session->terminate) {
  500. FURI_LOG_D(TAG, "Session terminated");
  501. break;
  502. }
  503. }
  504. return 0;
  505. }
  506. static void rpc_session_free_callback(FuriThreadState thread_state, void* context) {
  507. furi_assert(context);
  508. RpcSession* session = (RpcSession*)context;
  509. if(thread_state == FuriThreadStateStopped) {
  510. for(size_t i = 0; i < COUNT_OF(rpc_systems); ++i) {
  511. if(rpc_systems[i].free) {
  512. rpc_systems[i].free(session->system_contexts[i]);
  513. }
  514. }
  515. free(session->system_contexts);
  516. free(session->decoded_message);
  517. RpcHandlerDict_clear(session->handlers);
  518. vStreamBufferDelete(session->stream);
  519. furi_mutex_acquire(session->callbacks_mutex, FuriWaitForever);
  520. if(session->terminated_callback) {
  521. session->terminated_callback(session->context);
  522. }
  523. furi_mutex_release(session->callbacks_mutex);
  524. furi_mutex_free(session->callbacks_mutex);
  525. furi_thread_free(session->thread);
  526. free(session);
  527. }
  528. }
  529. RpcSession* rpc_session_open(Rpc* rpc) {
  530. furi_assert(rpc);
  531. RpcSession* session = malloc(sizeof(RpcSession));
  532. session->callbacks_mutex = furi_mutex_alloc(FuriMutexTypeNormal);
  533. session->stream = xStreamBufferCreate(RPC_BUFFER_SIZE, 1);
  534. session->rpc = rpc;
  535. session->terminate = false;
  536. session->decode_error = false;
  537. RpcHandlerDict_init(session->handlers);
  538. session->decoded_message = malloc(sizeof(PB_Main));
  539. session->decoded_message->cb_content.funcs.decode = content_callback;
  540. session->decoded_message->cb_content.arg = session;
  541. session->system_contexts = malloc(COUNT_OF(rpc_systems) * sizeof(void*));
  542. for(size_t i = 0; i < COUNT_OF(rpc_systems); ++i) {
  543. session->system_contexts[i] = rpc_systems[i].alloc(session);
  544. }
  545. RpcHandler rpc_handler = {
  546. .message_handler = rpc_close_session_process,
  547. .decode_submessage = NULL,
  548. .context = session,
  549. };
  550. rpc_add_handler(session, PB_Main_stop_session_tag, &rpc_handler);
  551. session->thread = furi_thread_alloc();
  552. furi_thread_set_name(session->thread, "RpcSessionWorker");
  553. furi_thread_set_stack_size(session->thread, 2048);
  554. furi_thread_set_context(session->thread, session);
  555. furi_thread_set_callback(session->thread, rpc_session_worker);
  556. furi_thread_set_state_context(session->thread, session);
  557. furi_thread_set_state_callback(session->thread, rpc_session_free_callback);
  558. furi_thread_start(session->thread);
  559. return session;
  560. }
  561. void rpc_session_close(RpcSession* session) {
  562. furi_assert(session);
  563. furi_assert(session->rpc);
  564. rpc_session_set_send_bytes_callback(session, NULL);
  565. rpc_session_set_close_callback(session, NULL);
  566. rpc_session_set_buffer_is_empty_callback(session, NULL);
  567. furi_thread_flags_set(furi_thread_get_id(session->thread), RpcEvtDisconnect);
  568. }
  569. int32_t rpc_srv(void* p) {
  570. UNUSED(p);
  571. Rpc* rpc = malloc(sizeof(Rpc));
  572. rpc->busy_mutex = furi_mutex_alloc(FuriMutexTypeNormal);
  573. Cli* cli = furi_record_open(RECORD_CLI);
  574. cli_add_command(
  575. cli, "start_rpc_session", CliCommandFlagParallelSafe, rpc_cli_command_start_session, rpc);
  576. furi_record_create(RECORD_RPC, rpc);
  577. return 0;
  578. }
  579. void rpc_add_handler(RpcSession* session, pb_size_t message_tag, RpcHandler* handler) {
  580. furi_assert(RpcHandlerDict_get(session->handlers, message_tag) == NULL);
  581. RpcHandlerDict_set_at(session->handlers, message_tag, *handler);
  582. }
  583. void rpc_send(RpcSession* session, PB_Main* message) {
  584. furi_assert(session);
  585. furi_assert(message);
  586. pb_ostream_t ostream = PB_OSTREAM_SIZING;
  587. #if SRV_RPC_DEBUG
  588. FURI_LOG_I(TAG, "OUTPUT:");
  589. rpc_print_message(message);
  590. #endif
  591. bool result = pb_encode_ex(&ostream, &PB_Main_msg, message, PB_ENCODE_DELIMITED);
  592. furi_check(result && ostream.bytes_written);
  593. uint8_t* buffer = malloc(ostream.bytes_written);
  594. ostream = pb_ostream_from_buffer(buffer, ostream.bytes_written);
  595. pb_encode_ex(&ostream, &PB_Main_msg, message, PB_ENCODE_DELIMITED);
  596. #if SRV_RPC_DEBUG
  597. rpc_print_data("OUTPUT", buffer, ostream.bytes_written);
  598. #endif
  599. furi_mutex_acquire(session->callbacks_mutex, FuriWaitForever);
  600. if(session->send_bytes_callback) {
  601. session->send_bytes_callback(session->context, buffer, ostream.bytes_written);
  602. }
  603. furi_mutex_release(session->callbacks_mutex);
  604. free(buffer);
  605. }
  606. void rpc_send_and_release(RpcSession* session, PB_Main* message) {
  607. rpc_send(session, message);
  608. pb_release(&PB_Main_msg, message);
  609. }
  610. void rpc_send_and_release_empty(RpcSession* session, uint32_t command_id, PB_CommandStatus status) {
  611. PB_Main message = {
  612. .command_id = command_id,
  613. .command_status = status,
  614. .has_next = false,
  615. .which_content = PB_Main_empty_tag,
  616. };
  617. rpc_send_and_release(session, &message);
  618. pb_release(&PB_Main_msg, &message);
  619. }