rpc.c 18 KB

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