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.

2742 lines
95KB

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