I’m programming an interface to a device called Launchpad. Launchpad features a grid of lightable buttons. My interface sets up an input and an output connection to the device. Additionally, there’s a shared state that both the input and the output connection need mutable access to.
I need the shared state because messages to the device affect how messages from the devices are interpreted. An example and how I would implement it:
There’s a “device inquiry” byte sequence/message. Launchpad replies to it with device information. The input connection I mentioned will receive the device information. To make sense of it, it needs to know that a device inquiry was sent. Otherwise, it has no idea what the bytes are supposed to mean.
I would try to implement this with a FIFO queue that both the output and the input connection have access to. When the output connection sends the device inquiry message, it pushes a device inquiry token onto the queue. When the input connection receives a message, it will pop the device inquiry token of the queue and process the message accordingly.
This idea, however, clashes with Rust’s rules of borrowing and ownership - there can’t be two mutable references to the queue at the same time.
This matter is further complicated by the callback that needs to be passed to the input connection. This callback holds a reference to the output connection to trigger a light. This reference is mutable because any action on the output connection might mutate the shared state. So I have another mutable reference…