/** * @file watchMain.cpp * @author Gustice * @brief ChaosWatch Application * * @copyright Copyright (c) 2024 */ /* Watchface 6/ 5 / 1 4 2 3 */ struct { const char *syslogDest = "syslogDst"; // example: "172.16.16.10" const char *mqttBroker = "mqttBroker"; // example: "172.16.16.10" const char *mqttPrefix = "mqttPrefix"; // example: "SomeTag" const char *spitServer = "spitServer"; // example: "172.16.16.10" } ConfigKeys; // MQTT Topics struct { // Subscriptions: const char *moveTo = /* / */ "watch/moveTo"; const char *startShuffle = /* / */ "watch/startShuffle"; // Publishes: const char *inPosition = /* / */ "watch/inPosition"; const char *changingPosition = /* / */ "watch/changingPosition"; } MqttTopics; struct { const char *expectedServer = ""; struct { const char *group = "CatasWatchMovement"; const char *startShuffle = "ActionStartShuffle"; const char *moveToX[6] = { "ActionMoveTo1", "ActionMoveTo2", "ActionMoveTo3", "ActionMoveTo4", "ActionMoveTo5", "ActionMoveTo6", }; } Provided; struct { const char *changingPos = "ChangingPositionScene"; const char *inPosX[6] = { "InPosition1Scene", "InPosition2Scene", "InPosition3Scene", "InPosition4Scene", "InPosition5Scene", "InPosition6Scene", }; } Expected; } SpitTypes; // ToDo: // - MQTT Integration // - OTA // - Syslog heartbeat // - Streamlined DMX // - #include "watchMain.hpp" string ClientName = "CatasWatchDev"; string ProjectName = "CatastrphicProj"; extern "C" { // This switch allows the ROS C-implementation to find this main void app_main(void); } struct DeviceState { uint8_t minJumps{6}; uint8_t maxJumps{32}; uint8_t profile{}; uint8_t shuffleRate{}; float speed = 1.0; // Rad/sec float accel = 1.0; // Rad/sec^2 Color color{0x80, 0x80, 0x80}; }; enum class MoveType { StepTo, Demo, Shuffle, }; enum class ResponseType { StepAt, StartMoving, }; struct MoveCommand { MoveType type; // 1..6 uint8_t pos; }; struct WatchIndex { ResponseType type; // 1..6 uint8_t pos; }; struct PictoIllumCommand { uint8_t pos; // 0 for none / Valid indexes 1 .. 6 }; static fos::Queue commandQueue(8); static fos::Queue responseQueue(8); static fos::Queue pictoIllumQue(2); DeviceState activeState; static const char *TAG = "Watch"; static bool EthernetIsConnected = false; std::unique_ptr pShell; void onCommand(std::string name, Cli::CArgs args) { ESP_LOGI(TAG, "Invoking: %s", name.c_str()); } void startUpdate(Cli::CArgs args) { ESP_LOGI(TAG, "Invoking Update"); if (args.size() != 1) { pShell->write("Need URL to application'\n"); return; } // @ToDo: Start Update here } void getConfig(Cli::CArgs args) { if (args.size() != 1) { pShell->write("Needs string key for query'\n"); return; } auto key = args[0]; auto &store = NvsApi::getInstance(); auto val = store.getValue(key); pShell->write(key + ": " + val + "\n"); } void testPictoIllum(Cli::CArgs args) { if (args.size() != 1) { pShell->write("Needs position argument for illuminated position 0 for off, 1..6 for pictograms'\n"); return; } try { int p = std::stoi(args[0]); pictoIllumQue.enqueue(std::make_unique(p)); } catch (const std::exception &e) { ESP_LOGI(TAG, "Failed to parse %s and %s", args[0].c_str(), args[1].c_str()); } } void testMovement(Cli::CArgs args) { ESP_LOGI(TAG, "on triggerMovement:"); if (args.size() != 1) { pShell->write("need target position (1..6)'\n"); return; } try { int p = std::stoi(args[0]); activeState.profile = p; commandQueue.enqueue(std::make_unique(MoveType::StepTo, p)); } catch (const std::exception &e) { ESP_LOGI(TAG, "Failed to parse %s and %s", args[0].c_str(), args[1].c_str()); } } void setConfig(Cli::CArgs args) { if (args.size() != 2) { pShell->write("Needs string key and value'\n"); return; } auto key = args[0]; auto val = args[1]; auto &store = NvsApi::getInstance(); pShell->write(std::string{"Storing value = '"} + val + "'\n"); store.setValue(key, val); } void setLogServerConfig(Cli::CArgs args) { ESP_LOGI(TAG, "on showLogServerConfig:"); auto &store = NvsApi::getInstance(); if (args.size() != 1) { auto logger = store.getValue("syslogDst"); pShell->write(std::string{"syslog destination = '"} + logger + "'\n"); pShell->write("provide argument to change syslog server'\n"); return; } pShell->write(std::string{"setting syslog destination to = '"} + args[0] + "'\n"); store.setValue("syslogDst", args[0]); } void setDynamics(Cli::CArgs args) { ESP_LOGI(TAG, "on setDynamics:"); if (args.size() != 2) { pShell->write("need float values for velocity and acceleration'\n"); return; } try { float v = std::stof(args[0]); float a = std::stof(args[1]); activeState.accel = a; activeState.speed = v; } catch (const std::exception &e) { ESP_LOGI(TAG, "Failed to parse %s and %s", args[0].c_str(), args[1].c_str()); } } void startDemoMovement(Cli::CArgs args) { ESP_LOGI(TAG, "on startDemoMovement:"); commandQueue.enqueue(std::make_unique(MoveType::Demo)); } /** * @brief Telnet socket via TCP/IP * * @details The ini-file for TeraTerm only changes CRReceive and CRSend values both to "=CR" * @param arg ignored task argument */ static void telnetSocketTask(int addrFamily) { ESP_LOGI(TAG, "Starting Telnet task"); try { TelnetServer telnet(addrFamily); telnet.run( [](TcpSession &session) { pShell = std::make_unique(session, [](std::string n, Cli::CArgs a) { onCommand(n, a); }); pShell->addBinding( {"update", "Start OTA-Update-Process", [](Cli::CArgs a) { startUpdate(a); }}); pShell->addBinding( {"logserver_set", "Set log server config ip", [](Cli::CArgs a) { setLogServerConfig(a); }}); pShell->addBinding( {"getcfg", "Get configuration value for key", [](Cli::CArgs a) { getConfig(a); }}); pShell->addBinding( {"setcfg", "Set configuration value by key and value", [](Cli::CArgs a) { setConfig(a); }}); pShell->addBinding( {"dyn_set", "set dynamics of movement (velocity,accelerations) as floats", [](Cli::CArgs a) { setDynamics(a); }}); pShell->addBinding( {"tstMove", "start movement (profile-idx,steps) as integers ", [](Cli::CArgs a) { testMovement(a); }}); pShell->addBinding( {"tstIllum", "test illumination command 0=off /1..6", [](Cli::CArgs a) { testPictoIllum(a); }}); }, [](TcpSession &session) { pShell->process(); Syslog::setupTask(session.getOther()); }); } catch (const std::exception &e) { ESP_LOGE("TCP", "%s", e.what()); } vTaskDelete(NULL); } constexpr uint32_t DmxUniverse = 0; constexpr int DmxChannelCount = 9; uint8_t scaledRgbChannel(uint8_t value, float scale) { return static_cast(value * scale); } /** * @brief Callback for ArtNet DMX-socket. Does not send data only updates the image * * @param data Pointer to dmx-values * @param size length of dmx-values */ static void UniverseCallback(const uint8_t *data, const uint16_t size) { int len = std::min(static_cast(size), DmxChannelCount); ESP_LOGD(TAG, "Got DMX"); ESP_LOG_BUFFER_HEXDUMP("DMX", data, len, ESP_LOG_DEBUG); Syslog::logv(Syslog::Severity::Debug, "Got DMX: r%0x g%0x b%0x i%0x m%i M%i p%i a%i w%i r%i", /* RGB*/ data[0], data[1], data[2], /*Intens*/ data[3], /* MinMaxJumps */ data[4], data[5], /*profile*/ data[6], /*accel/speed*/ data[7], data[8], /*shuffleRate*/ data[9]); float intens = (float)data[3] / UINT8_MAX; activeState.color = Color{ scaledRgbChannel(data[0], intens), scaledRgbChannel(data[1], intens), scaledRgbChannel(data[2], intens), 0}; activeState.minJumps = data[4]; activeState.maxJumps = data[5]; activeState.profile = data[6]; uint8_t accel = data[7]; uint8_t velo = data[8]; activeState.accel = (float)accel / 100 + 0.5; // min .5 / max 3 activeState.speed = (float)velo / 100 + 0.5; // min .5 / max 3 activeState.shuffleRate = data[9]; } void moveToSubs(std::string data) { ESP_LOGI(TAG, "MoveTo command '%s'", data.c_str()); try { int p = std::stoi(data); Syslog::logv(Syslog::Severity::Informational, "got MoveTo-Cmd->%i", p); commandQueue.enqueue(std::make_unique(MoveType::StepTo, p)); auto &client = MqttClient::getInstance(); client.publish(MqttTopics.inPosition, data + "Picto"); } catch (const std::exception &e) { ESP_LOGE(TAG, "Error to process data %s, with ex: %s", data.c_str(), e.what()); } } void startShuffle(std::string data) { ESP_LOGI(TAG, "StartShuffle command %s", data.c_str()); try { Syslog::logv(Syslog::Severity::Informational, "got Shuffle-Command"); commandQueue.enqueue(std::make_unique(MoveType::Shuffle, 0)); auto &client = MqttClient::getInstance(); client.publish(MqttTopics.changingPosition, "...."); } catch (const std::exception &e) { ESP_LOGE(TAG, "Error to process data %s, with ex: %s", data.c_str(), e.what()); } } /** * @brief DMX-Socket for ArtNet TCP/IP * * @details Tested with [Q Light Controller+](https://www.qlcplus.org/) * @param args ignored task argument */ static void dmxSocketSenderTask(UdpSocket &socket) { try { ArtnetSender artnet(socket); std::array data; while (socket.isActive()) { data[0]++; artnet.send("", 0, data.data(), data.size()); fos::Task::delayMs(500); } } catch (const std::exception &e) { ESP_LOGE("UDP", "%s", e.what()); } } /** * @brief DMX-Socket for ArtNet TCP/IP * * @details Tested with [Q Light Controller+](https://www.qlcplus.org/) * @param args ignored task argument */ static void dmxSocketTask(int addrFamily) { ESP_LOGI(TAG, "Starting ArtNet task"); constexpr uint16_t ArtNetPort = arx::artnet::DEFAULT_PORT; IpAdr address = addrFamily == AF_INET ? IpAdr(INADDR_ANY, ArtNetPort) : IpAdr(ArtNetPort); try { while (true) { UdpSocket socket(address); socket.bindTo(); ArtnetReceiver artnet(socket); artnet.subscribe(DmxUniverse, UniverseCallback); artnet.parse(); // parse artnet as long socket is active, then restart socket while (socket.isActive()) { ESP_LOGD(TAG, "Waiting for data"); artnet.parse(); } } } catch (const std::exception &e) { ESP_LOGE("UDP", "%s", e.what()); } } fos::Semaphore etherActive; fos::Semaphore spitProjectFinish; /** Event handler for IP_EVENT_ETH_GOT_IP */ static void got_ip_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data; const esp_netif_ip_info_t *ip_info = &event->ip_info; ESP_LOGI(TAG, "Ethernet Got IP Address"); ESP_LOGI(TAG, "~~~~~~~~~~~"); ESP_LOGI(TAG, "ETHIP:" IPSTR, IP2STR(&ip_info->ip)); ESP_LOGI(TAG, "ETHMASK:" IPSTR, IP2STR(&ip_info->netmask)); ESP_LOGI(TAG, "ETHGW:" IPSTR, IP2STR(&ip_info->gw)); ESP_LOGI(TAG, "~~~~~~~~~~~"); etherActive.give(); } // Event handler for Ethernet static void eth_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { uint8_t mac_addr[6] = {0}; switch (event_id) { case ETHERNET_EVENT_CONNECTED: ESP_LOGI(TAG, "Ethernet Link Up"); EthernetIsConnected = true; ESP_LOGI(TAG, "Ethernet Link Up"); ESP_LOGI(TAG, "Ethernet HW Addr %02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); break; case ETHERNET_EVENT_DISCONNECTED: ESP_LOGI(TAG, "Ethernet Link Down"); EthernetIsConnected = false; break; case ETHERNET_EVENT_START: ESP_LOGI(TAG, "Ethernet Started"); break; case ETHERNET_EVENT_STOP: ESP_LOGI(TAG, "Ethernet Stopped"); break; default: break; } } static void initialize_ethernet(void) { uint8_t eth_port_cnt = 0; esp_eth_handle_t *eth_handles; ESP_ERROR_CHECK(example_eth_init(ð_handles, ð_port_cnt)); if (eth_port_cnt > 1) { ESP_LOGW(TAG, "multiple Ethernet devices detected, the first initialized is to be used!"); } static esp_eth_handle_t s_eth_handle = NULL; s_eth_handle = eth_handles[0]; free(eth_handles); // Initialize TCP/IP network interface aka the esp-netif (should be called only once in application) ESP_ERROR_CHECK(esp_netif_init()); // Create default event loop that running in background ESP_ERROR_CHECK(esp_event_loop_create_default()); // Use ESP_NETIF_DEFAULT_ETH when just one Ethernet interface is used and you don't need to modify // default esp-netif configuration parameters. esp_netif_config_t cfg = ESP_NETIF_DEFAULT_ETH(); esp_netif_t *eth_netif = esp_netif_new(&cfg); // Attach Ethernet driver to TCP/IP stack ESP_ERROR_CHECK(esp_netif_attach(eth_netif, esp_eth_new_netif_glue(s_eth_handle))); ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, eth_event_handler, NULL)); ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &got_ip_event_handler, NULL)); ESP_ERROR_CHECK(esp_eth_start(s_eth_handle)); } namespace Effect { extern const WaveForm_t OffsetPulseWave{gau8_offsetPulse, cu16_TemplateLength}; extern const WaveForm_t InitSlopeWave{gau8_initSlope, cu16_TemplateLength}; extern const WaveForm_t OffsetSlopeWave{gau8_offsetSlope, cu16_TemplateLength}; extern const WaveForm_t FullSlopeWave{gau8_fullSlope, cu16_TemplateLength}; extern const WaveForm_t FullPulseWave{gau8_fullPulse, cu16_TemplateLength}; const Macro macDemoStart = { {64, 1, &InitSlopeWave, StateMachine::UpdateWave, 0xFF}, {32, 1, StateMachine::UpdateIdle, 0xFF}, }; const Macro macDemoPulse = { {64, 1, &InitSlopeWave, StateMachine::UpdateWave, 0xFF}, {32, 2, StateMachine::UpdateIdle, 0xFF}, {64, 1, &OffsetPulseWave, StateMachine::UpdateWave, 0xFF}, }; const Macro macDemoFlicker = { {16, 1, &InitSlopeWave, StateMachine::UpdateWave, 0xFF}, {32, 1, StateMachine::UpdateFlicker, 0xFF}, }; } void LightingTask() { ESP_LOGI(TAG, "Start Lighting"); static I2cMaster master(I2C_NUM_0, /*sda=*/GPIO_NUM_10, /*scl=*/GPIO_NUM_11); // static PmwExpanderPca9685 pca9685(master); static PmwExpanderPca9685 ledDriver1(master, /*iverted=*/false); static PmwExpanderPca9685 ledDriver2(master, /*iverted=*/false, 0x41); PmwExpanderPca9685::GrayValues values[2]{}; OutputPort pwmEnable(GPIO_NUM_1, GpioPort::Logic::Inverted); pwmEnable.write(true); auto const &colorSource = activeState.color; std::array processors{ Effect::EffectProcessor(8), Effect::EffectProcessor(8), Effect::EffectProcessor(8), Effect::EffectProcessor(8), Effect::EffectProcessor(8), Effect::EffectProcessor(8)}; processors[0].setEffect(Effect::macDark, &colorSource, 0); processors[1].setEffect(Effect::macDark, &colorSource, 0); processors[2].setEffect(Effect::macDark, &colorSource, 0); processors[3].setEffect(Effect::macDark, &colorSource, 0); processors[4].setEffect(Effect::macDark, &colorSource, 0); processors[5].setEffect(Effect::macDark, &colorSource, 0); const std::array PictoEffects{ Effect::macDemoPulse, // 1 Effect::macDemoPulse, Effect::macDemoPulse, Effect::macDemoPulse, Effect::macStartFlicker, Effect::macDemoPulse}; // 6 uint8_t lastPicto = 1; std::array startPoints{ &(values[0][4]), // 1 &(values[1][12]), &(values[1][8]), &(values[1][4]), &(values[0][12]), &(values[0][8]), // 6 }; while (true) { auto onPos = pictoIllumQue.dequeue(0); if (onPos) { ESP_LOGI(TAG, "Changing picto-Illum to pos = %i", onPos->pos); ESP_LOGI(TAG, "Current color set r%i g%i b%i ", activeState.color.getRed(), activeState.color.getGreen(), activeState.color.getBlue()); auto pos = onPos->pos; if (pos == 0) { Syslog::logv(Syslog::Severity::Informational, "Dimming picto-illum pos:%i ", lastPicto); processors[lastPicto - 1].setEffect(Effect::macDark, &colorSource, 0); } else if ((pos >= 1) && (pos <= 6)) { auto idx = pos - 1; Syslog::logv(Syslog::Severity::Informational, "Firing picto-illum pos:%i ", pos); processors[idx].setEffect(PictoEffects[idx], &colorSource, 0); lastPicto = pos; } else { Syslog::logv(Syslog::Severity::Error, "Got invalid index for illuminated pictogram =%i ", pos); } } for (size_t i = 0; i < processors.size(); i++) { auto col = processors[i].tick(); auto sp = startPoints[i]; sp[0] = (uint16_t)(col.getWhite()) << 7; sp[1] = (uint16_t)(col.getBlue()) << 7; sp[2] = (uint16_t)(col.getGreen()) << 7; sp[3] = (uint16_t)(col.getRed()) << 7; } ledDriver1.sendImage(values[0]); ledDriver2.sendImage(values[1]); fos::Task::delayMs(40); } } void MovementTask() { ESP_LOGI(TAG, "Start Stepper"); constexpr int MicroSteps = 32; StepperDriverDrv8833::Pins stepperPins{ LEDC_TIMER_0, {LEDC_CHANNEL_0, LEDC_CHANNEL_1, LEDC_CHANNEL_2, LEDC_CHANNEL_3}, {GPIO_NUM_21, GPIO_NUM_20, GPIO_NUM_23, GPIO_NUM_22}, }; StepperDriverDrv8833 stepperDriver(stepperPins, MicroSteps, 0.25F); stepperDriver.setPos(0); StepperConfig stepperCfg{1.8F, MicroSteps}; InputPort initSens(GPIO_NUM_18); InputPort motorFault(GPIO_NUM_8); motorFault.setLogic(GpioPort::Logic::Inverted); OutputPort motorSleep(GPIO_NUM_15, GpioPort::Logic::Inverted); motorSleep.write(false); StepperMotor stepper(stepperCfg, stepperDriver, initSens); WatchMotor watch(stepper, motorSleep); ESP_LOGI("Stepper", "Find Home"); stepper.findRef(); // Todo Set by User-Interface for (size_t i = 0; i < 7; i++) { stepper.fullStep(1); fos::Task::delayMs(40); } (void)stepper.zeroPosition(); while (!stepper.isIdle()) { fos::Task::delayMs(40); } // watch.moveTo(1, ProfileGenerator::Unitform); ESP_LOGI("Stepper", "Got to 1"); // Illum 6 pictoIllumQue.enqueue(std::make_unique(0)); ESP_LOGI(TAG, "Fist Position is %.2f", watch.getScaled()); fos::Task::delayMs(1000); while (true) { ESP_LOGD(TAG, "Waiting for command"); auto cmd = commandQueue.dequeue(); if (cmd->type == MoveType::StepTo) { if (stepper.isIdle()) { int newPos = cmd->pos; if ((newPos >= 1) && (newPos <= 6)) { Syslog::logv(Syslog::Severity::Informational, "Triggered movement to picto pos:%i ", newPos); } else { Syslog::logv(Syslog::Severity::Error, "Got invalid index for illuminated pictogram =%i ", newPos); continue; } int jumps = newPos - watch.getIndex(); if (jumps <= 0) { jumps += 6; } jumps = jumps + (activeState.minJumps % 6) * 6; if (jumps < activeState.minJumps) { jumps += 6; } Syslog::logv(Syslog::Severity::Notice, "Running Stepper by %i steps with prof=%i a=%.2f w=%.2f", jumps, activeState.profile, activeState.accel, activeState.speed); pictoIllumQue.enqueue(std::make_unique(0)); responseQueue.enqueue(std::make_unique(ResponseType::StartMoving, 0)); watch.moveTo(newPos, activeState.profile); pictoIllumQue.enqueue(std::make_unique(newPos)); responseQueue.enqueue(std::make_unique(ResponseType::StepAt, newPos)); } } else if (cmd->type == MoveType::Demo) { ESP_LOGI(TAG, "Running Demo"); for (size_t i = ProfileGenerator::Smooth; i < ProfileGenerator::NumProfiles; i++) { ESP_LOGI(TAG, "Running Profile %d ", i); fos::Task::delayMs(1000); int steps[3]{4, 2, 0}; for (size_t j = 0; j < 3; j++) { watch.moveTo(steps[j], i); fos::Task::delayMs(1000); } } } else { fos::Task::delayMs(100); } } } struct LocalSpitObj { string iD; string groupName; string name; }; std::map ProvidedSpitActions; std::map ExpectedObjects; void onServerEvent(SPIT_Client::ServerEvent event, const SAD_DetectedServer &p_DetectedServer) { switch (event) { case SPIT_Client::ServerEvent::Detect: ESP_LOGI(TAG, "SERVER DETECTED"); ESP_LOGI(TAG, " Name: %s", p_DetectedServer.getName().data()); ESP_LOGI(TAG, " ID: %s", p_DetectedServer.getID().data()); ESP_LOGI(TAG, " Computer: %s", p_DetectedServer.getComputerName().data()); ESP_LOGI(TAG, " IP: %s", p_DetectedServer.getIP().data()); ESP_LOGI(TAG, " Port: %s", p_DetectedServer.getPort().data()); ESP_LOGI(TAG, " Addition: %s", p_DetectedServer.getAdditions().data()); ESP_LOGI(TAG, " ClientIP: %s", p_DetectedServer.getClientIP().data()); break; case SPIT_Client::ServerEvent::Lost: ESP_LOGW(TAG, "Server lost Name: %s IP: %s", p_DetectedServer.getName().data(), p_DetectedServer.getIP().data()); break; case SPIT_Client::ServerEvent::Changed: ESP_LOGW(TAG, "Server lost Name: %s IP: %s", p_DetectedServer.getName().data(), p_DetectedServer.getIP().data()); break; default: break; } } void onConnectionStatus(string p_ServerID, string p_ServerComputerName, string p_ServerName, int p_ServerStepTime, int p_ConnectionStatus, int p_OldConnectionStatus) { ESP_LOGI(TAG, "MySPITApp: eventConnectionStatus %d ", p_ConnectionStatus); } // The transfer of the server's SPITTypes and SPITObjects is finished. void onProjectUpdate(SPIT_Client::ProjUpdate state, string projectId) { switch (state) { case SPIT_Client::ProjUpdate::ServerLoaded: ESP_LOGI(TAG, "eventProjectReport ID: %s ", projectId.data()); break; case SPIT_Client::ProjUpdate::StartTransfer: ESP_LOGI(TAG, "eventStartProjectTransfer"); break; case SPIT_Client::ProjUpdate::EndTransfer: ESP_LOGI(TAG, "eventEndProjectTransfer"); spitProjectFinish.give(); break; case SPIT_Client::ProjUpdate::ServerClosed: ESP_LOGI(TAG, "eventProjectClosed ID: %s", projectId.data()); // If we don't save SPITServer's project specific information // perhaps close all SPITObjects and RemoteSPITObjects to avoid conflicts, when the SPITServer loads a new project // SPITObject::clearSPITObjects(); // SPITObject::clearSPITObjectsRemote(); break; default: break; } } /** * The SPITCLientInterface (implemented by this) will be asked to veto the SPITType while SPIT_Client.parseReportSPITType.
* @param p_ReportSPITType * @return false = the SPITType is denied, true = the SPITType is accepted */ bool onCheckSpitTypeVeto(SPIT_Message::ReportSPITType *p_ReportSPITType) { return true; // Bypass veto if (p_ReportSPITType == NULL) return true; SPITType *ptrSPITType; ptrSPITType = SPITType::getSPITType(p_ReportSPITType->getID()); // Don't allow foreign SPITTypes if (ptrSPITType == NULL) { // ESP_LOGW(TAG, "ObjectVeto NoSpitType"); return false; } if (ptrSPITType->getCreatedByClient() == false) { // ESP_LOGW(TAG, "getCreatedByClient"); return false; } return true; } bool onCheckSpitObjectVeto(SPIT_Message::ReportSPITObject *p_ReportSPITObject) { return true; // Bypass veto if (p_ReportSPITObject == NULL) return true; SPITType *ptrSPITType = SPITType::getSPITType(p_ReportSPITObject->getSPITTypeID()); if (ptrSPITType == NULL) { // ESP_LOGW(TAG, "ObjectVeto NoSpitObj"); return false; } // Don't allow SPITObjects which refers to a SPITType which is not created by this client - other SPITTypes cannot be handled here if (ptrSPITType->getCreatedByClient() == false) { // ESP_LOGW(TAG, "getCreatedByClient"); return false; } SPITObject *ptrSPITObject = SPITObject::getSPITObject(p_ReportSPITObject->getID()); // Don't allow foreign SPITTypes if (ptrSPITObject == NULL) { // ESP_LOGE(TAG, "Unknown ID"); return false; } return true; } // Called when the server has created, loaded, changed or deleted a SPITType. // May also occur when the server confirms a SPITType created or changed by the client. void onSpitType(SPIT_Client::ObjectEvent event, const SPITType &p_SPITType) { if (event == SPIT_Client::ObjectEvent::Created) { // Whenever you provide an action for this SPITType take this over in your code. // call _SpitClient.setActionSPITType(p_SPITType.getID(), true); ESP_LOGI(TAG, "NEW SPIT-Type ID: %s GroupName: %s Name: %s confirmed: %d", p_SPITType.getID().data(), p_SPITType.getGroupName().data(), p_SPITType.getName().data(), p_SPITType.getConfirmed()); } else if (event == SPIT_Client::ObjectEvent::Changed) { ESP_LOGI(TAG, "SPIT-Type CHANGED ID: %s GroupName: %s Name: %s confirmed: %d", p_SPITType.getID().data(), p_SPITType.getGroupName().data(), p_SPITType.getName().data(), p_SPITType.getConfirmed()); } else if (event == SPIT_Client::ObjectEvent::Deleted) { ESP_LOGI(TAG, "SPIT-Type Removed ID: %s GroupName: %s Name: %s\n", p_SPITType.getID().data(), p_SPITType.getGroupName().data(), p_SPITType.getName().data()); } } /** * Called when the server has created or changed a Remote SPITType. * Remote SPITType are used in Remote SPITObjects. A Remote SPITObject is used to remote control the SPITServer. * @param p_New true = server created a new SPITType / false = server changed a existing SPITType */ void onSpitTypeRemote(SPIT_Client::ObjectEvent event, const SPITType &p_SPITType) { if (event == SPIT_Client::ObjectEvent::Created) { ESP_LOGI(TAG, "NEW SPIT-REMOTE-Type ID: %s GroupName: %s Name: %s confirmed: %d", p_SPITType.getID().data(), p_SPITType.getGroupName().data(), p_SPITType.getName().data(), p_SPITType.getConfirmed()); auto typeName = p_SPITType.getName(); if (ExpectedObjects.contains(typeName)) { ExpectedObjects[typeName] = p_SPITType.getID(); } } else if (event == SPIT_Client::ObjectEvent::Changed) { // we had to inform all Remote SPITObjects using the p_SPITType // perhaps the SPITObject uses information from the SPITType SPITObject *ptrSPITObject; int intSPITObjectCount; intSPITObjectCount = SPITObject::getSPITObjectRemoteCount(); for (int intObject = 0; intObject < intSPITObjectCount; intObject++) { ptrSPITObject = SPITObject::getSPITObjectRemote(intObject); if (ptrSPITObject == NULL) continue; if (ptrSPITObject->getSPITTypeID() == p_SPITType.getID()) { // call ecentSPITObjectRemote // onSpitObjectRemote(SPIT_Client::ObjectEvent::Changed, p_SPITType, *ptrSPITObject); } } ESP_LOGI(TAG, "SPIT-REMOTE-Type CHANGED ID: %s GroupName: %s Name: %s confirmed: %d", p_SPITType.getID().data(), p_SPITType.getGroupName().data(), p_SPITType.getName().data(), p_SPITType.getConfirmed()); } else if (event == SPIT_Client::ObjectEvent::Deleted) { ESP_LOGD(TAG, "SPIT-REMOTE-Type Removed ID: %s GroupName: %s Name: %s\n", p_SPITType.getID().data(), p_SPITType.getGroupName().data(), p_SPITType.getName().data()); } } /** * Called when the server has created, loaded or changed a SPITObject. * May also occur when the server confirms a SPITObject created by the client, what the client should never do!!. * false = server changed a existing SPITObject * @param p_SPITType a reference to a copy of the associated SPITType instance. * @param p_SPITObject a reference to a copy of the SPITObject instance. */ void onSpitObject(SPIT_Client::ObjectEvent event, const SPITType &p_SPITType, const SPITObject &p_SPITObject) { if (event == SPIT_Client::ObjectEvent::Created) { ESP_LOGI(TAG, "NEW SPIT-Object ID: %s Name: %s -> SPITType: %s", p_SPITObject.getID().data(), p_SPITObject.getName().data(), p_SPITType.getName().data()); // check your actions // Whenever you provide an action for this SPITObject take this over in your code. // call _SpitClient.setActionSPITObject(p_SPITObject.getID(), true); // for our little excample as described in loadClientProject: // We have only actions for SPITTypes - means every SPITObject with the associated "Actionx"-SPITTypes will trigger the action when it is played //-> no need to do something here, because setActionSPITType has been set prior and the SPITObject will automatically inherits this // SPITObjects with other SPITTypes asscciated will trigger no actions } else if (event == SPIT_Client::ObjectEvent::Changed) { ESP_LOGI(TAG, "SPIT-Object CHANGED ID: %s Name: %s -> SPITType: %s", p_SPITObject.getID().data(), p_SPITObject.getName().data(), p_SPITType.getName().data()); } else if (event == SPIT_Client::ObjectEvent::Deleted) { ESP_LOGD(TAG, "SPIT-Object Removed ID: %s Name: %s\n", p_SPITObject.getID().data(), p_SPITObject.getName().data()); // Check your actions // take the removal of the SPITObject over in your code // CAUTION: Deleted SPITObjects can be added later again (perhaps per UNDO on the SPITServer) //-> don't remove your assigned action immediately - keep it to reassign it later } } /** * Called when the server has created or changed a Remote SPITObject. * A Remote SPITObject is used to remote control the SPITServer. * @param p_New true = server created a new remote SPITObject * false = server changed a existing remote SPITObject * @param p_SPITType a reference to a copy of the associated SPITType instance. * @param p_SPITObject a reference to a copy of the SPITObject instance. */ void onSpitObjectRemote(SPIT_Client::ObjectEvent event, const SPITType &p_SPITType, const SPITObject &p_SPITObject) { if (event == SPIT_Client::ObjectEvent::Created) { ESP_LOGI(TAG, "NEW SPIT-REMOTE-Object ID: %s Name: %s -> SPITType: %s", p_SPITObject.getID().data(), p_SPITObject.getName().data(), p_SPITType.getName().data()); // This is a remote SPITObject which can be used to remote control the server. // If you want you can list this for later use } else if (event == SPIT_Client::ObjectEvent::Changed) { ESP_LOGI(TAG, "SPIT-REMOTE-Object CHANGED ID: %s Name: %s -> SPITType: %s", p_SPITObject.getID().data(), p_SPITObject.getName().data(), p_SPITType.getName().data()); } else if (event == SPIT_Client::ObjectEvent::Deleted) { ESP_LOGD(TAG, "SPIT-REMOTE-Object Removed ID: %s Name: %s\n", p_SPITObject.getID().data(), p_SPITObject.getName().data()); // This is a remote SPITObject // If you have listet this prior you should remove it from the list } } // SPITServer may use several methods for playing SPITObjects. // e.g. liveSHOWsoftware has the timeline and jingles which plays objects, where the timeline the main player is. // SPIT distinguishes between the different players. All eventPlay... functions contain the information which player plays the SPIT object. void onPlay(string p_PlayerID, string p_PlayerName, char p_PlayerType, bool p_PlayerIsRunning, long long p_TimeFrames) { ESP_LOGD(TAG, "eventPlay Player: %s Runs: %d Time: %lld", p_PlayerName.data(), p_PlayerIsRunning, p_TimeFrames); switch (p_PlayerType) { case SPIT_Client::PLAYERTYPE_MAIN: // p_FrameTimes contains the position inside the server's project, we can use it like a timecode // int intMilliseconds = (int)(((double)p_TimeFrames / (double)m_ServerFramesPerSecond) * 1000); break; case SPIT_Client::PLAYERTYPE_CONTINOUS: // The olayer is playing only single Object sequences sometime during the project break; case SPIT_Client::PLAYERTYPE_DISCRETE: // Only discrete values where submitted, e.g the fader position of remote faders. break; } } /** * Called when the SPITServer plays a SPITObject. For every played SPITObject one eventPlayObject is called. * You can decide here which action should be done or not. */ void onPlaySpitType(string p_PlayerID, string spitTypeId, bool p_PlayerIsRunning, bool p_Started, bool p_Ended, double p_Value) { // double doubleValue = ((double)p_PlayObject.getValue() / 1000000) * ((double)p_PlayObject.getValueFactor() / 1000000); ESP_LOGD(TAG, "eventPlayObject Player: %s is running: %d Object Started: %d Stopped: %d", p_PlayerID.data(), p_PlayerIsRunning, p_Started, p_Ended); // ESP_LOGD(TAG, " SPITType: %s SPITObject: %s Position: %lld Value: %f\n", spitTypeId.data(), p_SPITObject.getName().data(), p_PlayObject.getFrameInside(), doubleValue); ESP_LOGD(TAG, " SPITType: %s Value: %f\n", spitTypeId.data(), p_Value); if (!ProvidedSpitActions.contains(spitTypeId)) { ESP_LOGE(TAG, "SPIT ID %s is not accepted", spitTypeId.c_str()); return; } if (p_Started == true) { auto command = ProvidedSpitActions[spitTypeId]; ESP_LOGI(TAG, "Player: %s is running: %s Object", p_PlayerID.data(), spitTypeId.c_str()); commandQueue.enqueue(std::make_unique(command)); Syslog::logv(Syslog::Severity::Informational, "Got SPIT command for move ot : r%d", command.pos); } } /** * Called when a remote SpitObject which value function is changed by the server. * This allows the Client to adjust its display for the remote command. * @param p_SPITType the assigned remote SPITType of p_SPITObject * @param p_SPITObject the remote SPITObject which is changed * @param p_FrameInsideObject can be discarded * @param p_Value the new value */ void onPlayRemoteObjectStatus(const SPITType &p_SPITType, const SPITObject &p_SPITObject, long long p_FrameInsideObject, int p_Value) { ESP_EARLY_LOGI(TAG, "eventPlayRemoteObjectStatus RemoteSPITType: %s RemoteSPITObject: %s Position: %lld Value: %d", p_SPITType.getName().data(), p_SPITObject.getName().data(), p_FrameInsideObject, p_Value); } void SpitClientApp() { ESP_LOGI(TAG, "Starting SPIT task"); auto &provided = SpitTypes.Provided; auto &expected = SpitTypes.Expected; std::vector ProvidedObj; ProvidedSpitActions[provided.startShuffle] = MoveCommand{.type = MoveType::Shuffle, .pos = 0}; ProvidedObj.push_back(LocalSpitObj{.iD = provided.startShuffle, .groupName = provided.group, .name = provided.startShuffle}); ExpectedObjects[expected.changingPos] = ""; for (size_t i = 0; i < 6; i++) { ProvidedObj.push_back(LocalSpitObj{.iD = provided.moveToX[i], .groupName = provided.group, .name = provided.moveToX[i]}); ProvidedSpitActions[provided.moveToX[i]] = MoveCommand{.type = MoveType::StepTo, .pos = (uint8_t)(i + 1)}; ExpectedObjects[expected.inPosX[i]] = ""; } SPIT_Client spitClient(ClientName, ProjectName, { .onServerEvent = onServerEvent, .onConnectionStatus = onConnectionStatus, .onProjectUpdate = onProjectUpdate, .onSpitType = onSpitType, .onSpitTypeRemote = onSpitTypeRemote, .onSpitObject = onSpitObject, .onSpitObjectRemote = onSpitObjectRemote, .onPlay = onPlay, .onPlaySpitType = onPlaySpitType, .onPlayRemoteObjectStatus = onPlayRemoteObjectStatus, .onCheckSpitTypeVeto = onCheckSpitTypeVeto, .onCheckSpitObjectVeto = onCheckSpitObjectVeto, }); for (auto &obj : ProvidedObj) { SPITType *ptrSPITType1Fix = spitClient.createSPITTypeFixed(obj.iD, obj.groupName, obj.name, 0, 0); spitClient.setActionSPITType(ptrSPITType1Fix->getID(), true); // should be executed whenever a SPITObject with this SPITType is played } spitClient.clientProjectLoaded(); spitClient.startServerAutoDetect(); spitProjectFinish.take(); string serverProjectID = spitClient.getServerProjectID(); string serverProjectName = spitClient.getClientProjectName(); int serverFramesPerSecond = spitClient.getServerFramesPerSecond(); // set when the server reports his project, see eventProjectReport ESP_LOGI(TAG, "eventProjectReport ID: %s Name: %s FramesPerSecond: %d", serverProjectID.data(), serverProjectName.data(), serverFramesPerSecond); for (auto &&obj : ExpectedObjects) { if (obj.second == "") { ESP_LOGE(TAG, "No matching Remote ID for %s", obj.first.c_str()); } } while (true) { auto res = responseQueue.dequeue(); if (res->type == ResponseType::StartMoving) { spitClient.sendRemoteObject(ExpectedObjects[expected.changingPos]); } else if (res->type == ResponseType::StepAt) { spitClient.sendRemoteObject(ExpectedObjects[expected.inPosX[res->pos - 1]]); } } } void app_main(void) { esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_ERROR_CHECK(nvs_flash_erase()); ret = nvs_flash_init(); } ESP_ERROR_CHECK(ret); initialize_ethernet(); NvsApi::init(); static fos::Task lightingTask(LightingTask, "Lights", 0x8000uL); static fos::Task movementTask(MovementTask, "Motor", 0x8000uL); etherActive.take(); fos::Task::delayMs(10000); ESP_LOGI(TAG, "Start net services"); static int ipVersion = AF_INET; static fos::TaskT telnetSocket(telnetSocketTask, ipVersion, "tcpServer", 4096); static fos::TaskT dmxNode(dmxSocketTask, ipVersion, "dmxNode", 4096); // static Task otaUpdate(SystemFunctions::OtaTaskEntry, "otaTask", 8192); static fos::Task spit(SpitClientApp, "SpitClient"); auto &store = NvsApi::getInstance(); auto logger = store.getValue(ConfigKeys.syslogDest); if (logger != "") { Syslog::setupTask(IpAdr{logger, 0}); } // auto broker = store.getValue(ConfigKeys.mqttBroker); // if (broker != "") { // ESP_LOGI(TAG, "Initializing MQTT"); // auto prefix = store.getValue(ConfigKeys.mqttPrefix); // auto &client = MqttClient::init(broker, prefix); // if (!client.isRunning()) { // client.addSubscription(MqttTopics.moveTo, [](std::string d) { moveToSubs(d); }); // client.addSubscription(MqttTopics.startShuffle, [](std::string d) { startShuffle(d); }); // client.start(); // } // } while (true) { fos::Task::delayMs(5000); // ToDo send Syslog::logv(Syslog::Severity::Notice, "Health state"); } }