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.

2404 lines
84KB

  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 ([this] (Listener& l) { l.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& l) { l.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 && deviceVersion.isNotEmpty())
  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. const 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. if (dc.device1 <= 0 || dc.device2 <= 0)
  622. continue;
  623. dc.connectionPortOnDevice1 = convertConnectionPort (dc.device1, c.port1);
  624. dc.connectionPortOnDevice2 = convertConnectionPort (dc.device2, c.port2);
  625. result.add (dc);
  626. }
  627. return result;
  628. }
  629. Block::ConnectionPort convertConnectionPort (Block::UID uid, BlocksProtocol::ConnectorPort p) noexcept
  630. {
  631. if (auto* info = getDeviceInfoFromUID (uid))
  632. return BlocksProtocol::BlockDataSheet (info->serial).convertPortIndexToConnectorPort (p);
  633. jassertfalse;
  634. return { Block::ConnectionPort::DeviceEdge::north, 0 };
  635. }
  636. //==============================================================================
  637. void handleIncomingMessage (const void* data, size_t dataSize)
  638. {
  639. juce::MemoryBlock mb (data, dataSize);
  640. {
  641. const juce::ScopedLock sl (incomingPacketLock);
  642. incomingPackets.add (std::move (mb));
  643. }
  644. triggerAsyncUpdate();
  645. #if DUMP_BANDWIDTH_STATS
  646. registerBytesIn ((int) dataSize);
  647. #endif
  648. }
  649. void handleAsyncUpdate() override
  650. {
  651. juce::Array<juce::MemoryBlock> packets;
  652. packets.ensureStorageAllocated (32);
  653. {
  654. const juce::ScopedLock sl (incomingPacketLock);
  655. incomingPackets.swapWith (packets);
  656. }
  657. for (auto& packet : packets)
  658. {
  659. auto data = static_cast<const uint8*> (packet.getData());
  660. BlocksProtocol::HostPacketDecoder<ConnectedDeviceGroup>
  661. ::processNextPacket (*this, *data, data + 1, (int) packet.getSize() - 1);
  662. }
  663. lastGlobalPingTime = juce::Time::getCurrentTime();
  664. }
  665. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectedDeviceGroup)
  666. };
  667. //==============================================================================
  668. /** This is the main singleton object that keeps track of connected blocks */
  669. struct Detector : public juce::ReferenceCountedObject,
  670. private juce::Timer
  671. {
  672. Detector() : defaultDetector (new MIDIDeviceDetector()), deviceDetector (*defaultDetector)
  673. {
  674. topologyBroadcastThrottle.detector = this;
  675. startTimer (10);
  676. }
  677. Detector (DeviceDetector& dd) : deviceDetector (dd)
  678. {
  679. topologyBroadcastThrottle.detector = this;
  680. startTimer (10);
  681. }
  682. ~Detector()
  683. {
  684. jassert (activeTopologySources.isEmpty());
  685. jassert (activeControlButtons.isEmpty());
  686. }
  687. using Ptr = juce::ReferenceCountedObjectPtr<Detector>;
  688. static Detector::Ptr getDefaultDetector()
  689. {
  690. auto& d = getDefaultDetectorPointer();
  691. if (d == nullptr)
  692. d = new Detector();
  693. return d;
  694. }
  695. static Detector::Ptr& getDefaultDetectorPointer()
  696. {
  697. static Detector::Ptr defaultDetector;
  698. return defaultDetector;
  699. }
  700. void detach (PhysicalTopologySource* pts)
  701. {
  702. activeTopologySources.removeAllInstancesOf (pts);
  703. if (activeTopologySources.isEmpty())
  704. {
  705. for (auto& b : currentTopology.blocks)
  706. if (auto bi = BlockImplementation::getFrom (*b))
  707. bi->sendCommandMessage (BlocksProtocol::endAPIMode);
  708. currentTopology = {};
  709. topologyBroadcastThrottle.lastTopology = {};
  710. auto& d = getDefaultDetectorPointer();
  711. if (d != nullptr && d->getReferenceCount() == 2)
  712. getDefaultDetectorPointer() = nullptr;
  713. }
  714. }
  715. bool isConnected (Block::UID deviceID) const noexcept
  716. {
  717. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  718. for (auto&& b : currentTopology.blocks)
  719. if (b->uid == deviceID)
  720. return true;
  721. return false;
  722. }
  723. const BlocksProtocol::DeviceStatus* getLastStatus (Block::UID deviceID) const noexcept
  724. {
  725. for (auto d : connectedDeviceGroups)
  726. if (auto status = d->getLastStatus (deviceID))
  727. return status;
  728. return nullptr;
  729. }
  730. void handleTopologyChange()
  731. {
  732. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  733. {
  734. juce::Array<DeviceInfo> newDeviceInfo;
  735. juce::Array<BlockDeviceConnection> newDeviceConnections;
  736. for (auto d : connectedDeviceGroups)
  737. {
  738. newDeviceInfo.addArray (d->currentDeviceInfo);
  739. newDeviceConnections.addArray (d->currentDeviceConnections);
  740. }
  741. for (int i = currentTopology.blocks.size(); --i >= 0;)
  742. {
  743. auto block = currentTopology.blocks.getUnchecked (i);
  744. if (! containsBlockWithUID (newDeviceInfo, block->uid))
  745. {
  746. if (auto bi = BlockImplementation::getFrom (*block))
  747. bi->invalidate();
  748. currentTopology.blocks.remove (i);
  749. }
  750. else
  751. {
  752. if (versionNumberAddedToBlock (newDeviceInfo, block->uid, block->versionNumber))
  753. setVersionNumberForBlock (newDeviceInfo, *block);
  754. if (nameAddedToBlock (newDeviceInfo, block->uid))
  755. setNameForBlock (newDeviceInfo, *block);
  756. }
  757. }
  758. for (auto& info : newDeviceInfo)
  759. if (info.serial.isValid())
  760. if (! containsBlockWithUID (currentTopology.blocks, getBlockUIDFromSerialNumber (info.serial)))
  761. currentTopology.blocks.add (new BlockImplementation (info.serial, *this, info.version, info.name, info.isMaster));
  762. currentTopology.connections.swapWith (newDeviceConnections);
  763. }
  764. topologyBroadcastThrottle.scheduleTopologyChangeCallback();
  765. }
  766. void handleSharedDataACK (Block::UID deviceID, uint32 packetCounter) const
  767. {
  768. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  769. for (auto&& b : currentTopology.blocks)
  770. if (b->uid == deviceID)
  771. if (auto bi = BlockImplementation::getFrom (*b))
  772. bi->handleSharedDataACK (packetCounter);
  773. }
  774. void handleFirmwareUpdateACK (Block::UID deviceID, uint8 resultCode, uint32 resultDetail)
  775. {
  776. for (auto&& b : currentTopology.blocks)
  777. if (b->uid == deviceID)
  778. if (auto bi = BlockImplementation::getFrom (*b))
  779. bi->handleFirmwareUpdateACK (resultCode, resultDetail);
  780. }
  781. void handleConfigUpdateMessage (Block::UID deviceID, int32 item, int32 value, int32 min, int32 max)
  782. {
  783. for (auto&& b : currentTopology.blocks)
  784. if (b->uid == deviceID)
  785. if (auto bi = BlockImplementation::getFrom (*b))
  786. bi->handleConfigUpdateMessage (item, value, min, max);
  787. }
  788. void notifyBlockOfConfigChange (BlockImplementation& bi, uint32 item)
  789. {
  790. if (auto configChangedCallback = bi.configChangedCallback)
  791. {
  792. if (item >= bi.getMaxConfigIndex())
  793. configChangedCallback (bi, {}, item);
  794. else
  795. configChangedCallback (bi, bi.getLocalConfigMetaData (item), item);
  796. }
  797. }
  798. void handleConfigSetMessage (Block::UID deviceID, int32 item, int32 value)
  799. {
  800. for (auto&& b : currentTopology.blocks)
  801. {
  802. if (b->uid == deviceID)
  803. {
  804. if (auto bi = BlockImplementation::getFrom (*b))
  805. {
  806. bi->handleConfigSetMessage (item, value);
  807. notifyBlockOfConfigChange (*bi, uint32 (item));
  808. }
  809. }
  810. }
  811. }
  812. void handleConfigFactorySyncEndMessage (Block::UID deviceID)
  813. {
  814. for (auto&& b : currentTopology.blocks)
  815. if (b->uid == deviceID)
  816. if (auto bi = BlockImplementation::getFrom (*b))
  817. notifyBlockOfConfigChange (*bi, bi->getMaxConfigIndex());
  818. }
  819. void handleLogMessage (Block::UID deviceID, const String& message) const
  820. {
  821. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  822. for (auto&& b : currentTopology.blocks)
  823. if (b->uid == deviceID)
  824. if (auto bi = BlockImplementation::getFrom (*b))
  825. bi->handleLogMessage (message);
  826. }
  827. void handleButtonChange (Block::UID deviceID, Block::Timestamp timestamp, uint32 buttonIndex, bool isDown) const
  828. {
  829. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  830. for (auto b : activeControlButtons)
  831. {
  832. if (b->block.uid == deviceID)
  833. {
  834. if (auto bi = BlockImplementation::getFrom (b->block))
  835. {
  836. bi->pingFromDevice();
  837. if (buttonIndex < (uint32) bi->modelData.buttons.size())
  838. b->broadcastButtonChange (timestamp, bi->modelData.buttons[(int) buttonIndex].type, isDown);
  839. }
  840. }
  841. }
  842. }
  843. void handleTouchChange (Block::UID deviceID, const TouchSurface::Touch& touchEvent)
  844. {
  845. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  846. for (auto t : activeTouchSurfaces)
  847. {
  848. if (t->block.uid == deviceID)
  849. {
  850. TouchSurface::Touch scaledEvent (touchEvent);
  851. scaledEvent.x *= t->block.getWidth();
  852. scaledEvent.y *= t->block.getHeight();
  853. scaledEvent.startX *= t->block.getWidth();
  854. scaledEvent.startY *= t->block.getHeight();
  855. t->broadcastTouchChange (scaledEvent);
  856. }
  857. }
  858. }
  859. void cancelAllActiveTouches() noexcept
  860. {
  861. for (auto surface : activeTouchSurfaces)
  862. surface->cancelAllActiveTouches();
  863. }
  864. void handleCustomMessage (Block::UID deviceID, Block::Timestamp timestamp, const int32* data)
  865. {
  866. for (auto&& b : currentTopology.blocks)
  867. if (b->uid == deviceID)
  868. if (auto bi = BlockImplementation::getFrom (*b))
  869. bi->handleCustomMessage (timestamp, data);
  870. }
  871. //==============================================================================
  872. int getIndexFromDeviceID (Block::UID deviceID) const noexcept
  873. {
  874. for (auto* c : connectedDeviceGroups)
  875. {
  876. auto index = c->getIndexFromDeviceID (deviceID);
  877. if (index >= 0)
  878. return index;
  879. }
  880. return -1;
  881. }
  882. template <typename PacketBuilder>
  883. bool sendMessageToDevice (Block::UID deviceID, const PacketBuilder& builder) const
  884. {
  885. for (auto* c : connectedDeviceGroups)
  886. if (c->getIndexFromDeviceID (deviceID) >= 0)
  887. return c->sendMessageToDevice (builder);
  888. return false;
  889. }
  890. static Detector* getFrom (Block& b) noexcept
  891. {
  892. if (auto* bi = BlockImplementation::getFrom (b))
  893. return &(bi->detector);
  894. jassertfalse;
  895. return nullptr;
  896. }
  897. DeviceConnection* getDeviceConnectionFor (const Block& b)
  898. {
  899. for (const auto& d : connectedDeviceGroups)
  900. {
  901. for (const auto& info : d->currentDeviceInfo)
  902. {
  903. if (info.uid == b.uid)
  904. return d->getDeviceConnection();
  905. }
  906. }
  907. return nullptr;
  908. }
  909. std::unique_ptr<MIDIDeviceDetector> defaultDetector;
  910. DeviceDetector& deviceDetector;
  911. juce::Array<PhysicalTopologySource*> activeTopologySources;
  912. juce::Array<ControlButtonImplementation*> activeControlButtons;
  913. juce::Array<TouchSurfaceImplementation*> activeTouchSurfaces;
  914. BlockTopology currentTopology;
  915. private:
  916. void timerCallback() override
  917. {
  918. startTimer (1500);
  919. auto detectedDevices = deviceDetector.scanForDevices();
  920. handleDevicesRemoved (detectedDevices);
  921. handleDevicesAdded (detectedDevices);
  922. }
  923. void handleDevicesRemoved (const juce::StringArray& detectedDevices)
  924. {
  925. bool anyDevicesRemoved = false;
  926. for (int i = connectedDeviceGroups.size(); --i >= 0;)
  927. {
  928. if (! connectedDeviceGroups.getUnchecked(i)->isStillConnected (detectedDevices))
  929. {
  930. connectedDeviceGroups.remove (i);
  931. anyDevicesRemoved = true;
  932. }
  933. }
  934. if (anyDevicesRemoved)
  935. handleTopologyChange();
  936. }
  937. void handleDevicesAdded (const juce::StringArray& detectedDevices)
  938. {
  939. bool anyDevicesAdded = false;
  940. for (const auto& devName : detectedDevices)
  941. {
  942. if (! hasDeviceFor (devName))
  943. {
  944. if (auto d = deviceDetector.openDevice (detectedDevices.indexOf (devName)))
  945. {
  946. connectedDeviceGroups.add (new ConnectedDeviceGroup (*this, devName, d));
  947. anyDevicesAdded = true;
  948. }
  949. }
  950. }
  951. if (anyDevicesAdded)
  952. handleTopologyChange();
  953. }
  954. bool hasDeviceFor (const juce::String& devName) const
  955. {
  956. for (auto d : connectedDeviceGroups)
  957. if (d->deviceName == devName)
  958. return true;
  959. return false;
  960. }
  961. juce::OwnedArray<ConnectedDeviceGroup> connectedDeviceGroups;
  962. //==============================================================================
  963. /** Flurries of topology messages sometimes arrive due to loose connections.
  964. Avoid informing listeners until they've stabilised.
  965. */
  966. struct TopologyBroadcastThrottle : private juce::Timer
  967. {
  968. TopologyBroadcastThrottle() = default;
  969. void scheduleTopologyChangeCallback()
  970. {
  971. #ifdef JUCE_BLOCKS_TOPOLOGY_BROADCAST_THROTTLE_TIME
  972. startTimer (JUCE_BLOCKS_TOPOLOGY_BROADCAST_THROTTLE_TIME);
  973. #else
  974. startTimer (750);
  975. #endif
  976. }
  977. void timerCallback() override
  978. {
  979. if (detector->currentTopology != lastTopology)
  980. {
  981. lastTopology = detector->currentTopology;
  982. for (auto* d : detector->activeTopologySources)
  983. d->listeners.call ([] (TopologySource::Listener& l) { l.topologyChanged(); });
  984. #if DUMP_TOPOLOGY
  985. dumpTopology (lastTopology);
  986. #endif
  987. }
  988. stopTimer();
  989. }
  990. Detector* detector = nullptr;
  991. BlockTopology lastTopology;
  992. };
  993. TopologyBroadcastThrottle topologyBroadcastThrottle;
  994. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Detector)
  995. };
  996. //==============================================================================
  997. struct BlockImplementation : public Block,
  998. private MIDIDeviceConnection::Listener,
  999. private Timer
  1000. {
  1001. BlockImplementation (const BlocksProtocol::BlockSerialNumber& serial, Detector& detectorToUse, BlocksProtocol::VersionNumber version, BlocksProtocol::BlockName name, bool master)
  1002. : Block (juce::String ((const char*) serial.serial, sizeof (serial.serial)),
  1003. juce::String ((const char*) version.version, version.length),
  1004. juce::String ((const char*) name.name, name.length)),
  1005. modelData (serial),
  1006. remoteHeap (modelData.programAndHeapSize),
  1007. detector (detectorToUse),
  1008. isMaster (master)
  1009. {
  1010. sendCommandMessage (BlocksProtocol::beginAPIMode);
  1011. if (modelData.hasTouchSurface)
  1012. touchSurface.reset (new TouchSurfaceImplementation (*this));
  1013. int i = 0;
  1014. for (auto&& b : modelData.buttons)
  1015. controlButtons.add (new ControlButtonImplementation (*this, i++, b));
  1016. if (modelData.lightGridWidth > 0 && modelData.lightGridHeight > 0)
  1017. ledGrid.reset (new LEDGridImplementation (*this));
  1018. for (auto&& s : modelData.statusLEDs)
  1019. statusLights.add (new StatusLightImplementation (*this, s));
  1020. if (modelData.numLEDRowLEDs > 0)
  1021. ledRow.reset (new LEDRowImplementation (*this));
  1022. listenerToMidiConnection = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this));
  1023. if (listenerToMidiConnection != nullptr)
  1024. listenerToMidiConnection->addListener (this);
  1025. config.setDeviceComms (listenerToMidiConnection);
  1026. }
  1027. ~BlockImplementation()
  1028. {
  1029. if (listenerToMidiConnection != nullptr)
  1030. {
  1031. config.setDeviceComms (nullptr);
  1032. listenerToMidiConnection->removeListener (this);
  1033. }
  1034. }
  1035. void invalidate()
  1036. {
  1037. isStillConnected = false;
  1038. }
  1039. Type getType() const override { return modelData.apiType; }
  1040. juce::String getDeviceDescription() const override { return modelData.description; }
  1041. int getWidth() const override { return modelData.widthUnits; }
  1042. int getHeight() const override { return modelData.heightUnits; }
  1043. float getMillimetersPerUnit() const override { return 47.0f; }
  1044. bool isHardwareBlock() const override { return true; }
  1045. juce::Array<Block::ConnectionPort> getPorts() const override { return modelData.ports; }
  1046. bool isConnected() const override { return isStillConnected && detector.isConnected (uid); }
  1047. bool isMasterBlock() const override { return isMaster; }
  1048. TouchSurface* getTouchSurface() const override { return touchSurface.get(); }
  1049. LEDGrid* getLEDGrid() const override { return ledGrid.get(); }
  1050. LEDRow* getLEDRow() const override { return ledRow.get(); }
  1051. juce::Array<ControlButton*> getButtons() const override
  1052. {
  1053. juce::Array<ControlButton*> result;
  1054. result.addArray (controlButtons);
  1055. return result;
  1056. }
  1057. juce::Array<StatusLight*> getStatusLights() const override
  1058. {
  1059. juce::Array<StatusLight*> result;
  1060. result.addArray (statusLights);
  1061. return result;
  1062. }
  1063. float getBatteryLevel() const override
  1064. {
  1065. if (auto status = detector.getLastStatus (uid))
  1066. return status->batteryLevel.toUnipolarFloat();
  1067. return 0.0f;
  1068. }
  1069. bool isBatteryCharging() const override
  1070. {
  1071. if (auto status = detector.getLastStatus (uid))
  1072. return status->batteryCharging.get() != 0;
  1073. return false;
  1074. }
  1075. bool supportsGraphics() const override
  1076. {
  1077. return false;
  1078. }
  1079. int getDeviceIndex() const noexcept
  1080. {
  1081. return isConnected() ? detector.getIndexFromDeviceID (uid) : -1;
  1082. }
  1083. template <typename PacketBuilder>
  1084. bool sendMessageToDevice (const PacketBuilder& builder)
  1085. {
  1086. lastMessageSendTime = juce::Time::getCurrentTime();
  1087. return detector.sendMessageToDevice (uid, builder);
  1088. }
  1089. bool sendCommandMessage (uint32 commandID)
  1090. {
  1091. int index = getDeviceIndex();
  1092. if (index < 0)
  1093. return false;
  1094. BlocksProtocol::HostPacketBuilder<64> p;
  1095. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1096. p.deviceControlMessage (commandID);
  1097. p.writePacketSysexFooter();
  1098. return sendMessageToDevice (p);
  1099. }
  1100. void handleCustomMessage (Block::Timestamp, const int32* data)
  1101. {
  1102. ProgramEventMessage m;
  1103. for (uint32 i = 0; i < BlocksProtocol::numProgramMessageInts; ++i)
  1104. m.values[i] = data[i];
  1105. programEventListeners.call ([&] (ProgramEventListener& l) { l.handleProgramEvent (*this, m); });
  1106. }
  1107. static BlockImplementation* getFrom (Block& b) noexcept
  1108. {
  1109. if (auto bi = dynamic_cast<BlockImplementation*> (&b))
  1110. return bi;
  1111. jassertfalse;
  1112. return nullptr;
  1113. }
  1114. bool isControlBlock() const
  1115. {
  1116. auto type = getType();
  1117. return type == Block::Type::liveBlock
  1118. || type == Block::Type::loopBlock
  1119. || type == Block::Type::touchBlock
  1120. || type == Block::Type::developerControlBlock;
  1121. }
  1122. //==============================================================================
  1123. std::function<void(const String&)> logger;
  1124. void setLogger (std::function<void(const String&)> newLogger) override
  1125. {
  1126. logger = newLogger;
  1127. }
  1128. void handleLogMessage (const String& message) const
  1129. {
  1130. if (logger != nullptr)
  1131. logger (message);
  1132. }
  1133. //==============================================================================
  1134. juce::Result setProgram (Program* newProgram) override
  1135. {
  1136. if (newProgram == nullptr || program.get() != newProgram)
  1137. {
  1138. {
  1139. std::unique_ptr<Program> p (newProgram);
  1140. if (program != nullptr
  1141. && newProgram != nullptr
  1142. && program->getLittleFootProgram() == newProgram->getLittleFootProgram())
  1143. return juce::Result::ok();
  1144. stopTimer();
  1145. std::swap (program, p);
  1146. }
  1147. stopTimer();
  1148. programSize = 0;
  1149. if (program != nullptr)
  1150. {
  1151. littlefoot::Compiler compiler;
  1152. compiler.addNativeFunctions (PhysicalTopologySource::getStandardLittleFootFunctions());
  1153. auto err = compiler.compile (program->getLittleFootProgram(), 512);
  1154. if (err.failed())
  1155. return err;
  1156. DBG ("Compiled littlefoot program, space needed: "
  1157. << (int) compiler.getCompiledProgram().getTotalSpaceNeeded() << " bytes");
  1158. if (compiler.getCompiledProgram().getTotalSpaceNeeded() > getMemorySize())
  1159. return Result::fail ("Program too large!");
  1160. auto size = (size_t) compiler.compiledObjectCode.size();
  1161. programSize = (uint32) size;
  1162. remoteHeap.resetDataRangeToUnknown (0, remoteHeap.blockSize);
  1163. remoteHeap.clear();
  1164. remoteHeap.sendChanges (*this, true);
  1165. remoteHeap.resetDataRangeToUnknown (0, (uint32) size);
  1166. remoteHeap.setBytes (0, compiler.compiledObjectCode.begin(), size);
  1167. remoteHeap.sendChanges (*this, true);
  1168. this->resetConfigListActiveStatus();
  1169. if (auto changeCallback = this->configChangedCallback)
  1170. changeCallback (*this, {}, this->getMaxConfigIndex());
  1171. }
  1172. else
  1173. {
  1174. remoteHeap.clear();
  1175. }
  1176. }
  1177. else
  1178. {
  1179. jassertfalse;
  1180. }
  1181. return juce::Result::ok();
  1182. }
  1183. Program* getProgram() const override { return program.get(); }
  1184. void sendProgramEvent (const ProgramEventMessage& message) override
  1185. {
  1186. static_assert (sizeof (ProgramEventMessage::values) == 4 * BlocksProtocol::numProgramMessageInts,
  1187. "Need to keep the internal and external messages structures the same");
  1188. if (remoteHeap.isProgramLoaded())
  1189. {
  1190. auto index = getDeviceIndex();
  1191. if (index >= 0)
  1192. {
  1193. BlocksProtocol::HostPacketBuilder<128> p;
  1194. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1195. if (p.addProgramEventMessage (message.values))
  1196. {
  1197. p.writePacketSysexFooter();
  1198. sendMessageToDevice (p);
  1199. }
  1200. }
  1201. else
  1202. {
  1203. jassertfalse;
  1204. }
  1205. }
  1206. }
  1207. void timerCallback() override
  1208. {
  1209. if (remoteHeap.isFullySynced() && remoteHeap.isProgramLoaded())
  1210. {
  1211. stopTimer();
  1212. sendCommandMessage (BlocksProtocol::saveProgramAsDefault);
  1213. }
  1214. else
  1215. {
  1216. startTimer (100);
  1217. }
  1218. }
  1219. void saveProgramAsDefault() override
  1220. {
  1221. startTimer (10);
  1222. }
  1223. uint32 getMemorySize() override
  1224. {
  1225. return modelData.programAndHeapSize;
  1226. }
  1227. void setDataByte (size_t offset, uint8 value) override
  1228. {
  1229. remoteHeap.setByte (programSize + offset, value);
  1230. }
  1231. void setDataBytes (size_t offset, const void* newData, size_t num) override
  1232. {
  1233. remoteHeap.setBytes (programSize + offset, static_cast<const uint8*> (newData), num);
  1234. }
  1235. void setDataBits (uint32 startBit, uint32 numBits, uint32 value) override
  1236. {
  1237. remoteHeap.setBits (programSize * 8 + startBit, numBits, value);
  1238. }
  1239. uint8 getDataByte (size_t offset) override
  1240. {
  1241. return remoteHeap.getByte (programSize + offset);
  1242. }
  1243. void handleSharedDataACK (uint32 packetCounter) noexcept
  1244. {
  1245. pingFromDevice();
  1246. remoteHeap.handleACKFromDevice (*this, packetCounter);
  1247. }
  1248. bool sendFirmwareUpdatePacket (const uint8* data, uint8 size, std::function<void (uint8, uint32)> callback) override
  1249. {
  1250. firmwarePacketAckCallback = {};
  1251. auto index = getDeviceIndex();
  1252. if (index >= 0)
  1253. {
  1254. BlocksProtocol::HostPacketBuilder<256> p;
  1255. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1256. if (p.addFirmwareUpdatePacket (data, size))
  1257. {
  1258. p.writePacketSysexFooter();
  1259. if (sendMessageToDevice (p))
  1260. {
  1261. firmwarePacketAckCallback = callback;
  1262. return true;
  1263. }
  1264. }
  1265. }
  1266. else
  1267. {
  1268. jassertfalse;
  1269. }
  1270. return false;
  1271. }
  1272. void handleFirmwareUpdateACK (uint8 resultCode, uint32 resultDetail)
  1273. {
  1274. if (firmwarePacketAckCallback != nullptr)
  1275. {
  1276. firmwarePacketAckCallback (resultCode, resultDetail);
  1277. firmwarePacketAckCallback = {};
  1278. }
  1279. }
  1280. void handleConfigUpdateMessage (int32 item, int32 value, int32 min, int32 max)
  1281. {
  1282. config.handleConfigUpdateMessage (item, value, min, max);
  1283. }
  1284. void handleConfigSetMessage(int32 item, int32 value)
  1285. {
  1286. config.handleConfigSetMessage (item, value);
  1287. }
  1288. void pingFromDevice()
  1289. {
  1290. lastMessageReceiveTime = juce::Time::getCurrentTime();
  1291. }
  1292. void addDataInputPortListener (DataInputPortListener* listener) override
  1293. {
  1294. Block::addDataInputPortListener (listener);
  1295. if (auto midiInput = getMidiInput())
  1296. midiInput->start();
  1297. }
  1298. void sendMessage (const void* message, size_t messageSize) override
  1299. {
  1300. if (auto midiOutput = getMidiOutput())
  1301. midiOutput->sendMessageNow ({ message, (int) messageSize });
  1302. }
  1303. void handleTimerTick()
  1304. {
  1305. if (++resetMessagesSent < 3)
  1306. {
  1307. if (resetMessagesSent == 1)
  1308. sendCommandMessage (BlocksProtocol::endAPIMode);
  1309. sendCommandMessage (BlocksProtocol::beginAPIMode);
  1310. return;
  1311. }
  1312. if (ledGrid != nullptr)
  1313. if (auto renderer = ledGrid->getRenderer())
  1314. renderer->renderLEDGrid (*ledGrid);
  1315. remoteHeap.sendChanges (*this, false);
  1316. if (lastMessageSendTime < juce::Time::getCurrentTime() - juce::RelativeTime::milliseconds (pingIntervalMs))
  1317. sendCommandMessage (BlocksProtocol::ping);
  1318. }
  1319. //==============================================================================
  1320. int32 getLocalConfigValue (uint32 item) override
  1321. {
  1322. initialiseDeviceIndexAndConnection();
  1323. return config.getItemValue ((BlocksProtocol::ConfigItemId) item);
  1324. }
  1325. void setLocalConfigValue (uint32 item, int32 value) override
  1326. {
  1327. initialiseDeviceIndexAndConnection();
  1328. config.setItemValue ((BlocksProtocol::ConfigItemId) item, value);
  1329. }
  1330. void setLocalConfigRange (uint32 item, int32 min, int32 max) override
  1331. {
  1332. initialiseDeviceIndexAndConnection();
  1333. config.setItemMin ((BlocksProtocol::ConfigItemId) item, min);
  1334. config.setItemMax ((BlocksProtocol::ConfigItemId) item, max);
  1335. }
  1336. void setLocalConfigItemActive (uint32 item, bool isActive) override
  1337. {
  1338. initialiseDeviceIndexAndConnection();
  1339. config.setItemActive ((BlocksProtocol::ConfigItemId) item, isActive);
  1340. }
  1341. bool isLocalConfigItemActive (uint32 item) override
  1342. {
  1343. initialiseDeviceIndexAndConnection();
  1344. return config.getItemActive ((BlocksProtocol::ConfigItemId) item);
  1345. }
  1346. uint32 getMaxConfigIndex() override
  1347. {
  1348. return uint32 (BlocksProtocol::maxConfigIndex);
  1349. }
  1350. bool isValidUserConfigIndex (uint32 item) override
  1351. {
  1352. return item >= (uint32) BlocksProtocol::ConfigItemId::user0
  1353. && item < (uint32) (BlocksProtocol::ConfigItemId::user0 + numberOfUserConfigs);
  1354. }
  1355. ConfigMetaData getLocalConfigMetaData (uint32 item) override
  1356. {
  1357. initialiseDeviceIndexAndConnection();
  1358. return config.getMetaData ((BlocksProtocol::ConfigItemId) item);
  1359. }
  1360. void requestFactoryConfigSync() override
  1361. {
  1362. initialiseDeviceIndexAndConnection();
  1363. config.requestFactoryConfigSync();
  1364. }
  1365. void resetConfigListActiveStatus() override
  1366. {
  1367. config.resetConfigListActiveStatus();
  1368. }
  1369. void setConfigChangedCallback (std::function<void(Block&, const ConfigMetaData&, uint32)> configChanged) override
  1370. {
  1371. configChangedCallback = configChanged;
  1372. }
  1373. void factoryReset() override
  1374. {
  1375. auto index = getDeviceIndex();
  1376. if (index >= 0)
  1377. {
  1378. BlocksProtocol::HostPacketBuilder<32> p;
  1379. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1380. p.addFactoryReset();
  1381. p.writePacketSysexFooter();
  1382. sendMessageToDevice (p);
  1383. }
  1384. else
  1385. {
  1386. jassertfalse;
  1387. }
  1388. }
  1389. void blockReset() override
  1390. {
  1391. auto index = getDeviceIndex();
  1392. if (index >= 0)
  1393. {
  1394. BlocksProtocol::HostPacketBuilder<32> p;
  1395. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1396. p.addBlockReset();
  1397. p.writePacketSysexFooter();
  1398. sendMessageToDevice (p);
  1399. }
  1400. else
  1401. {
  1402. jassertfalse;
  1403. }
  1404. }
  1405. bool setName (const juce::String& newName) override
  1406. {
  1407. auto index = getDeviceIndex();
  1408. if (index >= 0)
  1409. {
  1410. BlocksProtocol::HostPacketBuilder<128> p;
  1411. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1412. if (p.addSetBlockName (newName))
  1413. {
  1414. p.writePacketSysexFooter();
  1415. if (sendMessageToDevice (p))
  1416. return true;
  1417. }
  1418. }
  1419. else
  1420. {
  1421. jassertfalse;
  1422. }
  1423. return false;
  1424. }
  1425. //==============================================================================
  1426. std::unique_ptr<TouchSurface> touchSurface;
  1427. juce::OwnedArray<ControlButton> controlButtons;
  1428. std::unique_ptr<LEDGridImplementation> ledGrid;
  1429. std::unique_ptr<LEDRowImplementation> ledRow;
  1430. juce::OwnedArray<StatusLight> statusLights;
  1431. BlocksProtocol::BlockDataSheet modelData;
  1432. MIDIDeviceConnection* listenerToMidiConnection = nullptr;
  1433. static constexpr int pingIntervalMs = 400;
  1434. static constexpr uint32 maxBlockSize = BlocksProtocol::padBlockProgramAndHeapSize;
  1435. static constexpr uint32 maxPacketCounter = BlocksProtocol::PacketCounter::maxValue;
  1436. static constexpr uint32 maxPacketSize = 200;
  1437. using PacketBuilder = BlocksProtocol::HostPacketBuilder<maxPacketSize>;
  1438. using RemoteHeapType = littlefoot::LittleFootRemoteHeap<BlockImplementation>;
  1439. RemoteHeapType remoteHeap;
  1440. Detector& detector;
  1441. juce::Time lastMessageSendTime, lastMessageReceiveTime;
  1442. BlockConfigManager config;
  1443. std::function<void(Block&, const ConfigMetaData&, uint32)> configChangedCallback;
  1444. private:
  1445. std::unique_ptr<Program> program;
  1446. uint32 programSize = 0;
  1447. std::function<void(uint8, uint32)> firmwarePacketAckCallback;
  1448. uint32 resetMessagesSent = 0;
  1449. bool isStillConnected = true;
  1450. bool isMaster = false;
  1451. void initialiseDeviceIndexAndConnection()
  1452. {
  1453. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  1454. config.setDeviceComms (listenerToMidiConnection);
  1455. }
  1456. const juce::MidiInput* getMidiInput() const
  1457. {
  1458. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1459. return c->midiInput.get();
  1460. jassertfalse;
  1461. return nullptr;
  1462. }
  1463. juce::MidiInput* getMidiInput()
  1464. {
  1465. return const_cast<juce::MidiInput*> (static_cast<const BlockImplementation&>(*this).getMidiInput());
  1466. }
  1467. const juce::MidiOutput* getMidiOutput() const
  1468. {
  1469. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1470. return c->midiOutput.get();
  1471. jassertfalse;
  1472. return nullptr;
  1473. }
  1474. juce::MidiOutput* getMidiOutput()
  1475. {
  1476. return const_cast<juce::MidiOutput*> (static_cast<const BlockImplementation&>(*this).getMidiOutput());
  1477. }
  1478. void handleIncomingMidiMessage (const juce::MidiMessage& message) override
  1479. {
  1480. dataInputPortListeners.call ([&] (DataInputPortListener& l) { l.handleIncomingDataPortMessage (*this, message.getRawData(),
  1481. (size_t) message.getRawDataSize()); });
  1482. }
  1483. void connectionBeingDeleted (const MIDIDeviceConnection& c) override
  1484. {
  1485. jassert (listenerToMidiConnection == &c);
  1486. juce::ignoreUnused (c);
  1487. listenerToMidiConnection->removeListener (this);
  1488. listenerToMidiConnection = nullptr;
  1489. config.setDeviceComms (nullptr);
  1490. }
  1491. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockImplementation)
  1492. };
  1493. //==============================================================================
  1494. struct LEDRowImplementation : public LEDRow,
  1495. private Timer
  1496. {
  1497. LEDRowImplementation (BlockImplementation& b) : LEDRow (b)
  1498. {
  1499. startTimer (300);
  1500. }
  1501. void setButtonColour (uint32 index, LEDColour colour)
  1502. {
  1503. if (index < 10)
  1504. {
  1505. colours[index] = colour;
  1506. flush();
  1507. }
  1508. }
  1509. int getNumLEDs() const override
  1510. {
  1511. return static_cast<const BlockImplementation&> (block).modelData.numLEDRowLEDs;
  1512. }
  1513. void setLEDColour (int index, LEDColour colour) override
  1514. {
  1515. if ((uint32) index < 15u)
  1516. {
  1517. colours[10 + index] = colour;
  1518. flush();
  1519. }
  1520. }
  1521. void setOverlayColour (LEDColour colour) override
  1522. {
  1523. colours[25] = colour;
  1524. flush();
  1525. }
  1526. void resetOverlayColour() override
  1527. {
  1528. setOverlayColour ({});
  1529. }
  1530. private:
  1531. LEDColour colours[26];
  1532. void timerCallback() override
  1533. {
  1534. stopTimer();
  1535. loadProgramOntoBlock();
  1536. flush();
  1537. }
  1538. void loadProgramOntoBlock()
  1539. {
  1540. if (block.getProgram() == nullptr)
  1541. {
  1542. auto err = block.setProgram (new DefaultLEDGridProgram (block));
  1543. if (err.failed())
  1544. {
  1545. DBG (err.getErrorMessage());
  1546. jassertfalse;
  1547. }
  1548. }
  1549. }
  1550. void flush()
  1551. {
  1552. if (block.getProgram() != nullptr)
  1553. for (uint32 i = 0; i < (uint32) numElementsInArray (colours); ++i)
  1554. write565Colour (16 * i, colours[i]);
  1555. }
  1556. void write565Colour (uint32 bitIndex, LEDColour colour)
  1557. {
  1558. block.setDataBits (bitIndex, 5, colour.getRed() >> 3);
  1559. block.setDataBits (bitIndex + 5, 6, colour.getGreen() >> 2);
  1560. block.setDataBits (bitIndex + 11, 5, colour.getBlue() >> 3);
  1561. }
  1562. struct DefaultLEDGridProgram : public Block::Program
  1563. {
  1564. DefaultLEDGridProgram (Block& b) : Block::Program (b) {}
  1565. juce::String getLittleFootProgram() override
  1566. {
  1567. /* Data format:
  1568. 0: 10 x 5-6-5 bits for button LED RGBs
  1569. 20: 15 x 5-6-5 bits for LED row colours
  1570. 50: 1 x 5-6-5 bits for LED row overlay colour
  1571. */
  1572. return R"littlefoot(
  1573. #heapsize: 128
  1574. int getColour (int bitIndex)
  1575. {
  1576. return makeARGB (255,
  1577. getHeapBits (bitIndex, 5) << 3,
  1578. getHeapBits (bitIndex + 5, 6) << 2,
  1579. getHeapBits (bitIndex + 11, 5) << 3);
  1580. }
  1581. int getButtonColour (int index)
  1582. {
  1583. return getColour (16 * index);
  1584. }
  1585. int getLEDColour (int index)
  1586. {
  1587. if (getHeapInt (50))
  1588. return getColour (50 * 8);
  1589. return getColour (20 * 8 + 16 * index);
  1590. }
  1591. void repaint()
  1592. {
  1593. for (int x = 0; x < 15; ++x)
  1594. fillPixel (getLEDColour (x), x, 0);
  1595. for (int i = 0; i < 10; ++i)
  1596. fillPixel (getButtonColour (i), i, 1);
  1597. }
  1598. void handleMessage (int p1, int p2) {}
  1599. )littlefoot";
  1600. }
  1601. };
  1602. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDRowImplementation)
  1603. };
  1604. //==============================================================================
  1605. struct TouchSurfaceImplementation : public TouchSurface,
  1606. private juce::Timer
  1607. {
  1608. TouchSurfaceImplementation (BlockImplementation& b) : TouchSurface (b), blockImpl (b)
  1609. {
  1610. if (auto det = Detector::getFrom (block))
  1611. det->activeTouchSurfaces.add (this);
  1612. startTimer (500);
  1613. }
  1614. ~TouchSurfaceImplementation()
  1615. {
  1616. if (auto det = Detector::getFrom (block))
  1617. det->activeTouchSurfaces.removeFirstMatchingValue (this);
  1618. }
  1619. int getNumberOfKeywaves() const noexcept override
  1620. {
  1621. return blockImpl.modelData.numKeywaves;
  1622. }
  1623. void broadcastTouchChange (const TouchSurface::Touch& touchEvent)
  1624. {
  1625. auto& status = touches.getValue (touchEvent);
  1626. // Fake a touch end if we receive a duplicate touch-start with no preceding touch-end (ie: comms error)
  1627. if (touchEvent.isTouchStart && status.isActive)
  1628. killTouch (touchEvent, status, juce::Time::getMillisecondCounter());
  1629. // Fake a touch start if we receive an unexpected event with no matching start event. (ie: comms error)
  1630. if (! touchEvent.isTouchStart && ! status.isActive)
  1631. {
  1632. TouchSurface::Touch t (touchEvent);
  1633. t.isTouchStart = true;
  1634. t.isTouchEnd = false;
  1635. if (t.zVelocity <= 0) t.zVelocity = status.lastStrikePressure;
  1636. if (t.zVelocity <= 0) t.zVelocity = t.z;
  1637. if (t.zVelocity <= 0) t.zVelocity = 0.9f;
  1638. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, t); });
  1639. }
  1640. // Normal handling:
  1641. status.lastEventTime = juce::Time::getMillisecondCounter();
  1642. status.isActive = ! touchEvent.isTouchEnd;
  1643. if (touchEvent.isTouchStart)
  1644. status.lastStrikePressure = touchEvent.zVelocity;
  1645. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, touchEvent); });
  1646. }
  1647. void timerCallback() override
  1648. {
  1649. // Find touches that seem to have become stuck, and fake a touch-end for them..
  1650. static const uint32 touchTimeOutMs = 500;
  1651. for (auto& t : touches)
  1652. {
  1653. auto& status = t.value;
  1654. auto now = juce::Time::getMillisecondCounter();
  1655. if (status.isActive && now > status.lastEventTime + touchTimeOutMs)
  1656. killTouch (t.touch, status, now);
  1657. }
  1658. }
  1659. struct TouchStatus
  1660. {
  1661. uint32 lastEventTime = 0;
  1662. float lastStrikePressure = 0;
  1663. bool isActive = false;
  1664. };
  1665. void killTouch (const TouchSurface::Touch& touch, TouchStatus& status, uint32 timeStamp) noexcept
  1666. {
  1667. jassert (status.isActive);
  1668. TouchSurface::Touch killTouch (touch);
  1669. killTouch.z = 0;
  1670. killTouch.xVelocity = 0;
  1671. killTouch.yVelocity = 0;
  1672. killTouch.zVelocity = -1.0f;
  1673. killTouch.eventTimestamp = timeStamp;
  1674. killTouch.isTouchStart = false;
  1675. killTouch.isTouchEnd = true;
  1676. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, killTouch); });
  1677. status.isActive = false;
  1678. }
  1679. void cancelAllActiveTouches() noexcept override
  1680. {
  1681. const auto now = juce::Time::getMillisecondCounter();
  1682. for (auto& t : touches)
  1683. if (t.value.isActive)
  1684. killTouch (t.touch, t.value, now);
  1685. touches.clear();
  1686. }
  1687. BlockImplementation& blockImpl;
  1688. TouchList<TouchStatus> touches;
  1689. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TouchSurfaceImplementation)
  1690. };
  1691. //==============================================================================
  1692. struct ControlButtonImplementation : public ControlButton
  1693. {
  1694. ControlButtonImplementation (BlockImplementation& b, int index, BlocksProtocol::BlockDataSheet::ButtonInfo info)
  1695. : ControlButton (b), blockImpl (b), buttonInfo (info), buttonIndex (index)
  1696. {
  1697. if (auto det = Detector::getFrom (block))
  1698. det->activeControlButtons.add (this);
  1699. }
  1700. ~ControlButtonImplementation()
  1701. {
  1702. if (auto det = Detector::getFrom (block))
  1703. det->activeControlButtons.removeFirstMatchingValue (this);
  1704. }
  1705. ButtonFunction getType() const override { return buttonInfo.type; }
  1706. juce::String getName() const override { return BlocksProtocol::getButtonNameForFunction (buttonInfo.type); }
  1707. float getPositionX() const override { return buttonInfo.x; }
  1708. float getPositionY() const override { return buttonInfo.y; }
  1709. bool hasLight() const override { return blockImpl.isControlBlock(); }
  1710. bool setLightColour (LEDColour colour) override
  1711. {
  1712. if (hasLight())
  1713. {
  1714. if (auto row = blockImpl.ledRow.get())
  1715. {
  1716. row->setButtonColour ((uint32) buttonIndex, colour);
  1717. return true;
  1718. }
  1719. }
  1720. return false;
  1721. }
  1722. void broadcastButtonChange (Block::Timestamp timestamp, ControlButton::ButtonFunction button, bool isDown)
  1723. {
  1724. if (button == buttonInfo.type)
  1725. {
  1726. if (wasDown == isDown)
  1727. sendButtonChangeToListeners (timestamp, ! isDown);
  1728. sendButtonChangeToListeners (timestamp, isDown);
  1729. wasDown = isDown;
  1730. }
  1731. }
  1732. void sendButtonChangeToListeners (Block::Timestamp timestamp, bool isDown)
  1733. {
  1734. if (isDown)
  1735. listeners.call ([&] (ControlButton::Listener& l) { l.buttonPressed (*this, timestamp); });
  1736. else
  1737. listeners.call ([&] (ControlButton::Listener& l) { l.buttonReleased (*this, timestamp); });
  1738. }
  1739. BlockImplementation& blockImpl;
  1740. BlocksProtocol::BlockDataSheet::ButtonInfo buttonInfo;
  1741. int buttonIndex;
  1742. bool wasDown = false;
  1743. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ControlButtonImplementation)
  1744. };
  1745. //==============================================================================
  1746. struct StatusLightImplementation : public StatusLight
  1747. {
  1748. StatusLightImplementation (Block& b, BlocksProtocol::BlockDataSheet::StatusLEDInfo i) : StatusLight (b), info (i)
  1749. {
  1750. }
  1751. juce::String getName() const override { return info.name; }
  1752. bool setColour (LEDColour newColour) override
  1753. {
  1754. // XXX TODO!
  1755. juce::ignoreUnused (newColour);
  1756. return false;
  1757. }
  1758. BlocksProtocol::BlockDataSheet::StatusLEDInfo info;
  1759. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StatusLightImplementation)
  1760. };
  1761. //==============================================================================
  1762. struct LEDGridImplementation : public LEDGrid
  1763. {
  1764. LEDGridImplementation (BlockImplementation& b) : LEDGrid (b), blockImpl (b)
  1765. {
  1766. }
  1767. int getNumColumns() const override { return blockImpl.modelData.lightGridWidth; }
  1768. int getNumRows() const override { return blockImpl.modelData.lightGridHeight; }
  1769. BlockImplementation& blockImpl;
  1770. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDGridImplementation)
  1771. };
  1772. //==============================================================================
  1773. #if DUMP_TOPOLOGY
  1774. static juce::String idToSerialNum (const BlockTopology& topology, Block::UID uid)
  1775. {
  1776. for (auto* b : topology.blocks)
  1777. if (b->uid == uid)
  1778. return b->serialNumber;
  1779. return "???";
  1780. }
  1781. static juce::String portEdgeToString (Block::ConnectionPort port)
  1782. {
  1783. switch (port.edge)
  1784. {
  1785. case Block::ConnectionPort::DeviceEdge::north: return "north";
  1786. case Block::ConnectionPort::DeviceEdge::south: return "south";
  1787. case Block::ConnectionPort::DeviceEdge::east: return "east";
  1788. case Block::ConnectionPort::DeviceEdge::west: return "west";
  1789. }
  1790. return {};
  1791. }
  1792. static juce::String portToString (Block::ConnectionPort port)
  1793. {
  1794. return portEdgeToString (port) + "_" + juce::String (port.index);
  1795. }
  1796. static void dumpTopology (const BlockTopology& topology)
  1797. {
  1798. MemoryOutputStream m;
  1799. m << "=============================================================================" << newLine
  1800. << "Topology: " << topology.blocks.size() << " device(s)" << newLine
  1801. << newLine;
  1802. int index = 0;
  1803. for (auto block : topology.blocks)
  1804. {
  1805. m << "Device " << index++ << (block->isMasterBlock() ? ": (MASTER)" : ":") << newLine;
  1806. m << " Description: " << block->getDeviceDescription() << newLine
  1807. << " Serial: " << block->serialNumber << newLine;
  1808. if (auto bi = BlockImplementation::getFrom (*block))
  1809. m << " Short address: " << (int) bi->getDeviceIndex() << newLine;
  1810. m << " Battery level: " + juce::String (juce::roundToInt (100.0f * block->getBatteryLevel())) + "%" << newLine
  1811. << " Battery charging: " + juce::String (block->isBatteryCharging() ? "y" : "n") << newLine
  1812. << " Width: " << block->getWidth() << newLine
  1813. << " Height: " << block->getHeight() << newLine
  1814. << " Millimeters per unit: " << block->getMillimetersPerUnit() << newLine
  1815. << newLine;
  1816. }
  1817. for (auto& connection : topology.connections)
  1818. {
  1819. m << idToSerialNum (topology, connection.device1)
  1820. << ":" << portToString (connection.connectionPortOnDevice1)
  1821. << " <-> "
  1822. << idToSerialNum (topology, connection.device2)
  1823. << ":" << portToString (connection.connectionPortOnDevice2) << newLine;
  1824. }
  1825. m << "=============================================================================" << newLine;
  1826. Logger::outputDebugString (m.toString());
  1827. }
  1828. #endif
  1829. };
  1830. //==============================================================================
  1831. struct PhysicalTopologySource::DetectorHolder : private juce::Timer
  1832. {
  1833. DetectorHolder (PhysicalTopologySource& pts)
  1834. : topologySource (pts),
  1835. detector (Internal::Detector::getDefaultDetector())
  1836. {
  1837. startTimerHz (30);
  1838. }
  1839. DetectorHolder (PhysicalTopologySource& pts, DeviceDetector& dd)
  1840. : topologySource (pts),
  1841. detector (new Internal::Detector (dd))
  1842. {
  1843. startTimerHz (30);
  1844. }
  1845. void timerCallback() override
  1846. {
  1847. if (! topologySource.hasOwnServiceTimer())
  1848. handleTimerTick();
  1849. }
  1850. void handleTimerTick()
  1851. {
  1852. for (auto& b : detector->currentTopology.blocks)
  1853. if (auto bi = Internal::BlockImplementation::getFrom (*b))
  1854. bi->handleTimerTick();
  1855. }
  1856. PhysicalTopologySource& topologySource;
  1857. Internal::Detector::Ptr detector;
  1858. };
  1859. //==============================================================================
  1860. PhysicalTopologySource::PhysicalTopologySource()
  1861. : detector (new DetectorHolder (*this))
  1862. {
  1863. detector->detector->activeTopologySources.add (this);
  1864. }
  1865. PhysicalTopologySource::PhysicalTopologySource (DeviceDetector& detectorToUse)
  1866. : detector (new DetectorHolder (*this, detectorToUse))
  1867. {
  1868. detector->detector->activeTopologySources.add (this);
  1869. }
  1870. PhysicalTopologySource::~PhysicalTopologySource()
  1871. {
  1872. detector->detector->detach (this);
  1873. detector = nullptr;
  1874. }
  1875. BlockTopology PhysicalTopologySource::getCurrentTopology() const
  1876. {
  1877. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  1878. return detector->detector->currentTopology;
  1879. }
  1880. void PhysicalTopologySource::cancelAllActiveTouches() noexcept
  1881. {
  1882. detector->detector->cancelAllActiveTouches();
  1883. }
  1884. bool PhysicalTopologySource::hasOwnServiceTimer() const { return false; }
  1885. void PhysicalTopologySource::handleTimerTick() { detector->handleTimerTick(); }
  1886. PhysicalTopologySource::DeviceConnection::DeviceConnection() {}
  1887. PhysicalTopologySource::DeviceConnection::~DeviceConnection() {}
  1888. PhysicalTopologySource::DeviceDetector::DeviceDetector() {}
  1889. PhysicalTopologySource::DeviceDetector::~DeviceDetector() {}
  1890. const char* const* PhysicalTopologySource::getStandardLittleFootFunctions() noexcept
  1891. {
  1892. return BlocksProtocol::ledProgramLittleFootFunctions;
  1893. }
  1894. template <typename ListType>
  1895. static bool collectionsMatch (const ListType& list1, const ListType& list2) noexcept
  1896. {
  1897. if (list1.size() != list2.size())
  1898. return false;
  1899. for (auto&& b : list1)
  1900. if (! list2.contains (b))
  1901. return false;
  1902. return true;
  1903. }
  1904. bool BlockTopology::operator== (const BlockTopology& other) const noexcept
  1905. {
  1906. return collectionsMatch (connections, other.connections) && collectionsMatch (blocks, other.blocks);
  1907. }
  1908. bool BlockTopology::operator!= (const BlockTopology& other) const noexcept
  1909. {
  1910. return ! operator== (other);
  1911. }
  1912. bool BlockDeviceConnection::operator== (const BlockDeviceConnection& other) const noexcept
  1913. {
  1914. return (device1 == other.device1 && device2 == other.device2
  1915. && connectionPortOnDevice1 == other.connectionPortOnDevice1
  1916. && connectionPortOnDevice2 == other.connectionPortOnDevice2)
  1917. || (device1 == other.device2 && device2 == other.device1
  1918. && connectionPortOnDevice1 == other.connectionPortOnDevice2
  1919. && connectionPortOnDevice2 == other.connectionPortOnDevice1);
  1920. }
  1921. bool BlockDeviceConnection::operator!= (const BlockDeviceConnection& other) const noexcept
  1922. {
  1923. return ! operator== (other);
  1924. }
  1925. } // namespace juce