Friday 20 May 2016

Connecting to the Novag Citrine using Python

I have been learning Python 3, and wrote a simple program to connect to the Novag Citrine:

import serial
port = '/dev/ttyUSB0'
ser = serial.Serial(port, 57600, timeout=0.05)
print(ser.name, 'opened')
print("When prompted, enter a Novag command, '' to read, or q to quit")

while True:
    while True:
        byteline = ser.readline()
        if byteline == b'':
            break
        print(byteline.decode(encoding='UTF-8')[:-1])

    command = input('Command? ')
    if command == 'q':
        break
    elif command != '':
        command += '\r\n'
        ser.write(command.encode(encoding='UTF-8'))


ser.close()

I tested this program on Ubuntu Linux. It should also work on Windows, a Mac and any other platform that supports Python 3. The variable "port" has to be set to the serial port that you are using to connect to the Citrine. Here is a sample session, in which the moves for white are entered on the Citrine, and the moves for black are sent from the PC:

/dev/ttyUSB0 opened
When prompted, enter a Novag command, '' to read, or q to quit
Command?
New Game
Command? u on
.Referee on
Command? x on
Xmit on
Command? l tr8
Level tr 8
Command?
M   1   e2-e4
Command? me7e5
Command? me7e5
M   1,  e7-e5
Command?
M   2   g1-f3
Command? mb8c6
Command? mb8c6
M   2,  b8-c6
Command?
M   3   d2-d4
Command? me5d4
Command? me5d4
M   3,  e5xd4
Command?
M   4   d1xd4
Command?
T   4   d1xd4
Command?
M   4   f3xd4
Command? q


Everything appears to work. After entering a move for white on the Citrine, enter an empty line as a command to read the reply from the PC. As noted previously, it is necessary to send the moves for black twice from the PC. Typing 'q' ends the session. Responses from the Citrine are buffered, and can be read after more commands have been sent.

No comments:

Post a Comment