(Updated to editing standards: added links, edited content to be more accurate, fixed some tenses, deleted extra words, removed 1st POV)
(reword;http->https;don't advertise;use syntaxhighlight;if this only works in py2 then use py2 syntax blin)
 
(One intermediate revision by one other user not shown)
Line 1: Line 1:
 
{{External Programs}}
 
{{External Programs}}
This is a tutorial on how to communicate with [[Scratch]] using [[Remote Sensor Connections]] through a Python program. It includes a minimal GUI window that prompts the user for a message to broadcast to Scratch. If the version used is Python 3.x, see [[Communicating to Scratch via Python|this article]].
+
This is a tutorial on how to communicate with [[Scratch]] using [[Remote Sensor Connections]] through a [[Python]] program. It includes a minimal GUI window that prompts the user for a message to broadcast to Scratch. If the version in use is Python 3.x, see [[Communicating to Scratch via Python|this article]].
  
There are also a few '''[[Python#Networking|Python libraries]]''' that can be used to interact with Scratch, which may be simpler.
+
There are also a few [[Python#Networking|Python libraries]] that can be used to interact with Scratch, which may be simpler to use.
  
 
== Install Python ==
 
== Install Python ==
 
* Mac OS X comes with Python built in.  It can be run from the command line using the terminal program via the command <code>python</code> or <code>python &lt;file&gt;</code>, with the file's path.
 
* Mac OS X comes with Python built in.  It can be run from the command line using the terminal program via the command <code>python</code> or <code>python &lt;file&gt;</code>, with the file's path.
* The latest version of Python is available [http://python.org here].
+
* The latest version of Python is available [https://python.org here].
* A free Python development environment is available from Active State
 
  
 
== Enabling Remote Sensor Connections ==
 
== Enabling Remote Sensor Connections ==
* In a [[Scratch]] [[project]], right click on one of the sensor tiles and click "enable remote sensor connections". This is necessary for the connection to be made.
+
In a Scratch [[project]], right click on one of the sensor tiles and click "enable remote sensor connections". This is necessary for the connection to be made.
  
== Creating Sample Client Program ==
+
== Sample Client Program ==
Sample client program to send messages and update variable:
+
Below is a sample client program to send messages and update variable:
  
Start off by creating a new Plain Text File in TextEdit for Mac or Notepad for Windows. If the IDLE editor for Python is being used, open it. Name the file SendBroadcast.py (it can be named anything, however, it must have ".py" at the end). For use in TextEdit, press Shift-Command-T to convert the document to plain text; the formatting bar at the top will disappear.
+
The first step is to create a new plaintext file. This can be done in {{wp|IDLE}}, if it is available, or in the operating system's plaintext editor. Name the file SendBroadcast.py (not necessarily, but it's good practice to name Python files with a <code>.py</code> at the end). If using TextEdit, press {{kp|Cmd|Shift|T}} to convert the document to a plaintext document; a sign of this being successful is the formatting bar disappearing.
  
 
Start by importing all of the necessary python modules and initiating Tkinker:
 
Start by importing all of the necessary python modules and initiating Tkinker:
 
{{note|This tutorial only works with Python 2.x. Later versions do not have the modules.}}
 
{{note|This tutorial only works with Python 2.x. Later versions do not have the modules.}}
<pre>from array import array
+
<syntaxhighlight lang="python">from array import array
 
import socket
 
import socket
 
import time
 
import time
Line 27: Line 26:
 
from tkSimpleDialog import askstring
 
from tkSimpleDialog import askstring
 
root = Tk()
 
root = Tk()
root.withdraw()</pre>
+
root.withdraw()</syntaxhighlight>
  
 
Next, add some text input to choose what IP to connect to:
 
Next, add some text input to choose what IP to connect to:
<pre>PORT = 42001
+
<syntaxhighlight lang="python">PORT = 42001
 
HOST = askstring('Scratch Connector', 'IP:')
 
HOST = askstring('Scratch Connector', 'IP:')
 
if not HOST:
 
if not HOST:
     sys.exit()
+
     sys.exit(1)
  
print("connecting...")
+
print "Connecting..."
 
scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
scratchSock.connect((HOST, PORT))
 
scratchSock.connect((HOST, PORT))
print("connected")</pre>
+
print "Connected!"</syntaxhighlight>
  
 
Then, create the function that sends the broadcast to Scratch:
 
Then, create the function that sends the broadcast to Scratch:
<pre>def sendScratchCommand(cmd):
+
<syntaxhighlight lang="python">def sendScratchCommand(cmd):
 
     n = len(cmd)
 
     n = len(cmd)
 
     a = array('c')
 
     a = array('c')
Line 48: Line 47:
 
     a.append(chr((n >>  8) & 0xFF))
 
     a.append(chr((n >>  8) & 0xFF))
 
     a.append(chr(n & 0xFF))
 
     a.append(chr(n & 0xFF))
     scratchSock.send(a.tostring() + cmd)</pre>
+
     scratchSock.send(a.tostring() + cmd)</syntaxhighlight>
  
 
Lastly, create a user input to show what broadcast would be sent to Scratch:
 
Lastly, create a user input to show what broadcast would be sent to Scratch:
<pre>while True:
+
<syntaxhighlight lang="python">while True:
 
     msg = askstring('Scratch Connector', 'Send Broadcast:')
 
     msg = askstring('Scratch Connector', 'Send Broadcast:')
 
     if msg:
 
     if msg:
         sendScratchCommand('broadcast "' + msg + '"')</pre>
+
         sendScratchCommand('broadcast "' + msg + '"')</syntaxhighlight>
  
 
The entire program:
 
The entire program:
<pre>from array import array
+
<syntaxhighlight lang="python">from array import array
 
import socket
 
import socket
 
import time
 
import time
Line 70: Line 69:
 
HOST = askstring('Scratch Connector', 'IP:')
 
HOST = askstring('Scratch Connector', 'IP:')
 
if not HOST:
 
if not HOST:
     sys.exit()
+
     sys.exit(1)
  
print("Connecting...")
+
print "Connecting..."
 
scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
scratchSock.connect((HOST, PORT))
 
scratchSock.connect((HOST, PORT))
print("Connected!")
+
print "Connected!"
  
 
def sendScratchCommand(cmd):
 
def sendScratchCommand(cmd):
Line 89: Line 88:
 
     msg = askstring('Scratch Connector', 'Send Broadcast:')
 
     msg = askstring('Scratch Connector', 'Send Broadcast:')
 
     if msg:
 
     if msg:
         sendScratchCommand('broadcast "' + msg + '"')</pre>
+
         sendScratchCommand('broadcast "{}"'.format(msg))</syntaxhighlight>
  
 
* Python should log that a successful connection has been made, it will then print the messages it is sending
 
* Python should log that a successful connection has been made, it will then print the messages it is sending
* In Scratch, create a [[script]] that starts with the "when I receive beat."  If you run the Python program, Scratch should respond.
+
* In Scratch, create a [[script]] that starts with <sb>when I receive [beat v]</sb>. Running the Python program and typing in "beat" should cause Scratch to react.
 
* The value of the note variable being changed by Python appears in the "sensor value" [[Blocks|block]]'s menu
 
* The value of the note variable being changed by Python appears in the "sensor value" [[Blocks|block]]'s menu
 
* Sending a [[broadcast]] from Scratch will be logged in the Python Console.
 
* Sending a [[broadcast]] from Scratch will be logged in the Python Console.

Latest revision as of 09:16, 14 February 2019

SandCastleIcon.png This page has links to websites or programs not trusted by Scratch or hosted by Wikipedia. Remember to stay safe while using the Internet, as we can't guarantee the safety of other websites.

This is a tutorial on how to communicate with Scratch using Remote Sensor Connections through a Python program. It includes a minimal GUI window that prompts the user for a message to broadcast to Scratch. If the version in use is Python 3.x, see this article.

There are also a few Python libraries that can be used to interact with Scratch, which may be simpler to use.

Install Python

  • Mac OS X comes with Python built in. It can be run from the command line using the terminal program via the command python or python <file>, with the file's path.
  • The latest version of Python is available here.

Enabling Remote Sensor Connections

In a Scratch project, right click on one of the sensor tiles and click "enable remote sensor connections". This is necessary for the connection to be made.

Sample Client Program

Below is a sample client program to send messages and update variable:

The first step is to create a new plaintext file. This can be done in IDLE, if it is available, or in the operating system's plaintext editor. Name the file SendBroadcast.py (not necessarily, but it's good practice to name Python files with a .py at the end). If using TextEdit, press ⌘ Cmd+⇧ Shift+T to convert the document to a plaintext document; a sign of this being successful is the formatting bar disappearing.

Start by importing all of the necessary python modules and initiating Tkinker:

Note Note: This tutorial only works with Python 2.x. Later versions do not have the modules.
from array import array
import socket
import time
import sys

from Tkinter import Tk
from tkSimpleDialog import askstring
root = Tk()
root.withdraw()

Next, add some text input to choose what IP to connect to:

PORT = 42001
HOST = askstring('Scratch Connector', 'IP:')
if not HOST:
    sys.exit(1)

print "Connecting..."
scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
scratchSock.connect((HOST, PORT))
print "Connected!"

Then, create the function that sends the broadcast to Scratch:

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)

Lastly, create a user input to show what broadcast would be sent to Scratch:

while True:
    msg = askstring('Scratch Connector', 'Send Broadcast:')
    if msg:
        sendScratchCommand('broadcast "' + msg + '"')

The entire program:

from array import array
import socket
import time
import sys

from Tkinter import Tk
from tkSimpleDialog import askstring
root = Tk()
root.withdraw()

PORT = 42001
HOST = askstring('Scratch Connector', 'IP:')
if not HOST:
    sys.exit(1)

print "Connecting..."
scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
scratchSock.connect((HOST, PORT))
print "Connected!"

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)

while True:
    msg = askstring('Scratch Connector', 'Send Broadcast:')
    if msg:
        sendScratchCommand('broadcast "{}"'.format(msg))
  • Python should log that a successful connection has been made, it will then print the messages it is sending
  • In Scratch, create a script that starts with when I receive [beat v]. Running the Python program and typing in "beat" should cause Scratch to react.
  • The value of the note variable being changed by Python appears in the "sensor value" block's menu
  • Sending a broadcast from Scratch will be logged in the Python Console.
  • Creating or updating a global variable in Scratch will be logged in the Python Console.