<size: 4 bytes><msg: size bytes>
The offline application provides a HTTP connection on localhost on port 42001. Here is the test python script:
from array import array import socket import time HOST = '127.0.0.1' PORT = 42001 //scratch protocol def sendScratchCommand(cmd): n = len(cmd) a = array('c') a.append(chr((n >> 24) & 0xFF)) a.append(chr((n >> 16) & 0xFF)) a.append(chr((n >> 8) & 0xFF)) a.append(chr(n & 0xFF)) scratchSock.send(a.tostring() + cmd) print("connecting...") scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) scratchSock.connect((HOST, PORT)) print("connected") for i in xrange(3): sendScratchCommand('sensor-update button 1') time.sleep(1) sendScratchCommand('sensor-update button 0') time.sleep(1) print("click!") print("closing socket...") scratchSock.close() print("done")
I have saved this file as test.py and I create a simple script in Scratch as follows:
I ran the python script in the terminal:
python test.py connecting... connected click! click! click! closing socket... done
and I get the results in Scratch:
Next is serial port communication from the same script to the /dev/ttyACM0 device of the Freedom board. For that I install PySerial.
sudo apt install python-pip python -m pip install pyserial Collecting pyserial Downloading pyserial-3.2.1-py2.py3-none-any.whl (189kB) 100% |████████████████████████████████| 194kB 569kB/s Installing collected packages: pyserial Successfully installed pyserial
Then I do a quick script to confirm its working.
import serial ser = serial.Serial("/dev/ttyACM0",57600) str = "hi" print str ser.write("Hello\n") str = ser.readline() print str ser.close()
Running this script works with the baremetal firmware on my Freedom board which echos back whatever you send to it.
I wonder if implementing the Scratch protocol in the firmware would be worthwhile. In any case, I will do a simple shell that responds to sensor update request data and receives commands to toggle GPIOs and update an LCD screen. I will put the two scripts together, creating a bridge between the HTTP port 42001 and serial port at /dev/ttyACM0 and run it on a while loop. I think I can handle termination cleaning up by closing the HTTP connection and the serial device.
To be continued…