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.

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