(Automated edit: added dates to templates)
(reword;http->https;don't advertise;use syntaxhighlight;if this only works in py2 then use py2 syntax blin)
 
(2 intermediate revisions by one other user not shown)
Line 1: Line 1:
 
{{External Programs}}
 
{{External Programs}}
{{Wiki Standards|lots of 1st person|date=July 2018}}
+
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]].
Here are some instructions for how to communicate with Scratch using [[Remote Sensor Connections]] from a Python program. It includes a minimal GUI window that prompts the user for a message to broadcast to Scratch. If you have Python 3.x, see [[Communicating to Scratch via Python|this article]].
 
  
There are also a few '''[[Python#Networking|Python libraries]]''' you can use to interact with Scratch, which may be easier.
+
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.  You can run it 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.
* You can get the latest version of Python from [http://python.org here].
+
* The latest version of Python is available [https://python.org here].
* You can get a free Python development environment from Active State
 
  
== Enable Remote Sensor Connections ==
+
== Enabling Remote Sensor Connections ==
* In your Scratch [[project]], right click on one of the sensor tiles and click "enable remote sensor connections". You must do this to connect to Python.
+
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 ==
+
== 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. Also, if you are using the IDLE editor for Python, make a new window in that. Name the file SendBroadcast.py (it can be named anything you want if you have .py at the end). If you are using TextEdit, press Shift-Command-T to convert the document to plain text; you should see the formatting bar at the top 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.
  
Let's start by importing everything:
+
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 28: Line 26:
 
from tkSimpleDialog import askstring
 
from tkSimpleDialog import askstring
 
root = Tk()
 
root = Tk()
root.withdraw()</pre>
+
root.withdraw()</syntaxhighlight>
  
Next, let's 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>
  
Now, we create the function that actually sends the broadcast to Scratch:
+
Then, create the function that sends the broadcast to Scratch:
 
+
<syntaxhighlight lang="python">def sendScratchCommand(cmd):
<pre>def sendScratchCommand(cmd):
 
 
     n = len(cmd)
 
     n = len(cmd)
 
     a = array('c')
 
     a = array('c')
Line 50: 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>
  
The last part is creating user input to show what broadcast to send to Scratch:
+
Lastly, create a user input to show what broadcast would be sent to Scratch:
 
+
<syntaxhighlight lang="python">while True:
<pre>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:
 
+
<syntaxhighlight lang="python">from array import array
<pre>from array import array
 
 
import socket
 
import socket
 
import time
 
import time
Line 74: 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 93: 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>
  
* If it works you should see Python say that it has connected, and then it will 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
* Now, in Scratch create a [[script]] that starts with the "when I receive beat."  If you restart 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.
* You can also see the value of the note variable being changed by Python; it 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
* If you send a [[broadcast]] from Scratch, you will see it print out on the Python Console.
+
* Sending a [[broadcast]] from Scratch will be logged in the Python Console.
* If you create or update a global [[variable]] in Scratch, you will see that on the Python Console.
+
* Creating or updating a global [[variable]] in Scratch will be logged in the Python Console.
  
 
[[Category:Scratch Connections Tutorials]]
 
[[Category:Scratch Connections Tutorials]]
 
[[Category:Scratch Networking]]
 
[[Category:Scratch Networking]]

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.