rpc.c 23 KB

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