rpc.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. #include "rpc_i.h"
  2. #include <pb.h>
  3. #include <pb_decode.h>
  4. #include <pb_encode.h>
  5. #include <status.pb.h>
  6. #include <storage.pb.h>
  7. #include <flipper.pb.h>
  8. #include <cmsis_os.h>
  9. #include <cmsis_os2.h>
  10. #include <portmacro.h>
  11. #include <furi.h>
  12. #include <cli/cli.h>
  13. #include <stdint.h>
  14. #include <stdio.h>
  15. #include <stream_buffer.h>
  16. #include <m-string.h>
  17. #include <m-dict.h>
  18. #define RPC_TAG "RPC"
  19. #define RPC_EVENT_NEW_DATA (1 << 0)
  20. #define RPC_EVENT_DISCONNECT (1 << 1)
  21. #define RPC_EVENTS_ALL (RPC_EVENT_DISCONNECT | RPC_EVENT_NEW_DATA)
  22. #define DEBUG_PRINT 0
  23. DICT_DEF2(RpcHandlerDict, pb_size_t, M_DEFAULT_OPLIST, RpcHandler, M_POD_OPLIST)
  24. typedef struct {
  25. RpcSystemAlloc alloc;
  26. RpcSystemFree free;
  27. void* context;
  28. } RpcSystemCallbacks;
  29. static RpcSystemCallbacks rpc_systems[] = {
  30. {
  31. .alloc = rpc_system_status_alloc,
  32. .free = NULL,
  33. },
  34. {
  35. .alloc = rpc_system_storage_alloc,
  36. .free = rpc_system_storage_free,
  37. },
  38. {
  39. .alloc = rpc_system_app_alloc,
  40. .free = NULL,
  41. },
  42. {
  43. .alloc = rpc_system_gui_alloc,
  44. .free = rpc_system_gui_free,
  45. },
  46. };
  47. struct RpcSession {
  48. RpcSendBytesCallback send_bytes_callback;
  49. RpcBufferIsEmptyCallback buffer_is_empty_callback;
  50. RpcSessionClosedCallback closed_callback;
  51. void* context;
  52. osMutexId_t callbacks_mutex;
  53. Rpc* rpc;
  54. bool terminate;
  55. void** system_contexts;
  56. };
  57. struct Rpc {
  58. bool busy;
  59. osMutexId_t busy_mutex;
  60. RpcSession session;
  61. osEventFlagsId_t events;
  62. StreamBufferHandle_t stream;
  63. RpcHandlerDict_t handlers;
  64. PB_Main* decoded_message;
  65. };
  66. static bool content_callback(pb_istream_t* stream, const pb_field_t* field, void** arg);
  67. static void rpc_close_session_process(const PB_Main* msg_request, void* context) {
  68. furi_assert(msg_request);
  69. furi_assert(context);
  70. Rpc* rpc = context;
  71. rpc_send_and_release_empty(rpc, msg_request->command_id, PB_CommandStatus_OK);
  72. osMutexAcquire(rpc->session.callbacks_mutex, osWaitForever);
  73. if(rpc->session.closed_callback) {
  74. rpc->session.closed_callback(rpc->session.context);
  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_clean(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_ping_request_tag:
  183. string_cat_printf(str, "\tping_request {\r\n");
  184. break;
  185. case PB_Main_ping_response_tag:
  186. string_cat_printf(str, "\tping_response {\r\n");
  187. break;
  188. case PB_Main_storage_mkdir_request_tag:
  189. string_cat_printf(str, "\tmkdir {\r\n");
  190. break;
  191. case PB_Main_storage_delete_request_tag: {
  192. string_cat_printf(str, "\tdelete {\r\n");
  193. const char* path = message->content.storage_delete_request.path;
  194. if(path) {
  195. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  196. }
  197. break;
  198. }
  199. case PB_Main_empty_tag:
  200. string_cat_printf(str, "\tempty {\r\n");
  201. break;
  202. case PB_Main_storage_list_request_tag: {
  203. string_cat_printf(str, "\tlist_request {\r\n");
  204. const char* path = message->content.storage_list_request.path;
  205. if(path) {
  206. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  207. }
  208. break;
  209. }
  210. case PB_Main_storage_read_request_tag: {
  211. string_cat_printf(str, "\tread_request {\r\n");
  212. const char* path = message->content.storage_read_request.path;
  213. if(path) {
  214. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  215. }
  216. break;
  217. }
  218. case PB_Main_storage_write_request_tag: {
  219. string_cat_printf(str, "\twrite_request {\r\n");
  220. const char* path = message->content.storage_write_request.path;
  221. if(path) {
  222. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  223. }
  224. if(message->content.storage_write_request.has_file) {
  225. const PB_Storage_File* msg_file = &message->content.storage_write_request.file;
  226. rpc_sprintf_msg_file(str, "\t\t\t", msg_file, 1);
  227. }
  228. break;
  229. }
  230. case PB_Main_storage_read_response_tag:
  231. string_cat_printf(str, "\tread_response {\r\n");
  232. if(message->content.storage_read_response.has_file) {
  233. const PB_Storage_File* msg_file = &message->content.storage_read_response.file;
  234. rpc_sprintf_msg_file(str, "\t\t\t", msg_file, 1);
  235. }
  236. break;
  237. case PB_Main_storage_list_response_tag: {
  238. const PB_Storage_File* msg_file = message->content.storage_list_response.file;
  239. size_t msg_file_count = message->content.storage_list_response.file_count;
  240. string_cat_printf(str, "\tlist_response {\r\n");
  241. rpc_sprintf_msg_file(str, "\t\t", msg_file, msg_file_count);
  242. }
  243. case PB_Main_gui_start_screen_stream_request_tag:
  244. string_cat_printf(str, "\tstart_screen_stream {\r\n");
  245. break;
  246. case PB_Main_gui_stop_screen_stream_request_tag:
  247. string_cat_printf(str, "\tstop_screen_stream {\r\n");
  248. break;
  249. case PB_Main_gui_screen_stream_frame_tag:
  250. string_cat_printf(str, "\tscreen_stream_frame {\r\n");
  251. break;
  252. case PB_Main_gui_send_input_event_request_tag:
  253. string_cat_printf(str, "\tsend_input_event {\r\n");
  254. string_cat_printf(
  255. str, "\t\tkey: %d\r\n", message->content.gui_send_input_event_request.key);
  256. string_cat_printf(
  257. str, "\t\type: %d\r\n", message->content.gui_send_input_event_request.type);
  258. break;
  259. }
  260. string_cat_printf(str, "\t}\r\n}\r\n");
  261. printf("%s", string_get_cstr(str));
  262. string_clear(str);
  263. }
  264. static Rpc* rpc_alloc(void) {
  265. Rpc* rpc = furi_alloc(sizeof(Rpc));
  266. rpc->busy_mutex = osMutexNew(NULL);
  267. rpc->busy = false;
  268. rpc->events = osEventFlagsNew(NULL);
  269. rpc->stream = xStreamBufferCreate(RPC_BUFFER_SIZE, 1);
  270. rpc->decoded_message = furi_alloc(sizeof(PB_Main));
  271. rpc->decoded_message->cb_content.funcs.decode = content_callback;
  272. rpc->decoded_message->cb_content.arg = rpc;
  273. RpcHandlerDict_init(rpc->handlers);
  274. return rpc;
  275. }
  276. RpcSession* rpc_session_open(Rpc* rpc) {
  277. furi_assert(rpc);
  278. bool result = false;
  279. furi_check(osMutexAcquire(rpc->busy_mutex, osWaitForever) == osOK);
  280. if(rpc->busy) {
  281. result = false;
  282. } else {
  283. rpc->busy = true;
  284. result = true;
  285. }
  286. furi_check(osMutexRelease(rpc->busy_mutex) == osOK);
  287. if(result) {
  288. RpcSession* session = &rpc->session;
  289. session->callbacks_mutex = osMutexNew(NULL);
  290. session->rpc = rpc;
  291. session->terminate = false;
  292. xStreamBufferReset(rpc->stream);
  293. session->system_contexts = furi_alloc(COUNT_OF(rpc_systems) * sizeof(void*));
  294. for(int i = 0; i < COUNT_OF(rpc_systems); ++i) {
  295. session->system_contexts[i] = rpc_systems[i].alloc(rpc);
  296. }
  297. RpcHandler rpc_handler = {
  298. .message_handler = rpc_close_session_process,
  299. .decode_submessage = NULL,
  300. .context = rpc,
  301. };
  302. rpc_add_handler(rpc, PB_Main_stop_session_tag, &rpc_handler);
  303. FURI_LOG_D(RPC_TAG, "Session started\r\n");
  304. }
  305. return result ? &rpc->session : NULL; /* support 1 open session for now */
  306. }
  307. void rpc_session_close(RpcSession* session) {
  308. furi_assert(session);
  309. furi_assert(session->rpc);
  310. furi_assert(session->rpc->busy);
  311. rpc_session_set_send_bytes_callback(session, NULL);
  312. rpc_session_set_close_callback(session, NULL);
  313. osEventFlagsSet(session->rpc->events, RPC_EVENT_DISCONNECT);
  314. }
  315. static void rpc_free_session(RpcSession* session) {
  316. furi_assert(session);
  317. for(int i = 0; i < COUNT_OF(rpc_systems); ++i) {
  318. if(rpc_systems[i].free) {
  319. rpc_systems[i].free(session->system_contexts[i]);
  320. }
  321. }
  322. free(session->system_contexts);
  323. osMutexDelete(session->callbacks_mutex);
  324. RpcHandlerDict_clean(session->rpc->handlers);
  325. session->context = NULL;
  326. session->closed_callback = NULL;
  327. session->send_bytes_callback = NULL;
  328. session->buffer_is_empty_callback = NULL;
  329. }
  330. void rpc_session_set_context(RpcSession* session, void* context) {
  331. furi_assert(session);
  332. furi_assert(session->rpc);
  333. furi_assert(session->rpc->busy);
  334. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  335. session->context = context;
  336. osMutexRelease(session->callbacks_mutex);
  337. }
  338. void rpc_session_set_close_callback(RpcSession* session, RpcSessionClosedCallback callback) {
  339. furi_assert(session);
  340. furi_assert(session->rpc);
  341. furi_assert(session->rpc->busy);
  342. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  343. session->closed_callback = callback;
  344. osMutexRelease(session->callbacks_mutex);
  345. }
  346. void rpc_session_set_send_bytes_callback(RpcSession* session, RpcSendBytesCallback callback) {
  347. furi_assert(session);
  348. furi_assert(session->rpc);
  349. furi_assert(session->rpc->busy);
  350. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  351. session->send_bytes_callback = callback;
  352. osMutexRelease(session->callbacks_mutex);
  353. }
  354. void rpc_session_set_buffer_is_empty_callback(
  355. RpcSession* session,
  356. RpcBufferIsEmptyCallback callback) {
  357. furi_assert(session);
  358. furi_assert(callback);
  359. furi_assert(session->rpc->busy);
  360. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  361. session->buffer_is_empty_callback = callback;
  362. osMutexRelease(session->callbacks_mutex);
  363. }
  364. /* Doesn't forbid using rpc_feed_bytes() after session close - it's safe.
  365. * Because any bytes received in buffer will be flushed before next session.
  366. * If bytes get into stream buffer before it's get epmtified and this
  367. * command is gets processed - it's safe either. But case of it is quite
  368. * odd: client sends close request and sends command after.
  369. */
  370. size_t
  371. rpc_session_feed(RpcSession* session, uint8_t* encoded_bytes, size_t size, TickType_t timeout) {
  372. furi_assert(session);
  373. Rpc* rpc = session->rpc;
  374. furi_assert(rpc->busy);
  375. size_t bytes_sent = xStreamBufferSend(rpc->stream, encoded_bytes, size, timeout);
  376. osEventFlagsSet(rpc->events, RPC_EVENT_NEW_DATA);
  377. return bytes_sent;
  378. }
  379. size_t rpc_session_get_available_size(RpcSession* session) {
  380. furi_assert(session);
  381. Rpc* rpc = session->rpc;
  382. return xStreamBufferSpacesAvailable(rpc->stream);
  383. }
  384. bool rpc_pb_stream_read(pb_istream_t* istream, pb_byte_t* buf, size_t count) {
  385. Rpc* rpc = istream->state;
  386. uint32_t flags = 0;
  387. size_t bytes_received = 0;
  388. furi_assert(istream->bytes_left);
  389. while(1) {
  390. bytes_received +=
  391. xStreamBufferReceive(rpc->stream, buf + bytes_received, count - bytes_received, 0);
  392. if(xStreamBufferIsEmpty(rpc->stream)) {
  393. if(rpc->session.buffer_is_empty_callback) {
  394. rpc->session.buffer_is_empty_callback(rpc->session.context);
  395. }
  396. }
  397. if(count == bytes_received) {
  398. break;
  399. } else {
  400. flags = osEventFlagsWait(rpc->events, RPC_EVENTS_ALL, 0, osWaitForever);
  401. if(flags & RPC_EVENT_DISCONNECT) {
  402. if(xStreamBufferIsEmpty(rpc->stream)) {
  403. rpc->session.terminate = true;
  404. istream->bytes_left = 0;
  405. bytes_received = 0;
  406. break;
  407. } else {
  408. /* Save disconnect flag and continue reading buffer */
  409. osEventFlagsSet(rpc->events, RPC_EVENT_DISCONNECT);
  410. }
  411. }
  412. }
  413. }
  414. #if DEBUG_PRINT
  415. rpc_print_data("INPUT", buf, bytes_received);
  416. #endif
  417. return (count == bytes_received);
  418. }
  419. void rpc_send_and_release(Rpc* rpc, PB_Main* message) {
  420. furi_assert(rpc);
  421. furi_assert(message);
  422. RpcSession* session = &rpc->session;
  423. pb_ostream_t ostream = PB_OSTREAM_SIZING;
  424. #if DEBUG_PRINT
  425. FURI_LOG_I(RPC_TAG, "OUTPUT:");
  426. rpc_print_message(message);
  427. #endif
  428. bool result = pb_encode_ex(&ostream, &PB_Main_msg, message, PB_ENCODE_DELIMITED);
  429. furi_check(result && ostream.bytes_written);
  430. uint8_t* buffer = furi_alloc(ostream.bytes_written);
  431. ostream = pb_ostream_from_buffer(buffer, ostream.bytes_written);
  432. pb_encode_ex(&ostream, &PB_Main_msg, message, PB_ENCODE_DELIMITED);
  433. #if DEBUG_PRINT
  434. rpc_print_data("OUTPUT", buffer, ostream.bytes_written);
  435. #endif
  436. osMutexAcquire(session->callbacks_mutex, osWaitForever);
  437. if(session->send_bytes_callback) {
  438. session->send_bytes_callback(session->context, buffer, ostream.bytes_written);
  439. }
  440. osMutexRelease(session->callbacks_mutex);
  441. free(buffer);
  442. pb_release(&PB_Main_msg, message);
  443. }
  444. static bool content_callback(pb_istream_t* stream, const pb_field_t* field, void** arg) {
  445. furi_assert(stream);
  446. Rpc* rpc = *arg;
  447. RpcHandler* handler = RpcHandlerDict_get(rpc->handlers, field->tag);
  448. if(handler && handler->decode_submessage) {
  449. handler->decode_submessage(stream, field, arg);
  450. }
  451. return true;
  452. }
  453. int32_t rpc_srv(void* p) {
  454. Rpc* rpc = rpc_alloc();
  455. furi_record_create("rpc", rpc);
  456. Cli* cli = furi_record_open("cli");
  457. cli_add_command(
  458. cli, "start_rpc_session", CliCommandFlagParallelSafe, rpc_cli_command_start_session, rpc);
  459. while(1) {
  460. pb_istream_t istream = {
  461. .callback = rpc_pb_stream_read,
  462. .state = rpc,
  463. .errmsg = NULL,
  464. .bytes_left = 1024, /* max incoming message size */
  465. };
  466. if(pb_decode_ex(&istream, &PB_Main_msg, rpc->decoded_message, PB_DECODE_DELIMITED)) {
  467. #if DEBUG_PRINT
  468. FURI_LOG_I(RPC_TAG, "INPUT:");
  469. rpc_print_message(rpc->decoded_message);
  470. #endif
  471. RpcHandler* handler =
  472. RpcHandlerDict_get(rpc->handlers, rpc->decoded_message->which_content);
  473. if(handler && handler->message_handler) {
  474. handler->message_handler(rpc->decoded_message, handler->context);
  475. } else if(!handler && !rpc->session.terminate) {
  476. FURI_LOG_E(
  477. RPC_TAG, "Unhandled message, tag: %d", rpc->decoded_message->which_content);
  478. }
  479. } else {
  480. xStreamBufferReset(rpc->stream);
  481. if(!rpc->session.terminate) {
  482. FURI_LOG_E(RPC_TAG, "Decode failed, error: \'%.128s\'", PB_GET_ERROR(&istream));
  483. }
  484. }
  485. pb_release(&PB_Main_msg, rpc->decoded_message);
  486. if(rpc->session.terminate) {
  487. FURI_LOG_D(RPC_TAG, "Session terminated");
  488. osEventFlagsClear(rpc->events, RPC_EVENTS_ALL);
  489. rpc_free_session(&rpc->session);
  490. rpc->busy = false;
  491. }
  492. }
  493. return 0;
  494. }
  495. void rpc_add_handler(Rpc* rpc, pb_size_t message_tag, RpcHandler* handler) {
  496. furi_assert(RpcHandlerDict_get(rpc->handlers, message_tag) == NULL);
  497. RpcHandlerDict_set_at(rpc->handlers, message_tag, *handler);
  498. }
  499. void rpc_send_and_release_empty(Rpc* rpc, uint32_t command_id, PB_CommandStatus status) {
  500. PB_Main message = {
  501. .command_id = command_id,
  502. .command_status = status,
  503. .has_next = false,
  504. .which_content = PB_Main_empty_tag,
  505. };
  506. rpc_send_and_release(rpc, &message);
  507. pb_release(&PB_Main_msg, &message);
  508. }