For reading: Let's write out everything the arduino says to a text file. This way we'll have an exact record of what happened. Other programs can parse this file for the results so far.
For writing: This was a little more difficult. I wanted a general interface that could be used by a human or another script to communicate with the Python chatting script. I decided to use a named pipe, which is similar to a file. Anything that is written to this file-like object will be picked up by the chatting script and communicated to the Arduino, line by line.
Here's the old code as well as the new code:
The syntax for reading from the pipe is a little clunky. I wanted it to be non-blocking, because otherwise the program halts if there is nothing to read. But the non-blocking read will raise an error whenever no data is found. So we catch that exception and ignore it.
To create the pipe named TO_DEV, we just need to run:
os.mkfifo('TO_DEV')
Now you can write to the pipe, either from another terminal like so:
echo "MESSAGE" > TO_DEV
This automatically appends a newline.
Or from another Python script:
pipeout = os.open('TO_DEV', os.O_WRONLY)
os.write(pipeout, 'MESSAGE\n')
Here you have to add your own newline.
Next time I'll package this up into a complete script and demonstrate it.
To create the pipe named TO_DEV, we just need to run:
os.mkfifo('TO_DEV')
Now you can write to the pipe, either from another terminal like so:
echo "MESSAGE" > TO_DEV
This automatically appends a newline.
Or from another Python script:
pipeout = os.open('TO_DEV', os.O_WRONLY)
os.write(pipeout, 'MESSAGE\n')
Here you have to add your own newline.
Next time I'll package this up into a complete script and demonstrate it.