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.

2685 lines
94KB

  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 juce::String getVersionString (const BlocksProtocol::VersionNumber& v)
  255. {
  256. return juce::String (reinterpret_cast<const char*> (v.version),
  257. std::min (sizeof (v.version), static_cast<size_t> (v.length)));
  258. }
  259. static juce::String getNameString (const BlocksProtocol::BlockName& n)
  260. {
  261. return juce::String (reinterpret_cast<const char*> (n.name),
  262. std::min (sizeof (n.name), static_cast<size_t> (n.length)));
  263. }
  264. static Block::Timestamp deviceTimestampToHost (uint32 timestamp) noexcept
  265. {
  266. return static_cast<Block::Timestamp> (timestamp);
  267. }
  268. static juce::Array<DeviceInfo> getArrayOfDeviceInfo (const juce::Array<BlocksProtocol::DeviceStatus>& devices)
  269. {
  270. juce::Array<DeviceInfo> result;
  271. bool isFirst = true;
  272. for (auto& device : devices)
  273. {
  274. BlocksProtocol::VersionNumber version;
  275. BlocksProtocol::BlockName name;
  276. result.add ({ getBlockUIDFromSerialNumber (device.serialNumber),
  277. device.index,
  278. device.serialNumber,
  279. version,
  280. name,
  281. isFirst });
  282. isFirst = false;
  283. }
  284. return result;
  285. }
  286. static bool containsBlockWithUID (const juce::Array<DeviceInfo>& devices, Block::UID uid) noexcept
  287. {
  288. for (auto&& d : devices)
  289. if (d.uid == uid)
  290. return true;
  291. return false;
  292. }
  293. static bool containsBlockWithUID (const Block::Array& blocks, Block::UID uid) noexcept
  294. {
  295. for (auto&& block : blocks)
  296. if (block->uid == uid)
  297. return true;
  298. return false;
  299. }
  300. static bool versionNumberChanged (const DeviceInfo& device, juce::String version) noexcept
  301. {
  302. auto deviceVersion = getVersionString (device.version);
  303. return deviceVersion != version && deviceVersion.isNotEmpty();
  304. }
  305. static bool nameIsValid (const DeviceInfo& device)
  306. {
  307. return device.name.length > 0;
  308. }
  309. static void setVersionNumberForBlock (const DeviceInfo& deviceInfo, Block& block) noexcept
  310. {
  311. if (deviceInfo.uid != block.uid)
  312. {
  313. jassertfalse;
  314. return;
  315. }
  316. block.versionNumber = getVersionString (deviceInfo.version);
  317. }
  318. static void setNameForBlock (const juce::Array<DeviceInfo>& devices, Block& block) noexcept
  319. {
  320. for (auto&& d : devices)
  321. {
  322. if (d.uid == block.uid)
  323. {
  324. setNameForBlock (d, block);
  325. return;
  326. }
  327. }
  328. }
  329. static void setNameForBlock (const DeviceInfo& deviceInfo, Block& block)
  330. {
  331. if (deviceInfo.uid != block.uid)
  332. {
  333. jassertfalse;
  334. return;
  335. }
  336. block.name = getNameString (deviceInfo.name);
  337. }
  338. //==============================================================================
  339. struct ConnectedDeviceGroup : private juce::AsyncUpdater,
  340. private juce::Timer
  341. {
  342. ConnectedDeviceGroup (Detector& d, const juce::String& name, DeviceConnection* connection)
  343. : detector (d), deviceName (name), deviceConnection (connection)
  344. {
  345. lastGlobalPingTime = juce::Time::getCurrentTime();
  346. deviceConnection->handleMessageFromDevice = [this] (const void* data, size_t dataSize)
  347. {
  348. this->handleIncomingMessage (data, dataSize);
  349. };
  350. startTimer (200);
  351. sendTopologyRequest();
  352. }
  353. bool isStillConnected (const juce::StringArray& detectedDevices) const noexcept
  354. {
  355. return detectedDevices.contains (deviceName)
  356. && ! failedToGetTopology()
  357. && lastGlobalPingTime > juce::Time::getCurrentTime() - juce::RelativeTime::seconds (pingTimeoutSeconds);
  358. }
  359. Block::UID getDeviceIDFromIndex (BlocksProtocol::TopologyIndex index) const noexcept
  360. {
  361. for (auto& d : currentDeviceInfo)
  362. if (d.index == index)
  363. return d.uid;
  364. return {};
  365. }
  366. int getIndexFromDeviceID (Block::UID uid) const noexcept
  367. {
  368. for (auto& d : currentDeviceInfo)
  369. if (d.uid == uid)
  370. return d.index;
  371. return -1;
  372. }
  373. const DeviceInfo* getDeviceInfoFromUID (Block::UID uid) const noexcept
  374. {
  375. for (auto& d : currentDeviceInfo)
  376. if (d.uid == uid)
  377. return &d;
  378. return nullptr;
  379. }
  380. const BlocksProtocol::DeviceStatus* getLastStatus (Block::UID deviceID) const noexcept
  381. {
  382. for (auto&& status : currentTopologyDevices)
  383. if (getBlockUIDFromSerialNumber (status.serialNumber) == deviceID)
  384. return &status;
  385. return nullptr;
  386. }
  387. //==============================================================================
  388. juce::Time lastTopologyRequestTime, lastTopologyReceiveTime;
  389. int numTopologyRequestsSent = 0;
  390. void sendTopologyRequest()
  391. {
  392. ++numTopologyRequestsSent;
  393. lastTopologyRequestTime = juce::Time::getCurrentTime();
  394. sendCommandMessage (0, BlocksProtocol::requestTopologyMessage);
  395. }
  396. void scheduleNewTopologyRequest()
  397. {
  398. numTopologyRequestsSent = 0;
  399. lastTopologyReceiveTime = juce::Time();
  400. }
  401. bool failedToGetTopology() const noexcept
  402. {
  403. return numTopologyRequestsSent > 4 && lastTopologyReceiveTime == juce::Time();
  404. }
  405. bool hasAnyBlockStoppedPinging() const noexcept
  406. {
  407. auto now = juce::Time::getCurrentTime();
  408. for (auto& ping : blockPings)
  409. if (ping.lastPing < now - juce::RelativeTime::seconds (pingTimeoutSeconds))
  410. return true;
  411. return false;
  412. }
  413. void timerCallback() override
  414. {
  415. auto now = juce::Time::getCurrentTime();
  416. if ((now > lastTopologyReceiveTime + juce::RelativeTime::seconds (30.0) || hasAnyBlockStoppedPinging())
  417. && now > lastTopologyRequestTime + juce::RelativeTime::seconds (1.0)
  418. && numTopologyRequestsSent < 4)
  419. sendTopologyRequest();
  420. }
  421. //==============================================================================
  422. // The following methods will be called by the HostPacketDecoder:
  423. void beginTopology (int numDevices, int numConnections)
  424. {
  425. incomingTopologyDevices.clearQuick();
  426. incomingTopologyDevices.ensureStorageAllocated (numDevices);
  427. incomingTopologyConnections.clearQuick();
  428. incomingTopologyConnections.ensureStorageAllocated (numConnections);
  429. }
  430. void extendTopology (int numDevices, int numConnections)
  431. {
  432. incomingTopologyDevices.ensureStorageAllocated (incomingTopologyDevices.size() + numDevices);
  433. incomingTopologyConnections.ensureStorageAllocated (incomingTopologyConnections.size() + numConnections);
  434. }
  435. void handleTopologyDevice (BlocksProtocol::DeviceStatus status)
  436. {
  437. incomingTopologyDevices.add (status);
  438. }
  439. void handleTopologyConnection (BlocksProtocol::DeviceConnection connection)
  440. {
  441. incomingTopologyConnections.add (connection);
  442. }
  443. void endTopology()
  444. {
  445. currentDeviceInfo = getArrayOfDeviceInfo (incomingTopologyDevices);
  446. currentDeviceConnections = getArrayOfConnections (incomingTopologyConnections);
  447. currentTopologyDevices = incomingTopologyDevices;
  448. lastTopologyReceiveTime = juce::Time::getCurrentTime();
  449. blockPings.clear();
  450. }
  451. void handleVersion (BlocksProtocol::DeviceVersion version)
  452. {
  453. for (auto& d : currentDeviceInfo)
  454. if (d.index == version.index && version.version.length > 1)
  455. d.version = version.version;
  456. }
  457. void notifyDetectorTopologyChanged()
  458. {
  459. detector.handleTopologyChange();
  460. }
  461. void handleName (BlocksProtocol::DeviceName name)
  462. {
  463. for (auto& d : currentDeviceInfo)
  464. if (d.index == name.index && name.name.length > 1)
  465. d.name = name.name;
  466. }
  467. void handleControlButtonUpDown (BlocksProtocol::TopologyIndex deviceIndex, uint32 timestamp,
  468. BlocksProtocol::ControlButtonID buttonID, bool isDown)
  469. {
  470. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  471. detector.handleButtonChange (deviceID, deviceTimestampToHost (timestamp), buttonID.get(), isDown);
  472. }
  473. void handleCustomMessage (BlocksProtocol::TopologyIndex deviceIndex, uint32 timestamp, const int32* data)
  474. {
  475. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  476. detector.handleCustomMessage (deviceID, deviceTimestampToHost (timestamp), data);
  477. }
  478. void handleTouchChange (BlocksProtocol::TopologyIndex deviceIndex,
  479. uint32 timestamp,
  480. BlocksProtocol::TouchIndex touchIndex,
  481. BlocksProtocol::TouchPosition position,
  482. BlocksProtocol::TouchVelocity velocity,
  483. bool isStart, bool isEnd)
  484. {
  485. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  486. {
  487. TouchSurface::Touch touch;
  488. touch.index = (int) touchIndex.get();
  489. touch.x = position.x.toUnipolarFloat();
  490. touch.y = position.y.toUnipolarFloat();
  491. touch.z = position.z.toUnipolarFloat();
  492. touch.xVelocity = velocity.vx.toBipolarFloat();
  493. touch.yVelocity = velocity.vy.toBipolarFloat();
  494. touch.zVelocity = velocity.vz.toBipolarFloat();
  495. touch.eventTimestamp = deviceTimestampToHost (timestamp);
  496. touch.isTouchStart = isStart;
  497. touch.isTouchEnd = isEnd;
  498. touch.blockUID = deviceID;
  499. setTouchStartPosition (touch);
  500. detector.handleTouchChange (deviceID, touch);
  501. }
  502. }
  503. void setTouchStartPosition (TouchSurface::Touch& touch)
  504. {
  505. auto& startPos = touchStartPositions.getValue (touch);
  506. if (touch.isTouchStart)
  507. startPos = { touch.x, touch.y };
  508. touch.startX = startPos.x;
  509. touch.startY = startPos.y;
  510. }
  511. void handlePacketACK (BlocksProtocol::TopologyIndex deviceIndex, BlocksProtocol::PacketCounter counter)
  512. {
  513. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  514. detector.handleSharedDataACK (deviceID, counter);
  515. }
  516. void handleFirmwareUpdateACK (BlocksProtocol::TopologyIndex deviceIndex, BlocksProtocol::FirmwareUpdateACKCode resultCode, BlocksProtocol::FirmwareUpdateACKDetail resultDetail)
  517. {
  518. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  519. detector.handleFirmwareUpdateACK (deviceID, (uint8) resultCode.get(), (uint32) resultDetail.get());
  520. }
  521. void handleConfigUpdateMessage (BlocksProtocol::TopologyIndex deviceIndex, int32 item, int32 value, int32 min, int32 max)
  522. {
  523. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  524. detector.handleConfigUpdateMessage (deviceID, item, value, min, max);
  525. }
  526. void handleConfigSetMessage (BlocksProtocol::TopologyIndex deviceIndex, int32 item, int32 value)
  527. {
  528. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  529. detector.handleConfigSetMessage (deviceID, item, value);
  530. }
  531. void handleConfigFactorySyncEndMessage (BlocksProtocol::TopologyIndex deviceIndex)
  532. {
  533. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  534. detector.handleConfigFactorySyncEndMessage (deviceID);
  535. }
  536. void handleConfigFactorySyncResetMessage (BlocksProtocol::TopologyIndex deviceIndex)
  537. {
  538. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  539. detector.handleConfigFactorySyncResetMessage (deviceID);
  540. }
  541. void handleLogMessage (BlocksProtocol::TopologyIndex deviceIndex, const String& message)
  542. {
  543. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  544. detector.handleLogMessage (deviceID, message);
  545. }
  546. //==============================================================================
  547. template <typename PacketBuilder>
  548. bool sendMessageToDevice (const PacketBuilder& builder) const
  549. {
  550. if (deviceConnection->sendMessageToDevice (builder.getData(), (size_t) builder.size()))
  551. {
  552. #if DUMP_BANDWIDTH_STATS
  553. registerBytesOut (builder.size());
  554. #endif
  555. return true;
  556. }
  557. return false;
  558. }
  559. bool sendCommandMessage (BlocksProtocol::TopologyIndex deviceIndex, uint32 commandID) const
  560. {
  561. BlocksProtocol::HostPacketBuilder<64> p;
  562. p.writePacketSysexHeaderBytes (deviceIndex);
  563. p.deviceControlMessage (commandID);
  564. p.writePacketSysexFooter();
  565. return sendMessageToDevice (p);
  566. }
  567. bool broadcastCommandMessage (uint32 commandID) const
  568. {
  569. return sendCommandMessage (BlocksProtocol::topologyIndexForBroadcast, commandID);
  570. }
  571. DeviceConnection* getDeviceConnection()
  572. {
  573. return deviceConnection.get();
  574. }
  575. Detector& detector;
  576. juce::String deviceName;
  577. juce::Array<DeviceInfo> currentDeviceInfo;
  578. juce::Array<BlockDeviceConnection> currentDeviceConnections;
  579. static constexpr double pingTimeoutSeconds = 6.0;
  580. private:
  581. //==============================================================================
  582. std::unique_ptr<DeviceConnection> deviceConnection;
  583. juce::Array<BlocksProtocol::DeviceStatus> incomingTopologyDevices, currentTopologyDevices;
  584. juce::Array<BlocksProtocol::DeviceConnection> incomingTopologyConnections;
  585. juce::CriticalSection incomingPacketLock;
  586. juce::Array<juce::MemoryBlock> incomingPackets;
  587. struct TouchStart
  588. {
  589. float x, y;
  590. };
  591. TouchList<TouchStart> touchStartPositions;
  592. juce::Time lastGlobalPingTime;
  593. struct BlockPingTime
  594. {
  595. Block::UID blockUID;
  596. juce::Time lastPing;
  597. };
  598. juce::Array<BlockPingTime> blockPings;
  599. Block::UID getDeviceIDFromMessageIndex (BlocksProtocol::TopologyIndex index) noexcept
  600. {
  601. auto uid = getDeviceIDFromIndex (index);
  602. if (uid == Block::UID())
  603. {
  604. scheduleNewTopologyRequest(); // force a re-request of the topology when we
  605. // get an event from a block that we don't know about
  606. }
  607. else
  608. {
  609. auto now = juce::Time::getCurrentTime();
  610. for (auto& ping : blockPings)
  611. {
  612. if (ping.blockUID == uid)
  613. {
  614. ping.lastPing = now;
  615. return uid;
  616. }
  617. }
  618. blockPings.add ({ uid, now });
  619. }
  620. return uid;
  621. }
  622. juce::Array<BlockDeviceConnection> getArrayOfConnections (const juce::Array<BlocksProtocol::DeviceConnection>& connections)
  623. {
  624. juce::Array<BlockDeviceConnection> result;
  625. for (auto&& c : connections)
  626. {
  627. BlockDeviceConnection dc;
  628. dc.device1 = getDeviceIDFromIndex (c.device1);
  629. dc.device2 = getDeviceIDFromIndex (c.device2);
  630. if (dc.device1 <= 0 || dc.device2 <= 0)
  631. continue;
  632. dc.connectionPortOnDevice1 = convertConnectionPort (dc.device1, c.port1);
  633. dc.connectionPortOnDevice2 = convertConnectionPort (dc.device2, c.port2);
  634. result.add (dc);
  635. }
  636. return result;
  637. }
  638. Block::ConnectionPort convertConnectionPort (Block::UID uid, BlocksProtocol::ConnectorPort p) noexcept
  639. {
  640. if (auto* info = getDeviceInfoFromUID (uid))
  641. return BlocksProtocol::BlockDataSheet (info->serial).convertPortIndexToConnectorPort (p);
  642. jassertfalse;
  643. return { Block::ConnectionPort::DeviceEdge::north, 0 };
  644. }
  645. //==============================================================================
  646. void handleIncomingMessage (const void* data, size_t dataSize)
  647. {
  648. juce::MemoryBlock mb (data, dataSize);
  649. {
  650. const juce::ScopedLock sl (incomingPacketLock);
  651. incomingPackets.add (std::move (mb));
  652. }
  653. triggerAsyncUpdate();
  654. #if DUMP_BANDWIDTH_STATS
  655. registerBytesIn ((int) dataSize);
  656. #endif
  657. }
  658. void handleAsyncUpdate() override
  659. {
  660. juce::Array<juce::MemoryBlock> packets;
  661. packets.ensureStorageAllocated (32);
  662. {
  663. const juce::ScopedLock sl (incomingPacketLock);
  664. incomingPackets.swapWith (packets);
  665. }
  666. for (auto& packet : packets)
  667. {
  668. auto data = static_cast<const uint8*> (packet.getData());
  669. BlocksProtocol::HostPacketDecoder<ConnectedDeviceGroup>
  670. ::processNextPacket (*this, *data, data + 1, (int) packet.getSize() - 1);
  671. }
  672. lastGlobalPingTime = juce::Time::getCurrentTime();
  673. }
  674. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectedDeviceGroup)
  675. };
  676. //==============================================================================
  677. /** This is the main singleton object that keeps track of connected blocks */
  678. struct Detector : public juce::ReferenceCountedObject,
  679. private juce::Timer
  680. {
  681. Detector() : defaultDetector (new MIDIDeviceDetector()), deviceDetector (*defaultDetector)
  682. {
  683. topologyBroadcastThrottle.detector = this;
  684. startTimer (10);
  685. }
  686. Detector (DeviceDetector& dd) : deviceDetector (dd)
  687. {
  688. topologyBroadcastThrottle.detector = this;
  689. startTimer (10);
  690. }
  691. ~Detector()
  692. {
  693. jassert (activeTopologySources.isEmpty());
  694. jassert (activeControlButtons.isEmpty());
  695. }
  696. using Ptr = juce::ReferenceCountedObjectPtr<Detector>;
  697. static Detector::Ptr getDefaultDetector()
  698. {
  699. auto& d = getDefaultDetectorPointer();
  700. if (d == nullptr)
  701. d = new Detector();
  702. return d;
  703. }
  704. static Detector::Ptr& getDefaultDetectorPointer()
  705. {
  706. static Detector::Ptr defaultDetector;
  707. return defaultDetector;
  708. }
  709. void detach (PhysicalTopologySource* pts)
  710. {
  711. activeTopologySources.removeAllInstancesOf (pts);
  712. if (activeTopologySources.isEmpty())
  713. {
  714. for (auto& b : currentTopology.blocks)
  715. if (auto bi = BlockImplementation::getFrom (*b))
  716. bi->sendCommandMessage (BlocksProtocol::endAPIMode);
  717. currentTopology = {};
  718. topologyBroadcastThrottle.lastTopology = {};
  719. auto& d = getDefaultDetectorPointer();
  720. if (d != nullptr && d->getReferenceCount() == 2)
  721. getDefaultDetectorPointer() = nullptr;
  722. }
  723. }
  724. bool isConnected (Block::UID deviceID) const noexcept
  725. {
  726. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  727. for (auto&& b : currentTopology.blocks)
  728. if (b->uid == deviceID)
  729. return true;
  730. return false;
  731. }
  732. const BlocksProtocol::DeviceStatus* getLastStatus (Block::UID deviceID) const noexcept
  733. {
  734. for (auto d : connectedDeviceGroups)
  735. if (auto status = d->getLastStatus (deviceID))
  736. return status;
  737. return nullptr;
  738. }
  739. void handleTopologyChange()
  740. {
  741. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  742. {
  743. juce::Array<DeviceInfo> newDeviceInfo;
  744. juce::Array<BlockDeviceConnection> newDeviceConnections;
  745. for (auto d : connectedDeviceGroups)
  746. {
  747. newDeviceInfo.addArray (d->currentDeviceInfo);
  748. newDeviceConnections.addArray (d->currentDeviceConnections);
  749. }
  750. for (int i = currentTopology.blocks.size(); --i >= 0;)
  751. {
  752. auto currentBlock = currentTopology.blocks.getUnchecked (i);
  753. auto newDeviceIter = std::find_if (newDeviceInfo.begin(), newDeviceInfo.end(),
  754. [&] (DeviceInfo& info) { return info.uid == currentBlock->uid; });
  755. if (newDeviceIter == newDeviceInfo.end())
  756. {
  757. if (auto bi = BlockImplementation::getFrom (*currentBlock))
  758. bi->invalidate();
  759. disconnectedBlocks.addIfNotAlreadyThere (currentTopology.blocks.removeAndReturn (i).get());
  760. }
  761. else
  762. {
  763. updateCurrentBlockInfo (currentBlock, *newDeviceIter);
  764. }
  765. }
  766. static const int maxBlocksToSave = 100;
  767. if (disconnectedBlocks.size() > maxBlocksToSave)
  768. disconnectedBlocks.removeRange (0, 2 * (disconnectedBlocks.size() - maxBlocksToSave));
  769. for (auto& info : newDeviceInfo)
  770. if (info.serial.isValid() && ! containsBlockWithUID (currentTopology.blocks, getBlockUIDFromSerialNumber (info.serial)))
  771. addBlock (info);
  772. currentTopology.connections.swapWith (newDeviceConnections);
  773. }
  774. topologyBroadcastThrottle.scheduleTopologyChangeCallback();
  775. }
  776. void handleSharedDataACK (Block::UID deviceID, uint32 packetCounter) const
  777. {
  778. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  779. for (auto&& b : currentTopology.blocks)
  780. if (b->uid == deviceID)
  781. if (auto bi = BlockImplementation::getFrom (*b))
  782. bi->handleSharedDataACK (packetCounter);
  783. }
  784. void handleFirmwareUpdateACK (Block::UID deviceID, uint8 resultCode, uint32 resultDetail)
  785. {
  786. for (auto&& b : currentTopology.blocks)
  787. if (b->uid == deviceID)
  788. if (auto bi = BlockImplementation::getFrom (*b))
  789. bi->handleFirmwareUpdateACK (resultCode, resultDetail);
  790. }
  791. void handleConfigUpdateMessage (Block::UID deviceID, int32 item, int32 value, int32 min, int32 max)
  792. {
  793. for (auto&& b : currentTopology.blocks)
  794. if (b->uid == deviceID)
  795. if (auto bi = BlockImplementation::getFrom (*b))
  796. bi->handleConfigUpdateMessage (item, value, min, max);
  797. }
  798. void notifyBlockOfConfigChange (BlockImplementation& bi, uint32 item)
  799. {
  800. if (auto configChangedCallback = bi.configChangedCallback)
  801. {
  802. if (item >= bi.getMaxConfigIndex())
  803. configChangedCallback (bi, {}, item);
  804. else
  805. configChangedCallback (bi, bi.getLocalConfigMetaData (item), item);
  806. }
  807. }
  808. void handleConfigSetMessage (Block::UID deviceID, int32 item, int32 value)
  809. {
  810. for (auto&& b : currentTopology.blocks)
  811. {
  812. if (b->uid == deviceID)
  813. {
  814. if (auto bi = BlockImplementation::getFrom (*b))
  815. {
  816. bi->handleConfigSetMessage (item, value);
  817. notifyBlockOfConfigChange (*bi, uint32 (item));
  818. }
  819. }
  820. }
  821. }
  822. void handleConfigFactorySyncEndMessage (Block::UID deviceID)
  823. {
  824. for (auto&& b : currentTopology.blocks)
  825. if (b->uid == deviceID)
  826. if (auto bi = BlockImplementation::getFrom (*b))
  827. notifyBlockOfConfigChange (*bi, bi->getMaxConfigIndex());
  828. }
  829. void handleConfigFactorySyncResetMessage (Block::UID deviceID)
  830. {
  831. for (auto&& b : currentTopology.blocks)
  832. if (b->uid == deviceID)
  833. if (auto bi = BlockImplementation::getFrom (*b))
  834. bi->resetConfigListActiveStatus();
  835. }
  836. void handleLogMessage (Block::UID deviceID, const String& message) const
  837. {
  838. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  839. for (auto&& b : currentTopology.blocks)
  840. if (b->uid == deviceID)
  841. if (auto bi = BlockImplementation::getFrom (*b))
  842. bi->handleLogMessage (message);
  843. }
  844. void handleButtonChange (Block::UID deviceID, Block::Timestamp timestamp, uint32 buttonIndex, bool isDown) const
  845. {
  846. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  847. for (auto b : activeControlButtons)
  848. {
  849. if (b->block.uid == deviceID)
  850. {
  851. if (auto bi = BlockImplementation::getFrom (b->block))
  852. {
  853. bi->pingFromDevice();
  854. if (buttonIndex < (uint32) bi->modelData.buttons.size())
  855. b->broadcastButtonChange (timestamp, bi->modelData.buttons[(int) buttonIndex].type, isDown);
  856. }
  857. }
  858. }
  859. }
  860. void handleTouchChange (Block::UID deviceID, const TouchSurface::Touch& touchEvent)
  861. {
  862. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  863. for (auto t : activeTouchSurfaces)
  864. {
  865. if (t->block.uid == deviceID)
  866. {
  867. TouchSurface::Touch scaledEvent (touchEvent);
  868. scaledEvent.x *= t->block.getWidth();
  869. scaledEvent.y *= t->block.getHeight();
  870. scaledEvent.startX *= t->block.getWidth();
  871. scaledEvent.startY *= t->block.getHeight();
  872. t->broadcastTouchChange (scaledEvent);
  873. }
  874. }
  875. }
  876. void cancelAllActiveTouches() noexcept
  877. {
  878. for (auto surface : activeTouchSurfaces)
  879. surface->cancelAllActiveTouches();
  880. }
  881. void handleCustomMessage (Block::UID deviceID, Block::Timestamp timestamp, const int32* data)
  882. {
  883. for (auto&& b : currentTopology.blocks)
  884. if (b->uid == deviceID)
  885. if (auto bi = BlockImplementation::getFrom (*b))
  886. bi->handleCustomMessage (timestamp, data);
  887. }
  888. //==============================================================================
  889. int getIndexFromDeviceID (Block::UID deviceID) const noexcept
  890. {
  891. for (auto* c : connectedDeviceGroups)
  892. {
  893. auto index = c->getIndexFromDeviceID (deviceID);
  894. if (index >= 0)
  895. return index;
  896. }
  897. return -1;
  898. }
  899. template <typename PacketBuilder>
  900. bool sendMessageToDevice (Block::UID deviceID, const PacketBuilder& builder) const
  901. {
  902. for (auto* c : connectedDeviceGroups)
  903. if (c->getIndexFromDeviceID (deviceID) >= 0)
  904. return c->sendMessageToDevice (builder);
  905. return false;
  906. }
  907. static Detector* getFrom (Block& b) noexcept
  908. {
  909. if (auto* bi = BlockImplementation::getFrom (b))
  910. return &(bi->detector);
  911. jassertfalse;
  912. return nullptr;
  913. }
  914. DeviceConnection* getDeviceConnectionFor (const Block& b)
  915. {
  916. for (const auto& d : connectedDeviceGroups)
  917. {
  918. for (const auto& info : d->currentDeviceInfo)
  919. {
  920. if (info.uid == b.uid)
  921. return d->getDeviceConnection();
  922. }
  923. }
  924. return nullptr;
  925. }
  926. std::unique_ptr<MIDIDeviceDetector> defaultDetector;
  927. DeviceDetector& deviceDetector;
  928. juce::Array<PhysicalTopologySource*> activeTopologySources;
  929. juce::Array<ControlButtonImplementation*> activeControlButtons;
  930. juce::Array<TouchSurfaceImplementation*> activeTouchSurfaces;
  931. BlockTopology currentTopology;
  932. juce::ReferenceCountedArray<Block, CriticalSection> disconnectedBlocks;
  933. private:
  934. void timerCallback() override
  935. {
  936. startTimer (1500);
  937. auto detectedDevices = deviceDetector.scanForDevices();
  938. handleDevicesRemoved (detectedDevices);
  939. handleDevicesAdded (detectedDevices);
  940. }
  941. void handleDevicesRemoved (const juce::StringArray& detectedDevices)
  942. {
  943. bool anyDevicesRemoved = false;
  944. for (int i = connectedDeviceGroups.size(); --i >= 0;)
  945. {
  946. if (! connectedDeviceGroups.getUnchecked(i)->isStillConnected (detectedDevices))
  947. {
  948. connectedDeviceGroups.remove (i);
  949. anyDevicesRemoved = true;
  950. }
  951. }
  952. if (anyDevicesRemoved)
  953. handleTopologyChange();
  954. }
  955. void handleDevicesAdded (const juce::StringArray& detectedDevices)
  956. {
  957. bool anyDevicesAdded = false;
  958. for (const auto& devName : detectedDevices)
  959. {
  960. if (! hasDeviceFor (devName))
  961. {
  962. if (auto d = deviceDetector.openDevice (detectedDevices.indexOf (devName)))
  963. {
  964. connectedDeviceGroups.add (new ConnectedDeviceGroup (*this, devName, d));
  965. anyDevicesAdded = true;
  966. }
  967. }
  968. }
  969. if (anyDevicesAdded)
  970. handleTopologyChange();
  971. }
  972. bool hasDeviceFor (const juce::String& devName) const
  973. {
  974. for (auto d : connectedDeviceGroups)
  975. if (d->deviceName == devName)
  976. return true;
  977. return false;
  978. }
  979. void addBlock (DeviceInfo info)
  980. {
  981. if (! reactivateBlockIfKnown (info))
  982. addNewBlock (info);
  983. }
  984. bool reactivateBlockIfKnown (DeviceInfo info)
  985. {
  986. auto uid = getBlockUIDFromSerialNumber (info.serial);
  987. for (int i = 0; i < disconnectedBlocks.size(); ++i)
  988. {
  989. if (disconnectedBlocks.getUnchecked (i)->uid == uid)
  990. {
  991. auto block = disconnectedBlocks.removeAndReturn (i);
  992. if (auto blockImpl = BlockImplementation::getFrom (*block))
  993. {
  994. blockImpl->revalidate (info.version, info.name, info.isMaster);
  995. currentTopology.blocks.add (block);
  996. return true;
  997. }
  998. }
  999. }
  1000. return false;
  1001. }
  1002. void addNewBlock (DeviceInfo info)
  1003. {
  1004. currentTopology.blocks.add (new BlockImplementation (info.serial, *this, info.version,
  1005. info.name, info.isMaster));
  1006. }
  1007. void updateCurrentBlockInfo (Block::Ptr blockToUpdate, DeviceInfo& updatedInfo)
  1008. {
  1009. if (versionNumberChanged (updatedInfo, blockToUpdate->versionNumber))
  1010. setVersionNumberForBlock (updatedInfo, *blockToUpdate);
  1011. if (nameIsValid (updatedInfo))
  1012. setNameForBlock (updatedInfo, *blockToUpdate);
  1013. if (updatedInfo.isMaster != blockToUpdate->isMasterBlock())
  1014. BlockImplementation::getFrom (*blockToUpdate)->setToMaster (updatedInfo.isMaster);
  1015. }
  1016. juce::OwnedArray<ConnectedDeviceGroup> connectedDeviceGroups;
  1017. //==============================================================================
  1018. /** Flurries of topology messages sometimes arrive due to loose connections.
  1019. Avoid informing listeners until they've stabilised.
  1020. */
  1021. struct TopologyBroadcastThrottle : private juce::Timer
  1022. {
  1023. TopologyBroadcastThrottle() = default;
  1024. void scheduleTopologyChangeCallback()
  1025. {
  1026. #ifdef JUCE_BLOCKS_TOPOLOGY_BROADCAST_THROTTLE_TIME
  1027. startTimer (JUCE_BLOCKS_TOPOLOGY_BROADCAST_THROTTLE_TIME);
  1028. #else
  1029. startTimer (750);
  1030. #endif
  1031. }
  1032. void timerCallback() override
  1033. {
  1034. if (detector->currentTopology != lastTopology)
  1035. {
  1036. lastTopology = detector->currentTopology;
  1037. BlocksTraverser traverser;
  1038. traverser.traverseBlockArray (detector->currentTopology);
  1039. for (auto* d : detector->activeTopologySources)
  1040. d->listeners.call ([] (TopologySource::Listener& l) { l.topologyChanged(); });
  1041. #if DUMP_TOPOLOGY
  1042. dumpTopology (lastTopology);
  1043. #endif
  1044. }
  1045. stopTimer();
  1046. }
  1047. Detector* detector = nullptr;
  1048. BlockTopology lastTopology;
  1049. };
  1050. TopologyBroadcastThrottle topologyBroadcastThrottle;
  1051. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Detector)
  1052. };
  1053. //==============================================================================
  1054. /** This is a friend of the BlocksImplementation that will scan and set the
  1055. physical positions of the blocks */
  1056. struct BlocksTraverser
  1057. {
  1058. void traverseBlockArray (const BlockTopology& topology)
  1059. {
  1060. juce::Array<Block::UID> visited;
  1061. for (auto& block : topology.blocks)
  1062. {
  1063. if (block->isMasterBlock() && ! visited.contains (block->uid))
  1064. {
  1065. if (auto* bi = dynamic_cast<BlockImplementation*> (block))
  1066. {
  1067. bi->masterUID = {};
  1068. bi->position = {};
  1069. bi->rotation = 0;
  1070. }
  1071. layoutNeighbours (*block, topology, block->uid, visited);
  1072. }
  1073. }
  1074. }
  1075. Block::Ptr findBlockWithUid (const BlockTopology& topology, Block::UID uid)
  1076. {
  1077. for (auto& block : topology.blocks)
  1078. if (block->uid == uid)
  1079. return *block;
  1080. return {};
  1081. }
  1082. // returns the distance from corner clockwise
  1083. int getUnitForIndex (Block::Ptr block, Block::ConnectionPort::DeviceEdge edge, int index)
  1084. {
  1085. if (block->getType() == Block::seaboardBlock)
  1086. {
  1087. if (edge == Block::ConnectionPort::DeviceEdge::north)
  1088. {
  1089. if (index == 0) return 1;
  1090. if (index == 1) return 4;
  1091. }
  1092. else if (edge == Block::ConnectionPort::DeviceEdge::east
  1093. || edge == Block::ConnectionPort::DeviceEdge::west)
  1094. {
  1095. return 1;
  1096. }
  1097. }
  1098. if (edge == Block::ConnectionPort::DeviceEdge::south)
  1099. return block->getWidth() - (index + 1);
  1100. if (edge == Block::ConnectionPort::DeviceEdge::west)
  1101. return block->getHeight() - (index + 1);
  1102. return index;
  1103. }
  1104. // returns how often north needs to rotate by 90 degrees
  1105. int getRotationForEdge (Block::ConnectionPort::DeviceEdge edge)
  1106. {
  1107. switch (edge)
  1108. {
  1109. case Block::ConnectionPort::DeviceEdge::north: return 0;
  1110. case Block::ConnectionPort::DeviceEdge::east: return 1;
  1111. case Block::ConnectionPort::DeviceEdge::south: return 2;
  1112. case Block::ConnectionPort::DeviceEdge::west: return 3;
  1113. }
  1114. jassertfalse;
  1115. return 0;
  1116. }
  1117. void layoutNeighbours (Block::Ptr block, const BlockTopology& topology,
  1118. Block::UID masterUid, juce::Array<Block::UID>& visited)
  1119. {
  1120. visited.add (block->uid);
  1121. for (auto& connection : topology.connections)
  1122. {
  1123. if ((connection.device1 == block->uid && ! visited.contains (connection.device2))
  1124. || (connection.device2 == block->uid && ! visited.contains (connection.device1)))
  1125. {
  1126. const auto theirUid = connection.device1 == block->uid ? connection.device2 : connection.device1;
  1127. const auto neighbourPtr = findBlockWithUid (topology, theirUid);
  1128. if (auto* neighbour = dynamic_cast<BlockImplementation*> (neighbourPtr.get()))
  1129. {
  1130. const auto myBounds = block->getBlockAreaWithinLayout();
  1131. const auto& myPort = connection.device1 == block->uid ? connection.connectionPortOnDevice1 : connection.connectionPortOnDevice2;
  1132. const auto& theirPort = connection.device1 == block->uid ? connection.connectionPortOnDevice2 : connection.connectionPortOnDevice1;
  1133. const auto myOffset = getUnitForIndex (block, myPort.edge, myPort.index);
  1134. const auto theirOffset = getUnitForIndex (neighbourPtr, theirPort.edge, theirPort.index);
  1135. neighbour->masterUID = masterUid;
  1136. neighbour->rotation = (2 + block->getRotation()
  1137. + getRotationForEdge (myPort.edge)
  1138. - getRotationForEdge (theirPort.edge)) % 4;
  1139. Point<int> delta;
  1140. const auto theirBounds = neighbour->getBlockAreaWithinLayout();
  1141. switch ((block->getRotation() + getRotationForEdge (myPort.edge)) % 4)
  1142. {
  1143. case 0: // over me
  1144. delta = { myOffset - (theirBounds.getWidth() - (theirOffset + 1)), -theirBounds.getHeight() };
  1145. break;
  1146. case 1: // right of me
  1147. delta = { myBounds.getWidth(), myOffset - (theirBounds.getHeight() - (theirOffset + 1)) };
  1148. break;
  1149. case 2: // under me
  1150. delta = { (myBounds.getWidth() - (myOffset + 1)) - theirOffset, myBounds.getHeight() };
  1151. break;
  1152. case 3: // left of me
  1153. delta = { -theirBounds.getWidth(), (myBounds.getHeight() - (myOffset + 1)) - theirOffset };
  1154. break;
  1155. }
  1156. neighbour->position = myBounds.getPosition() + delta;
  1157. }
  1158. layoutNeighbours (neighbourPtr, topology, masterUid, visited);
  1159. }
  1160. }
  1161. }
  1162. };
  1163. //==============================================================================
  1164. struct BlockImplementation : public Block,
  1165. private MIDIDeviceConnection::Listener,
  1166. private Timer
  1167. {
  1168. BlockImplementation (const BlocksProtocol::BlockSerialNumber& serial, Detector& detectorToUse, BlocksProtocol::VersionNumber version, BlocksProtocol::BlockName blockName, bool master)
  1169. : Block (juce::String ((const char*) serial.serial, sizeof (serial.serial)),
  1170. juce::String ((const char*) version.version, version.length),
  1171. juce::String ((const char*) blockName.name, blockName.length)),
  1172. modelData (serial),
  1173. remoteHeap (modelData.programAndHeapSize),
  1174. detector (detectorToUse),
  1175. isMaster (master)
  1176. {
  1177. sendCommandMessage (BlocksProtocol::beginAPIMode);
  1178. if (modelData.hasTouchSurface)
  1179. touchSurface.reset (new TouchSurfaceImplementation (*this));
  1180. int i = 0;
  1181. for (auto&& b : modelData.buttons)
  1182. controlButtons.add (new ControlButtonImplementation (*this, i++, b));
  1183. if (modelData.lightGridWidth > 0 && modelData.lightGridHeight > 0)
  1184. ledGrid.reset (new LEDGridImplementation (*this));
  1185. for (auto&& s : modelData.statusLEDs)
  1186. statusLights.add (new StatusLightImplementation (*this, s));
  1187. if (modelData.numLEDRowLEDs > 0)
  1188. ledRow.reset (new LEDRowImplementation (*this));
  1189. updateMidiConnectionListener();
  1190. }
  1191. ~BlockImplementation()
  1192. {
  1193. if (listenerToMidiConnection != nullptr)
  1194. {
  1195. config.setDeviceComms (nullptr);
  1196. listenerToMidiConnection->removeListener (this);
  1197. }
  1198. }
  1199. void invalidate()
  1200. {
  1201. isStillConnected = false;
  1202. if (auto surface = dynamic_cast<TouchSurfaceImplementation*> (touchSurface.get()))
  1203. surface->disableTouchSurface();
  1204. for (auto* b : controlButtons)
  1205. if (auto controlButton = dynamic_cast<ControlButtonImplementation*> (b))
  1206. controlButton->disableControlButton();
  1207. }
  1208. void revalidate (BlocksProtocol::VersionNumber newVersion, BlocksProtocol::BlockName newName, bool master)
  1209. {
  1210. versionNumber = getVersionString (newVersion);
  1211. name = getNameString (newName);
  1212. isMaster = master;
  1213. isStillConnected = true;
  1214. if (auto surface = dynamic_cast<TouchSurfaceImplementation*> (touchSurface.get()))
  1215. surface->activateTouchSurface();
  1216. for (auto* b : controlButtons)
  1217. if (auto controlButton = dynamic_cast<ControlButtonImplementation*> (b))
  1218. controlButton->activateControlButton();
  1219. updateMidiConnectionListener();
  1220. }
  1221. void setToMaster (bool shouldBeMaster)
  1222. {
  1223. isMaster = shouldBeMaster;
  1224. }
  1225. void updateMidiConnectionListener()
  1226. {
  1227. listenerToMidiConnection = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this));
  1228. if (listenerToMidiConnection != nullptr)
  1229. listenerToMidiConnection->addListener (this);
  1230. config.setDeviceComms (listenerToMidiConnection);
  1231. }
  1232. Type getType() const override { return modelData.apiType; }
  1233. juce::String getDeviceDescription() const override { return modelData.description; }
  1234. int getWidth() const override { return modelData.widthUnits; }
  1235. int getHeight() const override { return modelData.heightUnits; }
  1236. float getMillimetersPerUnit() const override { return 47.0f; }
  1237. bool isHardwareBlock() const override { return true; }
  1238. juce::Array<Block::ConnectionPort> getPorts() const override { return modelData.ports; }
  1239. bool isConnected() const override { return isStillConnected && detector.isConnected (uid); }
  1240. bool isMasterBlock() const override { return isMaster; }
  1241. Block::UID getConnectedMasterUID() const override { return masterUID; }
  1242. int getRotation() const override { return rotation; }
  1243. Rectangle<int> getBlockAreaWithinLayout() const override
  1244. {
  1245. if (rotation % 2 == 0)
  1246. return { position.getX(), position.getY(), modelData.widthUnits, modelData.heightUnits };
  1247. return { position.getX(), position.getY(), modelData.heightUnits, modelData.widthUnits };
  1248. }
  1249. TouchSurface* getTouchSurface() const override { return touchSurface.get(); }
  1250. LEDGrid* getLEDGrid() const override { return ledGrid.get(); }
  1251. LEDRow* getLEDRow() const override { return ledRow.get(); }
  1252. juce::Array<ControlButton*> getButtons() const override
  1253. {
  1254. juce::Array<ControlButton*> result;
  1255. result.addArray (controlButtons);
  1256. return result;
  1257. }
  1258. juce::Array<StatusLight*> getStatusLights() const override
  1259. {
  1260. juce::Array<StatusLight*> result;
  1261. result.addArray (statusLights);
  1262. return result;
  1263. }
  1264. float getBatteryLevel() const override
  1265. {
  1266. if (auto status = detector.getLastStatus (uid))
  1267. return status->batteryLevel.toUnipolarFloat();
  1268. return 0.0f;
  1269. }
  1270. bool isBatteryCharging() const override
  1271. {
  1272. if (auto status = detector.getLastStatus (uid))
  1273. return status->batteryCharging.get() != 0;
  1274. return false;
  1275. }
  1276. bool supportsGraphics() const override
  1277. {
  1278. return false;
  1279. }
  1280. int getDeviceIndex() const noexcept
  1281. {
  1282. return isConnected() ? detector.getIndexFromDeviceID (uid) : -1;
  1283. }
  1284. template <typename PacketBuilder>
  1285. bool sendMessageToDevice (const PacketBuilder& builder)
  1286. {
  1287. lastMessageSendTime = juce::Time::getCurrentTime();
  1288. return detector.sendMessageToDevice (uid, builder);
  1289. }
  1290. bool sendCommandMessage (uint32 commandID)
  1291. {
  1292. int index = getDeviceIndex();
  1293. if (index < 0)
  1294. return false;
  1295. BlocksProtocol::HostPacketBuilder<64> p;
  1296. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1297. p.deviceControlMessage (commandID);
  1298. p.writePacketSysexFooter();
  1299. return sendMessageToDevice (p);
  1300. }
  1301. void handleCustomMessage (Block::Timestamp, const int32* data)
  1302. {
  1303. ProgramEventMessage m;
  1304. for (uint32 i = 0; i < BlocksProtocol::numProgramMessageInts; ++i)
  1305. m.values[i] = data[i];
  1306. programEventListeners.call ([&] (ProgramEventListener& l) { l.handleProgramEvent (*this, m); });
  1307. }
  1308. static BlockImplementation* getFrom (Block& b) noexcept
  1309. {
  1310. if (auto bi = dynamic_cast<BlockImplementation*> (&b))
  1311. return bi;
  1312. jassertfalse;
  1313. return nullptr;
  1314. }
  1315. bool isControlBlock() const
  1316. {
  1317. auto type = getType();
  1318. return type == Block::Type::liveBlock
  1319. || type == Block::Type::loopBlock
  1320. || type == Block::Type::touchBlock
  1321. || type == Block::Type::developerControlBlock;
  1322. }
  1323. //==============================================================================
  1324. std::function<void(const String&)> logger;
  1325. void setLogger (std::function<void(const String&)> newLogger) override
  1326. {
  1327. logger = newLogger;
  1328. }
  1329. void handleLogMessage (const String& message) const
  1330. {
  1331. if (logger != nullptr)
  1332. logger (message);
  1333. }
  1334. //==============================================================================
  1335. juce::Result setProgram (Program* newProgram) override
  1336. {
  1337. if (newProgram == nullptr || program.get() != newProgram)
  1338. {
  1339. {
  1340. std::unique_ptr<Program> p (newProgram);
  1341. if (program != nullptr
  1342. && newProgram != nullptr
  1343. && program->getLittleFootProgram() == newProgram->getLittleFootProgram())
  1344. return juce::Result::ok();
  1345. stopTimer();
  1346. std::swap (program, p);
  1347. }
  1348. stopTimer();
  1349. programSize = 0;
  1350. if (program != nullptr)
  1351. {
  1352. littlefoot::Compiler compiler;
  1353. compiler.addNativeFunctions (PhysicalTopologySource::getStandardLittleFootFunctions());
  1354. auto err = compiler.compile (program->getLittleFootProgram(), 512);
  1355. if (err.failed())
  1356. return err;
  1357. DBG ("Compiled littlefoot program, space needed: "
  1358. << (int) compiler.getCompiledProgram().getTotalSpaceNeeded() << " bytes");
  1359. if (compiler.getCompiledProgram().getTotalSpaceNeeded() > getMemorySize())
  1360. return Result::fail ("Program too large!");
  1361. auto size = (size_t) compiler.compiledObjectCode.size();
  1362. programSize = (uint32) size;
  1363. remoteHeap.resetDataRangeToUnknown (0, remoteHeap.blockSize);
  1364. remoteHeap.clear();
  1365. remoteHeap.sendChanges (*this, true);
  1366. remoteHeap.resetDataRangeToUnknown (0, (uint32) size);
  1367. remoteHeap.setBytes (0, compiler.compiledObjectCode.begin(), size);
  1368. remoteHeap.sendChanges (*this, true);
  1369. this->resetConfigListActiveStatus();
  1370. if (auto changeCallback = this->configChangedCallback)
  1371. changeCallback (*this, {}, this->getMaxConfigIndex());
  1372. }
  1373. else
  1374. {
  1375. remoteHeap.clear();
  1376. }
  1377. }
  1378. else
  1379. {
  1380. jassertfalse;
  1381. }
  1382. return juce::Result::ok();
  1383. }
  1384. Program* getProgram() const override { return program.get(); }
  1385. void sendProgramEvent (const ProgramEventMessage& message) override
  1386. {
  1387. static_assert (sizeof (ProgramEventMessage::values) == 4 * BlocksProtocol::numProgramMessageInts,
  1388. "Need to keep the internal and external messages structures the same");
  1389. if (remoteHeap.isProgramLoaded())
  1390. {
  1391. auto index = getDeviceIndex();
  1392. if (index >= 0)
  1393. {
  1394. BlocksProtocol::HostPacketBuilder<128> p;
  1395. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1396. if (p.addProgramEventMessage (message.values))
  1397. {
  1398. p.writePacketSysexFooter();
  1399. sendMessageToDevice (p);
  1400. }
  1401. }
  1402. else
  1403. {
  1404. jassertfalse;
  1405. }
  1406. }
  1407. }
  1408. void timerCallback() override
  1409. {
  1410. if (remoteHeap.isFullySynced() && remoteHeap.isProgramLoaded())
  1411. {
  1412. stopTimer();
  1413. sendCommandMessage (BlocksProtocol::saveProgramAsDefault);
  1414. }
  1415. else
  1416. {
  1417. startTimer (100);
  1418. }
  1419. }
  1420. void saveProgramAsDefault() override
  1421. {
  1422. startTimer (10);
  1423. }
  1424. uint32 getMemorySize() override
  1425. {
  1426. return modelData.programAndHeapSize;
  1427. }
  1428. uint32 getHeapMemorySize() override
  1429. {
  1430. jassert (isPositiveAndNotGreaterThan (programSize, modelData.programAndHeapSize));
  1431. return modelData.programAndHeapSize - programSize;
  1432. }
  1433. void setDataByte (size_t offset, uint8 value) override
  1434. {
  1435. remoteHeap.setByte (programSize + offset, value);
  1436. }
  1437. void setDataBytes (size_t offset, const void* newData, size_t num) override
  1438. {
  1439. remoteHeap.setBytes (programSize + offset, static_cast<const uint8*> (newData), num);
  1440. }
  1441. void setDataBits (uint32 startBit, uint32 numBits, uint32 value) override
  1442. {
  1443. remoteHeap.setBits (programSize * 8 + startBit, numBits, value);
  1444. }
  1445. uint8 getDataByte (size_t offset) override
  1446. {
  1447. return remoteHeap.getByte (programSize + offset);
  1448. }
  1449. void handleSharedDataACK (uint32 packetCounter) noexcept
  1450. {
  1451. pingFromDevice();
  1452. remoteHeap.handleACKFromDevice (*this, packetCounter);
  1453. }
  1454. bool sendFirmwareUpdatePacket (const uint8* data, uint8 size, std::function<void (uint8, uint32)> callback) override
  1455. {
  1456. firmwarePacketAckCallback = {};
  1457. auto index = getDeviceIndex();
  1458. if (index >= 0)
  1459. {
  1460. BlocksProtocol::HostPacketBuilder<256> p;
  1461. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1462. if (p.addFirmwareUpdatePacket (data, size))
  1463. {
  1464. p.writePacketSysexFooter();
  1465. if (sendMessageToDevice (p))
  1466. {
  1467. firmwarePacketAckCallback = callback;
  1468. return true;
  1469. }
  1470. }
  1471. }
  1472. else
  1473. {
  1474. jassertfalse;
  1475. }
  1476. return false;
  1477. }
  1478. void handleFirmwareUpdateACK (uint8 resultCode, uint32 resultDetail)
  1479. {
  1480. if (firmwarePacketAckCallback != nullptr)
  1481. {
  1482. firmwarePacketAckCallback (resultCode, resultDetail);
  1483. firmwarePacketAckCallback = {};
  1484. }
  1485. }
  1486. void handleConfigUpdateMessage (int32 item, int32 value, int32 min, int32 max)
  1487. {
  1488. config.handleConfigUpdateMessage (item, value, min, max);
  1489. }
  1490. void handleConfigSetMessage(int32 item, int32 value)
  1491. {
  1492. config.handleConfigSetMessage (item, value);
  1493. }
  1494. void pingFromDevice()
  1495. {
  1496. lastMessageReceiveTime = juce::Time::getCurrentTime();
  1497. }
  1498. void addDataInputPortListener (DataInputPortListener* listener) override
  1499. {
  1500. Block::addDataInputPortListener (listener);
  1501. if (auto midiInput = getMidiInput())
  1502. midiInput->start();
  1503. }
  1504. void sendMessage (const void* message, size_t messageSize) override
  1505. {
  1506. if (auto midiOutput = getMidiOutput())
  1507. midiOutput->sendMessageNow ({ message, (int) messageSize });
  1508. }
  1509. void handleTimerTick()
  1510. {
  1511. if (++resetMessagesSent < 3)
  1512. {
  1513. if (resetMessagesSent == 1)
  1514. sendCommandMessage (BlocksProtocol::endAPIMode);
  1515. sendCommandMessage (BlocksProtocol::beginAPIMode);
  1516. return;
  1517. }
  1518. if (ledGrid != nullptr)
  1519. if (auto renderer = ledGrid->getRenderer())
  1520. renderer->renderLEDGrid (*ledGrid);
  1521. remoteHeap.sendChanges (*this, false);
  1522. if (lastMessageSendTime < juce::Time::getCurrentTime() - juce::RelativeTime::milliseconds (pingIntervalMs))
  1523. sendCommandMessage (BlocksProtocol::ping);
  1524. }
  1525. //==============================================================================
  1526. int32 getLocalConfigValue (uint32 item) override
  1527. {
  1528. initialiseDeviceIndexAndConnection();
  1529. return config.getItemValue ((BlocksProtocol::ConfigItemId) item);
  1530. }
  1531. void setLocalConfigValue (uint32 item, int32 value) override
  1532. {
  1533. initialiseDeviceIndexAndConnection();
  1534. config.setItemValue ((BlocksProtocol::ConfigItemId) item, value);
  1535. }
  1536. void setLocalConfigRange (uint32 item, int32 min, int32 max) override
  1537. {
  1538. initialiseDeviceIndexAndConnection();
  1539. config.setItemMin ((BlocksProtocol::ConfigItemId) item, min);
  1540. config.setItemMax ((BlocksProtocol::ConfigItemId) item, max);
  1541. }
  1542. void setLocalConfigItemActive (uint32 item, bool isActive) override
  1543. {
  1544. initialiseDeviceIndexAndConnection();
  1545. config.setItemActive ((BlocksProtocol::ConfigItemId) item, isActive);
  1546. }
  1547. bool isLocalConfigItemActive (uint32 item) override
  1548. {
  1549. initialiseDeviceIndexAndConnection();
  1550. return config.getItemActive ((BlocksProtocol::ConfigItemId) item);
  1551. }
  1552. uint32 getMaxConfigIndex() override
  1553. {
  1554. return uint32 (BlocksProtocol::maxConfigIndex);
  1555. }
  1556. bool isValidUserConfigIndex (uint32 item) override
  1557. {
  1558. return item >= (uint32) BlocksProtocol::ConfigItemId::user0
  1559. && item < (uint32) (BlocksProtocol::ConfigItemId::user0 + numberOfUserConfigs);
  1560. }
  1561. ConfigMetaData getLocalConfigMetaData (uint32 item) override
  1562. {
  1563. initialiseDeviceIndexAndConnection();
  1564. return config.getMetaData ((BlocksProtocol::ConfigItemId) item);
  1565. }
  1566. void requestFactoryConfigSync() override
  1567. {
  1568. initialiseDeviceIndexAndConnection();
  1569. config.requestFactoryConfigSync();
  1570. }
  1571. void resetConfigListActiveStatus() override
  1572. {
  1573. config.resetConfigListActiveStatus();
  1574. }
  1575. void setConfigChangedCallback (std::function<void(Block&, const ConfigMetaData&, uint32)> configChanged) override
  1576. {
  1577. configChangedCallback = configChanged;
  1578. }
  1579. void factoryReset() override
  1580. {
  1581. auto index = getDeviceIndex();
  1582. if (index >= 0)
  1583. {
  1584. BlocksProtocol::HostPacketBuilder<32> p;
  1585. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1586. p.addFactoryReset();
  1587. p.writePacketSysexFooter();
  1588. sendMessageToDevice (p);
  1589. }
  1590. else
  1591. {
  1592. jassertfalse;
  1593. }
  1594. }
  1595. void blockReset() override
  1596. {
  1597. auto index = getDeviceIndex();
  1598. if (index >= 0)
  1599. {
  1600. BlocksProtocol::HostPacketBuilder<32> p;
  1601. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1602. p.addBlockReset();
  1603. p.writePacketSysexFooter();
  1604. sendMessageToDevice (p);
  1605. }
  1606. else
  1607. {
  1608. jassertfalse;
  1609. }
  1610. }
  1611. bool setName (const juce::String& newName) override
  1612. {
  1613. auto index = getDeviceIndex();
  1614. if (index >= 0)
  1615. {
  1616. BlocksProtocol::HostPacketBuilder<128> p;
  1617. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1618. if (p.addSetBlockName (newName))
  1619. {
  1620. p.writePacketSysexFooter();
  1621. if (sendMessageToDevice (p))
  1622. return true;
  1623. }
  1624. }
  1625. else
  1626. {
  1627. jassertfalse;
  1628. }
  1629. return false;
  1630. }
  1631. //==============================================================================
  1632. std::unique_ptr<TouchSurface> touchSurface;
  1633. juce::OwnedArray<ControlButton> controlButtons;
  1634. std::unique_ptr<LEDGridImplementation> ledGrid;
  1635. std::unique_ptr<LEDRowImplementation> ledRow;
  1636. juce::OwnedArray<StatusLight> statusLights;
  1637. BlocksProtocol::BlockDataSheet modelData;
  1638. MIDIDeviceConnection* listenerToMidiConnection = nullptr;
  1639. static constexpr int pingIntervalMs = 400;
  1640. static constexpr uint32 maxBlockSize = BlocksProtocol::padBlockProgramAndHeapSize;
  1641. static constexpr uint32 maxPacketCounter = BlocksProtocol::PacketCounter::maxValue;
  1642. static constexpr uint32 maxPacketSize = 200;
  1643. using PacketBuilder = BlocksProtocol::HostPacketBuilder<maxPacketSize>;
  1644. using RemoteHeapType = littlefoot::LittleFootRemoteHeap<BlockImplementation>;
  1645. RemoteHeapType remoteHeap;
  1646. Detector& detector;
  1647. juce::Time lastMessageSendTime, lastMessageReceiveTime;
  1648. BlockConfigManager config;
  1649. std::function<void(Block&, const ConfigMetaData&, uint32)> configChangedCallback;
  1650. private:
  1651. std::unique_ptr<Program> program;
  1652. uint32 programSize = 0;
  1653. std::function<void(uint8, uint32)> firmwarePacketAckCallback;
  1654. uint32 resetMessagesSent = 0;
  1655. bool isStillConnected = true;
  1656. bool isMaster = false;
  1657. Block::UID masterUID = {};
  1658. Point<int> position;
  1659. int rotation = 0;
  1660. friend BlocksTraverser;
  1661. void initialiseDeviceIndexAndConnection()
  1662. {
  1663. config.setDeviceIndex ((TopologyIndex) getDeviceIndex());
  1664. config.setDeviceComms (listenerToMidiConnection);
  1665. }
  1666. const juce::MidiInput* getMidiInput() const
  1667. {
  1668. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1669. return c->midiInput.get();
  1670. jassertfalse;
  1671. return nullptr;
  1672. }
  1673. juce::MidiInput* getMidiInput()
  1674. {
  1675. return const_cast<juce::MidiInput*> (static_cast<const BlockImplementation&>(*this).getMidiInput());
  1676. }
  1677. const juce::MidiOutput* getMidiOutput() const
  1678. {
  1679. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1680. return c->midiOutput.get();
  1681. jassertfalse;
  1682. return nullptr;
  1683. }
  1684. juce::MidiOutput* getMidiOutput()
  1685. {
  1686. return const_cast<juce::MidiOutput*> (static_cast<const BlockImplementation&>(*this).getMidiOutput());
  1687. }
  1688. void handleIncomingMidiMessage (const juce::MidiMessage& message) override
  1689. {
  1690. dataInputPortListeners.call ([&] (DataInputPortListener& l) { l.handleIncomingDataPortMessage (*this, message.getRawData(),
  1691. (size_t) message.getRawDataSize()); });
  1692. }
  1693. void connectionBeingDeleted (const MIDIDeviceConnection& c) override
  1694. {
  1695. jassert (listenerToMidiConnection == &c);
  1696. juce::ignoreUnused (c);
  1697. listenerToMidiConnection->removeListener (this);
  1698. listenerToMidiConnection = nullptr;
  1699. config.setDeviceComms (nullptr);
  1700. }
  1701. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockImplementation)
  1702. };
  1703. //==============================================================================
  1704. struct LEDRowImplementation : public LEDRow,
  1705. private Timer
  1706. {
  1707. LEDRowImplementation (BlockImplementation& b) : LEDRow (b)
  1708. {
  1709. startTimer (300);
  1710. }
  1711. void setButtonColour (uint32 index, LEDColour colour)
  1712. {
  1713. if (index < 10)
  1714. {
  1715. colours[index] = colour;
  1716. flush();
  1717. }
  1718. }
  1719. int getNumLEDs() const override
  1720. {
  1721. return static_cast<const BlockImplementation&> (block).modelData.numLEDRowLEDs;
  1722. }
  1723. void setLEDColour (int index, LEDColour colour) override
  1724. {
  1725. if ((uint32) index < 15u)
  1726. {
  1727. colours[10 + index] = colour;
  1728. flush();
  1729. }
  1730. }
  1731. void setOverlayColour (LEDColour colour) override
  1732. {
  1733. colours[25] = colour;
  1734. flush();
  1735. }
  1736. void resetOverlayColour() override
  1737. {
  1738. setOverlayColour ({});
  1739. }
  1740. private:
  1741. LEDColour colours[26];
  1742. void timerCallback() override
  1743. {
  1744. stopTimer();
  1745. loadProgramOntoBlock();
  1746. flush();
  1747. }
  1748. void loadProgramOntoBlock()
  1749. {
  1750. if (block.getProgram() == nullptr)
  1751. {
  1752. auto err = block.setProgram (new DefaultLEDGridProgram (block));
  1753. if (err.failed())
  1754. {
  1755. DBG (err.getErrorMessage());
  1756. jassertfalse;
  1757. }
  1758. }
  1759. }
  1760. void flush()
  1761. {
  1762. if (block.getProgram() != nullptr)
  1763. for (uint32 i = 0; i < (uint32) numElementsInArray (colours); ++i)
  1764. write565Colour (16 * i, colours[i]);
  1765. }
  1766. void write565Colour (uint32 bitIndex, LEDColour colour)
  1767. {
  1768. block.setDataBits (bitIndex, 5, colour.getRed() >> 3);
  1769. block.setDataBits (bitIndex + 5, 6, colour.getGreen() >> 2);
  1770. block.setDataBits (bitIndex + 11, 5, colour.getBlue() >> 3);
  1771. }
  1772. struct DefaultLEDGridProgram : public Block::Program
  1773. {
  1774. DefaultLEDGridProgram (Block& b) : Block::Program (b) {}
  1775. juce::String getLittleFootProgram() override
  1776. {
  1777. /* Data format:
  1778. 0: 10 x 5-6-5 bits for button LED RGBs
  1779. 20: 15 x 5-6-5 bits for LED row colours
  1780. 50: 1 x 5-6-5 bits for LED row overlay colour
  1781. */
  1782. return R"littlefoot(
  1783. #heapsize: 128
  1784. int getColour (int bitIndex)
  1785. {
  1786. return makeARGB (255,
  1787. getHeapBits (bitIndex, 5) << 3,
  1788. getHeapBits (bitIndex + 5, 6) << 2,
  1789. getHeapBits (bitIndex + 11, 5) << 3);
  1790. }
  1791. int getButtonColour (int index)
  1792. {
  1793. return getColour (16 * index);
  1794. }
  1795. int getLEDColour (int index)
  1796. {
  1797. if (getHeapInt (50))
  1798. return getColour (50 * 8);
  1799. return getColour (20 * 8 + 16 * index);
  1800. }
  1801. void repaint()
  1802. {
  1803. for (int x = 0; x < 15; ++x)
  1804. fillPixel (getLEDColour (x), x, 0);
  1805. for (int i = 0; i < 10; ++i)
  1806. fillPixel (getButtonColour (i), i, 1);
  1807. }
  1808. void handleMessage (int p1, int p2) {}
  1809. )littlefoot";
  1810. }
  1811. };
  1812. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDRowImplementation)
  1813. };
  1814. //==============================================================================
  1815. struct TouchSurfaceImplementation : public TouchSurface,
  1816. private juce::Timer
  1817. {
  1818. TouchSurfaceImplementation (BlockImplementation& b) : TouchSurface (b), blockImpl (b)
  1819. {
  1820. activateTouchSurface();
  1821. }
  1822. ~TouchSurfaceImplementation()
  1823. {
  1824. disableTouchSurface();
  1825. }
  1826. void activateTouchSurface()
  1827. {
  1828. if (auto det = Detector::getFrom (block))
  1829. det->activeTouchSurfaces.add (this);
  1830. startTimer (500);
  1831. }
  1832. void disableTouchSurface()
  1833. {
  1834. stopTimer();
  1835. if (auto det = Detector::getFrom (block))
  1836. det->activeTouchSurfaces.removeFirstMatchingValue (this);
  1837. }
  1838. int getNumberOfKeywaves() const noexcept override
  1839. {
  1840. return blockImpl.modelData.numKeywaves;
  1841. }
  1842. void broadcastTouchChange (const TouchSurface::Touch& touchEvent)
  1843. {
  1844. auto& status = touches.getValue (touchEvent);
  1845. // Fake a touch end if we receive a duplicate touch-start with no preceding touch-end (ie: comms error)
  1846. if (touchEvent.isTouchStart && status.isActive)
  1847. killTouch (touchEvent, status, juce::Time::getMillisecondCounter());
  1848. // Fake a touch start if we receive an unexpected event with no matching start event. (ie: comms error)
  1849. if (! touchEvent.isTouchStart && ! status.isActive)
  1850. {
  1851. TouchSurface::Touch t (touchEvent);
  1852. t.isTouchStart = true;
  1853. t.isTouchEnd = false;
  1854. if (t.zVelocity <= 0) t.zVelocity = status.lastStrikePressure;
  1855. if (t.zVelocity <= 0) t.zVelocity = t.z;
  1856. if (t.zVelocity <= 0) t.zVelocity = 0.9f;
  1857. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, t); });
  1858. }
  1859. // Normal handling:
  1860. status.lastEventTime = juce::Time::getMillisecondCounter();
  1861. status.isActive = ! touchEvent.isTouchEnd;
  1862. if (touchEvent.isTouchStart)
  1863. status.lastStrikePressure = touchEvent.zVelocity;
  1864. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, touchEvent); });
  1865. }
  1866. void timerCallback() override
  1867. {
  1868. // Find touches that seem to have become stuck, and fake a touch-end for them..
  1869. static const uint32 touchTimeOutMs = 500;
  1870. for (auto& t : touches)
  1871. {
  1872. auto& status = t.value;
  1873. auto now = juce::Time::getMillisecondCounter();
  1874. if (status.isActive && now > status.lastEventTime + touchTimeOutMs)
  1875. killTouch (t.touch, status, now);
  1876. }
  1877. }
  1878. struct TouchStatus
  1879. {
  1880. uint32 lastEventTime = 0;
  1881. float lastStrikePressure = 0;
  1882. bool isActive = false;
  1883. };
  1884. void killTouch (const TouchSurface::Touch& touch, TouchStatus& status, uint32 timeStamp) noexcept
  1885. {
  1886. jassert (status.isActive);
  1887. TouchSurface::Touch killTouch (touch);
  1888. killTouch.z = 0;
  1889. killTouch.xVelocity = 0;
  1890. killTouch.yVelocity = 0;
  1891. killTouch.zVelocity = -1.0f;
  1892. killTouch.eventTimestamp = timeStamp;
  1893. killTouch.isTouchStart = false;
  1894. killTouch.isTouchEnd = true;
  1895. listeners.call ([&] (TouchSurface::Listener& l) { l.touchChanged (*this, killTouch); });
  1896. status.isActive = false;
  1897. }
  1898. void cancelAllActiveTouches() noexcept override
  1899. {
  1900. const auto now = juce::Time::getMillisecondCounter();
  1901. for (auto& t : touches)
  1902. if (t.value.isActive)
  1903. killTouch (t.touch, t.value, now);
  1904. touches.clear();
  1905. }
  1906. BlockImplementation& blockImpl;
  1907. TouchList<TouchStatus> touches;
  1908. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TouchSurfaceImplementation)
  1909. };
  1910. //==============================================================================
  1911. struct ControlButtonImplementation : public ControlButton
  1912. {
  1913. ControlButtonImplementation (BlockImplementation& b, int index, BlocksProtocol::BlockDataSheet::ButtonInfo info)
  1914. : ControlButton (b), blockImpl (b), buttonInfo (info), buttonIndex (index)
  1915. {
  1916. activateControlButton();
  1917. }
  1918. ~ControlButtonImplementation()
  1919. {
  1920. disableControlButton();
  1921. }
  1922. void activateControlButton()
  1923. {
  1924. if (auto det = Detector::getFrom (block))
  1925. det->activeControlButtons.add (this);
  1926. }
  1927. void disableControlButton()
  1928. {
  1929. if (auto det = Detector::getFrom (block))
  1930. det->activeControlButtons.removeFirstMatchingValue (this);
  1931. }
  1932. ButtonFunction getType() const override { return buttonInfo.type; }
  1933. juce::String getName() const override { return BlocksProtocol::getButtonNameForFunction (buttonInfo.type); }
  1934. float getPositionX() const override { return buttonInfo.x; }
  1935. float getPositionY() const override { return buttonInfo.y; }
  1936. bool hasLight() const override { return blockImpl.isControlBlock(); }
  1937. bool setLightColour (LEDColour colour) override
  1938. {
  1939. if (hasLight())
  1940. {
  1941. if (auto row = blockImpl.ledRow.get())
  1942. {
  1943. row->setButtonColour ((uint32) buttonIndex, colour);
  1944. return true;
  1945. }
  1946. }
  1947. return false;
  1948. }
  1949. void broadcastButtonChange (Block::Timestamp timestamp, ControlButton::ButtonFunction button, bool isDown)
  1950. {
  1951. if (button == buttonInfo.type)
  1952. {
  1953. if (wasDown == isDown)
  1954. sendButtonChangeToListeners (timestamp, ! isDown);
  1955. sendButtonChangeToListeners (timestamp, isDown);
  1956. wasDown = isDown;
  1957. }
  1958. }
  1959. void sendButtonChangeToListeners (Block::Timestamp timestamp, bool isDown)
  1960. {
  1961. if (isDown)
  1962. listeners.call ([&] (ControlButton::Listener& l) { l.buttonPressed (*this, timestamp); });
  1963. else
  1964. listeners.call ([&] (ControlButton::Listener& l) { l.buttonReleased (*this, timestamp); });
  1965. }
  1966. BlockImplementation& blockImpl;
  1967. BlocksProtocol::BlockDataSheet::ButtonInfo buttonInfo;
  1968. int buttonIndex;
  1969. bool wasDown = false;
  1970. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ControlButtonImplementation)
  1971. };
  1972. //==============================================================================
  1973. struct StatusLightImplementation : public StatusLight
  1974. {
  1975. StatusLightImplementation (Block& b, BlocksProtocol::BlockDataSheet::StatusLEDInfo i) : StatusLight (b), info (i)
  1976. {
  1977. }
  1978. juce::String getName() const override { return info.name; }
  1979. bool setColour (LEDColour newColour) override
  1980. {
  1981. // XXX TODO!
  1982. juce::ignoreUnused (newColour);
  1983. return false;
  1984. }
  1985. BlocksProtocol::BlockDataSheet::StatusLEDInfo info;
  1986. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StatusLightImplementation)
  1987. };
  1988. //==============================================================================
  1989. struct LEDGridImplementation : public LEDGrid
  1990. {
  1991. LEDGridImplementation (BlockImplementation& b) : LEDGrid (b), blockImpl (b)
  1992. {
  1993. }
  1994. int getNumColumns() const override { return blockImpl.modelData.lightGridWidth; }
  1995. int getNumRows() const override { return blockImpl.modelData.lightGridHeight; }
  1996. BlockImplementation& blockImpl;
  1997. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDGridImplementation)
  1998. };
  1999. //==============================================================================
  2000. #if DUMP_TOPOLOGY
  2001. static juce::String idToSerialNum (const BlockTopology& topology, Block::UID uid)
  2002. {
  2003. for (auto* b : topology.blocks)
  2004. if (b->uid == uid)
  2005. return b->serialNumber;
  2006. return "???";
  2007. }
  2008. static juce::String portEdgeToString (Block::ConnectionPort port)
  2009. {
  2010. switch (port.edge)
  2011. {
  2012. case Block::ConnectionPort::DeviceEdge::north: return "north";
  2013. case Block::ConnectionPort::DeviceEdge::south: return "south";
  2014. case Block::ConnectionPort::DeviceEdge::east: return "east";
  2015. case Block::ConnectionPort::DeviceEdge::west: return "west";
  2016. }
  2017. return {};
  2018. }
  2019. static juce::String portToString (Block::ConnectionPort port)
  2020. {
  2021. return portEdgeToString (port) + "_" + juce::String (port.index);
  2022. }
  2023. static void dumpTopology (const BlockTopology& topology)
  2024. {
  2025. MemoryOutputStream m;
  2026. m << "=============================================================================" << newLine
  2027. << "Topology: " << topology.blocks.size() << " device(s)" << newLine
  2028. << newLine;
  2029. int index = 0;
  2030. for (auto block : topology.blocks)
  2031. {
  2032. m << "Device " << index++ << (block->isMasterBlock() ? ": (MASTER)" : ":") << newLine;
  2033. m << " Description: " << block->getDeviceDescription() << newLine
  2034. << " Serial: " << block->serialNumber << newLine;
  2035. if (auto bi = BlockImplementation::getFrom (*block))
  2036. m << " Short address: " << (int) bi->getDeviceIndex() << newLine;
  2037. m << " Battery level: " + juce::String (juce::roundToInt (100.0f * block->getBatteryLevel())) + "%" << newLine
  2038. << " Battery charging: " + juce::String (block->isBatteryCharging() ? "y" : "n") << newLine
  2039. << " Width: " << block->getWidth() << newLine
  2040. << " Height: " << block->getHeight() << newLine
  2041. << " Millimeters per unit: " << block->getMillimetersPerUnit() << newLine
  2042. << newLine;
  2043. }
  2044. for (auto& connection : topology.connections)
  2045. {
  2046. m << idToSerialNum (topology, connection.device1)
  2047. << ":" << portToString (connection.connectionPortOnDevice1)
  2048. << " <-> "
  2049. << idToSerialNum (topology, connection.device2)
  2050. << ":" << portToString (connection.connectionPortOnDevice2) << newLine;
  2051. }
  2052. m << "=============================================================================" << newLine;
  2053. Logger::outputDebugString (m.toString());
  2054. }
  2055. #endif
  2056. };
  2057. //==============================================================================
  2058. struct PhysicalTopologySource::DetectorHolder : private juce::Timer
  2059. {
  2060. DetectorHolder (PhysicalTopologySource& pts)
  2061. : topologySource (pts),
  2062. detector (Internal::Detector::getDefaultDetector())
  2063. {
  2064. startTimerHz (30);
  2065. }
  2066. DetectorHolder (PhysicalTopologySource& pts, DeviceDetector& dd)
  2067. : topologySource (pts),
  2068. detector (new Internal::Detector (dd))
  2069. {
  2070. startTimerHz (30);
  2071. }
  2072. void timerCallback() override
  2073. {
  2074. if (! topologySource.hasOwnServiceTimer())
  2075. handleTimerTick();
  2076. }
  2077. void handleTimerTick()
  2078. {
  2079. for (auto& b : detector->currentTopology.blocks)
  2080. if (auto bi = Internal::BlockImplementation::getFrom (*b))
  2081. bi->handleTimerTick();
  2082. }
  2083. PhysicalTopologySource& topologySource;
  2084. Internal::Detector::Ptr detector;
  2085. };
  2086. //==============================================================================
  2087. PhysicalTopologySource::PhysicalTopologySource()
  2088. : detector (new DetectorHolder (*this))
  2089. {
  2090. detector->detector->activeTopologySources.add (this);
  2091. }
  2092. PhysicalTopologySource::PhysicalTopologySource (DeviceDetector& detectorToUse)
  2093. : detector (new DetectorHolder (*this, detectorToUse))
  2094. {
  2095. detector->detector->activeTopologySources.add (this);
  2096. }
  2097. PhysicalTopologySource::~PhysicalTopologySource()
  2098. {
  2099. detector->detector->detach (this);
  2100. detector = nullptr;
  2101. }
  2102. BlockTopology PhysicalTopologySource::getCurrentTopology() const
  2103. {
  2104. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  2105. return detector->detector->currentTopology;
  2106. }
  2107. void PhysicalTopologySource::cancelAllActiveTouches() noexcept
  2108. {
  2109. detector->detector->cancelAllActiveTouches();
  2110. }
  2111. bool PhysicalTopologySource::hasOwnServiceTimer() const { return false; }
  2112. void PhysicalTopologySource::handleTimerTick() { detector->handleTimerTick(); }
  2113. PhysicalTopologySource::DeviceConnection::DeviceConnection() {}
  2114. PhysicalTopologySource::DeviceConnection::~DeviceConnection() {}
  2115. PhysicalTopologySource::DeviceDetector::DeviceDetector() {}
  2116. PhysicalTopologySource::DeviceDetector::~DeviceDetector() {}
  2117. const char* const* PhysicalTopologySource::getStandardLittleFootFunctions() noexcept
  2118. {
  2119. return BlocksProtocol::ledProgramLittleFootFunctions;
  2120. }
  2121. template <typename ListType>
  2122. static bool collectionsMatch (const ListType& list1, const ListType& list2) noexcept
  2123. {
  2124. if (list1.size() != list2.size())
  2125. return false;
  2126. for (auto&& b : list1)
  2127. if (! list2.contains (b))
  2128. return false;
  2129. return true;
  2130. }
  2131. bool BlockTopology::operator== (const BlockTopology& other) const noexcept
  2132. {
  2133. return collectionsMatch (connections, other.connections) && collectionsMatch (blocks, other.blocks);
  2134. }
  2135. bool BlockTopology::operator!= (const BlockTopology& other) const noexcept
  2136. {
  2137. return ! operator== (other);
  2138. }
  2139. bool BlockDeviceConnection::operator== (const BlockDeviceConnection& other) const noexcept
  2140. {
  2141. return (device1 == other.device1 && device2 == other.device2
  2142. && connectionPortOnDevice1 == other.connectionPortOnDevice1
  2143. && connectionPortOnDevice2 == other.connectionPortOnDevice2)
  2144. || (device1 == other.device2 && device2 == other.device1
  2145. && connectionPortOnDevice1 == other.connectionPortOnDevice2
  2146. && connectionPortOnDevice2 == other.connectionPortOnDevice1);
  2147. }
  2148. bool BlockDeviceConnection::operator!= (const BlockDeviceConnection& other) const noexcept
  2149. {
  2150. return ! operator== (other);
  2151. }
  2152. } // namespace juce