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.

2053 lines
71KB

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