rpc.c 24 KB

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