Shim.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. * This software is released under the MIT License.
  3. * https://opensource.org/licenses/MIT
  4. *
  5. */
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <inttypes.h>
  9. #include "sdkconfig.h"
  10. #include "freertos/FreeRTOS.h"
  11. #include "freertos/task.h"
  12. #include "esp_system.h"
  13. #include "esp_wifi.h"
  14. #include "esp_event.h"
  15. #include "esp_log.h"
  16. #include "esp_http_server.h"
  17. #include <ConstantParameters.h>
  18. #include <Session.h>
  19. #include <SpircController.h>
  20. #include <MercuryManager.h>
  21. #include <ZeroconfAuthenticator.h>
  22. #include <ApResolve.h>
  23. #include <HTTPServer.h>
  24. #include "ConfigJSON.h"
  25. #include "Logger.h"
  26. #include "platform_config.h"
  27. #include "tools.h"
  28. #include "cspot_private.h"
  29. #include "cspot_sink.h"
  30. #include "Shim.h"
  31. extern "C" {
  32. httpd_handle_t get_http_server(int *port);
  33. static esp_err_t handlerWrapper(httpd_req_t *req);
  34. };
  35. #define CSPOT_STACK_SIZE (8*1024)
  36. static const char *TAG = "cspot";
  37. // using a global is pretty ugly, but it's easier with all Lambda below
  38. static EXT_RAM_ATTR struct cspot_s {
  39. char name[32];
  40. cspot_cmd_cb_t cHandler;
  41. cspot_data_cb_t dHandler;
  42. TaskHandle_t TaskHandle;
  43. std::shared_ptr<LoginBlob> blob;
  44. } cspot;
  45. std::shared_ptr<ConfigJSON> configMan;
  46. std::shared_ptr<NVSFile> file;
  47. std::shared_ptr<MercuryManager> mercuryManager;
  48. std::shared_ptr<SpircController> spircController;
  49. /****************************************************************************************
  50. * Main task (could it be deleted after spirc has started?)
  51. */
  52. static void cspotTask(void *pvParameters) {
  53. char configName[] = "cspot_config";
  54. std::string jsonConfig;
  55. // Config file
  56. file = std::make_shared<NVSFile>();
  57. configMan = std::make_shared<ConfigJSON>(configName, file);
  58. // We might have no config at all
  59. if (!file->readFile(configName, jsonConfig) || !jsonConfig.length()) {
  60. ESP_LOGW(TAG, "Cannot load config, using default");
  61. configMan->deviceName = cspot.name;
  62. configMan->format = AudioFormat_OGG_VORBIS_160;
  63. configMan->volume = 32767;
  64. configMan->save();
  65. }
  66. // safely load config now
  67. configMan->load();
  68. if (!configMan->deviceName.length()) configMan->deviceName = cspot.name;
  69. ESP_LOGI(TAG, "Started CSpot with %s (bitrate %d)", configMan->deviceName.c_str(), configMan->format == AudioFormat_OGG_VORBIS_320 ? 320 : (configMan->format == AudioFormat_OGG_VORBIS_160 ? 160 : 96));
  70. // All we do here is notify the task to start the mercury loop
  71. auto createPlayerCallback = [](std::shared_ptr<LoginBlob> blob) {
  72. // TODO: handle/refuse that another user takes ownership
  73. cspot.blob = blob;
  74. xTaskNotifyGive(cspot.TaskHandle);
  75. };
  76. int port;
  77. httpd_handle_t server = get_http_server(&port);
  78. auto httpServer = std::make_shared<ShimHTTPServer>(server, port);
  79. auto authenticator = std::make_shared<ZeroconfAuthenticator>(createPlayerCallback, httpServer);
  80. authenticator->registerHandlers();
  81. // wait to be notified and have a mercury loop
  82. while (1) {
  83. ulTaskNotifyTake(pdFALSE, portMAX_DELAY);
  84. auto session = std::make_unique<Session>();
  85. session->connectWithRandomAp();
  86. auto token = session->authenticate(cspot.blob);
  87. ESP_LOGI(TAG, "Creating Spotify (using CSpot) player");
  88. // Auth successful
  89. if (token.size() > 0 && cspot.cHandler(CSPOT_SETUP, 44100)) {
  90. auto audioSink = std::make_shared<ShimAudioSink>();
  91. mercuryManager = std::make_shared<MercuryManager>(std::move(session));
  92. mercuryManager->startTask();
  93. spircController = std::make_shared<SpircController>(mercuryManager, cspot.blob->username, audioSink);
  94. spircController->setEventHandler([](CSpotEvent &event) {
  95. ESP_LOGI(TAG, "Getting Spotify event %d ", (int) event.eventType);
  96. switch (event.eventType) {
  97. case CSpotEventType::TRACK_INFO: {
  98. TrackInfo track = std::get<TrackInfo>(event.data);
  99. cspot.cHandler(CSPOT_TRACK, 44100, track.duration, track.artist.c_str(),
  100. track.album.c_str(), track.name.c_str(), track.imageUrl.c_str());
  101. break;
  102. }
  103. case CSpotEventType::PLAY_PAUSE: {
  104. bool isPaused = std::get<bool>(event.data);
  105. if (isPaused) cspot.cHandler(CSPOT_PAUSE);
  106. else cspot.cHandler(CSPOT_PLAY, false);
  107. break;
  108. }
  109. case CSpotEventType::PLAYBACK_START:
  110. cspot.cHandler(CSPOT_PLAY, (int) std::get<bool>(event.data));
  111. break;
  112. case CSpotEventType::LOAD:
  113. cspot.cHandler(CSPOT_LOAD, std::get<int>(event.data), -1);
  114. break;
  115. case CSpotEventType::SEEK:
  116. cspot.cHandler(CSPOT_SEEK, std::get<int>(event.data));
  117. break;
  118. case CSpotEventType::DISC:
  119. cspot.cHandler(CSPOT_DISC);
  120. spircController->stopPlayer();
  121. mercuryManager->stop();
  122. break;
  123. case CSpotEventType::PREV:
  124. case CSpotEventType::NEXT:
  125. cspot.cHandler(CSPOT_FLUSH);
  126. break;
  127. /*
  128. // we use volume from sink which is a 16 bits value
  129. case CSpotEventType::VOLUME: {
  130. int volume = std::get<int>(event.data);
  131. cspot.cHandler(CSPOT_VOLUME, volume);
  132. ESP_LOGW(TAG, "cspot volume : %d", volume);
  133. break;
  134. }
  135. */
  136. default:
  137. break;
  138. }
  139. });
  140. // need to make sure mercuryManager is running otherwise we'll loop and destroy instances
  141. while (!mercuryManager->isRunning) vTaskDelay(pdMS_TO_TICKS(25));
  142. mercuryManager->reconnectedCallback = []() {
  143. return spircController->subscribe();
  144. };
  145. mercuryManager->handleQueue();
  146. // release controllers
  147. mercuryManager.reset();
  148. spircController.reset();
  149. }
  150. // release auth blob and flush files
  151. cspot.blob.reset();
  152. file->flush();
  153. ESP_LOGI(TAG, "Shutting down CSpot player");
  154. }
  155. // we should not be here
  156. vTaskDelete(NULL);
  157. }
  158. /****************************************************************************************
  159. * API to create and start a cspot instance
  160. */
  161. struct cspot_s* cspot_create(const char *name, cspot_cmd_cb_t cmd_cb, cspot_data_cb_t data_cb) {
  162. static DRAM_ATTR StaticTask_t xTaskBuffer __attribute__ ((aligned (4)));
  163. static EXT_RAM_ATTR StackType_t xStack[CSPOT_STACK_SIZE] __attribute__ ((aligned (4)));
  164. bell::setDefaultLogger();
  165. cspot.cHandler = cmd_cb;
  166. cspot.dHandler = data_cb;
  167. strncpy(cspot.name, name, sizeof(cspot.name) - 1);
  168. cspot.TaskHandle = xTaskCreateStatic(&cspotTask, "cspot", CSPOT_STACK_SIZE, NULL, CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT - 2, xStack, &xTaskBuffer);
  169. return &cspot;
  170. }
  171. /****************************************************************************************
  172. * Commands sent by local buttons/actions
  173. */
  174. bool cspot_cmd(struct cspot_s* ctx, cspot_event_t event, void *param) {
  175. // we might have not controller left
  176. if (!spircController.use_count()) return false;
  177. switch(event) {
  178. case CSPOT_PREV:
  179. spircController->prevSong();
  180. break;
  181. case CSPOT_NEXT:
  182. spircController->nextSong();
  183. break;
  184. case CSPOT_TOGGLE:
  185. spircController->playToggle();
  186. break;
  187. case CSPOT_PAUSE:
  188. spircController->setPause(true);
  189. break;
  190. case CSPOT_PLAY:
  191. spircController->setPause(false);
  192. break;
  193. case CSPOT_DISC:
  194. spircController->disconnect();
  195. break;
  196. case CSPOT_STOP:
  197. spircController->stopPlayer();
  198. break;
  199. case CSPOT_VOLUME_UP:
  200. spircController->adjustVolume(MAX_VOLUME / 100 + 1);
  201. break;
  202. case CSPOT_VOLUME_DOWN:
  203. spircController->adjustVolume(-(MAX_VOLUME / 100 + 1));
  204. break;
  205. default:
  206. break;
  207. }
  208. return true;
  209. }
  210. /****************************************************************************************
  211. * AudioSink class to push data to squeezelite backend (decode_external)
  212. */
  213. void ShimAudioSink::volumeChanged(uint16_t volume) {
  214. cspot.cHandler(CSPOT_VOLUME, volume);
  215. }
  216. void ShimAudioSink::feedPCMFrames(const uint8_t *data, size_t bytes) {
  217. cspot.dHandler(data, bytes);
  218. }
  219. /****************************************************************************************
  220. * NVSFile class to store config
  221. */
  222. bool NVSFile::readFile(std::string filename, std::string &fileContent) {
  223. auto search = files.find(filename);
  224. // cache
  225. if (search == files.end()) {
  226. char *content = (char*) config_alloc_get(NVS_TYPE_STR, filename.c_str());
  227. if (!content) return false;
  228. fileContent = content;
  229. free(content);
  230. } else {
  231. fileContent = search->second;
  232. }
  233. return true;
  234. }
  235. bool NVSFile::writeFile(std::string filename, std::string fileContent) {
  236. auto search = files.find(filename);
  237. files[filename] = fileContent;
  238. if (search == files.end()) return (ESP_OK == config_set_value(NVS_TYPE_STR, filename.c_str(), fileContent.c_str()));
  239. return true;
  240. }
  241. bool NVSFile::flush() {
  242. esp_err_t err = ESP_OK;
  243. for (auto it = files.begin(); it != files.end(); ++it) {
  244. err |= config_set_value(NVS_TYPE_STR, it->first.c_str(), it->second.c_str());
  245. }
  246. return (err == ESP_OK);
  247. }
  248. /****************************************************************************************
  249. * Shim HTTP server for spirc
  250. */
  251. static esp_err_t handlerWrapper(httpd_req_t *req) {
  252. std::unique_ptr<bell::HTTPRequest> request = std::make_unique<bell::HTTPRequest>();
  253. char *query = NULL, *body = NULL;
  254. bell::httpHandler *handler = (bell::httpHandler*) req->user_ctx;
  255. size_t query_len = httpd_req_get_url_query_len(req);
  256. request->connection = httpd_req_to_sockfd(req);
  257. // get body if any (add '\0' at the end if used as string)
  258. if (req->content_len) {
  259. body = (char*) calloc(1, req->content_len + 1);
  260. int size = httpd_req_recv(req, body, req->content_len);
  261. request->body = body;
  262. ESP_LOGD(TAG,"wrapper received body %d/%d", size, req->content_len);
  263. }
  264. // parse query if any (can be in body as well for url-encoded)
  265. if (query_len) {
  266. query = (char*) malloc(query_len + 1);
  267. httpd_req_get_url_query_str(req, query, query_len + 1);
  268. } else if (body && strchr(body, '&')) {
  269. query = body;
  270. body = NULL;
  271. }
  272. // I know this is very crude and unsafe...
  273. url_decode(query);
  274. char *key = strtok(query, "&");
  275. while (key) {
  276. char *value = strchr(key, '=');
  277. *value++ = '\0';
  278. request->queryParams[key] = value;
  279. ESP_LOGD(TAG,"wrapper received key:%s value:%s", key, value);
  280. key = strtok(NULL, "&");
  281. };
  282. if (query) free(query);
  283. if (body) free(body);
  284. /*
  285. This is a strange construct as the C++ handler will call the ShimHTTPSer::respond
  286. and then we'll return. So we can't obtain the response to be sent, as esp_http_server
  287. normally expects, instead respond() will use raw socket and close connection
  288. */
  289. (*handler)(std::move(request));
  290. return ESP_OK;
  291. }
  292. void ShimHTTPServer::registerHandler(bell::RequestType requestType, const std::string &routeUrl, bell::httpHandler handler, bool readDataToStr) {
  293. httpd_uri_t request = {
  294. .uri = routeUrl.c_str(),
  295. .method = (requestType == bell::RequestType::GET ? HTTP_GET : HTTP_POST),
  296. .handler = handlerWrapper,
  297. .user_ctx = NULL,
  298. };
  299. // find the first free spot and register handler
  300. for (int i = 0; i < sizeof(uriHandlers)/sizeof(bell::httpHandler); i++) {
  301. if (!uriHandlers[i]) {
  302. uriHandlers[i] = handler;
  303. request.user_ctx = uriHandlers + i;
  304. httpd_register_uri_handler(serverHandle, &request);
  305. break;
  306. }
  307. }
  308. if (!request.user_ctx) ESP_LOGW(TAG, "Cannot add handler for %s", routeUrl.c_str());
  309. }
  310. void ShimHTTPServer::respond(const bell::HTTPResponse &response) {
  311. char *buf;
  312. size_t len = asprintf(&buf, "HTTP/1.1 %d OK\r\n"
  313. "Server: SQUEEZEESP32\r\n"
  314. "Connection: close\r\n"
  315. "Content-type: %s\r\n"
  316. "Content-length: %d\r\n"
  317. "Access-Control-Allow-Origin: *\r\n"
  318. "Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS\r\n"
  319. "Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token\r\n"
  320. "\r\n%s",
  321. response.status, response.contentType.c_str(),
  322. response.body.size(), response.body.c_str()
  323. );
  324. // use raw socket send and close connection
  325. httpd_socket_send(serverHandle, response.connectionFd, buf, len, 0);
  326. free(buf);
  327. // we want to close the socket due to the strange construct
  328. httpd_sess_trigger_close(serverHandle, response.connectionFd);
  329. }