'''
PythonSerialChatv1.py

    @author: Hamish Trolove
    @website: www.techmonkeybusiness.com
    @copyright: Nah – Do what you like with it.
  
This is a script which will ultimately be used in the Blender Game Engine.  It takes a stream of data
in a CSV form that has been issued by an Arduino through the serial port. At this stage the code just
listens to the Serial port, reads the incoming data stream and splits it up into some useful variables.

When run in the Blender Game Engine or Pyzo you will need to have pySerial installed in your Blender Python
or Pyzo Site-packages directory for this to work.  See www.techmonkeybusiness.com.
You will also need an Arduino connected and running a sketch to issue serial messages with the
following format.  This development program was run in Pyzo2105 with the pyserial library copied into the pyzo2015a/lib/python3.4/site-packages location.

Data,14,-127,
Data,13,-127,
Data,13,-127,
Data,13,-127,
Data,13,-126,
Data,13,-127,
Data,13,-127,
Data,13,-127,
Data,13,-127,

In this case the header is "Data" and the next two numbers are from an XY joystick
potentiometer attached to the Analogue pins.

Python reads this from the serial port

b'Data,13,-127,\r\n'


'''


import serial

port0 = "/dev/ttyUSB0"     # For a Linux machine.
port1 = "/dev/ttyUSB1"     # Just in case

try:
    arduino = serial.Serial(port0, 9600)
except serial.serialutil.SerialException:
    arduino = serial.Serial(port1, 9600)

runMe = 1
ArduRunSig = 1

while runMe:
    data = str(arduino.readline())
    print ("Got:", data)
    ArduData = data.split(",")
    print(ArduData)
    print("X",ArduData[1],"Y",ArduData[2])
    ArduRunSig = ArduRunSig + 1
    XaxisVal = int(ArduData[1])
    YaxisVal = int(ArduData[2])
    print(XaxisVal,YaxisVal)
    if ArduRunSig > 800:
        runMe = 0

print("Finished")
