rpc.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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 = NULL,
  39. },
  40. {
  41. .alloc = rpc_system_gui_alloc,
  42. .free = rpc_system_gui_free,
  43. },
  44. };
  45. struct RpcSession {
  46. Rpc* rpc;
  47. FuriThread* thread;
  48. RpcHandlerDict_t handlers;
  49. StreamBufferHandle_t stream;
  50. PB_Main* decoded_message;
  51. bool terminate;
  52. void** system_contexts;
  53. bool decode_error;
  54. osMutexId_t callbacks_mutex;
  55. RpcSendBytesCallback send_bytes_callback;
  56. RpcBufferIsEmptyCallback buffer_is_empty_callback;
  57. RpcSessionClosedCallback closed_callback;
  58. RpcSessionTerminatedCallback terminated_callback;
  59. void* context;
  60. };
  61. struct Rpc {
  62. osMutexId_t busy_mutex;
  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* request, void* context) {
  66. furi_assert(request);
  67. RpcSession* session = (RpcSession*)context;
  68. furi_assert(session);
  69. rpc_send_and_release_empty(session, request->command_id, PB_CommandStatus_OK);
  70. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  71. if(session->closed_callback) {
  72. session->closed_callback(session->context);
  73. } else {
  74. FURI_LOG_W(TAG, "Session stop isn't processed by transport layer");
  75. }
  76. osMutexRelease(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. void rpc_session_set_context(RpcSession* session, void* context) {
  323. furi_assert(session);
  324. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  325. session->context = context;
  326. osMutexRelease(session->callbacks_mutex);
  327. }
  328. void rpc_session_set_close_callback(RpcSession* session, RpcSessionClosedCallback callback) {
  329. furi_assert(session);
  330. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  331. session->closed_callback = callback;
  332. osMutexRelease(session->callbacks_mutex);
  333. }
  334. void rpc_session_set_send_bytes_callback(RpcSession* session, RpcSendBytesCallback callback) {
  335. furi_assert(session);
  336. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  337. session->send_bytes_callback = callback;
  338. osMutexRelease(session->callbacks_mutex);
  339. }
  340. void rpc_session_set_buffer_is_empty_callback(
  341. RpcSession* session,
  342. RpcBufferIsEmptyCallback callback) {
  343. furi_assert(session);
  344. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  345. session->buffer_is_empty_callback = callback;
  346. osMutexRelease(session->callbacks_mutex);
  347. }
  348. void rpc_session_set_terminated_callback(
  349. RpcSession* session,
  350. RpcSessionTerminatedCallback callback) {
  351. furi_assert(session);
  352. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  353. session->terminated_callback = callback;
  354. osMutexRelease(session->callbacks_mutex);
  355. }
  356. /* Doesn't forbid using rpc_feed_bytes() after session close - it's safe.
  357. * Because any bytes received in buffer will be flushed before next session.
  358. * If bytes get into stream buffer before it's get epmtified and this
  359. * command is gets processed - it's safe either. But case of it is quite
  360. * odd: client sends close request and sends command after.
  361. */
  362. size_t
  363. rpc_session_feed(RpcSession* session, uint8_t* encoded_bytes, size_t size, TickType_t timeout) {
  364. furi_assert(session);
  365. size_t bytes_sent = xStreamBufferSend(session->stream, encoded_bytes, size, timeout);
  366. osThreadFlagsSet(furi_thread_get_thread_id(session->thread), RpcEvtNewData);
  367. return bytes_sent;
  368. }
  369. size_t rpc_session_get_available_size(RpcSession* session) {
  370. furi_assert(session);
  371. return xStreamBufferSpacesAvailable(session->stream);
  372. }
  373. bool rpc_pb_stream_read(pb_istream_t* istream, pb_byte_t* buf, size_t count) {
  374. RpcSession* session = istream->state;
  375. furi_assert(session);
  376. furi_assert(istream->bytes_left);
  377. uint32_t flags = 0;
  378. size_t bytes_received = 0;
  379. while(1) {
  380. bytes_received +=
  381. xStreamBufferReceive(session->stream, buf + bytes_received, count - bytes_received, 0);
  382. if(xStreamBufferIsEmpty(session->stream)) {
  383. if(session->buffer_is_empty_callback) {
  384. session->buffer_is_empty_callback(session->context);
  385. }
  386. }
  387. if(session->decode_error) {
  388. /* never go out till RPC_EVENT_DISCONNECT come */
  389. bytes_received = 0;
  390. }
  391. if(count == bytes_received) {
  392. break;
  393. } else {
  394. flags = osThreadFlagsWait(RPC_ALL_EVENTS, osFlagsWaitAny, osWaitForever);
  395. if(flags & RpcEvtDisconnect) {
  396. if(xStreamBufferIsEmpty(session->stream)) {
  397. session->terminate = true;
  398. istream->bytes_left = 0;
  399. bytes_received = 0;
  400. break;
  401. } else {
  402. /* Save disconnect flag and continue reading buffer */
  403. osThreadFlagsSet(furi_thread_get_thread_id(session->thread), RpcEvtDisconnect);
  404. }
  405. } else if(flags & RpcEvtNewData) {
  406. // Just wake thread up
  407. }
  408. }
  409. }
  410. #if SRV_RPC_DEBUG
  411. rpc_print_data("INPUT", buf, bytes_received);
  412. #endif
  413. return (count == bytes_received);
  414. }
  415. static bool content_callback(pb_istream_t* stream, const pb_field_t* field, void** arg) {
  416. furi_assert(stream);
  417. RpcSession* session = stream->state;
  418. furi_assert(session);
  419. RpcHandler* handler = RpcHandlerDict_get(session->handlers, field->tag);
  420. if(handler && handler->decode_submessage) {
  421. handler->decode_submessage(stream, field, arg);
  422. }
  423. return true;
  424. }
  425. static int32_t rpc_session_worker(void* context) {
  426. furi_assert(context);
  427. RpcSession* session = (RpcSession*)context;
  428. Rpc* rpc = session->rpc;
  429. FURI_LOG_D(TAG, "Session started");
  430. while(1) {
  431. pb_istream_t istream = {
  432. .callback = rpc_pb_stream_read,
  433. .state = session,
  434. .errmsg = NULL,
  435. .bytes_left = RPC_MAX_MESSAGE_SIZE, /* max incoming message size */
  436. };
  437. bool message_decode_failed = false;
  438. if(pb_decode_ex(&istream, &PB_Main_msg, session->decoded_message, PB_DECODE_DELIMITED)) {
  439. #if SRV_RPC_DEBUG
  440. FURI_LOG_I(TAG, "INPUT:");
  441. rpc_print_message(session->decoded_message);
  442. #endif
  443. RpcHandler* handler =
  444. RpcHandlerDict_get(session->handlers, session->decoded_message->which_content);
  445. if(handler && handler->message_handler) {
  446. furi_check(osMutexAcquire(rpc->busy_mutex, osWaitForever) == osOK);
  447. handler->message_handler(session->decoded_message, handler->context);
  448. furi_check(osMutexRelease(rpc->busy_mutex) == osOK);
  449. } else if(session->decoded_message->which_content == 0) {
  450. /* Receiving zeroes means message is 0-length, which
  451. * is valid for proto3: all fields are filled with default values.
  452. * 0 - is default value for which_content field.
  453. * Mark it as decode error, because there is no content message
  454. * in Main message with tag 0.
  455. */
  456. message_decode_failed = true;
  457. } else if(!handler && !session->terminate) {
  458. FURI_LOG_E(
  459. TAG,
  460. "Message(%d) decoded, but not implemented",
  461. session->decoded_message->which_content);
  462. rpc_send_and_release_empty(
  463. session,
  464. session->decoded_message->command_id,
  465. PB_CommandStatus_ERROR_NOT_IMPLEMENTED);
  466. }
  467. } else {
  468. message_decode_failed = true;
  469. }
  470. if(message_decode_failed) {
  471. xStreamBufferReset(session->stream);
  472. if(!session->terminate) {
  473. /* Protobuf can't determine start and end of message.
  474. * Handle this by adding varint at beginning
  475. * of a message (PB_ENCODE_DELIMITED). But decoding fail
  476. * means we can't be sure next bytes are varint for next
  477. * message, so the only way to close session.
  478. * RPC itself can't make decision to close session. It has
  479. * to notify:
  480. * 1) down layer (transport)
  481. * 2) other side (companion app)
  482. * Who are responsible to handle RPC session lifecycle.
  483. * Companion receives 2 messages: ERROR_DECODE and session_closed.
  484. */
  485. FURI_LOG_E(TAG, "Decode failed, error: \'%.128s\'", PB_GET_ERROR(&istream));
  486. session->decode_error = true;
  487. rpc_send_and_release_empty(session, 0, PB_CommandStatus_ERROR_DECODE);
  488. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  489. if(session->closed_callback) {
  490. session->closed_callback(session->context);
  491. }
  492. osMutexRelease(session->callbacks_mutex);
  493. }
  494. }
  495. pb_release(&PB_Main_msg, session->decoded_message);
  496. if(session->terminate) {
  497. FURI_LOG_D(TAG, "Session terminated");
  498. break;
  499. }
  500. }
  501. return 0;
  502. }
  503. static void rpc_session_free_callback(FuriThreadState thread_state, void* context) {
  504. furi_assert(context);
  505. RpcSession* session = (RpcSession*)context;
  506. if(thread_state == FuriThreadStateStopped) {
  507. for(int i = 0; i < COUNT_OF(rpc_systems); ++i) {
  508. if(rpc_systems[i].free) {
  509. rpc_systems[i].free(session->system_contexts[i]);
  510. }
  511. }
  512. free(session->system_contexts);
  513. free(session->decoded_message);
  514. RpcHandlerDict_clear(session->handlers);
  515. vStreamBufferDelete(session->stream);
  516. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  517. if(session->terminated_callback) {
  518. session->terminated_callback(session->context);
  519. }
  520. osMutexRelease(session->callbacks_mutex);
  521. osMutexDelete(session->callbacks_mutex);
  522. furi_thread_free(session->thread);
  523. free(session);
  524. }
  525. }
  526. RpcSession* rpc_session_open(Rpc* rpc) {
  527. furi_assert(rpc);
  528. RpcSession* session = malloc(sizeof(RpcSession));
  529. session->callbacks_mutex = osMutexNew(NULL);
  530. session->stream = xStreamBufferCreate(RPC_BUFFER_SIZE, 1);
  531. session->rpc = rpc;
  532. session->terminate = false;
  533. session->decode_error = false;
  534. RpcHandlerDict_init(session->handlers);
  535. session->decoded_message = malloc(sizeof(PB_Main));
  536. session->decoded_message->cb_content.funcs.decode = content_callback;
  537. session->decoded_message->cb_content.arg = session;
  538. session->system_contexts = malloc(COUNT_OF(rpc_systems) * sizeof(void*));
  539. for(int i = 0; i < COUNT_OF(rpc_systems); ++i) {
  540. session->system_contexts[i] = rpc_systems[i].alloc(session);
  541. }
  542. RpcHandler rpc_handler = {
  543. .message_handler = rpc_close_session_process,
  544. .decode_submessage = NULL,
  545. .context = session,
  546. };
  547. rpc_add_handler(session, PB_Main_stop_session_tag, &rpc_handler);
  548. session->thread = furi_thread_alloc();
  549. furi_thread_set_name(session->thread, "RpcSessionWorker");
  550. furi_thread_set_stack_size(session->thread, 2048);
  551. furi_thread_set_context(session->thread, session);
  552. furi_thread_set_callback(session->thread, rpc_session_worker);
  553. furi_thread_set_state_context(session->thread, session);
  554. furi_thread_set_state_callback(session->thread, rpc_session_free_callback);
  555. furi_thread_start(session->thread);
  556. return session;
  557. }
  558. void rpc_session_close(RpcSession* session) {
  559. furi_assert(session);
  560. furi_assert(session->rpc);
  561. rpc_session_set_send_bytes_callback(session, NULL);
  562. rpc_session_set_close_callback(session, NULL);
  563. rpc_session_set_buffer_is_empty_callback(session, NULL);
  564. osThreadFlagsSet(furi_thread_get_thread_id(session->thread), RpcEvtDisconnect);
  565. }
  566. int32_t rpc_srv(void* p) {
  567. Rpc* rpc = malloc(sizeof(Rpc));
  568. rpc->busy_mutex = osMutexNew(NULL);
  569. Cli* cli = furi_record_open("cli");
  570. cli_add_command(
  571. cli, "start_rpc_session", CliCommandFlagParallelSafe, rpc_cli_command_start_session, rpc);
  572. furi_record_create("rpc", rpc);
  573. return 0;
  574. }
  575. void rpc_add_handler(RpcSession* session, pb_size_t message_tag, RpcHandler* handler) {
  576. furi_assert(RpcHandlerDict_get(session->handlers, message_tag) == NULL);
  577. RpcHandlerDict_set_at(session->handlers, message_tag, *handler);
  578. }
  579. void rpc_send(RpcSession* session, PB_Main* message) {
  580. furi_assert(session);
  581. furi_assert(message);
  582. pb_ostream_t ostream = PB_OSTREAM_SIZING;
  583. #if SRV_RPC_DEBUG
  584. FURI_LOG_I(TAG, "OUTPUT:");
  585. rpc_print_message(message);
  586. #endif
  587. bool result = pb_encode_ex(&ostream, &PB_Main_msg, message, PB_ENCODE_DELIMITED);
  588. furi_check(result && ostream.bytes_written);
  589. uint8_t* buffer = malloc(ostream.bytes_written);
  590. ostream = pb_ostream_from_buffer(buffer, ostream.bytes_written);
  591. pb_encode_ex(&ostream, &PB_Main_msg, message, PB_ENCODE_DELIMITED);
  592. #if SRV_RPC_DEBUG
  593. rpc_print_data("OUTPUT", buffer, ostream.bytes_written);
  594. #endif
  595. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  596. if(session->send_bytes_callback) {
  597. session->send_bytes_callback(session->context, buffer, ostream.bytes_written);
  598. }
  599. osMutexRelease(session->callbacks_mutex);
  600. free(buffer);
  601. }
  602. void rpc_send_and_release(RpcSession* session, PB_Main* message) {
  603. rpc_send(session, message);
  604. pb_release(&PB_Main_msg, message);
  605. }
  606. void rpc_send_and_release_empty(RpcSession* session, uint32_t command_id, PB_CommandStatus status) {
  607. PB_Main message = {
  608. .command_id = command_id,
  609. .command_status = status,
  610. .has_next = false,
  611. .which_content = PB_Main_empty_tag,
  612. };
  613. rpc_send_and_release(session, &message);
  614. pb_release(&PB_Main_msg, &message);
  615. }