2
0

MercuryManager.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. #include "MercuryManager.h"
  2. #include <iostream>
  3. #include "Logger.h"
  4. std::map<MercuryType, std::string> MercuryTypeMap({
  5. {MercuryType::GET, "GET"},
  6. {MercuryType::SEND, "SEND"},
  7. {MercuryType::SUB, "SUB"},
  8. {MercuryType::UNSUB, "UNSUB"},
  9. });
  10. MercuryManager::MercuryManager(std::unique_ptr<Session> session): bell::Task("mercuryManager", 6 * 1024, +1, 1)
  11. {
  12. this->timeProvider = std::make_shared<TimeProvider>();
  13. this->callbacks = std::map<uint64_t, mercuryCallback>();
  14. this->subscriptions = std::map<std::string, mercuryCallback>();
  15. this->session = std::move(session);
  16. this->sequenceId = 0x00000001;
  17. this->audioChunkManager = std::make_unique<AudioChunkManager>();
  18. this->audioChunkSequence = 0;
  19. this->audioKeySequence = 0;
  20. this->queue = std::vector<std::unique_ptr<Packet>>();
  21. queueSemaphore = std::make_unique<WrappedSemaphore>(200);
  22. this->session->shanConn->conn->timeoutHandler = [this]() {
  23. return this->timeoutHandler();
  24. };
  25. }
  26. bool MercuryManager::timeoutHandler()
  27. {
  28. if (!isRunning) return true;
  29. auto currentTimestamp = timeProvider->getSyncedTimestamp();
  30. if (this->lastRequestTimestamp != -1 && currentTimestamp - this->lastRequestTimestamp > AUDIOCHUNK_TIMEOUT_MS)
  31. {
  32. CSPOT_LOG(debug, "Reconnection required, no mercury response");
  33. return true;
  34. }
  35. if (currentTimestamp - this->lastPingTimestamp > PING_TIMEOUT_MS)
  36. {
  37. CSPOT_LOG(debug, "Reconnection required, no ping received");
  38. return true;
  39. }
  40. return false;
  41. }
  42. void MercuryManager::unregisterMercuryCallback(uint64_t seqId)
  43. {
  44. auto element = this->callbacks.find(seqId);
  45. if (element != this->callbacks.end())
  46. {
  47. this->callbacks.erase(element);
  48. }
  49. }
  50. void MercuryManager::requestAudioKey(std::vector<uint8_t> trackId, std::vector<uint8_t> fileId, audioKeyCallback& audioCallback)
  51. {
  52. std::lock_guard<std::mutex> guard(reconnectionMutex);
  53. auto buffer = fileId;
  54. this->keyCallback = audioCallback;
  55. // Structure: [FILEID] [TRACKID] [4 BYTES SEQUENCE ID] [0x00, 0x00]
  56. buffer.insert(buffer.end(), trackId.begin(), trackId.end());
  57. auto audioKeySequence = pack<uint32_t>(htonl(this->audioKeySequence));
  58. buffer.insert(buffer.end(), audioKeySequence.begin(), audioKeySequence.end());
  59. auto suffix = std::vector<uint8_t>({ 0x00, 0x00 });
  60. buffer.insert(buffer.end(), suffix.begin(), suffix.end());
  61. // Bump audio key sequence
  62. this->audioKeySequence += 1;
  63. // Used for broken connection detection
  64. this->lastRequestTimestamp = timeProvider->getSyncedTimestamp();
  65. this->session->shanConn->sendPacket(static_cast<uint8_t>(MercuryType::AUDIO_KEY_REQUEST_COMMAND), buffer);
  66. }
  67. void MercuryManager::freeAudioKeyCallback()
  68. {
  69. this->keyCallback = nullptr;
  70. }
  71. std::shared_ptr<AudioChunk> MercuryManager::fetchAudioChunk(std::vector<uint8_t> fileId, std::vector<uint8_t>& audioKey, uint16_t index)
  72. {
  73. return this->fetchAudioChunk(fileId, audioKey, index * AUDIO_CHUNK_SIZE / 4, (index + 1) * AUDIO_CHUNK_SIZE / 4);
  74. }
  75. std::shared_ptr<AudioChunk> MercuryManager::fetchAudioChunk(std::vector<uint8_t> fileId, std::vector<uint8_t>& audioKey, uint32_t startPos, uint32_t endPos)
  76. {
  77. std::lock_guard<std::mutex> guard(reconnectionMutex);
  78. auto sampleStartBytes = pack<uint32_t>(htonl(startPos));
  79. auto sampleEndBytes = pack<uint32_t>(htonl(endPos));
  80. auto buffer = pack<uint16_t>(htons(this->audioChunkSequence));
  81. auto hardcodedData = std::vector<uint8_t>(
  82. { 0x00, 0x01, // Channel num, currently just hardcoded to 1
  83. 0x00, 0x00,
  84. 0x00, 0x00, 0x00, 0x00, // bytes magic
  85. 0x00, 0x00, 0x9C, 0x40,
  86. 0x00, 0x02, 0x00, 0x00 });
  87. buffer.insert(buffer.end(), hardcodedData.begin(), hardcodedData.end());
  88. buffer.insert(buffer.end(), fileId.begin(), fileId.end());
  89. buffer.insert(buffer.end(), sampleStartBytes.begin(), sampleStartBytes.end());
  90. buffer.insert(buffer.end(), sampleEndBytes.begin(), sampleEndBytes.end());
  91. // Bump chunk sequence
  92. this->audioChunkSequence += 1;
  93. this->session->shanConn->sendPacket(static_cast<uint8_t>(MercuryType::AUDIO_CHUNK_REQUEST_COMMAND), buffer);
  94. // Used for broken connection detection
  95. this->lastRequestTimestamp = this->timeProvider->getSyncedTimestamp();
  96. return this->audioChunkManager->registerNewChunk(this->audioChunkSequence - 1, audioKey, startPos, endPos);
  97. }
  98. void MercuryManager::reconnect()
  99. {
  100. std::lock_guard<std::mutex> guard(this->reconnectionMutex);
  101. this->lastPingTimestamp = -1;
  102. this->lastRequestTimestamp = -1;
  103. RECONNECT:
  104. if (!isRunning) return;
  105. CSPOT_LOG(debug, "Trying to reconnect...");
  106. try
  107. {
  108. if (this->session->shanConn->conn != nullptr)
  109. {
  110. this->session->shanConn->conn->timeoutHandler = nullptr;
  111. }
  112. this->audioChunkManager->failAllChunks();
  113. if (this->session->authBlob != nullptr)
  114. {
  115. this->lastAuthBlob = this->session->authBlob;
  116. }
  117. this->session = std::make_unique<Session>();
  118. this->session->connectWithRandomAp();
  119. this->session->authenticate(this->lastAuthBlob);
  120. this->session->shanConn->conn->timeoutHandler = [this]() {
  121. return this->timeoutHandler();
  122. };
  123. CSPOT_LOG(debug, "Reconnected successfuly :)");
  124. }
  125. catch (...)
  126. {
  127. CSPOT_LOG(debug, "Reconnection failed, willl retry in %d secs", RECONNECTION_RETRY_MS / 1000);
  128. usleep(RECONNECTION_RETRY_MS * 1000);
  129. goto RECONNECT;
  130. //reconnect();
  131. }
  132. }
  133. void MercuryManager::runTask()
  134. {
  135. std::scoped_lock lock(this->runningMutex);
  136. // Listen for mercury replies and handle them accordingly
  137. isRunning = true;
  138. while (isRunning)
  139. {
  140. std::unique_ptr<Packet> packet;
  141. try
  142. {
  143. packet = this->session->shanConn->recvPacket();
  144. }
  145. catch (const std::runtime_error& e)
  146. {
  147. if (!isRunning) break;
  148. // Reconnection required
  149. this->reconnect();
  150. this->reconnectedCallback();
  151. continue;
  152. }
  153. if (static_cast<MercuryType>(packet->command) == MercuryType::PING) // @TODO: Handle time synchronization through ping
  154. {
  155. CSPOT_LOG(debug, "Got ping, syncing timestamp");
  156. this->timeProvider->syncWithPingPacket(packet->data);
  157. this->lastPingTimestamp = this->timeProvider->getSyncedTimestamp();
  158. this->session->shanConn->sendPacket(0x49, packet->data);
  159. }
  160. else if (static_cast<MercuryType>(packet->command) == MercuryType::AUDIO_CHUNK_SUCCESS_RESPONSE)
  161. {
  162. this->lastRequestTimestamp = -1;
  163. this->audioChunkManager->handleChunkData(packet->data, false);
  164. }
  165. else
  166. {
  167. this->queue.push_back(std::move(packet));
  168. this->queueSemaphore->give();
  169. }
  170. }
  171. }
  172. void MercuryManager::stop() {
  173. std::scoped_lock stop(this->stopMutex);
  174. CSPOT_LOG(debug, "Stopping mercury manager");
  175. isRunning = false;
  176. audioChunkManager->close();
  177. std::scoped_lock lock(this->runningMutex);
  178. CSPOT_LOG(debug, "mercury stopped");
  179. }
  180. void MercuryManager::updateQueue() {
  181. if (queueSemaphore->twait() == 0) {
  182. if (this->queue.size() > 0)
  183. {
  184. auto packet = std::move(this->queue[0]);
  185. this->queue.erase(this->queue.begin());
  186. CSPOT_LOG(debug, "Received packet with code %d of length %d", packet->command, packet->data.size());
  187. switch (static_cast<MercuryType>(packet->command))
  188. {
  189. case MercuryType::COUNTRY_CODE_RESPONSE:
  190. {
  191. countryCode = std::string(packet->data.begin(), packet->data.end());
  192. CSPOT_LOG(debug, "Received country code: %s", countryCode.c_str());
  193. break;
  194. }
  195. case MercuryType::AUDIO_KEY_FAILURE_RESPONSE:
  196. case MercuryType::AUDIO_KEY_SUCCESS_RESPONSE:
  197. {
  198. this->lastRequestTimestamp = -1;
  199. // First four bytes mark the sequence id
  200. auto seqId = ntohl(extract<uint32_t>(packet->data, 0));
  201. if (seqId == (this->audioKeySequence - 1) && this->keyCallback != nullptr)
  202. {
  203. auto success = static_cast<MercuryType>(packet->command) == MercuryType::AUDIO_KEY_SUCCESS_RESPONSE;
  204. this->keyCallback(success, packet->data);
  205. }
  206. break;
  207. }
  208. case MercuryType::AUDIO_CHUNK_FAILURE_RESPONSE:
  209. {
  210. CSPOT_LOG(error, "Audio Chunk failure!");
  211. this->audioChunkManager->handleChunkData(packet->data, true);
  212. this->lastRequestTimestamp = -1;
  213. break;
  214. }
  215. case MercuryType::SEND:
  216. case MercuryType::SUB:
  217. case MercuryType::UNSUB:
  218. {
  219. auto response = std::make_unique<MercuryResponse>(packet->data);
  220. if (response->parts.size() > 0)
  221. {
  222. CSPOT_LOG(debug, " MercuryType::UNSUB response->parts[0].size() = %d", response->parts[0].size());
  223. }
  224. if (this->callbacks.count(response->sequenceId) > 0)
  225. {
  226. auto seqId = response->sequenceId;
  227. this->callbacks[response->sequenceId](std::move(response));
  228. this->callbacks.erase(this->callbacks.find(seqId));
  229. }
  230. break;
  231. }
  232. case MercuryType::SUBRES:
  233. {
  234. auto response = std::make_unique<MercuryResponse>(packet->data);
  235. if (this->subscriptions.count(response->mercuryHeader.uri.value()) > 0)
  236. {
  237. this->subscriptions[response->mercuryHeader.uri.value()](std::move(response));
  238. //this->subscriptions.erase(std::string(response->mercuryHeader.uri));
  239. }
  240. break;
  241. }
  242. default:
  243. break;
  244. }
  245. }
  246. }
  247. }
  248. void MercuryManager::handleQueue()
  249. {
  250. while (isRunning)
  251. {
  252. this->updateQueue();
  253. }
  254. std::scoped_lock lock(this->stopMutex);
  255. }
  256. uint64_t MercuryManager::execute(MercuryType method, std::string uri, mercuryCallback& callback, mercuryCallback& subscription, mercuryParts& payload)
  257. {
  258. if (!isRunning) return -1;
  259. std::lock_guard<std::mutex> guard(reconnectionMutex);
  260. // Construct mercury header
  261. CSPOT_LOG(debug, "executing MercuryType %s", MercuryTypeMap[method].c_str());
  262. Header mercuryHeader;
  263. mercuryHeader.uri = uri;
  264. mercuryHeader.method = MercuryTypeMap[method];
  265. // GET and SEND are actually the same. Therefore the override
  266. // The difference between them is only in header's method
  267. if (method == MercuryType::GET)
  268. {
  269. method = MercuryType::SEND;
  270. }
  271. auto headerBytes = encodePb(mercuryHeader);
  272. // Register a subscription when given method is called
  273. if (method == MercuryType::SUB)
  274. {
  275. this->subscriptions.insert({ uri, subscription });
  276. }
  277. this->callbacks.insert({ sequenceId, callback });
  278. // Structure: [Sequence size] [SequenceId] [0x1] [Payloads number]
  279. // [Header size] [Header] [Payloads (size + data)]
  280. // Pack sequenceId
  281. auto sequenceIdBytes = pack<uint64_t>(hton64(this->sequenceId));
  282. auto sequenceSizeBytes = pack<uint16_t>(htons(sequenceIdBytes.size()));
  283. sequenceIdBytes.insert(sequenceIdBytes.begin(), sequenceSizeBytes.begin(), sequenceSizeBytes.end());
  284. sequenceIdBytes.push_back(0x01);
  285. auto payloadNum = pack<uint16_t>(htons(payload.size() + 1));
  286. sequenceIdBytes.insert(sequenceIdBytes.end(), payloadNum.begin(), payloadNum.end());
  287. auto headerSizePayload = pack<uint16_t>(htons(headerBytes.size()));
  288. sequenceIdBytes.insert(sequenceIdBytes.end(), headerSizePayload.begin(), headerSizePayload.end());
  289. sequenceIdBytes.insert(sequenceIdBytes.end(), headerBytes.begin(), headerBytes.end());
  290. // Encode all the payload parts
  291. for (int x = 0; x < payload.size(); x++)
  292. {
  293. headerSizePayload = pack<uint16_t>(htons(payload[x].size()));
  294. sequenceIdBytes.insert(sequenceIdBytes.end(), headerSizePayload.begin(), headerSizePayload.end());
  295. sequenceIdBytes.insert(sequenceIdBytes.end(), payload[x].begin(), payload[x].end());
  296. }
  297. // Bump sequence id
  298. this->sequenceId += 1;
  299. this->session->shanConn->sendPacket(static_cast<std::underlying_type<MercuryType>::type>(method), sequenceIdBytes);
  300. return this->sequenceId - 1;
  301. }
  302. uint64_t MercuryManager::execute(MercuryType method, std::string uri, mercuryCallback& callback, mercuryParts& payload)
  303. {
  304. mercuryCallback subscription = nullptr;
  305. return this->execute(method, uri, callback, subscription, payload);
  306. }
  307. uint64_t MercuryManager::execute(MercuryType method, std::string uri, mercuryCallback& callback, mercuryCallback& subscription)
  308. {
  309. auto payload = mercuryParts(0);
  310. return this->execute(method, uri, callback, subscription, payload);
  311. }
  312. uint64_t MercuryManager::execute(MercuryType method, std::string uri, mercuryCallback& callback)
  313. {
  314. auto payload = mercuryParts(0);
  315. return this->execute(method, uri, callback, payload);
  316. }