The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2391 lines
83KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. #define JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED \
  20. jassert (juce::MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  21. #if DUMP_BANDWIDTH_STATS
  22. namespace
  23. {
  24. struct PortIOStats
  25. {
  26. PortIOStats (const char* nm) : name (nm) {}
  27. const char* const name;
  28. int byteCount = 0;
  29. int messageCount = 0;
  30. int bytesPerSec = 0;
  31. int largestMessageBytes = 0;
  32. int lastMessageBytes = 0;
  33. void update (double elapsedSec)
  34. {
  35. if (byteCount > 0)
  36. {
  37. bytesPerSec = (int) (byteCount / elapsedSec);
  38. byteCount = 0;
  39. juce::Logger::writeToLog (getString());
  40. }
  41. }
  42. juce::String getString() const
  43. {
  44. return juce::String (name) + ": "
  45. + "count=" + juce::String (messageCount).paddedRight (' ', 7)
  46. + "rate=" + (juce::String (bytesPerSec / 1024.0f, 1) + " Kb/sec").paddedRight (' ', 11)
  47. + "largest=" + (juce::String (largestMessageBytes) + " bytes").paddedRight (' ', 11)
  48. + "last=" + (juce::String (lastMessageBytes) + " bytes").paddedRight (' ', 11);
  49. }
  50. void registerMessage (int numBytes) noexcept
  51. {
  52. byteCount += numBytes;
  53. ++messageCount;
  54. lastMessageBytes = numBytes;
  55. largestMessageBytes = juce::jmax (largestMessageBytes, numBytes);
  56. }
  57. };
  58. static PortIOStats inputStats { "Input" }, outputStats { "Output" };
  59. static uint32 startTime = 0;
  60. static inline void resetOnSecondBoundary()
  61. {
  62. auto now = juce::Time::getMillisecondCounter();
  63. double elapsedSec = (now - startTime) / 1000.0;
  64. if (elapsedSec >= 1.0)
  65. {
  66. inputStats.update (elapsedSec);
  67. outputStats.update (elapsedSec);
  68. startTime = now;
  69. }
  70. }
  71. static inline void registerBytesOut (int numBytes)
  72. {
  73. outputStats.registerMessage (numBytes);
  74. resetOnSecondBoundary();
  75. }
  76. static inline void registerBytesIn (int numBytes)
  77. {
  78. inputStats.registerMessage (numBytes);
  79. resetOnSecondBoundary();
  80. }
  81. }
  82. juce::String getMidiIOStats()
  83. {
  84. return inputStats.getString() + " " + outputStats.getString();
  85. }
  86. #endif
  87. //==============================================================================
  88. struct PhysicalTopologySource::Internal
  89. {
  90. struct Detector;
  91. struct BlockImplementation;
  92. struct ControlButtonImplementation;
  93. struct RotaryDialImplementation;
  94. struct TouchSurfaceImplementation;
  95. struct LEDGridImplementation;
  96. struct LEDRowImplementation;
  97. //==============================================================================
  98. struct MIDIDeviceConnection : public DeviceConnection,
  99. public juce::MidiInputCallback
  100. {
  101. MIDIDeviceConnection() {}
  102. ~MIDIDeviceConnection()
  103. {
  104. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  105. listeners.call (&Listener::connectionBeingDeleted, *this);
  106. if (midiInput != nullptr)
  107. midiInput->stop();
  108. if (interprocessLock != nullptr)
  109. interprocessLock->exit();
  110. }
  111. bool lockAgainstOtherProcesses (const String& midiInName, const String& midiOutName)
  112. {
  113. interprocessLock.reset (new juce::InterProcessLock ("blocks_sdk_"
  114. + File::createLegalFileName (midiInName)
  115. + "_" + File::createLegalFileName (midiOutName)));
  116. if (interprocessLock->enter (500))
  117. return true;
  118. interprocessLock = nullptr;
  119. return false;
  120. }
  121. struct Listener
  122. {
  123. virtual ~Listener() {}
  124. virtual void handleIncomingMidiMessage (const juce::MidiMessage& message) = 0;
  125. virtual void connectionBeingDeleted (const MIDIDeviceConnection&) = 0;
  126. };
  127. void addListener (Listener* l)
  128. {
  129. listeners.add (l);
  130. }
  131. void removeListener (Listener* l)
  132. {
  133. listeners.remove (l);
  134. }
  135. bool sendMessageToDevice (const void* data, size_t dataSize) override
  136. {
  137. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  138. jassert (dataSize > sizeof (BlocksProtocol::roliSysexHeader) + 2);
  139. jassert (memcmp (data, BlocksProtocol::roliSysexHeader, sizeof (BlocksProtocol::roliSysexHeader)) == 0);
  140. jassert (static_cast<const uint8*> (data)[dataSize - 1] == 0xf7);
  141. if (midiOutput != nullptr)
  142. {
  143. midiOutput->sendMessageNow (juce::MidiMessage (data, (int) dataSize));
  144. return true;
  145. }
  146. return false;
  147. }
  148. void handleIncomingMidiMessage (juce::MidiInput*, const juce::MidiMessage& message) override
  149. {
  150. const auto data = message.getRawData();
  151. const int dataSize = message.getRawDataSize();
  152. const int bodySize = dataSize - (int) (sizeof (BlocksProtocol::roliSysexHeader) + 1);
  153. if (bodySize > 0 && memcmp (data, BlocksProtocol::roliSysexHeader, sizeof (BlocksProtocol::roliSysexHeader)) == 0)
  154. if (handleMessageFromDevice != nullptr)
  155. handleMessageFromDevice (data + sizeof (BlocksProtocol::roliSysexHeader), (size_t) bodySize);
  156. listeners.call (&Listener::handleIncomingMidiMessage, message);
  157. }
  158. std::unique_ptr<juce::MidiInput> midiInput;
  159. std::unique_ptr<juce::MidiOutput> midiOutput;
  160. private:
  161. juce::ListenerList<Listener> listeners;
  162. std::unique_ptr<juce::InterProcessLock> interprocessLock;
  163. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MIDIDeviceConnection)
  164. };
  165. struct MIDIDeviceDetector : public DeviceDetector
  166. {
  167. MIDIDeviceDetector() {}
  168. juce::StringArray scanForDevices() override
  169. {
  170. juce::StringArray result;
  171. for (auto& pair : findDevices())
  172. result.add (pair.inputName + " & " + pair.outputName);
  173. return result;
  174. }
  175. DeviceConnection* openDevice (int index) override
  176. {
  177. auto pair = findDevices()[index];
  178. if (pair.inputIndex >= 0 && pair.outputIndex >= 0)
  179. {
  180. std::unique_ptr<MIDIDeviceConnection> dev (new MIDIDeviceConnection());
  181. if (dev->lockAgainstOtherProcesses (pair.inputName, pair.outputName))
  182. {
  183. dev->midiInput.reset (juce::MidiInput::openDevice (pair.inputIndex, dev.get()));
  184. dev->midiOutput.reset (juce::MidiOutput::openDevice (pair.outputIndex));
  185. if (dev->midiInput != nullptr)
  186. {
  187. dev->midiInput->start();
  188. return dev.release();
  189. }
  190. }
  191. }
  192. return nullptr;
  193. }
  194. static bool isBlocksMidiDeviceName (const juce::String& name)
  195. {
  196. return name.indexOf (" BLOCK") > 0 || name.indexOf (" Block") > 0;
  197. }
  198. static String cleanBlocksDeviceName (juce::String name)
  199. {
  200. name = name.trim();
  201. if (name.endsWith (" IN)"))
  202. return name.dropLastCharacters (4);
  203. if (name.endsWith (" OUT)"))
  204. return name.dropLastCharacters (5);
  205. const int openBracketPosition = name.lastIndexOfChar ('[');
  206. if (openBracketPosition != -1 && name.endsWith ("]"))
  207. return name.dropLastCharacters (name.length() - openBracketPosition);
  208. return name;
  209. }
  210. struct MidiInputOutputPair
  211. {
  212. juce::String outputName, inputName;
  213. int outputIndex = -1, inputIndex = -1;
  214. };
  215. static juce::Array<MidiInputOutputPair> findDevices()
  216. {
  217. juce::Array<MidiInputOutputPair> result;
  218. auto midiInputs = juce::MidiInput::getDevices();
  219. auto midiOutputs = juce::MidiOutput::getDevices();
  220. for (int j = 0; j < midiInputs.size(); ++j)
  221. {
  222. if (isBlocksMidiDeviceName (midiInputs[j]))
  223. {
  224. MidiInputOutputPair pair;
  225. pair.inputName = midiInputs[j];
  226. pair.inputIndex = j;
  227. String cleanedInputName = cleanBlocksDeviceName (pair.inputName);
  228. for (int i = 0; i < midiOutputs.size(); ++i)
  229. {
  230. if (cleanBlocksDeviceName (midiOutputs[i]) == cleanedInputName)
  231. {
  232. pair.outputName = midiOutputs[i];
  233. pair.outputIndex = i;
  234. break;
  235. }
  236. }
  237. result.add (pair);
  238. }
  239. }
  240. return result;
  241. }
  242. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MIDIDeviceDetector)
  243. };
  244. //==============================================================================
  245. struct DeviceInfo
  246. {
  247. Block::UID uid;
  248. BlocksProtocol::TopologyIndex index;
  249. BlocksProtocol::BlockSerialNumber serial;
  250. BlocksProtocol::VersionNumber version;
  251. BlocksProtocol::BlockName name;
  252. bool isMaster;
  253. };
  254. static Block::Timestamp deviceTimestampToHost (uint32 timestamp) noexcept
  255. {
  256. return static_cast<Block::Timestamp> (timestamp);
  257. }
  258. static juce::Array<DeviceInfo> getArrayOfDeviceInfo (const juce::Array<BlocksProtocol::DeviceStatus>& devices)
  259. {
  260. juce::Array<DeviceInfo> result;
  261. bool isFirst = true;
  262. for (auto& device : devices)
  263. {
  264. BlocksProtocol::VersionNumber version;
  265. BlocksProtocol::BlockName name;
  266. result.add ({ getBlockUIDFromSerialNumber (device.serialNumber),
  267. device.index,
  268. device.serialNumber,
  269. version,
  270. name,
  271. isFirst });
  272. isFirst = false;
  273. }
  274. return result;
  275. }
  276. static bool containsBlockWithUID (const juce::Array<DeviceInfo>& devices, Block::UID uid) noexcept
  277. {
  278. for (auto&& d : devices)
  279. if (d.uid == uid)
  280. return true;
  281. return false;
  282. }
  283. static bool containsBlockWithUID (const Block::Array& blocks, Block::UID uid) noexcept
  284. {
  285. for (auto&& block : blocks)
  286. if (block->uid == uid)
  287. return true;
  288. return false;
  289. }
  290. static bool versionNumberAddedToBlock (const juce::Array<DeviceInfo>& devices, Block::UID uid, juce::String version) noexcept
  291. {
  292. for (auto&& d : devices)
  293. {
  294. String deviceVersion (reinterpret_cast<const char*> (d.version.version),
  295. jmin (static_cast<size_t> (d.version.length), sizeof (d.version.version)));
  296. if (d.uid == uid && deviceVersion != version)
  297. return true;
  298. }
  299. return false;
  300. }
  301. static bool nameAddedToBlock (const juce::Array<DeviceInfo>& devices, Block::UID uid) noexcept
  302. {
  303. for (auto&& d : devices)
  304. if (d.uid == uid && d.name.length)
  305. return true;
  306. return false;
  307. }
  308. static void setVersionNumberForBlock (const juce::Array<DeviceInfo>& devices, Block& block) noexcept
  309. {
  310. for (auto&& d : devices)
  311. if (d.uid == block.uid)
  312. block.versionNumber = juce::String ((const char*) d.version.version, d.version.length);
  313. }
  314. static void setNameForBlock (const juce::Array<DeviceInfo>& devices, Block& block) noexcept
  315. {
  316. for (auto&& d : devices)
  317. if (d.uid == block.uid)
  318. block.name = juce::String ((const char*) d.name.name, d.name.length);
  319. }
  320. //==============================================================================
  321. struct ConnectedDeviceGroup : private juce::AsyncUpdater,
  322. private juce::Timer
  323. {
  324. ConnectedDeviceGroup (Detector& d, const juce::String& name, DeviceConnection* connection)
  325. : detector (d), deviceName (name), deviceConnection (connection)
  326. {
  327. lastGlobalPingTime = juce::Time::getCurrentTime();
  328. deviceConnection->handleMessageFromDevice = [this] (const void* data, size_t dataSize)
  329. {
  330. this->handleIncomingMessage (data, dataSize);
  331. };
  332. startTimer (200);
  333. sendTopologyRequest();
  334. }
  335. bool isStillConnected (const juce::StringArray& detectedDevices) const noexcept
  336. {
  337. return detectedDevices.contains (deviceName)
  338. && ! failedToGetTopology()
  339. && lastGlobalPingTime > juce::Time::getCurrentTime() - juce::RelativeTime::seconds (pingTimeoutSeconds);
  340. }
  341. Block::UID getDeviceIDFromIndex (BlocksProtocol::TopologyIndex index) const noexcept
  342. {
  343. for (auto& d : currentDeviceInfo)
  344. if (d.index == index)
  345. return d.uid;
  346. return {};
  347. }
  348. int getIndexFromDeviceID (Block::UID uid) const noexcept
  349. {
  350. for (auto& d : currentDeviceInfo)
  351. if (d.uid == uid)
  352. return d.index;
  353. return -1;
  354. }
  355. DeviceInfo* getDeviceInfoFromUID (Block::UID uid) const noexcept
  356. {
  357. for (auto& d : currentDeviceInfo)
  358. if (d.uid == uid)
  359. return &d;
  360. return nullptr;
  361. }
  362. const BlocksProtocol::DeviceStatus* getLastStatus (Block::UID deviceID) const noexcept
  363. {
  364. for (auto&& status : currentTopologyDevices)
  365. if (getBlockUIDFromSerialNumber (status.serialNumber) == deviceID)
  366. return &status;
  367. return nullptr;
  368. }
  369. //==============================================================================
  370. juce::Time lastTopologyRequestTime, lastTopologyReceiveTime;
  371. int numTopologyRequestsSent = 0;
  372. void sendTopologyRequest()
  373. {
  374. ++numTopologyRequestsSent;
  375. lastTopologyRequestTime = juce::Time::getCurrentTime();
  376. sendCommandMessage (0, BlocksProtocol::requestTopologyMessage);
  377. }
  378. void scheduleNewTopologyRequest()
  379. {
  380. numTopologyRequestsSent = 0;
  381. lastTopologyReceiveTime = juce::Time();
  382. }
  383. bool failedToGetTopology() const noexcept
  384. {
  385. return numTopologyRequestsSent > 4 && lastTopologyReceiveTime == juce::Time();
  386. }
  387. bool hasAnyBlockStoppedPinging() const noexcept
  388. {
  389. auto now = juce::Time::getCurrentTime();
  390. for (auto& ping : blockPings)
  391. if (ping.lastPing < now - juce::RelativeTime::seconds (pingTimeoutSeconds))
  392. return true;
  393. return false;
  394. }
  395. void timerCallback() override
  396. {
  397. auto now = juce::Time::getCurrentTime();
  398. if ((now > lastTopologyReceiveTime + juce::RelativeTime::seconds (30.0) || hasAnyBlockStoppedPinging())
  399. && now > lastTopologyRequestTime + juce::RelativeTime::seconds (1.0)
  400. && numTopologyRequestsSent < 4)
  401. sendTopologyRequest();
  402. }
  403. //==============================================================================
  404. // The following methods will be called by the HostPacketDecoder:
  405. void beginTopology (int numDevices, int numConnections)
  406. {
  407. incomingTopologyDevices.clearQuick();
  408. incomingTopologyDevices.ensureStorageAllocated (numDevices);
  409. incomingTopologyConnections.clearQuick();
  410. incomingTopologyConnections.ensureStorageAllocated (numConnections);
  411. }
  412. void extendTopology (int numDevices, int numConnections)
  413. {
  414. incomingTopologyDevices.ensureStorageAllocated (incomingTopologyDevices.size() + numDevices);
  415. incomingTopologyConnections.ensureStorageAllocated (incomingTopologyConnections.size() + numConnections);
  416. }
  417. void handleTopologyDevice (BlocksProtocol::DeviceStatus status)
  418. {
  419. incomingTopologyDevices.add (status);
  420. }
  421. void handleTopologyConnection (BlocksProtocol::DeviceConnection connection)
  422. {
  423. incomingTopologyConnections.add (connection);
  424. }
  425. void endTopology()
  426. {
  427. currentDeviceInfo = getArrayOfDeviceInfo (incomingTopologyDevices);
  428. currentDeviceConnections = getArrayOfConnections (incomingTopologyConnections);
  429. currentTopologyDevices = incomingTopologyDevices;
  430. currentTopologyConnections = incomingTopologyConnections;
  431. detector.handleTopologyChange();
  432. lastTopologyReceiveTime = juce::Time::getCurrentTime();
  433. blockPings.clear();
  434. }
  435. void handleVersion (BlocksProtocol::DeviceVersion version)
  436. {
  437. for (auto i = 0; i < currentDeviceInfo.size(); ++i)
  438. {
  439. if (currentDeviceInfo[i].index == version.index && version.version.length > 1)
  440. {
  441. if (memcmp (currentDeviceInfo.getReference (i).version.version, version.version.version, sizeof (version.version)))
  442. {
  443. currentDeviceInfo.getReference(i).version = version.version;
  444. detector.handleTopologyChange();
  445. }
  446. }
  447. }
  448. }
  449. void handleName (BlocksProtocol::DeviceName name)
  450. {
  451. for (auto i = 0; i < currentDeviceInfo.size(); ++i)
  452. {
  453. if (currentDeviceInfo[i].index == name.index && name.name.length > 1)
  454. {
  455. if (memcmp (currentDeviceInfo.getReference (i).name.name, name.name.name, sizeof (name.name)))
  456. {
  457. currentDeviceInfo.getReference (i).name = name.name;
  458. detector.handleTopologyChange();
  459. }
  460. }
  461. }
  462. }
  463. void handleControlButtonUpDown (BlocksProtocol::TopologyIndex deviceIndex, uint32 timestamp,
  464. BlocksProtocol::ControlButtonID buttonID, bool isDown)
  465. {
  466. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  467. detector.handleButtonChange (deviceID, deviceTimestampToHost (timestamp), buttonID.get(), isDown);
  468. }
  469. void handleCustomMessage (BlocksProtocol::TopologyIndex deviceIndex, uint32 timestamp, const int32* data)
  470. {
  471. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  472. detector.handleCustomMessage (deviceID, deviceTimestampToHost (timestamp), data);
  473. }
  474. void handleTouchChange (BlocksProtocol::TopologyIndex deviceIndex,
  475. uint32 timestamp,
  476. BlocksProtocol::TouchIndex touchIndex,
  477. BlocksProtocol::TouchPosition position,
  478. BlocksProtocol::TouchVelocity velocity,
  479. bool isStart, bool isEnd)
  480. {
  481. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  482. {
  483. TouchSurface::Touch touch;
  484. touch.index = (int) touchIndex.get();
  485. touch.x = position.x.toUnipolarFloat();
  486. touch.y = position.y.toUnipolarFloat();
  487. touch.z = position.z.toUnipolarFloat();
  488. touch.xVelocity = velocity.vx.toBipolarFloat();
  489. touch.yVelocity = velocity.vy.toBipolarFloat();
  490. touch.zVelocity = velocity.vz.toBipolarFloat();
  491. touch.eventTimestamp = deviceTimestampToHost (timestamp);
  492. touch.isTouchStart = isStart;
  493. touch.isTouchEnd = isEnd;
  494. touch.blockUID = deviceID;
  495. setTouchStartPosition (touch);
  496. detector.handleTouchChange (deviceID, touch);
  497. }
  498. }
  499. void setTouchStartPosition (TouchSurface::Touch& touch)
  500. {
  501. auto& startPos = touchStartPositions.getValue (touch);
  502. if (touch.isTouchStart)
  503. startPos = { touch.x, touch.y };
  504. touch.startX = startPos.x;
  505. touch.startY = startPos.y;
  506. }
  507. void handlePacketACK (BlocksProtocol::TopologyIndex deviceIndex, BlocksProtocol::PacketCounter counter)
  508. {
  509. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  510. detector.handleSharedDataACK (deviceID, counter);
  511. }
  512. void handleFirmwareUpdateACK (BlocksProtocol::TopologyIndex deviceIndex, BlocksProtocol::FirmwareUpdateACKCode resultCode, BlocksProtocol::FirmwareUpdateACKDetail resultDetail)
  513. {
  514. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  515. detector.handleFirmwareUpdateACK (deviceID, (uint8) resultCode.get(), (uint32) resultDetail.get());
  516. }
  517. void handleConfigUpdateMessage (BlocksProtocol::TopologyIndex deviceIndex, int32 item, int32 value, int32 min, int32 max)
  518. {
  519. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  520. detector.handleConfigUpdateMessage (deviceID, item, value, min, max);
  521. }
  522. void handleConfigSetMessage (BlocksProtocol::TopologyIndex deviceIndex, int32 item, int32 value)
  523. {
  524. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  525. detector.handleConfigSetMessage (deviceID, item, value);
  526. }
  527. void handleConfigFactorySyncEndMessage (BlocksProtocol::TopologyIndex deviceIndex)
  528. {
  529. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  530. detector.handleConfigFactorySyncEndMessage (deviceID);
  531. }
  532. void handleLogMessage (BlocksProtocol::TopologyIndex deviceIndex, const String& message)
  533. {
  534. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  535. detector.handleLogMessage (deviceID, message);
  536. }
  537. //==============================================================================
  538. template <typename PacketBuilder>
  539. bool sendMessageToDevice (const PacketBuilder& builder) const
  540. {
  541. if (deviceConnection->sendMessageToDevice (builder.getData(), (size_t) builder.size()))
  542. {
  543. #if DUMP_BANDWIDTH_STATS
  544. registerBytesOut (builder.size());
  545. #endif
  546. return true;
  547. }
  548. return false;
  549. }
  550. bool sendCommandMessage (BlocksProtocol::TopologyIndex deviceIndex, uint32 commandID) const
  551. {
  552. BlocksProtocol::HostPacketBuilder<64> p;
  553. p.writePacketSysexHeaderBytes (deviceIndex);
  554. p.deviceControlMessage (commandID);
  555. p.writePacketSysexFooter();
  556. return sendMessageToDevice (p);
  557. }
  558. bool broadcastCommandMessage (uint32 commandID) const
  559. {
  560. return sendCommandMessage (BlocksProtocol::topologyIndexForBroadcast, commandID);
  561. }
  562. DeviceConnection* getDeviceConnection()
  563. {
  564. return deviceConnection.get();
  565. }
  566. Detector& detector;
  567. juce::String deviceName;
  568. juce::Array<DeviceInfo> currentDeviceInfo;
  569. juce::Array<BlockDeviceConnection> currentDeviceConnections;
  570. static constexpr double pingTimeoutSeconds = 6.0;
  571. private:
  572. //==============================================================================
  573. std::unique_ptr<DeviceConnection> deviceConnection;
  574. juce::Array<BlocksProtocol::DeviceStatus> incomingTopologyDevices, currentTopologyDevices;
  575. juce::Array<BlocksProtocol::DeviceConnection> incomingTopologyConnections, currentTopologyConnections;
  576. juce::CriticalSection incomingPacketLock;
  577. juce::Array<juce::MemoryBlock> incomingPackets;
  578. struct TouchStart
  579. {
  580. float x, y;
  581. };
  582. TouchList<TouchStart> touchStartPositions;
  583. juce::Time lastGlobalPingTime;
  584. struct BlockPingTime
  585. {
  586. Block::UID blockUID;
  587. juce::Time lastPing;
  588. };
  589. juce::Array<BlockPingTime> blockPings;
  590. Block::UID getDeviceIDFromMessageIndex (BlocksProtocol::TopologyIndex index) noexcept
  591. {
  592. auto uid = getDeviceIDFromIndex (index);
  593. if (uid == Block::UID())
  594. {
  595. scheduleNewTopologyRequest(); // force a re-request of the topology when we
  596. // get an event from a block that we don't know about
  597. }
  598. else
  599. {
  600. auto now = juce::Time::getCurrentTime();
  601. for (auto& ping : blockPings)
  602. {
  603. if (ping.blockUID == uid)
  604. {
  605. ping.lastPing = now;
  606. return uid;
  607. }
  608. }
  609. blockPings.add ({ uid, now });
  610. }
  611. return uid;
  612. }
  613. juce::Array<BlockDeviceConnection> getArrayOfConnections (const juce::Array<BlocksProtocol::DeviceConnection>& connections)
  614. {
  615. juce::Array<BlockDeviceConnection> result;
  616. for (auto&& c : connections)
  617. {
  618. BlockDeviceConnection dc;
  619. dc.device1 = getDeviceIDFromIndex (c.device1);
  620. dc.device2 = getDeviceIDFromIndex (c.device2);
  621. dc.connectionPortOnDevice1 = convertConnectionPort (dc.device1, c.port1);
  622. dc.connectionPortOnDevice2 = convertConnectionPort (dc.device2, c.port2);
  623. result.add (dc);
  624. }
  625. return result;
  626. }
  627. Block::ConnectionPort convertConnectionPort (Block::UID uid, BlocksProtocol::ConnectorPort p) noexcept
  628. {
  629. if (auto* info = getDeviceInfoFromUID (uid))
  630. return BlocksProtocol::BlockDataSheet (info->serial).convertPortIndexToConnectorPort (p);
  631. jassertfalse;
  632. return { Block::ConnectionPort::DeviceEdge::north, 0 };
  633. }
  634. //==============================================================================
  635. void handleIncomingMessage (const void* data, size_t dataSize)
  636. {
  637. juce::MemoryBlock mb (data, dataSize);
  638. {
  639. const juce::ScopedLock sl (incomingPacketLock);
  640. incomingPackets.add (std::move (mb));
  641. }
  642. triggerAsyncUpdate();
  643. #if DUMP_BANDWIDTH_STATS
  644. registerBytesIn ((int) dataSize);
  645. #endif
  646. }
  647. void handleAsyncUpdate() override
  648. {
  649. juce::Array<juce::MemoryBlock> packets;
  650. packets.ensureStorageAllocated (32);
  651. {
  652. const juce::ScopedLock sl (incomingPacketLock);
  653. incomingPackets.swapWith (packets);
  654. }
  655. for (auto& packet : packets)
  656. {
  657. auto data = static_cast<const uint8*> (packet.getData());
  658. BlocksProtocol::HostPacketDecoder<ConnectedDeviceGroup>
  659. ::processNextPacket (*this, *data, data + 1, (int) packet.getSize() - 1);
  660. }
  661. lastGlobalPingTime = juce::Time::getCurrentTime();
  662. }
  663. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectedDeviceGroup)
  664. };
  665. //==============================================================================
  666. /** This is the main singleton object that keeps track of connected blocks */
  667. struct Detector : public juce::ReferenceCountedObject,
  668. private juce::Timer
  669. {
  670. Detector() : defaultDetector (new MIDIDeviceDetector()), deviceDetector (*defaultDetector)
  671. {
  672. topologyBroadcastThrottle.detector = this;
  673. startTimer (10);
  674. }
  675. Detector (DeviceDetector& dd) : deviceDetector (dd)
  676. {
  677. topologyBroadcastThrottle.detector = this;
  678. startTimer (10);
  679. }
  680. ~Detector()
  681. {
  682. jassert (activeTopologySources.isEmpty());
  683. jassert (activeControlButtons.isEmpty());
  684. }
  685. using Ptr = juce::ReferenceCountedObjectPtr<Detector>;
  686. static Detector::Ptr getDefaultDetector()
  687. {
  688. auto& d = getDefaultDetectorPointer();
  689. if (d == nullptr)
  690. d = new Detector();
  691. return d;
  692. }
  693. static Detector::Ptr& getDefaultDetectorPointer()
  694. {
  695. static Detector::Ptr defaultDetector;
  696. return defaultDetector;
  697. }
  698. void detach (PhysicalTopologySource* pts)
  699. {
  700. activeTopologySources.removeAllInstancesOf (pts);
  701. if (activeTopologySources.isEmpty())
  702. {
  703. for (auto& b : currentTopology.blocks)
  704. if (auto bi = BlockImplementation::getFrom (*b))
  705. bi->sendCommandMessage (BlocksProtocol::endAPIMode);
  706. currentTopology = {};
  707. auto& d = getDefaultDetectorPointer();
  708. if (d != nullptr && d->getReferenceCount() == 2)
  709. getDefaultDetectorPointer() = nullptr;
  710. }
  711. }
  712. bool isConnected (Block::UID deviceID) const noexcept
  713. {
  714. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  715. for (auto&& b : currentTopology.blocks)
  716. if (b->uid == deviceID)
  717. return true;
  718. return false;
  719. }
  720. const BlocksProtocol::DeviceStatus* getLastStatus (Block::UID deviceID) const noexcept
  721. {
  722. for (auto d : connectedDeviceGroups)
  723. if (auto status = d->getLastStatus (deviceID))
  724. return status;
  725. return nullptr;
  726. }
  727. void handleTopologyChange()
  728. {
  729. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  730. {
  731. juce::Array<DeviceInfo> newDeviceInfo;
  732. juce::Array<BlockDeviceConnection> newDeviceConnections;
  733. for (auto d : connectedDeviceGroups)
  734. {
  735. newDeviceInfo.addArray (d->currentDeviceInfo);
  736. newDeviceConnections.addArray (d->currentDeviceConnections);
  737. }
  738. for (int i = currentTopology.blocks.size(); --i >= 0;)
  739. {
  740. auto block = currentTopology.blocks.getUnchecked(i);
  741. if (! containsBlockWithUID (newDeviceInfo, block->uid))
  742. {
  743. if (auto bi = BlockImplementation::getFrom (*block))
  744. bi->invalidate();
  745. currentTopology.blocks.remove (i);
  746. }
  747. else
  748. {
  749. if (versionNumberAddedToBlock (newDeviceInfo, block->uid, block->versionNumber))
  750. setVersionNumberForBlock (newDeviceInfo, *block);
  751. if (nameAddedToBlock (newDeviceInfo, block->uid))
  752. setNameForBlock (newDeviceInfo, *block);
  753. }
  754. }
  755. for (auto& info : newDeviceInfo)
  756. if (info.serial.isValid())
  757. if (! containsBlockWithUID (currentTopology.blocks, getBlockUIDFromSerialNumber (info.serial)))
  758. currentTopology.blocks.add (new BlockImplementation (info.serial, *this, info.version, info.name, info.isMaster));
  759. currentTopology.connections.swapWith (newDeviceConnections);
  760. }
  761. topologyBroadcastThrottle.scheduleTopologyChangeCallback();
  762. }
  763. void handleSharedDataACK (Block::UID deviceID, uint32 packetCounter) const
  764. {
  765. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  766. for (auto&& b : currentTopology.blocks)
  767. if (b->uid == deviceID)
  768. if (auto bi = BlockImplementation::getFrom (*b))
  769. bi->handleSharedDataACK (packetCounter);
  770. }
  771. void handleFirmwareUpdateACK (Block::UID deviceID, uint8 resultCode, uint32 resultDetail)
  772. {
  773. for (auto&& b : currentTopology.blocks)
  774. if (b->uid == deviceID)
  775. if (auto bi = BlockImplementation::getFrom (*b))
  776. bi->handleFirmwareUpdateACK (resultCode, resultDetail);
  777. }
  778. void handleConfigUpdateMessage (Block::UID deviceID, int32 item, int32 value, int32 min, int32 max)
  779. {
  780. for (auto&& b : currentTopology.blocks)
  781. if (b->uid == deviceID)
  782. if (auto bi = BlockImplementation::getFrom (*b))
  783. bi->handleConfigUpdateMessage (item, value, min, max);
  784. }
  785. void notifyBlockOfConfigChange (BlockImplementation& bi, uint32 item)
  786. {
  787. if (auto configChangedCallback = bi.configChangedCallback)
  788. {
  789. if (item >= bi.getMaxConfigIndex())
  790. configChangedCallback (bi, {}, item);
  791. else
  792. configChangedCallback (bi, bi.getLocalConfigMetaData (item), item);
  793. }
  794. }
  795. void handleConfigSetMessage (Block::UID deviceID, int32 item, int32 value)
  796. {
  797. for (auto&& b : currentTopology.blocks)
  798. {
  799. if (b->uid == deviceID)
  800. {
  801. if (auto bi = BlockImplementation::getFrom (*b))
  802. {
  803. bi->handleConfigSetMessage (item, value);
  804. notifyBlockOfConfigChange (*bi, uint32 (item));
  805. }
  806. }
  807. }
  808. }
  809. void handleConfigFactorySyncEndMessage (Block::UID deviceID)
  810. {
  811. for (auto&& b : currentTopology.blocks)
  812. if (b->uid == deviceID)
  813. if (auto bi = BlockImplementation::getFrom (*b))
  814. notifyBlockOfConfigChange (*bi, bi->getMaxConfigIndex());
  815. }
  816. void handleLogMessage (Block::UID deviceID, const String& message) const
  817. {
  818. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  819. for (auto&& b : currentTopology.blocks)
  820. if (b->uid == deviceID)
  821. if (auto bi = BlockImplementation::getFrom (*b))
  822. bi->handleLogMessage (message);
  823. }
  824. void handleButtonChange (Block::UID deviceID, Block::Timestamp timestamp, uint32 buttonIndex, bool isDown) const
  825. {
  826. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  827. for (auto b : activeControlButtons)
  828. {
  829. if (b->block.uid == deviceID)
  830. {
  831. if (auto bi = BlockImplementation::getFrom (b->block))
  832. {
  833. bi->pingFromDevice();
  834. if (buttonIndex < (uint32) bi->modelData.buttons.size())
  835. b->broadcastButtonChange (timestamp, bi->modelData.buttons[(int) buttonIndex].type, isDown);
  836. }
  837. }
  838. }
  839. }
  840. void handleTouchChange (Block::UID deviceID, const TouchSurface::Touch& touchEvent)
  841. {
  842. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  843. for (auto t : activeTouchSurfaces)
  844. {
  845. if (t->block.uid == deviceID)
  846. {
  847. TouchSurface::Touch scaledEvent (touchEvent);
  848. scaledEvent.x *= t->block.getWidth();
  849. scaledEvent.y *= t->block.getHeight();
  850. scaledEvent.startX *= t->block.getWidth();
  851. scaledEvent.startY *= t->block.getHeight();
  852. t->broadcastTouchChange (scaledEvent);
  853. }
  854. }
  855. }
  856. void cancelAllActiveTouches() noexcept
  857. {
  858. for (auto surface : activeTouchSurfaces)
  859. surface->cancelAllActiveTouches();
  860. }
  861. void handleCustomMessage (Block::UID deviceID, Block::Timestamp timestamp, const int32* data)
  862. {
  863. for (auto&& b : currentTopology.blocks)
  864. if (b->uid == deviceID)
  865. if (auto bi = BlockImplementation::getFrom (*b))
  866. bi->handleCustomMessage (timestamp, data);
  867. }
  868. //==============================================================================
  869. int getIndexFromDeviceID (Block::UID deviceID) const noexcept
  870. {
  871. for (auto* c : connectedDeviceGroups)
  872. {
  873. auto index = c->getIndexFromDeviceID (deviceID);
  874. if (index >= 0)
  875. return index;
  876. }
  877. return -1;
  878. }
  879. template <typename PacketBuilder>
  880. bool sendMessageToDevice (Block::UID deviceID, const PacketBuilder& builder) const
  881. {
  882. for (auto* c : connectedDeviceGroups)
  883. if (c->getIndexFromDeviceID (deviceID) >= 0)
  884. return c->sendMessageToDevice (builder);
  885. return false;
  886. }
  887. static Detector* getFrom (Block& b) noexcept
  888. {
  889. if (auto* bi = BlockImplementation::getFrom (b))
  890. return &(bi->detector);
  891. jassertfalse;
  892. return nullptr;
  893. }
  894. DeviceConnection* getDeviceConnectionFor (const Block& b)
  895. {
  896. for (const auto& d : connectedDeviceGroups)
  897. {
  898. for (const auto& info : d->currentDeviceInfo)
  899. {
  900. if (info.uid == b.uid)
  901. return d->getDeviceConnection();
  902. }
  903. }
  904. return nullptr;
  905. }
  906. std::unique_ptr<MIDIDeviceDetector> defaultDetector;
  907. DeviceDetector& deviceDetector;
  908. juce::Array<PhysicalTopologySource*> activeTopologySources;
  909. juce::Array<ControlButtonImplementation*> activeControlButtons;
  910. juce::Array<TouchSurfaceImplementation*> activeTouchSurfaces;
  911. BlockTopology currentTopology;
  912. private:
  913. void timerCallback() override
  914. {
  915. startTimer (1500);
  916. auto detectedDevices = deviceDetector.scanForDevices();
  917. handleDevicesRemoved (detectedDevices);
  918. handleDevicesAdded (detectedDevices);
  919. }
  920. void handleDevicesRemoved (const juce::StringArray& detectedDevices)
  921. {
  922. bool anyDevicesRemoved = false;
  923. for (int i = connectedDeviceGroups.size(); --i >= 0;)
  924. {
  925. if (! connectedDeviceGroups.getUnchecked(i)->isStillConnected (detectedDevices))
  926. {
  927. connectedDeviceGroups.remove (i);
  928. anyDevicesRemoved = true;
  929. }
  930. }
  931. if (anyDevicesRemoved)
  932. handleTopologyChange();
  933. }
  934. void handleDevicesAdded (const juce::StringArray& detectedDevices)
  935. {
  936. bool anyDevicesAdded = false;
  937. for (const auto& devName : detectedDevices)
  938. {
  939. if (! hasDeviceFor (devName))
  940. {
  941. if (auto d = deviceDetector.openDevice (detectedDevices.indexOf (devName)))
  942. {
  943. connectedDeviceGroups.add (new ConnectedDeviceGroup (*this, devName, d));
  944. anyDevicesAdded = true;
  945. }
  946. }
  947. }
  948. if (anyDevicesAdded)
  949. handleTopologyChange();
  950. }
  951. bool hasDeviceFor (const juce::String& devName) const
  952. {
  953. for (auto d : connectedDeviceGroups)
  954. if (d->deviceName == devName)
  955. return true;
  956. return false;
  957. }
  958. juce::OwnedArray<ConnectedDeviceGroup> connectedDeviceGroups;
  959. //==============================================================================
  960. /** Flurries of topology messages sometimes arrive due to loose connections.
  961. Avoid informing listeners until they've stabilised.
  962. */
  963. struct TopologyBroadcastThrottle : private juce::Timer
  964. {
  965. TopologyBroadcastThrottle() = default;
  966. void scheduleTopologyChangeCallback() { startTimer (750); }
  967. void timerCallback() override
  968. {
  969. if (detector->currentTopology != lastTopology)
  970. {
  971. lastTopology = detector->currentTopology;
  972. for (auto* d : detector->activeTopologySources)
  973. d->listeners.call (&TopologySource::Listener::topologyChanged);
  974. #if DUMP_TOPOLOGY
  975. dumpTopology (lastTopology);
  976. #endif
  977. }
  978. stopTimer();
  979. }
  980. Detector* detector = nullptr;
  981. BlockTopology lastTopology;
  982. };
  983. TopologyBroadcastThrottle topologyBroadcastThrottle;
  984. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Detector)
  985. };
  986. //==============================================================================
  987. struct BlockImplementation : public Block,
  988. private MIDIDeviceConnection::Listener,
  989. private Timer
  990. {
  991. BlockImplementation (const BlocksProtocol::BlockSerialNumber& serial, Detector& detectorToUse, BlocksProtocol::VersionNumber version, BlocksProtocol::BlockName name, bool master)
  992. : Block (juce::String ((const char*) serial.serial, sizeof (serial.serial)),
  993. juce::String ((const char*) version.version, version.length),
  994. juce::String ((const char*) name.name, name.length)),
  995. modelData (serial),
  996. remoteHeap (modelData.programAndHeapSize),
  997. detector (detectorToUse),
  998. isMaster (master)
  999. {
  1000. sendCommandMessage (BlocksProtocol::beginAPIMode);
  1001. if (modelData.hasTouchSurface)
  1002. touchSurface.reset (new TouchSurfaceImplementation (*this));
  1003. int i = 0;
  1004. for (auto&& b : modelData.buttons)
  1005. controlButtons.add (new ControlButtonImplementation (*this, i++, b));
  1006. if (modelData.lightGridWidth > 0 && modelData.lightGridHeight > 0)
  1007. ledGrid.reset (new LEDGridImplementation (*this));
  1008. for (auto&& s : modelData.statusLEDs)
  1009. statusLights.add (new StatusLightImplementation (*this, s));
  1010. if (modelData.numLEDRowLEDs > 0)
  1011. ledRow.reset (new LEDRowImplementation (*this));
  1012. listenerToMidiConnection = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this));
  1013. if (listenerToMidiConnection != nullptr)
  1014. listenerToMidiConnection->addListener (this);
  1015. config.setDeviceComms (listenerToMidiConnection);
  1016. }
  1017. ~BlockImplementation()
  1018. {
  1019. if (listenerToMidiConnection != nullptr)
  1020. {
  1021. config.setDeviceComms (nullptr);
  1022. listenerToMidiConnection->removeListener (this);
  1023. }
  1024. }
  1025. void invalidate()
  1026. {
  1027. isStillConnected = false;
  1028. }
  1029. Type getType() const override { return modelData.apiType; }
  1030. juce::String getDeviceDescription() const override { return modelData.description; }
  1031. int getWidth() const override { return modelData.widthUnits; }
  1032. int getHeight() const override { return modelData.heightUnits; }
  1033. float getMillimetersPerUnit() const override { return 47.0f; }
  1034. bool isHardwareBlock() const override { return true; }
  1035. juce::Array<Block::ConnectionPort> getPorts() const override { return modelData.ports; }
  1036. bool isConnected() const override { return isStillConnected && detector.isConnected (uid); }
  1037. bool isMasterBlock() const override { return isMaster; }
  1038. TouchSurface* getTouchSurface() const override { return touchSurface.get(); }
  1039. LEDGrid* getLEDGrid() const override { return ledGrid.get(); }
  1040. LEDRow* getLEDRow() const override { return ledRow.get(); }
  1041. juce::Array<ControlButton*> getButtons() const override
  1042. {
  1043. juce::Array<ControlButton*> result;
  1044. result.addArray (controlButtons);
  1045. return result;
  1046. }
  1047. juce::Array<StatusLight*> getStatusLights() const override
  1048. {
  1049. juce::Array<StatusLight*> result;
  1050. result.addArray (statusLights);
  1051. return result;
  1052. }
  1053. float getBatteryLevel() const override
  1054. {
  1055. if (auto status = detector.getLastStatus (uid))
  1056. return status->batteryLevel.toUnipolarFloat();
  1057. return 0.0f;
  1058. }
  1059. bool isBatteryCharging() const override
  1060. {
  1061. if (auto status = detector.getLastStatus (uid))
  1062. return status->batteryCharging.get() != 0;
  1063. return false;
  1064. }
  1065. bool supportsGraphics() const override
  1066. {
  1067. return false;
  1068. }
  1069. int getDeviceIndex() const noexcept
  1070. {
  1071. return isConnected() ? detector.getIndexFromDeviceID (uid) : -1;
  1072. }
  1073. template <typename PacketBuilder>
  1074. bool sendMessageToDevice (const PacketBuilder& builder)
  1075. {
  1076. lastMessageSendTime = juce::Time::getCurrentTime();
  1077. return detector.sendMessageToDevice (uid, builder);
  1078. }
  1079. bool sendCommandMessage (uint32 commandID)
  1080. {
  1081. int index = getDeviceIndex();
  1082. if (index < 0)
  1083. return false;
  1084. BlocksProtocol::HostPacketBuilder<64> p;
  1085. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1086. p.deviceControlMessage (commandID);
  1087. p.writePacketSysexFooter();
  1088. return sendMessageToDevice (p);
  1089. }
  1090. void handleCustomMessage (Block::Timestamp, const int32* data)
  1091. {
  1092. ProgramEventMessage m;
  1093. for (uint32 i = 0; i < BlocksProtocol::numProgramMessageInts; ++i)
  1094. m.values[i] = data[i];
  1095. programEventListeners.call (&Block::ProgramEventListener::handleProgramEvent, *this, m);
  1096. }
  1097. static BlockImplementation* getFrom (Block& b) noexcept
  1098. {
  1099. if (auto bi = dynamic_cast<BlockImplementation*> (&b))
  1100. return bi;
  1101. jassertfalse;
  1102. return nullptr;
  1103. }
  1104. bool isControlBlock() const
  1105. {
  1106. auto type = getType();
  1107. return type == Block::Type::liveBlock
  1108. || type == Block::Type::loopBlock
  1109. || type == Block::Type::touchBlock
  1110. || type == Block::Type::developerControlBlock;
  1111. }
  1112. //==============================================================================
  1113. std::function<void(const String&)> logger;
  1114. void setLogger (std::function<void(const String&)> newLogger) override
  1115. {
  1116. logger = newLogger;
  1117. }
  1118. void handleLogMessage (const String& message) const
  1119. {
  1120. if (logger != nullptr)
  1121. logger (message);
  1122. }
  1123. //==============================================================================
  1124. juce::Result setProgram (Program* newProgram) override
  1125. {
  1126. if (newProgram == nullptr || program.get() != newProgram)
  1127. {
  1128. {
  1129. std::unique_ptr<Program> p (newProgram);
  1130. if (program != nullptr
  1131. && newProgram != nullptr
  1132. && program->getLittleFootProgram() == newProgram->getLittleFootProgram())
  1133. return juce::Result::ok();
  1134. stopTimer();
  1135. std::swap (program, p);
  1136. }
  1137. stopTimer();
  1138. programSize = 0;
  1139. if (program != nullptr)
  1140. {
  1141. littlefoot::Compiler compiler;
  1142. compiler.addNativeFunctions (PhysicalTopologySource::getStandardLittleFootFunctions());
  1143. auto err = compiler.compile (program->getLittleFootProgram(), 512);
  1144. if (err.failed())
  1145. return err;
  1146. DBG ("Compiled littlefoot program, space needed: "
  1147. << (int) compiler.getCompiledProgram().getTotalSpaceNeeded() << " bytes");
  1148. if (compiler.getCompiledProgram().getTotalSpaceNeeded() > getMemorySize())
  1149. return Result::fail ("Program too large!");
  1150. auto size = (size_t) compiler.compiledObjectCode.size();
  1151. programSize = (uint32) size;
  1152. remoteHeap.resetDataRangeToUnknown (0, remoteHeap.blockSize);
  1153. remoteHeap.clear();
  1154. remoteHeap.sendChanges (*this, true);
  1155. remoteHeap.resetDataRangeToUnknown (0, (uint32) size);
  1156. remoteHeap.setBytes (0, compiler.compiledObjectCode.begin(), size);
  1157. remoteHeap.sendChanges (*this, true);
  1158. this->resetConfigListActiveStatus();
  1159. if (auto changeCallback = this->configChangedCallback)
  1160. changeCallback (*this, {}, this->getMaxConfigIndex());
  1161. }
  1162. else
  1163. {
  1164. remoteHeap.clear();
  1165. }
  1166. }
  1167. else
  1168. {
  1169. jassertfalse;
  1170. }
  1171. return juce::Result::ok();
  1172. }
  1173. Program* getProgram() const override { return program.get(); }
  1174. void sendProgramEvent (const ProgramEventMessage& message) override
  1175. {
  1176. static_assert (sizeof (ProgramEventMessage::values) == 4 * BlocksProtocol::numProgramMessageInts,
  1177. "Need to keep the internal and external messages structures the same");
  1178. if (remoteHeap.isProgramLoaded())
  1179. {
  1180. auto index = getDeviceIndex();
  1181. if (index >= 0)
  1182. {
  1183. BlocksProtocol::HostPacketBuilder<128> p;
  1184. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1185. if (p.addProgramEventMessage (message.values))
  1186. {
  1187. p.writePacketSysexFooter();
  1188. sendMessageToDevice (p);
  1189. }
  1190. }
  1191. else
  1192. {
  1193. jassertfalse;
  1194. }
  1195. }
  1196. }
  1197. void timerCallback() override
  1198. {
  1199. if (remoteHeap.isFullySynced() && remoteHeap.isProgramLoaded())
  1200. {
  1201. stopTimer();
  1202. sendCommandMessage (BlocksProtocol::saveProgramAsDefault);
  1203. }
  1204. else
  1205. {
  1206. startTimer (100);
  1207. }
  1208. }
  1209. void saveProgramAsDefault() override
  1210. {
  1211. startTimer (10);
  1212. }
  1213. uint32 getMemorySize() override
  1214. {
  1215. return modelData.programAndHeapSize;
  1216. }
  1217. void setDataByte (size_t offset, uint8 value) override
  1218. {
  1219. remoteHeap.setByte (programSize + offset, value);
  1220. }
  1221. void setDataBytes (size_t offset, const void* newData, size_t num) override
  1222. {
  1223. remoteHeap.setBytes (programSize + offset, static_cast<const uint8*> (newData), num);
  1224. }
  1225. void setDataBits (uint32 startBit, uint32 numBits, uint32 value) override
  1226. {
  1227. remoteHeap.setBits (programSize * 8 + startBit, numBits, value);
  1228. }
  1229. uint8 getDataByte (size_t offset) override
  1230. {
  1231. return remoteHeap.getByte (programSize + offset);
  1232. }
  1233. void handleSharedDataACK (uint32 packetCounter) noexcept
  1234. {
  1235. pingFromDevice();
  1236. remoteHeap.handleACKFromDevice (*this, packetCounter);
  1237. }
  1238. bool sendFirmwareUpdatePacket (const uint8* data, uint8 size, std::function<void (uint8, uint32)> callback) override
  1239. {
  1240. firmwarePacketAckCallback = {};
  1241. auto index = getDeviceIndex();
  1242. if (index >= 0)
  1243. {
  1244. BlocksProtocol::HostPacketBuilder<256> p;
  1245. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1246. if (p.addFirmwareUpdatePacket (data, size))
  1247. {
  1248. p.writePacketSysexFooter();
  1249. if (sendMessageToDevice (p))
  1250. {
  1251. firmwarePacketAckCallback = callback;
  1252. return true;
  1253. }
  1254. }
  1255. }
  1256. else
  1257. {
  1258. jassertfalse;
  1259. }
  1260. return false;
  1261. }
  1262. void handleFirmwareUpdateACK (uint8 resultCode, uint32 resultDetail)
  1263. {
  1264. if (firmwarePacketAckCallback != nullptr)
  1265. {
  1266. firmwarePacketAckCallback (resultCode, resultDetail);
  1267. firmwarePacketAckCallback = {};
  1268. }
  1269. }
  1270. void handleConfigUpdateMessage (int32 item, int32 value, int32 min, int32 max)
  1271. {
  1272. config.handleConfigUpdateMessage (item, value, min, max);
  1273. }
  1274. void handleConfigSetMessage(int32 item, int32 value)
  1275. {
  1276. config.handleConfigSetMessage (item, value);
  1277. }
  1278. void pingFromDevice()
  1279. {
  1280. lastMessageReceiveTime = juce::Time::getCurrentTime();
  1281. }
  1282. void addDataInputPortListener (DataInputPortListener* listener) override
  1283. {
  1284. Block::addDataInputPortListener (listener);
  1285. if (auto midiInput = getMidiInput())
  1286. midiInput->start();
  1287. }
  1288. void sendMessage (const void* message, size_t messageSize) override
  1289. {
  1290. if (auto midiOutput = getMidiOutput())
  1291. midiOutput->sendMessageNow ({ message, (int) messageSize });
  1292. }
  1293. void handleTimerTick()
  1294. {
  1295. if (++resetMessagesSent < 3)
  1296. {
  1297. if (resetMessagesSent == 1)
  1298. sendCommandMessage (BlocksProtocol::endAPIMode);
  1299. sendCommandMessage (BlocksProtocol::beginAPIMode);
  1300. return;
  1301. }
  1302. if (ledGrid != nullptr)
  1303. if (auto renderer = ledGrid->getRenderer())
  1304. renderer->renderLEDGrid (*ledGrid);
  1305. remoteHeap.sendChanges (*this, false);
  1306. if (lastMessageSendTime < juce::Time::getCurrentTime() - juce::RelativeTime::milliseconds (pingIntervalMs))
  1307. sendCommandMessage (BlocksProtocol::ping);
  1308. }
  1309. //==============================================================================
  1310. int32 getLocalConfigValue (uint32 item) override
  1311. {
  1312. initialiseDeviceIndexAndConnection();
  1313. return config.getItemValue ((BlocksProtocol::ConfigItemId) item);
  1314. }
  1315. void setLocalConfigValue (uint32 item, int32 value) override
  1316. {
  1317. initialiseDeviceIndexAndConnection();
  1318. config.setItemValue ((BlocksProtocol::ConfigItemId) item, value);
  1319. }
  1320. void setLocalConfigRange (uint32 item, int32 min, int32 max) override
  1321. {
  1322. initialiseDeviceIndexAndConnection();
  1323. config.setItemMin ((BlocksProtocol::ConfigItemId) item, min);
  1324. config.setItemMax ((BlocksProtocol::ConfigItemId) item, max);
  1325. }
  1326. void setLocalConfigItemActive (uint32 item, bool isActive) override
  1327. {
  1328. initialiseDeviceIndexAndConnection();
  1329. config.setItemActive ((BlocksProtocol::ConfigItemId) item, isActive);
  1330. }
  1331. bool isLocalConfigItemActive (uint32 item) override
  1332. {
  1333. initialiseDeviceIndexAndConnection();
  1334. return config.getItemActive ((BlocksProtocol::ConfigItemId) item);
  1335. }
  1336. uint32 getMaxConfigIndex () override
  1337. {
  1338. return uint32 (BlocksProtocol::maxConfigIndex);
  1339. }
  1340. bool isValidUserConfigIndex (uint32 item) override
  1341. {
  1342. return item >= (uint32) BlocksProtocol::ConfigItemId::user0
  1343. && item < (uint32) (BlocksProtocol::ConfigItemId::user0 + numberOfUserConfigs);
  1344. }
  1345. ConfigMetaData getLocalConfigMetaData (uint32 item) override
  1346. {
  1347. initialiseDeviceIndexAndConnection();
  1348. return config.getMetaData ((BlocksProtocol::ConfigItemId) item);
  1349. }
  1350. void requestFactoryConfigSync() override
  1351. {
  1352. initialiseDeviceIndexAndConnection();
  1353. config.requestFactoryConfigSync();
  1354. }
  1355. void resetConfigListActiveStatus() override
  1356. {
  1357. config.resetConfigListActiveStatus();
  1358. }
  1359. void setConfigChangedCallback (std::function<void(Block&, const ConfigMetaData&, uint32)> configChanged) override
  1360. {
  1361. configChangedCallback = configChanged;
  1362. }
  1363. void factoryReset() override
  1364. {
  1365. auto index = getDeviceIndex();
  1366. if (index >= 0)
  1367. {
  1368. BlocksProtocol::HostPacketBuilder<32> p;
  1369. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1370. p.addFactoryReset();
  1371. p.writePacketSysexFooter();
  1372. sendMessageToDevice (p);
  1373. }
  1374. else
  1375. {
  1376. jassertfalse;
  1377. }
  1378. }
  1379. void blockReset() override
  1380. {
  1381. auto index = getDeviceIndex();
  1382. if (index >= 0)
  1383. {
  1384. BlocksProtocol::HostPacketBuilder<32> p;
  1385. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1386. p.addBlockReset();
  1387. p.writePacketSysexFooter();
  1388. sendMessageToDevice (p);
  1389. }
  1390. else
  1391. {
  1392. jassertfalse;
  1393. }
  1394. }
  1395. bool setName (const juce::String& newName) override
  1396. {
  1397. auto index = getDeviceIndex();
  1398. if (index >= 0)
  1399. {
  1400. BlocksProtocol::HostPacketBuilder<128> p;
  1401. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1402. if (p.addSetBlockName (newName))
  1403. {
  1404. p.writePacketSysexFooter();
  1405. if (sendMessageToDevice (p))
  1406. return true;
  1407. }
  1408. }
  1409. else
  1410. {
  1411. jassertfalse;
  1412. }
  1413. return false;
  1414. }
  1415. //==============================================================================
  1416. std::unique_ptr<TouchSurface> touchSurface;
  1417. juce::OwnedArray<ControlButton> controlButtons;
  1418. std::unique_ptr<LEDGridImplementation> ledGrid;
  1419. std::unique_ptr<LEDRowImplementation> ledRow;
  1420. juce::OwnedArray<StatusLight> statusLights;
  1421. BlocksProtocol::BlockDataSheet modelData;
  1422. MIDIDeviceConnection* listenerToMidiConnection = nullptr;
  1423. static constexpr int pingIntervalMs = 400;
  1424. static constexpr uint32 maxBlockSize = BlocksProtocol::padBlockProgramAndHeapSize;
  1425. static constexpr uint32 maxPacketCounter = BlocksProtocol::PacketCounter::maxValue;
  1426. static constexpr uint32 maxPacketSize = 200;
  1427. using PacketBuilder = BlocksProtocol::HostPacketBuilder<maxPacketSize>;
  1428. using RemoteHeapType = littlefoot::LittleFootRemoteHeap<BlockImplementation>;
  1429. RemoteHeapType remoteHeap;
  1430. Detector& detector;
  1431. juce::Time lastMessageSendTime, lastMessageReceiveTime;
  1432. BlockConfigManager config;
  1433. std::function<void(Block&, const ConfigMetaData&, uint32)> configChangedCallback;
  1434. private:
  1435. std::unique_ptr<Program> program;
  1436. uint32 programSize = 0;
  1437. std::function<void(uint8, uint32)> firmwarePacketAckCallback;
  1438. uint32 resetMessagesSent = 0;
  1439. bool isStillConnected = true;
  1440. bool isMaster = false;
  1441. void initialiseDeviceIndexAndConnection()
  1442. {
  1443. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  1444. config.setDeviceComms (listenerToMidiConnection);
  1445. }
  1446. const juce::MidiInput* getMidiInput() const
  1447. {
  1448. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1449. return c->midiInput.get();
  1450. jassertfalse;
  1451. return nullptr;
  1452. }
  1453. juce::MidiInput* getMidiInput()
  1454. {
  1455. return const_cast<juce::MidiInput*> (static_cast<const BlockImplementation&>(*this).getMidiInput());
  1456. }
  1457. const juce::MidiOutput* getMidiOutput() const
  1458. {
  1459. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1460. return c->midiOutput.get();
  1461. jassertfalse;
  1462. return nullptr;
  1463. }
  1464. juce::MidiOutput* getMidiOutput()
  1465. {
  1466. return const_cast<juce::MidiOutput*> (static_cast<const BlockImplementation&>(*this).getMidiOutput());
  1467. }
  1468. void handleIncomingMidiMessage (const juce::MidiMessage& message) override
  1469. {
  1470. dataInputPortListeners.call (&Block::DataInputPortListener::handleIncomingDataPortMessage,
  1471. *this, message.getRawData(), (size_t) message.getRawDataSize());
  1472. }
  1473. void connectionBeingDeleted (const MIDIDeviceConnection& c) override
  1474. {
  1475. jassert (listenerToMidiConnection == &c);
  1476. juce::ignoreUnused (c);
  1477. listenerToMidiConnection->removeListener (this);
  1478. listenerToMidiConnection = nullptr;
  1479. config.setDeviceComms (nullptr);
  1480. }
  1481. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockImplementation)
  1482. };
  1483. //==============================================================================
  1484. struct LEDRowImplementation : public LEDRow,
  1485. private Timer
  1486. {
  1487. LEDRowImplementation (BlockImplementation& b) : LEDRow (b)
  1488. {
  1489. startTimer (300);
  1490. }
  1491. void setButtonColour (uint32 index, LEDColour colour)
  1492. {
  1493. if (index < 10)
  1494. {
  1495. colours[index] = colour;
  1496. flush();
  1497. }
  1498. }
  1499. int getNumLEDs() const override
  1500. {
  1501. return static_cast<const BlockImplementation&> (block).modelData.numLEDRowLEDs;
  1502. }
  1503. void setLEDColour (int index, LEDColour colour) override
  1504. {
  1505. if ((uint32) index < 15u)
  1506. {
  1507. colours[10 + index] = colour;
  1508. flush();
  1509. }
  1510. }
  1511. void setOverlayColour (LEDColour colour) override
  1512. {
  1513. colours[25] = colour;
  1514. flush();
  1515. }
  1516. void resetOverlayColour() override
  1517. {
  1518. setOverlayColour ({});
  1519. }
  1520. private:
  1521. LEDColour colours[26];
  1522. void timerCallback() override
  1523. {
  1524. stopTimer();
  1525. loadProgramOntoBlock();
  1526. flush();
  1527. }
  1528. void loadProgramOntoBlock()
  1529. {
  1530. if (block.getProgram() == nullptr)
  1531. {
  1532. auto err = block.setProgram (new DefaultLEDGridProgram (block));
  1533. if (err.failed())
  1534. {
  1535. DBG (err.getErrorMessage());
  1536. jassertfalse;
  1537. }
  1538. }
  1539. }
  1540. void flush()
  1541. {
  1542. if (block.getProgram() != nullptr)
  1543. for (uint32 i = 0; i < (uint32) numElementsInArray (colours); ++i)
  1544. write565Colour (16 * i, colours[i]);
  1545. }
  1546. void write565Colour (uint32 bitIndex, LEDColour colour)
  1547. {
  1548. block.setDataBits (bitIndex, 5, colour.getRed() >> 3);
  1549. block.setDataBits (bitIndex + 5, 6, colour.getGreen() >> 2);
  1550. block.setDataBits (bitIndex + 11, 5, colour.getBlue() >> 3);
  1551. }
  1552. struct DefaultLEDGridProgram : public Block::Program
  1553. {
  1554. DefaultLEDGridProgram (Block& b) : Block::Program (b) {}
  1555. juce::String getLittleFootProgram() override
  1556. {
  1557. /* Data format:
  1558. 0: 10 x 5-6-5 bits for button LED RGBs
  1559. 20: 15 x 5-6-5 bits for LED row colours
  1560. 50: 1 x 5-6-5 bits for LED row overlay colour
  1561. */
  1562. return R"littlefoot(
  1563. #heapsize: 128
  1564. int getColour (int bitIndex)
  1565. {
  1566. return makeARGB (255,
  1567. getHeapBits (bitIndex, 5) << 3,
  1568. getHeapBits (bitIndex + 5, 6) << 2,
  1569. getHeapBits (bitIndex + 11, 5) << 3);
  1570. }
  1571. int getButtonColour (int index)
  1572. {
  1573. return getColour (16 * index);
  1574. }
  1575. int getLEDColour (int index)
  1576. {
  1577. if (getHeapInt (50))
  1578. return getColour (50 * 8);
  1579. return getColour (20 * 8 + 16 * index);
  1580. }
  1581. void repaint()
  1582. {
  1583. for (int x = 0; x < 15; ++x)
  1584. fillPixel (getLEDColour (x), x, 0);
  1585. for (int i = 0; i < 10; ++i)
  1586. fillPixel (getButtonColour (i), i, 1);
  1587. }
  1588. void handleMessage (int p1, int p2) {}
  1589. )littlefoot";
  1590. }
  1591. };
  1592. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDRowImplementation)
  1593. };
  1594. //==============================================================================
  1595. struct TouchSurfaceImplementation : public TouchSurface,
  1596. private juce::Timer
  1597. {
  1598. TouchSurfaceImplementation (BlockImplementation& b) : TouchSurface (b), blockImpl (b)
  1599. {
  1600. if (auto det = Detector::getFrom (block))
  1601. det->activeTouchSurfaces.add (this);
  1602. startTimer (500);
  1603. }
  1604. ~TouchSurfaceImplementation()
  1605. {
  1606. if (auto det = Detector::getFrom (block))
  1607. det->activeTouchSurfaces.removeFirstMatchingValue (this);
  1608. }
  1609. int getNumberOfKeywaves() const noexcept override
  1610. {
  1611. return blockImpl.modelData.numKeywaves;
  1612. }
  1613. void broadcastTouchChange (const TouchSurface::Touch& touchEvent)
  1614. {
  1615. auto& status = touches.getValue (touchEvent);
  1616. // Fake a touch end if we receive a duplicate touch-start with no preceding touch-end (ie: comms error)
  1617. if (touchEvent.isTouchStart && status.isActive)
  1618. killTouch (touchEvent, status, juce::Time::getMillisecondCounter());
  1619. // Fake a touch start if we receive an unexpected event with no matching start event. (ie: comms error)
  1620. if (! touchEvent.isTouchStart && ! status.isActive)
  1621. {
  1622. TouchSurface::Touch t (touchEvent);
  1623. t.isTouchStart = true;
  1624. t.isTouchEnd = false;
  1625. if (t.zVelocity <= 0) t.zVelocity = status.lastStrikePressure;
  1626. if (t.zVelocity <= 0) t.zVelocity = t.z;
  1627. if (t.zVelocity <= 0) t.zVelocity = 0.9f;
  1628. listeners.call (&TouchSurface::Listener::touchChanged, *this, t);
  1629. }
  1630. // Normal handling:
  1631. status.lastEventTime = juce::Time::getMillisecondCounter();
  1632. status.isActive = ! touchEvent.isTouchEnd;
  1633. if (touchEvent.isTouchStart)
  1634. status.lastStrikePressure = touchEvent.zVelocity;
  1635. listeners.call (&TouchSurface::Listener::touchChanged, *this, touchEvent);
  1636. }
  1637. void timerCallback() override
  1638. {
  1639. // Find touches that seem to have become stuck, and fake a touch-end for them..
  1640. static const uint32 touchTimeOutMs = 500;
  1641. for (auto& t : touches)
  1642. {
  1643. auto& status = t.value;
  1644. auto now = juce::Time::getMillisecondCounter();
  1645. if (status.isActive && now > status.lastEventTime + touchTimeOutMs)
  1646. killTouch (t.touch, status, now);
  1647. }
  1648. }
  1649. struct TouchStatus
  1650. {
  1651. uint32 lastEventTime = 0;
  1652. float lastStrikePressure = 0;
  1653. bool isActive = false;
  1654. };
  1655. void killTouch (const TouchSurface::Touch& touch, TouchStatus& status, uint32 timeStamp) noexcept
  1656. {
  1657. jassert (status.isActive);
  1658. TouchSurface::Touch killTouch (touch);
  1659. killTouch.z = 0;
  1660. killTouch.xVelocity = 0;
  1661. killTouch.yVelocity = 0;
  1662. killTouch.zVelocity = -1.0f;
  1663. killTouch.eventTimestamp = timeStamp;
  1664. killTouch.isTouchStart = false;
  1665. killTouch.isTouchEnd = true;
  1666. listeners.call (&TouchSurface::Listener::touchChanged, *this, killTouch);
  1667. status.isActive = false;
  1668. }
  1669. void cancelAllActiveTouches() noexcept override
  1670. {
  1671. const auto now = juce::Time::getMillisecondCounter();
  1672. for (auto& t : touches)
  1673. if (t.value.isActive)
  1674. killTouch (t.touch, t.value, now);
  1675. touches.clear();
  1676. }
  1677. BlockImplementation& blockImpl;
  1678. TouchList<TouchStatus> touches;
  1679. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TouchSurfaceImplementation)
  1680. };
  1681. //==============================================================================
  1682. struct ControlButtonImplementation : public ControlButton
  1683. {
  1684. ControlButtonImplementation (BlockImplementation& b, int index, BlocksProtocol::BlockDataSheet::ButtonInfo info)
  1685. : ControlButton (b), blockImpl (b), buttonInfo (info), buttonIndex (index)
  1686. {
  1687. if (auto det = Detector::getFrom (block))
  1688. det->activeControlButtons.add (this);
  1689. }
  1690. ~ControlButtonImplementation()
  1691. {
  1692. if (auto det = Detector::getFrom (block))
  1693. det->activeControlButtons.removeFirstMatchingValue (this);
  1694. }
  1695. ButtonFunction getType() const override { return buttonInfo.type; }
  1696. juce::String getName() const override { return BlocksProtocol::getButtonNameForFunction (buttonInfo.type); }
  1697. float getPositionX() const override { return buttonInfo.x; }
  1698. float getPositionY() const override { return buttonInfo.y; }
  1699. bool hasLight() const override { return blockImpl.isControlBlock(); }
  1700. bool setLightColour (LEDColour colour) override
  1701. {
  1702. if (hasLight())
  1703. {
  1704. if (auto row = blockImpl.ledRow.get())
  1705. {
  1706. row->setButtonColour ((uint32) buttonIndex, colour);
  1707. return true;
  1708. }
  1709. }
  1710. return false;
  1711. }
  1712. void broadcastButtonChange (Block::Timestamp timestamp, ControlButton::ButtonFunction button, bool isDown)
  1713. {
  1714. if (button == buttonInfo.type)
  1715. {
  1716. if (wasDown == isDown)
  1717. sendButtonChangeToListeners (timestamp, ! isDown);
  1718. sendButtonChangeToListeners (timestamp, isDown);
  1719. wasDown = isDown;
  1720. }
  1721. }
  1722. void sendButtonChangeToListeners (Block::Timestamp timestamp, bool isDown)
  1723. {
  1724. if (isDown)
  1725. listeners.call (&ControlButton::Listener::buttonPressed, *this, timestamp);
  1726. else
  1727. listeners.call (&ControlButton::Listener::buttonReleased, *this, timestamp);
  1728. }
  1729. BlockImplementation& blockImpl;
  1730. BlocksProtocol::BlockDataSheet::ButtonInfo buttonInfo;
  1731. int buttonIndex;
  1732. bool wasDown = false;
  1733. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ControlButtonImplementation)
  1734. };
  1735. //==============================================================================
  1736. struct StatusLightImplementation : public StatusLight
  1737. {
  1738. StatusLightImplementation (Block& b, BlocksProtocol::BlockDataSheet::StatusLEDInfo i) : StatusLight (b), info (i)
  1739. {
  1740. }
  1741. juce::String getName() const override { return info.name; }
  1742. bool setColour (LEDColour newColour) override
  1743. {
  1744. // XXX TODO!
  1745. juce::ignoreUnused (newColour);
  1746. return false;
  1747. }
  1748. BlocksProtocol::BlockDataSheet::StatusLEDInfo info;
  1749. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StatusLightImplementation)
  1750. };
  1751. //==============================================================================
  1752. struct LEDGridImplementation : public LEDGrid
  1753. {
  1754. LEDGridImplementation (BlockImplementation& b) : LEDGrid (b), blockImpl (b)
  1755. {
  1756. }
  1757. int getNumColumns() const override { return blockImpl.modelData.lightGridWidth; }
  1758. int getNumRows() const override { return blockImpl.modelData.lightGridHeight; }
  1759. BlockImplementation& blockImpl;
  1760. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDGridImplementation)
  1761. };
  1762. //==============================================================================
  1763. #if DUMP_TOPOLOGY
  1764. static juce::String idToSerialNum (const BlockTopology& topology, Block::UID uid)
  1765. {
  1766. for (auto* b : topology.blocks)
  1767. if (b->uid == uid)
  1768. return b->serialNumber;
  1769. return "???";
  1770. }
  1771. static juce::String portEdgeToString (Block::ConnectionPort port)
  1772. {
  1773. switch (port.edge)
  1774. {
  1775. case Block::ConnectionPort::DeviceEdge::north: return "north";
  1776. case Block::ConnectionPort::DeviceEdge::south: return "south";
  1777. case Block::ConnectionPort::DeviceEdge::east: return "east";
  1778. case Block::ConnectionPort::DeviceEdge::west: return "west";
  1779. }
  1780. return {};
  1781. }
  1782. static juce::String portToString (Block::ConnectionPort port)
  1783. {
  1784. return portEdgeToString (port) + "_" + juce::String (port.index);
  1785. }
  1786. static void dumpTopology (const BlockTopology& topology)
  1787. {
  1788. MemoryOutputStream m;
  1789. m << "=============================================================================" << newLine
  1790. << "Topology: " << topology.blocks.size() << " device(s)" << newLine
  1791. << newLine;
  1792. int index = 0;
  1793. for (auto block : topology.blocks)
  1794. {
  1795. m << "Device " << index++ << (block->isMasterBlock() ? ": (MASTER)" : ":") << newLine;
  1796. m << " Description: " << block->getDeviceDescription() << newLine
  1797. << " Serial: " << block->serialNumber << newLine;
  1798. if (auto bi = BlockImplementation::getFrom (*block))
  1799. m << " Short address: " << (int) bi->getDeviceIndex() << newLine;
  1800. m << " Battery level: " + juce::String (juce::roundToInt (100.0f * block->getBatteryLevel())) + "%" << newLine
  1801. << " Battery charging: " + juce::String (block->isBatteryCharging() ? "y" : "n") << newLine
  1802. << " Width: " << block->getWidth() << newLine
  1803. << " Height: " << block->getHeight() << newLine
  1804. << " Millimeters per unit: " << block->getMillimetersPerUnit() << newLine
  1805. << newLine;
  1806. }
  1807. for (auto& connection : topology.connections)
  1808. {
  1809. m << idToSerialNum (topology, connection.device1)
  1810. << ":" << portToString (connection.connectionPortOnDevice1)
  1811. << " <-> "
  1812. << idToSerialNum (topology, connection.device2)
  1813. << ":" << portToString (connection.connectionPortOnDevice2) << newLine;
  1814. }
  1815. m << "=============================================================================" << newLine;
  1816. Logger::outputDebugString (m.toString());
  1817. }
  1818. #endif
  1819. };
  1820. //==============================================================================
  1821. struct PhysicalTopologySource::DetectorHolder : private juce::Timer
  1822. {
  1823. DetectorHolder (PhysicalTopologySource& pts)
  1824. : topologySource (pts),
  1825. detector (Internal::Detector::getDefaultDetector())
  1826. {
  1827. startTimerHz (30);
  1828. }
  1829. DetectorHolder (PhysicalTopologySource& pts, DeviceDetector& dd)
  1830. : topologySource (pts),
  1831. detector (new Internal::Detector (dd))
  1832. {
  1833. startTimerHz (30);
  1834. }
  1835. void timerCallback() override
  1836. {
  1837. if (! topologySource.hasOwnServiceTimer())
  1838. handleTimerTick();
  1839. }
  1840. void handleTimerTick()
  1841. {
  1842. for (auto& b : detector->currentTopology.blocks)
  1843. if (auto bi = Internal::BlockImplementation::getFrom (*b))
  1844. bi->handleTimerTick();
  1845. }
  1846. PhysicalTopologySource& topologySource;
  1847. Internal::Detector::Ptr detector;
  1848. };
  1849. //==============================================================================
  1850. PhysicalTopologySource::PhysicalTopologySource()
  1851. : detector (new DetectorHolder (*this))
  1852. {
  1853. detector->detector->activeTopologySources.add (this);
  1854. }
  1855. PhysicalTopologySource::PhysicalTopologySource (DeviceDetector& detectorToUse)
  1856. : detector (new DetectorHolder (*this, detectorToUse))
  1857. {
  1858. detector->detector->activeTopologySources.add (this);
  1859. }
  1860. PhysicalTopologySource::~PhysicalTopologySource()
  1861. {
  1862. detector->detector->detach (this);
  1863. detector = nullptr;
  1864. }
  1865. BlockTopology PhysicalTopologySource::getCurrentTopology() const
  1866. {
  1867. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  1868. return detector->detector->currentTopology;
  1869. }
  1870. void PhysicalTopologySource::cancelAllActiveTouches() noexcept
  1871. {
  1872. detector->detector->cancelAllActiveTouches();
  1873. }
  1874. bool PhysicalTopologySource::hasOwnServiceTimer() const { return false; }
  1875. void PhysicalTopologySource::handleTimerTick() { detector->handleTimerTick(); }
  1876. PhysicalTopologySource::DeviceConnection::DeviceConnection() {}
  1877. PhysicalTopologySource::DeviceConnection::~DeviceConnection() {}
  1878. PhysicalTopologySource::DeviceDetector::DeviceDetector() {}
  1879. PhysicalTopologySource::DeviceDetector::~DeviceDetector() {}
  1880. const char* const* PhysicalTopologySource::getStandardLittleFootFunctions() noexcept
  1881. {
  1882. return BlocksProtocol::ledProgramLittleFootFunctions;
  1883. }
  1884. static bool blocksMatch (const Block::Array& list1, const Block::Array& list2) noexcept
  1885. {
  1886. if (list1.size() != list2.size())
  1887. return false;
  1888. for (auto&& b : list1)
  1889. if (! list2.contains (b))
  1890. return false;
  1891. return true;
  1892. }
  1893. bool BlockTopology::operator== (const BlockTopology& other) const noexcept
  1894. {
  1895. return connections == other.connections && blocksMatch (blocks, other.blocks);
  1896. }
  1897. bool BlockTopology::operator!= (const BlockTopology& other) const noexcept
  1898. {
  1899. return ! operator== (other);
  1900. }
  1901. bool BlockDeviceConnection::operator== (const BlockDeviceConnection& other) const noexcept
  1902. {
  1903. return (device1 == other.device1 && device2 == other.device2
  1904. && connectionPortOnDevice1 == other.connectionPortOnDevice1
  1905. && connectionPortOnDevice2 == other.connectionPortOnDevice2)
  1906. || (device1 == other.device2 && device2 == other.device1
  1907. && connectionPortOnDevice1 == other.connectionPortOnDevice2
  1908. && connectionPortOnDevice2 == other.connectionPortOnDevice1);
  1909. }
  1910. bool BlockDeviceConnection::operator!= (const BlockDeviceConnection& other) const noexcept
  1911. {
  1912. return ! operator== (other);
  1913. }
  1914. } // namespace juce