#! /usr/bin/python

# Scratch client test program
# Demonstrates the Scratch Network Connection Functionality


# Adopted from program posted by "rubiks_cube_guy238" on 2009-07-02
# at http://scratch.mit.edu/forums/viewtopic.php?id=43522


# Right click on sensor tile to enable remote server connections

from array import array
import socket

HOST = '127.0.0.1'

PORT = 42001

# sendScratchCommand(cmd)
# this function packages a message according the Scratch Networking Protocol
# and then sends it off
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)

# Make a connection to Scratch
print("connecting to Scratch")
scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
scratchSock.connect((HOST, PORT))
print("connected  to Scratch")

# Emulate the green flag being clicked (optional)
sendScratchCommand('broadcast "moveit"')

scratchSock.close()
