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.

2361 lines
82KB

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