rpc.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. #include "cmsis_os.h"
  2. #include "cmsis_os2.h"
  3. #include "flipper.pb.h"
  4. #include "furi-hal-delay.h"
  5. #include "furi/check.h"
  6. #include "furi/log.h"
  7. #include <m-string.h>
  8. #include "pb.h"
  9. #include "pb_decode.h"
  10. #include "pb_encode.h"
  11. #include "portmacro.h"
  12. #include "status.pb.h"
  13. #include "storage.pb.h"
  14. #include <stdint.h>
  15. #include <stdio.h>
  16. #include <furi.h>
  17. #include <stream_buffer.h>
  18. #include <m-dict.h>
  19. #include "rpc_i.h"
  20. #define RPC_TAG "RPC"
  21. #define RPC_EVENT_NEW_DATA (1 << 0)
  22. #define RPC_EVENT_DISCONNECT (1 << 1)
  23. #define RPC_EVENTS_ALL (RPC_EVENT_DISCONNECT | RPC_EVENT_NEW_DATA)
  24. #define DEBUG_PRINT 0
  25. DICT_DEF2(RpcHandlerDict, pb_size_t, M_DEFAULT_OPLIST, RpcHandler, M_POD_OPLIST)
  26. typedef struct {
  27. RpcSystemAlloc alloc;
  28. RpcSystemFree free;
  29. void* context;
  30. } RpcSystemCallbacks;
  31. static RpcSystemCallbacks rpc_systems[] = {
  32. {
  33. .alloc = rpc_system_status_alloc,
  34. .free = NULL,
  35. },
  36. {
  37. .alloc = rpc_system_storage_alloc,
  38. .free = rpc_system_storage_free,
  39. },
  40. {
  41. .alloc = rpc_system_app_alloc,
  42. .free = NULL,
  43. },
  44. };
  45. struct RpcSession {
  46. RpcSendBytesCallback send_bytes_callback;
  47. void* send_bytes_context;
  48. osMutexId_t send_bytes_mutex;
  49. Rpc* rpc;
  50. bool terminate_session;
  51. void** system_contexts;
  52. };
  53. struct Rpc {
  54. bool busy;
  55. osMutexId_t busy_mutex;
  56. RpcSession session;
  57. osEventFlagsId_t events;
  58. StreamBufferHandle_t stream;
  59. RpcHandlerDict_t handlers;
  60. PB_Main* decoded_message;
  61. };
  62. static bool content_callback(pb_istream_t* stream, const pb_field_t* field, void** arg);
  63. static size_t rpc_sprintf_msg_file(
  64. string_t str,
  65. const char* prefix,
  66. const PB_Storage_File* msg_file,
  67. size_t msg_files_size) {
  68. size_t cnt = 0;
  69. for(int i = 0; i < msg_files_size; ++i, ++msg_file) {
  70. string_cat_printf(
  71. str,
  72. "%s[%c] size: %5ld",
  73. prefix,
  74. msg_file->type == PB_Storage_File_FileType_DIR ? 'd' : 'f',
  75. msg_file->size);
  76. if(msg_file->name) {
  77. string_cat_printf(str, " \'%s\'", msg_file->name);
  78. }
  79. if(msg_file->data && msg_file->data->size) {
  80. string_cat_printf(
  81. str,
  82. " (%d):\'%.*s%s\'",
  83. msg_file->data->size,
  84. MIN(msg_file->data->size, 30),
  85. msg_file->data->bytes,
  86. msg_file->data->size > 30 ? "..." : "");
  87. }
  88. string_cat_printf(str, "\r\n");
  89. }
  90. return cnt;
  91. }
  92. void rpc_print_message(const PB_Main* message) {
  93. string_t str;
  94. string_init(str);
  95. string_cat_printf(
  96. str,
  97. "PB_Main: {\r\n\tresult: %d cmd_id: %ld (%s)\r\n",
  98. message->command_status,
  99. message->command_id,
  100. message->has_next ? "has_next" : "last");
  101. switch(message->which_content) {
  102. default:
  103. /* not implemented yet */
  104. string_cat_printf(str, "\tNOT_IMPLEMENTED (%d) {\r\n", message->which_content);
  105. break;
  106. case PB_Main_app_start_tag: {
  107. string_cat_printf(str, "\tapp_start {\r\n");
  108. const char* name = message->content.app_start.name;
  109. const char* args = message->content.app_start.args;
  110. if(name) {
  111. string_cat_printf(str, "\t\tname: %s\r\n", name);
  112. }
  113. if(args) {
  114. string_cat_printf(str, "\t\targs: %s\r\n", args);
  115. }
  116. break;
  117. }
  118. case PB_Main_app_lock_status_request_tag: {
  119. string_cat_printf(str, "\tapp_lock_status_request {\r\n");
  120. break;
  121. }
  122. case PB_Main_app_lock_status_response_tag: {
  123. string_cat_printf(str, "\tapp_lock_status_response {\r\n");
  124. bool lock_status = message->content.app_lock_status_response.locked;
  125. string_cat_printf(str, "\t\tlocked: %s\r\n", lock_status ? "true" : "false");
  126. break;
  127. }
  128. case PB_Main_storage_md5sum_request_tag: {
  129. string_cat_printf(str, "\tmd5sum_request {\r\n");
  130. const char* path = message->content.storage_md5sum_request.path;
  131. if(path) {
  132. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  133. }
  134. break;
  135. }
  136. case PB_Main_storage_md5sum_response_tag: {
  137. string_cat_printf(str, "\tmd5sum_response {\r\n");
  138. const char* path = message->content.storage_md5sum_response.md5sum;
  139. if(path) {
  140. string_cat_printf(str, "\t\tmd5sum: %s\r\n", path);
  141. }
  142. break;
  143. }
  144. case PB_Main_ping_request_tag:
  145. string_cat_printf(str, "\tping_request {\r\n");
  146. break;
  147. case PB_Main_ping_response_tag:
  148. string_cat_printf(str, "\tping_response {\r\n");
  149. break;
  150. case PB_Main_storage_mkdir_request_tag:
  151. string_cat_printf(str, "\tmkdir {\r\n");
  152. break;
  153. case PB_Main_storage_delete_request_tag: {
  154. string_cat_printf(str, "\tdelete {\r\n");
  155. const char* path = message->content.storage_delete_request.path;
  156. if(path) {
  157. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  158. }
  159. break;
  160. }
  161. case PB_Main_empty_tag:
  162. string_cat_printf(str, "\tempty {\r\n");
  163. break;
  164. case PB_Main_storage_list_request_tag: {
  165. string_cat_printf(str, "\tlist_request {\r\n");
  166. const char* path = message->content.storage_list_request.path;
  167. if(path) {
  168. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  169. }
  170. break;
  171. }
  172. case PB_Main_storage_read_request_tag: {
  173. string_cat_printf(str, "\tread_request {\r\n");
  174. const char* path = message->content.storage_read_request.path;
  175. if(path) {
  176. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  177. }
  178. break;
  179. }
  180. case PB_Main_storage_write_request_tag: {
  181. string_cat_printf(str, "\twrite_request {\r\n");
  182. const char* path = message->content.storage_write_request.path;
  183. if(path) {
  184. string_cat_printf(str, "\t\tpath: %s\r\n", path);
  185. }
  186. if(message->content.storage_write_request.has_file) {
  187. const PB_Storage_File* msg_file = &message->content.storage_write_request.file;
  188. rpc_sprintf_msg_file(str, "\t\t\t", msg_file, 1);
  189. }
  190. break;
  191. }
  192. case PB_Main_storage_read_response_tag:
  193. string_cat_printf(str, "\tread_response {\r\n");
  194. if(message->content.storage_read_response.has_file) {
  195. const PB_Storage_File* msg_file = &message->content.storage_read_response.file;
  196. rpc_sprintf_msg_file(str, "\t\t\t", msg_file, 1);
  197. }
  198. break;
  199. case PB_Main_storage_list_response_tag: {
  200. const PB_Storage_File* msg_file = message->content.storage_list_response.file;
  201. size_t msg_file_count = message->content.storage_list_response.file_count;
  202. string_cat_printf(str, "\tlist_response {\r\n");
  203. rpc_sprintf_msg_file(str, "\t\t", msg_file, msg_file_count);
  204. }
  205. }
  206. string_cat_printf(str, "\t}\r\n}\r\n");
  207. printf("%s", string_get_cstr(str));
  208. string_clear(str);
  209. }
  210. static Rpc* rpc_alloc(void) {
  211. Rpc* rpc = furi_alloc(sizeof(Rpc));
  212. rpc->busy_mutex = osMutexNew(NULL);
  213. rpc->busy = false;
  214. rpc->events = osEventFlagsNew(NULL);
  215. rpc->stream = xStreamBufferCreate(256, 1);
  216. rpc->decoded_message = furi_alloc(sizeof(PB_Main));
  217. rpc->decoded_message->cb_content.funcs.decode = content_callback;
  218. rpc->decoded_message->cb_content.arg = rpc;
  219. RpcHandlerDict_init(rpc->handlers);
  220. return rpc;
  221. }
  222. RpcSession* rpc_open_session(Rpc* rpc) {
  223. furi_assert(rpc);
  224. bool result = false;
  225. furi_check(osMutexAcquire(rpc->busy_mutex, osWaitForever) == osOK);
  226. if(rpc->busy) {
  227. result = false;
  228. } else {
  229. rpc->busy = true;
  230. result = true;
  231. }
  232. furi_check(osMutexRelease(rpc->busy_mutex) == osOK);
  233. if(result) {
  234. RpcSession* session = &rpc->session;
  235. session->send_bytes_mutex = osMutexNew(NULL);
  236. session->rpc = rpc;
  237. session->terminate_session = false;
  238. session->system_contexts = furi_alloc(COUNT_OF(rpc_systems) * sizeof(void*));
  239. for(int i = 0; i < COUNT_OF(rpc_systems); ++i) {
  240. session->system_contexts[i] = rpc_systems[i].alloc(rpc);
  241. }
  242. FURI_LOG_D(RPC_TAG, "Session started\r\n");
  243. }
  244. return result ? &rpc->session : NULL; /* support 1 open session for now */
  245. }
  246. void rpc_close_session(RpcSession* session) {
  247. furi_assert(session);
  248. furi_assert(session->rpc);
  249. furi_assert(session->rpc->busy);
  250. rpc_set_send_bytes_callback(session, NULL, NULL);
  251. osEventFlagsSet(session->rpc->events, RPC_EVENT_DISCONNECT);
  252. }
  253. void rpc_set_send_bytes_callback(RpcSession* session, RpcSendBytesCallback callback, void* context) {
  254. furi_assert(session);
  255. furi_assert(session->rpc);
  256. furi_assert(session->rpc->busy);
  257. osMutexAcquire(session->send_bytes_mutex, osWaitForever);
  258. session->send_bytes_callback = callback;
  259. session->send_bytes_context = context;
  260. osMutexRelease(session->send_bytes_mutex);
  261. }
  262. size_t
  263. rpc_feed_bytes(RpcSession* session, uint8_t* encoded_bytes, size_t size, TickType_t timeout) {
  264. furi_assert(session);
  265. Rpc* rpc = session->rpc;
  266. furi_assert(rpc->busy);
  267. size_t bytes_sent = xStreamBufferSend(rpc->stream, encoded_bytes, size, timeout);
  268. osEventFlagsSet(rpc->events, RPC_EVENT_NEW_DATA);
  269. return bytes_sent;
  270. }
  271. bool rpc_pb_stream_read(pb_istream_t* istream, pb_byte_t* buf, size_t count) {
  272. Rpc* rpc = istream->state;
  273. uint32_t flags = 0;
  274. size_t bytes_received = 0;
  275. while(1) {
  276. bytes_received +=
  277. xStreamBufferReceive(rpc->stream, buf + bytes_received, count - bytes_received, 0);
  278. if(count == bytes_received) {
  279. break;
  280. } else {
  281. flags = osEventFlagsWait(rpc->events, RPC_EVENTS_ALL, 0, osWaitForever);
  282. if(flags & RPC_EVENT_DISCONNECT) {
  283. if(xStreamBufferIsEmpty(rpc->stream)) {
  284. rpc->session.terminate_session = true;
  285. break;
  286. } else {
  287. /* Save disconnect flag and continue reading buffer */
  288. osEventFlagsSet(rpc->events, RPC_EVENT_DISCONNECT);
  289. }
  290. }
  291. }
  292. }
  293. return (count == bytes_received);
  294. }
  295. void rpc_encode_and_send(Rpc* rpc, PB_Main* main_message) {
  296. furi_assert(rpc);
  297. furi_assert(main_message);
  298. RpcSession* session = &rpc->session;
  299. pb_ostream_t ostream = PB_OSTREAM_SIZING;
  300. #if DEBUG_PRINT
  301. FURI_LOG_I(RPC_TAG, "OUTPUT:");
  302. rpc_print_message(main_message);
  303. #endif
  304. bool result = pb_encode_ex(&ostream, &PB_Main_msg, main_message, PB_ENCODE_DELIMITED);
  305. furi_check(result && ostream.bytes_written);
  306. uint8_t* buffer = furi_alloc(ostream.bytes_written);
  307. ostream = pb_ostream_from_buffer(buffer, ostream.bytes_written);
  308. pb_encode_ex(&ostream, &PB_Main_msg, main_message, PB_ENCODE_DELIMITED);
  309. {
  310. #if DEBUG_PRINT
  311. string_t str;
  312. string_init(str);
  313. string_reserve(str, 100 + ostream.bytes_written * 5);
  314. string_cat_printf(str, "\r\nREPONSE DEC(%d): {", ostream.bytes_written);
  315. for(int i = 0; i < ostream.bytes_written; ++i) {
  316. string_cat_printf(str, "%d, ", buffer[i]);
  317. }
  318. string_cat_printf(str, "}\r\n");
  319. printf("%s", string_get_cstr(str));
  320. string_clean(str);
  321. string_reserve(str, 100 + ostream.bytes_written * 3);
  322. string_cat_printf(str, "REPONSE HEX(%d): {", ostream.bytes_written);
  323. for(int i = 0; i < ostream.bytes_written; ++i) {
  324. string_cat_printf(str, "%02X", buffer[i]);
  325. }
  326. string_cat_printf(str, "}\r\n\r\n");
  327. printf("%s", string_get_cstr(str));
  328. #endif // DEBUG_PRINT
  329. osMutexAcquire(session->send_bytes_mutex, osWaitForever);
  330. if(session->send_bytes_callback) {
  331. session->send_bytes_callback(
  332. session->send_bytes_context, buffer, ostream.bytes_written);
  333. }
  334. osMutexRelease(session->send_bytes_mutex);
  335. }
  336. free(buffer);
  337. }
  338. static bool content_callback(pb_istream_t* stream, const pb_field_t* field, void** arg) {
  339. furi_assert(stream);
  340. Rpc* rpc = *arg;
  341. RpcHandler* handler = RpcHandlerDict_get(rpc->handlers, field->tag);
  342. if(handler && handler->decode_submessage) {
  343. handler->decode_submessage(stream, field, arg);
  344. }
  345. return true;
  346. }
  347. int32_t rpc_srv(void* p) {
  348. Rpc* rpc = rpc_alloc();
  349. furi_record_create("rpc", rpc);
  350. while(1) {
  351. pb_istream_t istream = {
  352. .callback = rpc_pb_stream_read,
  353. .state = rpc,
  354. .errmsg = NULL,
  355. .bytes_left = 0x7FFFFFFF,
  356. };
  357. if(pb_decode_ex(&istream, &PB_Main_msg, rpc->decoded_message, PB_DECODE_DELIMITED)) {
  358. #if DEBUG_PRINT
  359. FURI_LOG_I(RPC_TAG, "INPUT:");
  360. rpc_print_message(rpc->decoded_message);
  361. #endif
  362. RpcHandler* handler =
  363. RpcHandlerDict_get(rpc->handlers, rpc->decoded_message->which_content);
  364. if(handler && handler->message_handler) {
  365. handler->message_handler(rpc->decoded_message, handler->context);
  366. } else if(!handler) {
  367. FURI_LOG_E(
  368. RPC_TAG,
  369. "Unhandled message, tag: %d\r\n",
  370. rpc->decoded_message->which_content);
  371. }
  372. pb_release(&PB_Main_msg, rpc->decoded_message);
  373. } else {
  374. pb_release(&PB_Main_msg, rpc->decoded_message);
  375. RpcSession* session = &rpc->session;
  376. if(session->terminate_session) {
  377. session->terminate_session = false;
  378. osEventFlagsClear(rpc->events, RPC_EVENTS_ALL);
  379. FURI_LOG_D(RPC_TAG, "Session terminated\r\n");
  380. for(int i = 0; i < COUNT_OF(rpc_systems); ++i) {
  381. if(rpc_systems[i].free) {
  382. rpc_systems[i].free(session->system_contexts[i]);
  383. }
  384. }
  385. free(session->system_contexts);
  386. osMutexDelete(session->send_bytes_mutex);
  387. RpcHandlerDict_clean(rpc->handlers);
  388. rpc->busy = false;
  389. } else {
  390. xStreamBufferReset(rpc->stream);
  391. FURI_LOG_E(
  392. RPC_TAG, "Decode failed, error: \'%.128s\'\r\n", PB_GET_ERROR(&istream));
  393. }
  394. }
  395. }
  396. return 0;
  397. }
  398. void rpc_add_handler(Rpc* rpc, pb_size_t message_tag, RpcHandler* handler) {
  399. furi_assert(RpcHandlerDict_get(rpc->handlers, message_tag) == NULL);
  400. RpcHandlerDict_set_at(rpc->handlers, message_tag, *handler);
  401. }
  402. void rpc_encode_and_send_empty(Rpc* rpc, uint32_t command_id, PB_CommandStatus status) {
  403. PB_Main message = {
  404. .command_id = command_id,
  405. .command_status = status,
  406. .has_next = false,
  407. .which_content = PB_Main_empty_tag,
  408. };
  409. rpc_encode_and_send(rpc, &message);
  410. pb_release(&PB_Main_msg, &message);
  411. }