Communicating Between Scratch and The NXT
Blueprint on LaunchPad"Scratchable Java" is a chapter from Killer Game Programming in Java by Dr. Andrew Davison. The Back End of Enchanting uses modified code from this (with permission) to allow communication between Enchanting's Front End and Back End, between the Back End and Scratch, and between the Back End and the NXT.
Diagrammatically, it looks like this:
It is only through the Back End that the Front End communicates with anything. Fortunately, the Back End was designed so that it relays any messages from one source to all other sources.
There are two principal kinds of messages that the Scratch Protocol supports.
- Broadcasts.
- Variable/Sensor updates.
Communication's Test
The test described below does not work in Enchanting 0.0.4 Beta as the broadcast blocks have been removed. The video on Running Enchanting shows how to connect Scratch to the Back End, but it is hard to see anything happening with the blocks disabled. (Contact Clinton if you want to do some testing in this area).
You can test this by:
run Enchanting
run Scratch
Enable Remote Sensor Connections in Scratch?.
In Scratch, put down a block that starts with "When I Receive" hat block (in the control section), and add some code that'll do something obvious (like playing a sound). Click on the drop-down in the "When I Receive" block, click "new..." and define a new message. Let's call it "Howdy".
In Enchanting, find the "broadcast" block in the control menu, add a new message, likewise, call it "Howdy" and double-click on the block. The Enchanting Front End will send the message to the Back End which will relay it to Scratch, which will then trigger the section of code that starts whenever "Howdy" is received.
Communication Between the NXT and Back End
At the moment, the Back End will intercept some specific commands for the NXT, and act on them. Specifically, given a specific command, it will compile, link, upload, and run a file generated by the Front End, and it runs nicely on the NXT.
However, the NXT does not actually send messages to and front the Back End, yet. This needs to change if messages are to be broadcast and variables are to be updated.
In the NXT code:
- the Scratch Protocol code needs to be ported to work with the NXT
- the NXT needs to be able to deal with broadcast commands
- the NXT needs to monitor variables and, when they change, flag the change. Whenever communication channels are available, it needs to transmit all the variables that have changed. (Note that this can be done in one packet, if size is not an issue.)
The Back End needs to change to deal with sending and receiving messages to/from the NXT.