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.

2045 lines
70KB

  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. bool isMaster;
  249. };
  250. static Block::Timestamp deviceTimestampToHost (uint32 timestamp) noexcept
  251. {
  252. return static_cast<Block::Timestamp> (timestamp);
  253. }
  254. static juce::Array<DeviceInfo> getArrayOfDeviceInfo (const juce::Array<BlocksProtocol::DeviceStatus>& devices)
  255. {
  256. juce::Array<DeviceInfo> result;
  257. bool isFirst = true;
  258. for (auto& device : devices)
  259. {
  260. result.add ({ getBlockUIDFromSerialNumber (device.serialNumber),
  261. device.index,
  262. device.serialNumber,
  263. isFirst });
  264. isFirst = false;
  265. }
  266. return result;
  267. }
  268. static bool containsBlockWithUID (const juce::Array<DeviceInfo>& devices, Block::UID uid) noexcept
  269. {
  270. for (auto&& d : devices)
  271. if (d.uid == uid)
  272. return true;
  273. return false;
  274. }
  275. static bool containsBlockWithUID (const Block::Array& blocks, Block::UID uid) noexcept
  276. {
  277. for (auto&& block : blocks)
  278. if (block->uid == uid)
  279. return true;
  280. return false;
  281. }
  282. //==============================================================================
  283. struct ConnectedDeviceGroup : private juce::AsyncUpdater,
  284. private juce::Timer
  285. {
  286. ConnectedDeviceGroup (Detector& d, const juce::String& name, DeviceConnection* connection)
  287. : detector (d), deviceName (name), deviceConnection (connection)
  288. {
  289. lastGlobalPingTime = juce::Time::getCurrentTime();
  290. deviceConnection->handleMessageFromDevice = [this] (const void* data, size_t dataSize)
  291. {
  292. this->handleIncomingMessage (data, dataSize);
  293. };
  294. startTimer (200);
  295. sendTopologyRequest();
  296. }
  297. bool isStillConnected (const juce::StringArray& detectedDevices) const noexcept
  298. {
  299. return detectedDevices.contains (deviceName)
  300. && ! failedToGetTopology()
  301. && lastGlobalPingTime > juce::Time::getCurrentTime() - juce::RelativeTime::seconds (pingTimeoutSeconds);
  302. }
  303. Block::UID getDeviceIDFromIndex (BlocksProtocol::TopologyIndex index) const noexcept
  304. {
  305. for (auto& d : currentDeviceInfo)
  306. if (d.index == index)
  307. return d.uid;
  308. return {};
  309. }
  310. int getIndexFromDeviceID (Block::UID uid) const noexcept
  311. {
  312. for (auto& d : currentDeviceInfo)
  313. if (d.uid == uid)
  314. return d.index;
  315. return -1;
  316. }
  317. DeviceInfo* getDeviceInfoFromUID (Block::UID uid) const noexcept
  318. {
  319. for (auto& d : currentDeviceInfo)
  320. if (d.uid == uid)
  321. return &d;
  322. return nullptr;
  323. }
  324. const BlocksProtocol::DeviceStatus* getLastStatus (Block::UID deviceID) const noexcept
  325. {
  326. for (auto&& status : currentTopologyDevices)
  327. if (getBlockUIDFromSerialNumber (status.serialNumber) == deviceID)
  328. return &status;
  329. return nullptr;
  330. }
  331. //==============================================================================
  332. juce::Time lastTopologyRequestTime, lastTopologyReceiveTime;
  333. int numTopologyRequestsSent = 0;
  334. void sendTopologyRequest()
  335. {
  336. ++numTopologyRequestsSent;
  337. lastTopologyRequestTime = juce::Time::getCurrentTime();
  338. sendCommandMessage (0, BlocksProtocol::requestTopologyMessage);
  339. }
  340. void scheduleNewTopologyRequest()
  341. {
  342. numTopologyRequestsSent = 0;
  343. lastTopologyReceiveTime = juce::Time();
  344. }
  345. bool failedToGetTopology() const noexcept
  346. {
  347. return numTopologyRequestsSent > 4 && lastTopologyReceiveTime == juce::Time();
  348. }
  349. bool hasAnyBlockStoppedPinging() const noexcept
  350. {
  351. auto now = juce::Time::getCurrentTime();
  352. for (auto& ping : blockPings)
  353. if (ping.lastPing < now - juce::RelativeTime::seconds (pingTimeoutSeconds))
  354. return true;
  355. return false;
  356. }
  357. void timerCallback() override
  358. {
  359. auto now = juce::Time::getCurrentTime();
  360. if ((now > lastTopologyReceiveTime + juce::RelativeTime::seconds (30.0) || hasAnyBlockStoppedPinging())
  361. && now > lastTopologyRequestTime + juce::RelativeTime::seconds (1.0)
  362. && numTopologyRequestsSent < 4)
  363. sendTopologyRequest();
  364. }
  365. //==============================================================================
  366. // The following methods will be called by the DeviceToHostPacketDecoder:
  367. void beginTopology (int numDevices, int numConnections)
  368. {
  369. incomingTopologyDevices.clearQuick();
  370. incomingTopologyDevices.ensureStorageAllocated (numDevices);
  371. incomingTopologyConnections.clearQuick();
  372. incomingTopologyConnections.ensureStorageAllocated (numConnections);
  373. }
  374. void handleTopologyDevice (BlocksProtocol::DeviceStatus status)
  375. {
  376. incomingTopologyDevices.add (status);
  377. }
  378. void handleTopologyConnection (BlocksProtocol::DeviceConnection connection)
  379. {
  380. incomingTopologyConnections.add (connection);
  381. }
  382. void endTopology()
  383. {
  384. currentDeviceInfo = getArrayOfDeviceInfo (incomingTopologyDevices);
  385. currentDeviceConnections = getArrayOfConnections (incomingTopologyConnections);
  386. currentTopologyDevices = incomingTopologyDevices;
  387. currentTopologyConnections = incomingTopologyConnections;
  388. detector.handleTopologyChange();
  389. lastTopologyReceiveTime = juce::Time::getCurrentTime();
  390. blockPings.clear();
  391. }
  392. void handleControlButtonUpDown (BlocksProtocol::TopologyIndex deviceIndex, uint32 timestamp,
  393. BlocksProtocol::ControlButtonID buttonID, bool isDown)
  394. {
  395. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  396. detector.handleButtonChange (deviceID, deviceTimestampToHost (timestamp), buttonID.get(), isDown);
  397. }
  398. void handleCustomMessage (BlocksProtocol::TopologyIndex deviceIndex, uint32 timestamp, const int32* data)
  399. {
  400. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  401. detector.handleCustomMessage (deviceID, deviceTimestampToHost (timestamp), data);
  402. }
  403. void handleTouchChange (BlocksProtocol::TopologyIndex deviceIndex,
  404. uint32 timestamp,
  405. BlocksProtocol::TouchIndex touchIndex,
  406. BlocksProtocol::TouchPosition position,
  407. BlocksProtocol::TouchVelocity velocity,
  408. bool isStart, bool isEnd)
  409. {
  410. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  411. {
  412. TouchSurface::Touch touch;
  413. touch.index = (int) touchIndex.get();
  414. touch.x = position.x.toUnipolarFloat();
  415. touch.y = position.y.toUnipolarFloat();
  416. touch.z = position.z.toUnipolarFloat();
  417. touch.xVelocity = velocity.vx.toBipolarFloat();
  418. touch.yVelocity = velocity.vy.toBipolarFloat();
  419. touch.zVelocity = velocity.vz.toBipolarFloat();
  420. touch.eventTimestamp = deviceTimestampToHost (timestamp);
  421. touch.isTouchStart = isStart;
  422. touch.isTouchEnd = isEnd;
  423. touch.blockUID = deviceID;
  424. setTouchStartPosition (touch);
  425. detector.handleTouchChange (deviceID, touch);
  426. }
  427. }
  428. void setTouchStartPosition (TouchSurface::Touch& touch)
  429. {
  430. auto& startPos = touchStartPositions.getValue (touch);
  431. if (touch.isTouchStart)
  432. startPos = { touch.x, touch.y };
  433. touch.startX = startPos.x;
  434. touch.startY = startPos.y;
  435. }
  436. void handlePacketACK (BlocksProtocol::TopologyIndex deviceIndex, BlocksProtocol::PacketCounter counter)
  437. {
  438. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  439. detector.handleSharedDataACK (deviceID, counter);
  440. }
  441. void handleFirmwareUpdateACK (BlocksProtocol::TopologyIndex deviceIndex, BlocksProtocol::FirmwareUpdateACKCode resultCode)
  442. {
  443. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  444. detector.handleFirmwareUpdateACK (deviceID, (uint8) resultCode.get());
  445. }
  446. void handleLogMessage (BlocksProtocol::TopologyIndex deviceIndex, const String& message)
  447. {
  448. if (auto deviceID = getDeviceIDFromMessageIndex (deviceIndex))
  449. detector.handleLogMessage (deviceID, message);
  450. }
  451. //==============================================================================
  452. template <typename PacketBuilder>
  453. bool sendMessageToDevice (const PacketBuilder& builder) const
  454. {
  455. if (deviceConnection->sendMessageToDevice (builder.getData(), (size_t) builder.size()))
  456. {
  457. #if DUMP_BANDWIDTH_STATS
  458. registerBytesOut (builder.size());
  459. #endif
  460. return true;
  461. }
  462. return false;
  463. }
  464. bool sendCommandMessage (BlocksProtocol::TopologyIndex deviceIndex, uint32 commandID) const
  465. {
  466. BlocksProtocol::HostPacketBuilder<64> p;
  467. p.writePacketSysexHeaderBytes (deviceIndex);
  468. p.deviceControlMessage (commandID);
  469. p.writePacketSysexFooter();
  470. return sendMessageToDevice (p);
  471. }
  472. bool broadcastCommandMessage (uint32 commandID) const
  473. {
  474. return sendCommandMessage (BlocksProtocol::topologyIndexForBroadcast, commandID);
  475. }
  476. DeviceConnection* getDeviceConnection()
  477. {
  478. return deviceConnection.get();
  479. }
  480. Detector& detector;
  481. juce::String deviceName;
  482. juce::Array<DeviceInfo> currentDeviceInfo;
  483. juce::Array<BlockDeviceConnection> currentDeviceConnections;
  484. static constexpr double pingTimeoutSeconds = 6.0;
  485. private:
  486. //==============================================================================
  487. std::unique_ptr<DeviceConnection> deviceConnection;
  488. juce::Array<BlocksProtocol::DeviceStatus> incomingTopologyDevices, currentTopologyDevices;
  489. juce::Array<BlocksProtocol::DeviceConnection> incomingTopologyConnections, currentTopologyConnections;
  490. juce::CriticalSection incomingPacketLock;
  491. juce::Array<juce::MemoryBlock> incomingPackets;
  492. struct TouchStart
  493. {
  494. float x, y;
  495. };
  496. TouchList<TouchStart> touchStartPositions;
  497. juce::Time lastGlobalPingTime;
  498. struct BlockPingTime
  499. {
  500. Block::UID blockUID;
  501. juce::Time lastPing;
  502. };
  503. juce::Array<BlockPingTime> blockPings;
  504. Block::UID getDeviceIDFromMessageIndex (BlocksProtocol::TopologyIndex index) noexcept
  505. {
  506. auto uid = getDeviceIDFromIndex (index);
  507. if (uid == Block::UID())
  508. {
  509. scheduleNewTopologyRequest(); // force a re-request of the topology when we
  510. // get an event from a block that we don't know about
  511. }
  512. else
  513. {
  514. auto now = juce::Time::getCurrentTime();
  515. for (auto& ping : blockPings)
  516. {
  517. if (ping.blockUID == uid)
  518. {
  519. ping.lastPing = now;
  520. return uid;
  521. }
  522. }
  523. blockPings.add ({ uid, now });
  524. }
  525. return uid;
  526. }
  527. juce::Array<BlockDeviceConnection> getArrayOfConnections (const juce::Array<BlocksProtocol::DeviceConnection>& connections)
  528. {
  529. juce::Array<BlockDeviceConnection> result;
  530. for (auto&& c : connections)
  531. {
  532. BlockDeviceConnection dc;
  533. dc.device1 = getDeviceIDFromIndex (c.device1);
  534. dc.device2 = getDeviceIDFromIndex (c.device2);
  535. dc.connectionPortOnDevice1 = convertConnectionPort (dc.device1, c.port1);
  536. dc.connectionPortOnDevice2 = convertConnectionPort (dc.device2, c.port2);
  537. result.add (dc);
  538. }
  539. return result;
  540. }
  541. Block::ConnectionPort convertConnectionPort (Block::UID uid, BlocksProtocol::ConnectorPort p) noexcept
  542. {
  543. if (auto* info = getDeviceInfoFromUID (uid))
  544. return BlocksProtocol::BlockDataSheet (info->serial).convertPortIndexToConnectorPort (p);
  545. jassertfalse;
  546. return { Block::ConnectionPort::DeviceEdge::north, 0 };
  547. }
  548. //==============================================================================
  549. void handleIncomingMessage (const void* data, size_t dataSize)
  550. {
  551. juce::MemoryBlock mb (data, dataSize);
  552. {
  553. const juce::ScopedLock sl (incomingPacketLock);
  554. incomingPackets.add (std::move (mb));
  555. }
  556. triggerAsyncUpdate();
  557. #if DUMP_BANDWIDTH_STATS
  558. registerBytesIn ((int) dataSize);
  559. #endif
  560. }
  561. void handleAsyncUpdate() override
  562. {
  563. juce::Array<juce::MemoryBlock> packets;
  564. packets.ensureStorageAllocated (32);
  565. {
  566. const juce::ScopedLock sl (incomingPacketLock);
  567. incomingPackets.swapWith (packets);
  568. }
  569. for (auto& packet : packets)
  570. {
  571. lastGlobalPingTime = juce::Time::getCurrentTime();
  572. auto data = static_cast<const uint8*> (packet.getData());
  573. BlocksProtocol::HostPacketDecoder<ConnectedDeviceGroup>
  574. ::processNextPacket (*this, *data, data + 1, (int) packet.getSize() - 1);
  575. }
  576. }
  577. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectedDeviceGroup)
  578. };
  579. //==============================================================================
  580. /** This is the main singleton object that keeps track of connected blocks */
  581. struct Detector : public juce::ReferenceCountedObject,
  582. private juce::Timer
  583. {
  584. Detector() : defaultDetector (new MIDIDeviceDetector()), deviceDetector (*defaultDetector)
  585. {
  586. startTimer (10);
  587. }
  588. Detector (DeviceDetector& dd) : deviceDetector (dd)
  589. {
  590. startTimer (10);
  591. }
  592. ~Detector()
  593. {
  594. jassert (activeTopologySources.isEmpty());
  595. jassert (activeControlButtons.isEmpty());
  596. }
  597. using Ptr = juce::ReferenceCountedObjectPtr<Detector>;
  598. static Detector::Ptr getDefaultDetector()
  599. {
  600. auto& d = getDefaultDetectorPointer();
  601. if (d == nullptr)
  602. d = new Detector();
  603. return d;
  604. }
  605. static Detector::Ptr& getDefaultDetectorPointer()
  606. {
  607. static Detector::Ptr defaultDetector;
  608. return defaultDetector;
  609. }
  610. void detach (PhysicalTopologySource* pts)
  611. {
  612. activeTopologySources.removeAllInstancesOf (pts);
  613. if (activeTopologySources.isEmpty())
  614. {
  615. for (auto& b : currentTopology.blocks)
  616. if (auto bi = BlockImplementation::getFrom (*b))
  617. bi->sendCommandMessage (BlocksProtocol::endAPIMode);
  618. currentTopology = {};
  619. auto& d = getDefaultDetectorPointer();
  620. if (d != nullptr && d->getReferenceCount() == 2)
  621. getDefaultDetectorPointer() = nullptr;
  622. }
  623. }
  624. bool isConnected (Block::UID deviceID) const noexcept
  625. {
  626. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  627. for (auto&& b : currentTopology.blocks)
  628. if (b->uid == deviceID)
  629. return true;
  630. return false;
  631. }
  632. const BlocksProtocol::DeviceStatus* getLastStatus (Block::UID deviceID) const noexcept
  633. {
  634. for (auto d : connectedDeviceGroups)
  635. if (auto status = d->getLastStatus (deviceID))
  636. return status;
  637. return nullptr;
  638. }
  639. void handleTopologyChange()
  640. {
  641. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  642. {
  643. juce::Array<DeviceInfo> newDeviceInfo;
  644. juce::Array<BlockDeviceConnection> newDeviceConnections;
  645. for (auto d : connectedDeviceGroups)
  646. {
  647. newDeviceInfo.addArray (d->currentDeviceInfo);
  648. newDeviceConnections.addArray (d->currentDeviceConnections);
  649. }
  650. for (int i = currentTopology.blocks.size(); --i >= 0;)
  651. {
  652. auto block = currentTopology.blocks.getUnchecked(i);
  653. if (! containsBlockWithUID (newDeviceInfo, block->uid))
  654. {
  655. if (auto bi = BlockImplementation::getFrom (*block))
  656. bi->invalidate();
  657. currentTopology.blocks.remove (i);
  658. }
  659. }
  660. for (auto& info : newDeviceInfo)
  661. if (info.serial.isValid())
  662. if (! containsBlockWithUID (currentTopology.blocks, getBlockUIDFromSerialNumber (info.serial)))
  663. currentTopology.blocks.add (new BlockImplementation (info.serial, *this, info.isMaster));
  664. currentTopology.connections.swapWith (newDeviceConnections);
  665. }
  666. for (auto d : activeTopologySources)
  667. d->listeners.call (&TopologySource::Listener::topologyChanged);
  668. #if DUMP_TOPOLOGY
  669. dumpTopology (currentTopology);
  670. #endif
  671. }
  672. void handleSharedDataACK (Block::UID deviceID, uint32 packetCounter) const
  673. {
  674. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  675. for (auto&& b : currentTopology.blocks)
  676. if (b->uid == deviceID)
  677. if (auto bi = BlockImplementation::getFrom (*b))
  678. bi->handleSharedDataACK (packetCounter);
  679. }
  680. void handleFirmwareUpdateACK (Block::UID deviceID, uint8 resultCode)
  681. {
  682. for (auto&& b : currentTopology.blocks)
  683. if (b->uid == deviceID)
  684. if (auto bi = BlockImplementation::getFrom (*b))
  685. bi->handleFirmwareUpdateACK (resultCode);
  686. }
  687. void handleLogMessage (Block::UID deviceID, const String& message) const
  688. {
  689. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  690. for (auto&& b : currentTopology.blocks)
  691. if (b->uid == deviceID)
  692. if (auto bi = BlockImplementation::getFrom (*b))
  693. bi->handleLogMessage (message);
  694. }
  695. void handleButtonChange (Block::UID deviceID, Block::Timestamp timestamp, uint32 buttonIndex, bool isDown) const
  696. {
  697. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  698. for (auto b : activeControlButtons)
  699. {
  700. if (b->block.uid == deviceID)
  701. {
  702. if (auto bi = BlockImplementation::getFrom (b->block))
  703. {
  704. bi->pingFromDevice();
  705. if (buttonIndex < (uint32) bi->modelData.buttons.size())
  706. b->broadcastButtonChange (timestamp, bi->modelData.buttons[(int) buttonIndex].type, isDown);
  707. }
  708. }
  709. }
  710. }
  711. void handleTouchChange (Block::UID deviceID, const TouchSurface::Touch& touchEvent)
  712. {
  713. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
  714. for (auto t : activeTouchSurfaces)
  715. {
  716. if (t->block.uid == deviceID)
  717. {
  718. TouchSurface::Touch scaledEvent (touchEvent);
  719. scaledEvent.x *= t->block.getWidth();
  720. scaledEvent.y *= t->block.getHeight();
  721. scaledEvent.startX *= t->block.getWidth();
  722. scaledEvent.startY *= t->block.getHeight();
  723. t->broadcastTouchChange (scaledEvent);
  724. }
  725. }
  726. }
  727. void cancelAllActiveTouches() noexcept
  728. {
  729. for (auto surface : activeTouchSurfaces)
  730. surface->cancelAllActiveTouches();
  731. }
  732. void handleCustomMessage (Block::UID deviceID, Block::Timestamp timestamp, const int32* data)
  733. {
  734. for (auto&& b : currentTopology.blocks)
  735. if (b->uid == deviceID)
  736. if (auto bi = BlockImplementation::getFrom (*b))
  737. bi->handleCustomMessage (timestamp, data);
  738. }
  739. //==============================================================================
  740. int getIndexFromDeviceID (Block::UID deviceID) const noexcept
  741. {
  742. for (auto c : connectedDeviceGroups)
  743. {
  744. const int index = c->getIndexFromDeviceID (deviceID);
  745. if (index >= 0)
  746. return index;
  747. }
  748. return -1;
  749. }
  750. template <typename PacketBuilder>
  751. bool sendMessageToDevice (Block::UID deviceID, const PacketBuilder& builder) const
  752. {
  753. for (auto c : connectedDeviceGroups)
  754. if (c->getIndexFromDeviceID (deviceID) >= 0)
  755. return c->sendMessageToDevice (builder);
  756. return false;
  757. }
  758. static Detector* getFrom (Block& b) noexcept
  759. {
  760. if (auto bi = BlockImplementation::getFrom (b))
  761. return &(bi->detector);
  762. jassertfalse;
  763. return nullptr;
  764. }
  765. DeviceConnection* getDeviceConnectionFor (const Block& b)
  766. {
  767. for (const auto& d : connectedDeviceGroups)
  768. {
  769. for (const auto& info : d->currentDeviceInfo)
  770. {
  771. if (info.uid == b.uid)
  772. return d->getDeviceConnection();
  773. }
  774. }
  775. return nullptr;
  776. }
  777. std::unique_ptr<MIDIDeviceDetector> defaultDetector;
  778. DeviceDetector& deviceDetector;
  779. juce::Array<PhysicalTopologySource*> activeTopologySources;
  780. juce::Array<ControlButtonImplementation*> activeControlButtons;
  781. juce::Array<TouchSurfaceImplementation*> activeTouchSurfaces;
  782. BlockTopology currentTopology;
  783. private:
  784. void timerCallback() override
  785. {
  786. startTimer (1500);
  787. auto detectedDevices = deviceDetector.scanForDevices();
  788. handleDevicesRemoved (detectedDevices);
  789. handleDevicesAdded (detectedDevices);
  790. }
  791. void handleDevicesRemoved (const juce::StringArray& detectedDevices)
  792. {
  793. bool anyDevicesRemoved = false;
  794. for (int i = connectedDeviceGroups.size(); --i >= 0;)
  795. {
  796. if (! connectedDeviceGroups.getUnchecked(i)->isStillConnected (detectedDevices))
  797. {
  798. connectedDeviceGroups.remove (i);
  799. anyDevicesRemoved = true;
  800. }
  801. }
  802. if (anyDevicesRemoved)
  803. handleTopologyChange();
  804. }
  805. void handleDevicesAdded (const juce::StringArray& detectedDevices)
  806. {
  807. bool anyDevicesAdded = false;
  808. for (const auto& devName : detectedDevices)
  809. {
  810. if (! hasDeviceFor (devName))
  811. {
  812. if (auto d = deviceDetector.openDevice (detectedDevices.indexOf (devName)))
  813. {
  814. connectedDeviceGroups.add (new ConnectedDeviceGroup (*this, devName, d));
  815. anyDevicesAdded = true;
  816. }
  817. }
  818. }
  819. if (anyDevicesAdded)
  820. handleTopologyChange();
  821. }
  822. bool hasDeviceFor (const juce::String& devName) const
  823. {
  824. for (auto d : connectedDeviceGroups)
  825. if (d->deviceName == devName)
  826. return true;
  827. return false;
  828. }
  829. juce::OwnedArray<ConnectedDeviceGroup> connectedDeviceGroups;
  830. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Detector)
  831. };
  832. //==============================================================================
  833. struct BlockImplementation : public Block,
  834. private MIDIDeviceConnection::Listener,
  835. private Timer
  836. {
  837. BlockImplementation (const BlocksProtocol::BlockSerialNumber& serial, Detector& detectorToUse, bool master)
  838. : Block (juce::String ((const char*) serial.serial, sizeof (serial.serial))), modelData (serial),
  839. remoteHeap (modelData.programAndHeapSize), detector (detectorToUse), isMaster (master)
  840. {
  841. sendCommandMessage (BlocksProtocol::beginAPIMode);
  842. if (modelData.hasTouchSurface)
  843. touchSurface.reset (new TouchSurfaceImplementation (*this));
  844. int i = 0;
  845. for (auto b : modelData.buttons)
  846. controlButtons.add (new ControlButtonImplementation (*this, i++, b));
  847. if (modelData.lightGridWidth > 0 && modelData.lightGridHeight > 0)
  848. ledGrid.reset (new LEDGridImplementation (*this));
  849. for (auto s : modelData.statusLEDs)
  850. statusLights.add (new StatusLightImplementation (*this, s));
  851. if (modelData.numLEDRowLEDs > 0)
  852. ledRow.reset (new LEDRowImplementation (*this));
  853. listenerToMidiConnection = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this));
  854. if (listenerToMidiConnection != nullptr)
  855. listenerToMidiConnection->addListener (this);
  856. }
  857. ~BlockImplementation()
  858. {
  859. if (listenerToMidiConnection != nullptr)
  860. listenerToMidiConnection->removeListener (this);
  861. }
  862. void invalidate()
  863. {
  864. isStillConnected = false;
  865. }
  866. Type getType() const override { return modelData.apiType; }
  867. juce::String getDeviceDescription() const override { return modelData.description; }
  868. int getWidth() const override { return modelData.widthUnits; }
  869. int getHeight() const override { return modelData.heightUnits; }
  870. float getMillimetersPerUnit() const override { return 47.0f; }
  871. bool isHardwareBlock() const override { return true; }
  872. juce::Array<Block::ConnectionPort> getPorts() const override { return modelData.ports; }
  873. bool isConnected() const override { return isStillConnected && detector.isConnected (uid); }
  874. bool isMasterBlock() const override { return isMaster; }
  875. TouchSurface* getTouchSurface() const override { return touchSurface.get(); }
  876. LEDGrid* getLEDGrid() const override { return ledGrid.get(); }
  877. LEDRow* getLEDRow() const override { return ledRow.get(); }
  878. juce::Array<ControlButton*> getButtons() const override
  879. {
  880. juce::Array<ControlButton*> result;
  881. result.addArray (controlButtons);
  882. return result;
  883. }
  884. juce::Array<StatusLight*> getStatusLights() const override
  885. {
  886. juce::Array<StatusLight*> result;
  887. result.addArray (statusLights);
  888. return result;
  889. }
  890. float getBatteryLevel() const override
  891. {
  892. if (auto status = detector.getLastStatus (uid))
  893. return status->batteryLevel.toUnipolarFloat();
  894. return 0.0f;
  895. }
  896. bool isBatteryCharging() const override
  897. {
  898. if (auto status = detector.getLastStatus (uid))
  899. return status->batteryCharging.get() != 0;
  900. return false;
  901. }
  902. bool supportsGraphics() const override
  903. {
  904. return false;
  905. }
  906. int getDeviceIndex() const noexcept
  907. {
  908. return isConnected() ? detector.getIndexFromDeviceID (uid) : -1;
  909. }
  910. template <typename PacketBuilder>
  911. bool sendMessageToDevice (const PacketBuilder& builder)
  912. {
  913. lastMessageSendTime = juce::Time::getCurrentTime();
  914. return detector.sendMessageToDevice (uid, builder);
  915. }
  916. bool sendCommandMessage (uint32 commandID)
  917. {
  918. int index = getDeviceIndex();
  919. if (index < 0)
  920. return false;
  921. BlocksProtocol::HostPacketBuilder<64> p;
  922. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  923. p.deviceControlMessage (commandID);
  924. p.writePacketSysexFooter();
  925. return sendMessageToDevice (p);
  926. }
  927. void handleCustomMessage (Block::Timestamp, const int32* data)
  928. {
  929. ProgramEventMessage m;
  930. for (uint32 i = 0; i < BlocksProtocol::numProgramMessageInts; ++i)
  931. m.values[i] = data[i];
  932. programEventListeners.call (&Block::ProgramEventListener::handleProgramEvent, *this, m);
  933. }
  934. static BlockImplementation* getFrom (Block& b) noexcept
  935. {
  936. if (auto bi = dynamic_cast<BlockImplementation*> (&b))
  937. return bi;
  938. jassertfalse;
  939. return nullptr;
  940. }
  941. bool isControlBlock() const
  942. {
  943. auto type = getType();
  944. return type == Block::Type::liveBlock
  945. || type == Block::Type::loopBlock
  946. || type == Block::Type::developerControlBlock;
  947. }
  948. //==============================================================================
  949. std::function<void(const String&)> logger;
  950. void setLogger (std::function<void(const String&)> newLogger) override
  951. {
  952. logger = newLogger;
  953. }
  954. void handleLogMessage (const String& message) const
  955. {
  956. if (logger != nullptr)
  957. logger (message);
  958. }
  959. //==============================================================================
  960. juce::Result setProgram (Program* newProgram) override
  961. {
  962. if (newProgram == nullptr || program.get() != newProgram)
  963. {
  964. {
  965. std::unique_ptr<Program> p (newProgram);
  966. if (program != nullptr
  967. && newProgram != nullptr
  968. && program->getLittleFootProgram() == newProgram->getLittleFootProgram())
  969. return juce::Result::ok();
  970. stopTimer();
  971. std::swap (program, p);
  972. }
  973. stopTimer();
  974. programSize = 0;
  975. if (program != nullptr)
  976. {
  977. littlefoot::Compiler compiler;
  978. compiler.addNativeFunctions (PhysicalTopologySource::getStandardLittleFootFunctions());
  979. auto err = compiler.compile (program->getLittleFootProgram(), 512);
  980. if (err.failed())
  981. return err;
  982. DBG ("Compiled littlefoot program, space needed: "
  983. << (int) compiler.getCompiledProgram().getTotalSpaceNeeded() << " bytes");
  984. if (compiler.getCompiledProgram().getTotalSpaceNeeded() > getMemorySize())
  985. return Result::fail ("Program too large!");
  986. size_t size = (size_t) compiler.compiledObjectCode.size();
  987. programSize = (uint32) size;
  988. remoteHeap.resetDataRangeToUnknown (0, remoteHeap.blockSize);
  989. remoteHeap.clear();
  990. remoteHeap.sendChanges (*this, true);
  991. remoteHeap.resetDataRangeToUnknown (0, (uint32) size);
  992. remoteHeap.setBytes (0, compiler.compiledObjectCode.begin(), size);
  993. remoteHeap.sendChanges (*this, true);
  994. }
  995. else
  996. {
  997. remoteHeap.clear();
  998. }
  999. }
  1000. else
  1001. {
  1002. jassertfalse;
  1003. }
  1004. return juce::Result::ok();
  1005. }
  1006. Program* getProgram() const override { return program.get(); }
  1007. void sendProgramEvent (const ProgramEventMessage& message) override
  1008. {
  1009. static_assert (sizeof (ProgramEventMessage::values) == 4 * BlocksProtocol::numProgramMessageInts,
  1010. "Need to keep the internal and external messages structures the same");
  1011. if (remoteHeap.isProgramLoaded())
  1012. {
  1013. auto index = getDeviceIndex();
  1014. if (index >= 0)
  1015. {
  1016. BlocksProtocol::HostPacketBuilder<128> p;
  1017. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1018. if (p.addProgramEventMessage (message.values))
  1019. {
  1020. p.writePacketSysexFooter();
  1021. sendMessageToDevice (p);
  1022. }
  1023. }
  1024. else
  1025. {
  1026. jassertfalse;
  1027. }
  1028. }
  1029. }
  1030. void timerCallback() override
  1031. {
  1032. if (remoteHeap.isFullySynced() && remoteHeap.isProgramLoaded())
  1033. {
  1034. stopTimer();
  1035. sendCommandMessage (BlocksProtocol::saveProgramAsDefault);
  1036. }
  1037. else
  1038. {
  1039. startTimer (100);
  1040. }
  1041. }
  1042. void saveProgramAsDefault() override
  1043. {
  1044. startTimer (10);
  1045. }
  1046. uint32 getMemorySize() override
  1047. {
  1048. return modelData.programAndHeapSize;
  1049. }
  1050. void setDataByte (size_t offset, uint8 value) override
  1051. {
  1052. remoteHeap.setByte (programSize + offset, value);
  1053. }
  1054. void setDataBytes (size_t offset, const void* newData, size_t num) override
  1055. {
  1056. remoteHeap.setBytes (programSize + offset, static_cast<const uint8*> (newData), num);
  1057. }
  1058. void setDataBits (uint32 startBit, uint32 numBits, uint32 value) override
  1059. {
  1060. remoteHeap.setBits (programSize * 8 + startBit, numBits, value);
  1061. }
  1062. uint8 getDataByte (size_t offset) override
  1063. {
  1064. return remoteHeap.getByte (programSize + offset);
  1065. }
  1066. void handleSharedDataACK (uint32 packetCounter) noexcept
  1067. {
  1068. pingFromDevice();
  1069. remoteHeap.handleACKFromDevice (*this, packetCounter);
  1070. }
  1071. bool sendFirmwareUpdatePacket (const uint8* data, uint8 size, std::function<void (uint8)> callback) override
  1072. {
  1073. firmwarePacketAckCallback = {};
  1074. auto index = getDeviceIndex();
  1075. if (index >= 0)
  1076. {
  1077. BlocksProtocol::HostPacketBuilder<256> p;
  1078. p.writePacketSysexHeaderBytes ((BlocksProtocol::TopologyIndex) index);
  1079. if (p.addFirmwareUpdatePacket (data, size))
  1080. {
  1081. p.writePacketSysexFooter();
  1082. if (sendMessageToDevice (p))
  1083. {
  1084. firmwarePacketAckCallback = callback;
  1085. return true;
  1086. }
  1087. }
  1088. }
  1089. else
  1090. {
  1091. jassertfalse;
  1092. }
  1093. return false;
  1094. }
  1095. void handleFirmwareUpdateACK (uint8 resultCode)
  1096. {
  1097. if (firmwarePacketAckCallback != nullptr)
  1098. {
  1099. firmwarePacketAckCallback (resultCode);
  1100. firmwarePacketAckCallback = {};
  1101. }
  1102. }
  1103. void pingFromDevice()
  1104. {
  1105. lastMessageReceiveTime = juce::Time::getCurrentTime();
  1106. }
  1107. void addDataInputPortListener (DataInputPortListener* listener) override
  1108. {
  1109. Block::addDataInputPortListener (listener);
  1110. if (auto midiInput = getMidiInput())
  1111. midiInput->start();
  1112. }
  1113. void sendMessage (const void* message, size_t messageSize) override
  1114. {
  1115. if (auto midiOutput = getMidiOutput())
  1116. midiOutput->sendMessageNow ({ message, (int) messageSize });
  1117. }
  1118. void handleTimerTick()
  1119. {
  1120. if (++resetMessagesSent < 3)
  1121. {
  1122. if (resetMessagesSent == 1)
  1123. sendCommandMessage (BlocksProtocol::endAPIMode);
  1124. sendCommandMessage (BlocksProtocol::beginAPIMode);
  1125. return;
  1126. }
  1127. if (ledGrid != nullptr)
  1128. if (auto renderer = ledGrid->getRenderer())
  1129. renderer->renderLEDGrid (*ledGrid);
  1130. remoteHeap.sendChanges (*this, false);
  1131. if (lastMessageSendTime < juce::Time::getCurrentTime() - juce::RelativeTime::milliseconds (pingIntervalMs))
  1132. sendCommandMessage (BlocksProtocol::ping);
  1133. }
  1134. //==============================================================================
  1135. std::unique_ptr<TouchSurface> touchSurface;
  1136. juce::OwnedArray<ControlButton> controlButtons;
  1137. std::unique_ptr<LEDGridImplementation> ledGrid;
  1138. std::unique_ptr<LEDRowImplementation> ledRow;
  1139. juce::OwnedArray<StatusLight> statusLights;
  1140. BlocksProtocol::BlockDataSheet modelData;
  1141. MIDIDeviceConnection* listenerToMidiConnection = nullptr;
  1142. static constexpr int pingIntervalMs = 400;
  1143. static constexpr uint32 maxBlockSize = BlocksProtocol::padBlockProgramAndHeapSize;
  1144. static constexpr uint32 maxPacketCounter = BlocksProtocol::PacketCounter::maxValue;
  1145. static constexpr uint32 maxPacketSize = 200;
  1146. using PacketBuilder = BlocksProtocol::HostPacketBuilder<maxPacketSize>;
  1147. using RemoteHeapType = littlefoot::LittleFootRemoteHeap<BlockImplementation>;
  1148. RemoteHeapType remoteHeap;
  1149. Detector& detector;
  1150. juce::Time lastMessageSendTime, lastMessageReceiveTime;
  1151. private:
  1152. std::unique_ptr<Program> program;
  1153. uint32 programSize = 0;
  1154. std::function<void (uint8)> firmwarePacketAckCallback;
  1155. uint32 resetMessagesSent = 0;
  1156. bool isStillConnected = true;
  1157. bool isMaster = false;
  1158. const juce::MidiInput* getMidiInput() const
  1159. {
  1160. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1161. return c->midiInput.get();
  1162. jassertfalse;
  1163. return nullptr;
  1164. }
  1165. juce::MidiInput* getMidiInput()
  1166. {
  1167. return const_cast<juce::MidiInput*> (static_cast<const BlockImplementation&>(*this).getMidiInput());
  1168. }
  1169. const juce::MidiOutput* getMidiOutput() const
  1170. {
  1171. if (auto c = dynamic_cast<MIDIDeviceConnection*> (detector.getDeviceConnectionFor (*this)))
  1172. return c->midiOutput.get();
  1173. jassertfalse;
  1174. return nullptr;
  1175. }
  1176. juce::MidiOutput* getMidiOutput()
  1177. {
  1178. return const_cast<juce::MidiOutput*> (static_cast<const BlockImplementation&>(*this).getMidiOutput());
  1179. }
  1180. void handleIncomingMidiMessage (const juce::MidiMessage& message) override
  1181. {
  1182. dataInputPortListeners.call (&Block::DataInputPortListener::handleIncomingDataPortMessage,
  1183. *this, message.getRawData(), (size_t) message.getRawDataSize());
  1184. }
  1185. void connectionBeingDeleted (const MIDIDeviceConnection& c) override
  1186. {
  1187. jassert (listenerToMidiConnection == &c);
  1188. juce::ignoreUnused (c);
  1189. listenerToMidiConnection->removeListener (this);
  1190. listenerToMidiConnection = nullptr;
  1191. }
  1192. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockImplementation)
  1193. };
  1194. //==============================================================================
  1195. struct LEDRowImplementation : public LEDRow,
  1196. private Timer
  1197. {
  1198. LEDRowImplementation (BlockImplementation& b) : LEDRow (b)
  1199. {
  1200. startTimer (300);
  1201. }
  1202. void setButtonColour (uint32 index, LEDColour colour)
  1203. {
  1204. if (index < 10)
  1205. {
  1206. colours[index] = colour;
  1207. flush();
  1208. }
  1209. }
  1210. int getNumLEDs() const override
  1211. {
  1212. return static_cast<const BlockImplementation&> (block).modelData.numLEDRowLEDs;
  1213. }
  1214. void setLEDColour (int index, LEDColour colour) override
  1215. {
  1216. if ((uint32) index < 15u)
  1217. {
  1218. colours[10 + index] = colour;
  1219. flush();
  1220. }
  1221. }
  1222. void setOverlayColour (LEDColour colour) override
  1223. {
  1224. colours[25] = colour;
  1225. flush();
  1226. }
  1227. void resetOverlayColour() override
  1228. {
  1229. setOverlayColour ({});
  1230. }
  1231. private:
  1232. LEDColour colours[26];
  1233. void timerCallback() override
  1234. {
  1235. stopTimer();
  1236. loadProgramOntoBlock();
  1237. flush();
  1238. }
  1239. void loadProgramOntoBlock()
  1240. {
  1241. if (block.getProgram() == nullptr)
  1242. {
  1243. auto err = block.setProgram (new DefaultLEDGridProgram (block));
  1244. if (err.failed())
  1245. {
  1246. DBG (err.getErrorMessage());
  1247. jassertfalse;
  1248. }
  1249. }
  1250. }
  1251. void flush()
  1252. {
  1253. if (block.getProgram() != nullptr)
  1254. for (uint32 i = 0; i < (uint32) numElementsInArray (colours); ++i)
  1255. write565Colour (16 * i, colours[i]);
  1256. }
  1257. void write565Colour (uint32 bitIndex, LEDColour colour)
  1258. {
  1259. block.setDataBits (bitIndex, 5, colour.getRed() >> 3);
  1260. block.setDataBits (bitIndex + 5, 6, colour.getGreen() >> 2);
  1261. block.setDataBits (bitIndex + 11, 5, colour.getBlue() >> 3);
  1262. }
  1263. struct DefaultLEDGridProgram : public Block::Program
  1264. {
  1265. DefaultLEDGridProgram (Block& b) : Block::Program (b) {}
  1266. juce::String getLittleFootProgram() override
  1267. {
  1268. /* Data format:
  1269. 0: 10 x 5-6-5 bits for button LED RGBs
  1270. 20: 15 x 5-6-5 bits for LED row colours
  1271. 50: 1 x 5-6-5 bits for LED row overlay colour
  1272. */
  1273. return R"littlefoot(
  1274. #heapsize: 128
  1275. int getColour (int bitIndex)
  1276. {
  1277. return makeARGB (255,
  1278. getHeapBits (bitIndex, 5) << 3,
  1279. getHeapBits (bitIndex + 5, 6) << 2,
  1280. getHeapBits (bitIndex + 11, 5) << 3);
  1281. }
  1282. int getButtonColour (int index)
  1283. {
  1284. return getColour (16 * index);
  1285. }
  1286. int getLEDColour (int index)
  1287. {
  1288. if (getHeapInt (50))
  1289. return getColour (50 * 8);
  1290. return getColour (20 * 8 + 16 * index);
  1291. }
  1292. void repaint()
  1293. {
  1294. for (int x = 0; x < 15; ++x)
  1295. fillPixel (getLEDColour (x), x, 0);
  1296. for (int i = 0; i < 10; ++i)
  1297. fillPixel (getButtonColour (i), i, 1);
  1298. }
  1299. void handleMessage (int p1, int p2) {}
  1300. )littlefoot";
  1301. }
  1302. };
  1303. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDRowImplementation)
  1304. };
  1305. //==============================================================================
  1306. struct TouchSurfaceImplementation : public TouchSurface,
  1307. private juce::Timer
  1308. {
  1309. TouchSurfaceImplementation (BlockImplementation& b) : TouchSurface (b), blockImpl (b)
  1310. {
  1311. if (auto det = Detector::getFrom (block))
  1312. det->activeTouchSurfaces.add (this);
  1313. startTimer (500);
  1314. }
  1315. ~TouchSurfaceImplementation()
  1316. {
  1317. if (auto det = Detector::getFrom (block))
  1318. det->activeTouchSurfaces.removeFirstMatchingValue (this);
  1319. }
  1320. int getNumberOfKeywaves() const noexcept override
  1321. {
  1322. return blockImpl.modelData.numKeywaves;
  1323. }
  1324. void broadcastTouchChange (const TouchSurface::Touch& touchEvent)
  1325. {
  1326. auto& status = touches.getValue (touchEvent);
  1327. // Fake a touch end if we receive a duplicate touch-start with no preceding touch-end (ie: comms error)
  1328. if (touchEvent.isTouchStart && status.isActive)
  1329. killTouch (touchEvent, status, juce::Time::getMillisecondCounter());
  1330. // Fake a touch start if we receive an unexpected event with no matching start event. (ie: comms error)
  1331. if (! touchEvent.isTouchStart && ! status.isActive)
  1332. {
  1333. TouchSurface::Touch t (touchEvent);
  1334. t.isTouchStart = true;
  1335. t.isTouchEnd = false;
  1336. if (t.zVelocity <= 0) t.zVelocity = status.lastStrikePressure;
  1337. if (t.zVelocity <= 0) t.zVelocity = t.z;
  1338. if (t.zVelocity <= 0) t.zVelocity = 0.9f;
  1339. listeners.call (&TouchSurface::Listener::touchChanged, *this, t);
  1340. }
  1341. // Normal handling:
  1342. status.lastEventTime = juce::Time::getMillisecondCounter();
  1343. status.isActive = ! touchEvent.isTouchEnd;
  1344. if (touchEvent.isTouchStart)
  1345. status.lastStrikePressure = touchEvent.zVelocity;
  1346. listeners.call (&TouchSurface::Listener::touchChanged, *this, touchEvent);
  1347. }
  1348. void timerCallback() override
  1349. {
  1350. // Find touches that seem to have become stuck, and fake a touch-end for them..
  1351. static const uint32 touchTimeOutMs = 40;
  1352. for (auto& t : touches)
  1353. {
  1354. auto& status = t.value;
  1355. auto now = juce::Time::getMillisecondCounter();
  1356. if (status.isActive && now > status.lastEventTime + touchTimeOutMs)
  1357. killTouch (t.touch, status, now);
  1358. }
  1359. }
  1360. struct TouchStatus
  1361. {
  1362. uint32 lastEventTime = 0;
  1363. float lastStrikePressure = 0;
  1364. bool isActive = false;
  1365. };
  1366. void killTouch (const TouchSurface::Touch& touch, TouchStatus& status, uint32 timeStamp) noexcept
  1367. {
  1368. jassert (status.isActive);
  1369. TouchSurface::Touch killTouch (touch);
  1370. killTouch.z = 0;
  1371. killTouch.xVelocity = 0;
  1372. killTouch.yVelocity = 0;
  1373. killTouch.zVelocity = -1.0f;
  1374. killTouch.eventTimestamp = timeStamp;
  1375. killTouch.isTouchStart = false;
  1376. killTouch.isTouchEnd = true;
  1377. listeners.call (&TouchSurface::Listener::touchChanged, *this, killTouch);
  1378. status.isActive = false;
  1379. }
  1380. void cancelAllActiveTouches() noexcept override
  1381. {
  1382. const auto now = juce::Time::getMillisecondCounter();
  1383. for (auto& t : touches)
  1384. if (t.value.isActive)
  1385. killTouch (t.touch, t.value, now);
  1386. touches.clear();
  1387. }
  1388. BlockImplementation& blockImpl;
  1389. TouchList<TouchStatus> touches;
  1390. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TouchSurfaceImplementation)
  1391. };
  1392. //==============================================================================
  1393. struct ControlButtonImplementation : public ControlButton
  1394. {
  1395. ControlButtonImplementation (BlockImplementation& b, int index, BlocksProtocol::BlockDataSheet::ButtonInfo info)
  1396. : ControlButton (b), blockImpl (b), buttonInfo (info), buttonIndex (index)
  1397. {
  1398. if (auto det = Detector::getFrom (block))
  1399. det->activeControlButtons.add (this);
  1400. }
  1401. ~ControlButtonImplementation()
  1402. {
  1403. if (auto det = Detector::getFrom (block))
  1404. det->activeControlButtons.removeFirstMatchingValue (this);
  1405. }
  1406. ButtonFunction getType() const override { return buttonInfo.type; }
  1407. juce::String getName() const override { return BlocksProtocol::getButtonNameForFunction (buttonInfo.type); }
  1408. float getPositionX() const override { return buttonInfo.x; }
  1409. float getPositionY() const override { return buttonInfo.y; }
  1410. bool hasLight() const override { return blockImpl.isControlBlock(); }
  1411. bool setLightColour (LEDColour colour) override
  1412. {
  1413. if (hasLight())
  1414. {
  1415. if (auto row = blockImpl.ledRow.get())
  1416. {
  1417. row->setButtonColour ((uint32) buttonIndex, colour);
  1418. return true;
  1419. }
  1420. }
  1421. return false;
  1422. }
  1423. void broadcastButtonChange (Block::Timestamp timestamp, ControlButton::ButtonFunction button, bool isDown)
  1424. {
  1425. if (button == buttonInfo.type)
  1426. {
  1427. if (wasDown == isDown)
  1428. sendButtonChangeToListeners (timestamp, ! isDown);
  1429. sendButtonChangeToListeners (timestamp, isDown);
  1430. wasDown = isDown;
  1431. }
  1432. }
  1433. void sendButtonChangeToListeners (Block::Timestamp timestamp, bool isDown)
  1434. {
  1435. if (isDown)
  1436. listeners.call (&ControlButton::Listener::buttonPressed, *this, timestamp);
  1437. else
  1438. listeners.call (&ControlButton::Listener::buttonReleased, *this, timestamp);
  1439. }
  1440. BlockImplementation& blockImpl;
  1441. BlocksProtocol::BlockDataSheet::ButtonInfo buttonInfo;
  1442. int buttonIndex;
  1443. bool wasDown = false;
  1444. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ControlButtonImplementation)
  1445. };
  1446. //==============================================================================
  1447. struct StatusLightImplementation : public StatusLight
  1448. {
  1449. StatusLightImplementation (Block& b, BlocksProtocol::BlockDataSheet::StatusLEDInfo i) : StatusLight (b), info (i)
  1450. {
  1451. }
  1452. juce::String getName() const override { return info.name; }
  1453. bool setColour (LEDColour newColour) override
  1454. {
  1455. // XXX TODO!
  1456. juce::ignoreUnused (newColour);
  1457. return false;
  1458. }
  1459. BlocksProtocol::BlockDataSheet::StatusLEDInfo info;
  1460. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StatusLightImplementation)
  1461. };
  1462. //==============================================================================
  1463. struct LEDGridImplementation : public LEDGrid
  1464. {
  1465. LEDGridImplementation (BlockImplementation& b) : LEDGrid (b), blockImpl (b)
  1466. {
  1467. }
  1468. int getNumColumns() const override { return blockImpl.modelData.lightGridWidth; }
  1469. int getNumRows() const override { return blockImpl.modelData.lightGridHeight; }
  1470. BlockImplementation& blockImpl;
  1471. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LEDGridImplementation)
  1472. };
  1473. //==============================================================================
  1474. #if DUMP_TOPOLOGY
  1475. static juce::String idToSerialNum (const BlockTopology& topology, Block::UID uid)
  1476. {
  1477. for (auto* b : topology.blocks)
  1478. if (b->uid == uid)
  1479. return b->serialNumber;
  1480. return "???";
  1481. }
  1482. static juce::String portEdgeToString (Block::ConnectionPort port)
  1483. {
  1484. switch (port.edge)
  1485. {
  1486. case Block::ConnectionPort::DeviceEdge::north: return "north";
  1487. case Block::ConnectionPort::DeviceEdge::south: return "south";
  1488. case Block::ConnectionPort::DeviceEdge::east: return "east";
  1489. case Block::ConnectionPort::DeviceEdge::west: return "west";
  1490. }
  1491. return {};
  1492. }
  1493. static juce::String portToString (Block::ConnectionPort port)
  1494. {
  1495. return portEdgeToString (port) + "_" + juce::String (port.index);
  1496. }
  1497. static void dumpTopology (const BlockTopology& topology)
  1498. {
  1499. MemoryOutputStream m;
  1500. m << "=============================================================================" << newLine
  1501. << "Topology: " << topology.blocks.size() << " device(s)" << newLine
  1502. << newLine;
  1503. int index = 0;
  1504. for (auto block : topology.blocks)
  1505. {
  1506. m << "Device " << index++ << (block->isMasterBlock() ? ": (MASTER)" : ":") << newLine;
  1507. m << " Description: " << block->getDeviceDescription() << newLine
  1508. << " Serial: " << block->serialNumber << newLine;
  1509. if (auto bi = BlockImplementation::getFrom (*block))
  1510. m << " Short address: " << (int) bi->getDeviceIndex() << newLine;
  1511. m << " Battery level: " + juce::String (juce::roundToInt (100.0f * block->getBatteryLevel())) + "%" << newLine
  1512. << " Battery charging: " + juce::String (block->isBatteryCharging() ? "y" : "n") << newLine
  1513. << " Width: " << block->getWidth() << newLine
  1514. << " Height: " << block->getHeight() << newLine
  1515. << " Millimeters per unit: " << block->getMillimetersPerUnit() << newLine
  1516. << newLine;
  1517. }
  1518. for (auto& connection : topology.connections)
  1519. {
  1520. m << idToSerialNum (topology, connection.device1)
  1521. << ":" << portToString (connection.connectionPortOnDevice1)
  1522. << " <-> "
  1523. << idToSerialNum (topology, connection.device2)
  1524. << ":" << portToString (connection.connectionPortOnDevice2) << newLine;
  1525. }
  1526. m << "=============================================================================" << newLine;
  1527. Logger::outputDebugString (m.toString());
  1528. }
  1529. #endif
  1530. };
  1531. //==============================================================================
  1532. struct PhysicalTopologySource::DetectorHolder : private juce::Timer
  1533. {
  1534. DetectorHolder (PhysicalTopologySource& pts)
  1535. : topologySource (pts),
  1536. detector (Internal::Detector::getDefaultDetector())
  1537. {
  1538. startTimerHz (30);
  1539. }
  1540. DetectorHolder (PhysicalTopologySource& pts, DeviceDetector& dd)
  1541. : topologySource (pts),
  1542. detector (new Internal::Detector (dd))
  1543. {
  1544. startTimerHz (30);
  1545. }
  1546. void timerCallback() override
  1547. {
  1548. if (! topologySource.hasOwnServiceTimer())
  1549. handleTimerTick();
  1550. }
  1551. void handleTimerTick()
  1552. {
  1553. for (auto& b : detector->currentTopology.blocks)
  1554. if (auto bi = Internal::BlockImplementation::getFrom (*b))
  1555. bi->handleTimerTick();
  1556. }
  1557. PhysicalTopologySource& topologySource;
  1558. Internal::Detector::Ptr detector;
  1559. };
  1560. //==============================================================================
  1561. PhysicalTopologySource::PhysicalTopologySource()
  1562. : detector (new DetectorHolder (*this))
  1563. {
  1564. detector->detector->activeTopologySources.add (this);
  1565. }
  1566. PhysicalTopologySource::PhysicalTopologySource (DeviceDetector& detectorToUse)
  1567. : detector (new DetectorHolder (*this, detectorToUse))
  1568. {
  1569. detector->detector->activeTopologySources.add (this);
  1570. }
  1571. PhysicalTopologySource::~PhysicalTopologySource()
  1572. {
  1573. detector->detector->detach (this);
  1574. detector = nullptr;
  1575. }
  1576. BlockTopology PhysicalTopologySource::getCurrentTopology() const
  1577. {
  1578. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // This method must only be called from the message thread!
  1579. return detector->detector->currentTopology;
  1580. }
  1581. void PhysicalTopologySource::cancelAllActiveTouches() noexcept
  1582. {
  1583. detector->detector->cancelAllActiveTouches();
  1584. }
  1585. bool PhysicalTopologySource::hasOwnServiceTimer() const { return false; }
  1586. void PhysicalTopologySource::handleTimerTick() { detector->handleTimerTick(); }
  1587. PhysicalTopologySource::DeviceConnection::DeviceConnection() {}
  1588. PhysicalTopologySource::DeviceConnection::~DeviceConnection() {}
  1589. PhysicalTopologySource::DeviceDetector::DeviceDetector() {}
  1590. PhysicalTopologySource::DeviceDetector::~DeviceDetector() {}
  1591. const char* const* PhysicalTopologySource::getStandardLittleFootFunctions() noexcept
  1592. {
  1593. return BlocksProtocol::ledProgramLittleFootFunctions;
  1594. }
  1595. static bool blocksMatch (const Block::Array& list1, const Block::Array& list2) noexcept
  1596. {
  1597. if (list1.size() != list2.size())
  1598. return false;
  1599. for (auto&& b : list1)
  1600. if (! list2.contains (b))
  1601. return false;
  1602. return true;
  1603. }
  1604. bool BlockTopology::operator== (const BlockTopology& other) const noexcept
  1605. {
  1606. return connections == other.connections && blocksMatch (blocks, other.blocks);
  1607. }
  1608. bool BlockTopology::operator!= (const BlockTopology& other) const noexcept
  1609. {
  1610. return ! operator== (other);
  1611. }
  1612. bool BlockDeviceConnection::operator== (const BlockDeviceConnection& other) const noexcept
  1613. {
  1614. return (device1 == other.device1 && device2 == other.device2
  1615. && connectionPortOnDevice1 == other.connectionPortOnDevice1
  1616. && connectionPortOnDevice2 == other.connectionPortOnDevice2)
  1617. || (device1 == other.device2 && device2 == other.device1
  1618. && connectionPortOnDevice1 == other.connectionPortOnDevice2
  1619. && connectionPortOnDevice2 == other.connectionPortOnDevice1);
  1620. }
  1621. bool BlockDeviceConnection::operator!= (const BlockDeviceConnection& other) const noexcept
  1622. {
  1623. return ! operator== (other);
  1624. }