[ Not Finished ]
Now I'm sure many wonder how they can connect different programming languages ( like Python, Ruby, Java, C#, C, C++, etc ). I'm going to try to make a guide on how to do this.
One thing you will need to do is turn on "Remote Sensors":
In the Sensors section of blocks, if you go to the bottom of the list of blocks, Right-Click ( or hold down the left-key for about 2-3 seconds ) and a menu will pop up, there is an option called "enable remote sensor connection" click that and a box should show up say "Remote Sensor Connections enabled". That is the first step to letting Python or any other language connect to Scratch.
Now how you communicate is through variables or broadcasts. This Python Program shows how to use both:
# Scratch client test program
# sends 10 "beat" broadcasts to Scratch
from array import array
import socket
import time
HOST = '127.0.0.1'
PORT = 42001
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)
print a.tostring() + cmd
print("connecting...")
scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
scratchSock.connect((HOST, PORT))
print("connected")
for i in xrange(10):
sendScratchCommand('sensor-update note ' + str(60 + (2 * i)) + ' beats 0.4')
sendScratchCommand('broadcast "beat"')
print("beat!")
time.sleep(0.5)
print("closing socket...")
scratchSock.close()
print("done")There's the code: sendScratchCommand('sensor-update note ' + str(60 + (2 * i) ) + ' beats 0.4')
That sets the variable "note" to whatever "i" is ( for i in xrange(10) # Repeats the code 10 times, i = the amount of times it has run the code ) will set "note" to 60 + 2 * i for example:
The first time round i will be 62, the second time 64, third time 66 and so on.
To find this variable you will need to run the Python Code above. When that is finished, open up the Scratch window go to Sensing then
The line after that is how to send broadcasts: sendScratchCommand('broadcast "beat"')
That will broadcast whatever is in the double-quotes ( " " ). Though the 'broadcast "broadcast"' needs to be in single-quotes.
And that is how you get Python to send things to Scratch. Now you will probably be wondering, how do you get Scratch to tell Python stuff?
This is where things start to get complicated:
Credit goes to the person that made this script ( I forgot who, sorry ):
# Parse Data Definitions
def parseData(str):
#Check for a broadcast
e = re.search('broadcast\s\"(.*)\"',str)
if e:
#We have a broadcast!
return 'parsed = broadcastIn("'+e.group(1)+'")'
#Check for a sensor-update with quoted second value (string)
e = re.search('sensor-update\s\"(.*?)\"\s\"(.*?)\"',str)
if e:
#Got one!
return 'parsed = sensorUpdateIn("'+e.group(1)+'","'+e.group(2)+'")'
#Look for a sensor-update with a numeric second value
e = re.search('sensor-update\s\"(.*?)\"\s([-|\d|.]+)',str)
if e:
#Success!
return 'parsed = sensorUpdateIn("'+e.group(1)+'","'+e.group(2)+'")'What this code does is take the data that is sent from Scratch and finds out if it's a variable update or broadcast.
So you will need to add ifs like: if parsed == 'broadcast start': [Python Reply Code]
------
So, to connect to Scratch locally or over the internet you would need to set the IP ( 127.0.0.1 is the local computer IP ) and Port (42001 is the Scratch port ). Through these two things you can connect to Scratch through any Programming Language. Like Java ( only connects to Scratch, does nothing else since I just looked up this code on the internet xD ):
try {
InetAddress addr = InetAddress.getByName("127.0.0.1");
int port = 42001;
Socket socket = new Socket(addr, port);
} catch (UnknownHostException e) {
} catch (IOException e) {
}So that's basically how it's done, for each programming language search "[programming language] networking" or search for your languages sockets.
Any questions?
Last edited by Magnie (2011-04-23 10:08:27)
Offline
And where do we find scratchSock? I'm wondering if it's possible to use it in other languages such as C++ or VB...
Offline
To stop the blocks glitch, use )[b][/b]).
Offline
TheSuccessor wrote:
To stop the blocks glitch, use )[b][/b]).
![]()
Even better avoid the brackets
Offline
As it says on the top, it's not finished.
I hadn't finished and I had to close the browser.
But LS97: I am unsure what you mean by the first question, but for the second, yes you can. You can use any Programming Language with Socket connects.
Offline
LS97 wrote:
TheSuccessor wrote:
To stop the blocks glitch, use )[b][/b]).
![]()
Even better avoid the brackets
![]()
Or disable smilies.
Last edited by johnnydean1 (2011-04-23 10:30:22)
Offline
Hehe, thanks fg123.
You'll have to link me to Prism ( I haven't seen it yet o.O )
Offline
I tried but it didn't work... I'm trying to figure out what I should say for IP.
I have a laptop which uses a wireless connection...
also, can I have a description of what is supposed to happen?
because nothing happens...
Offline
If you are trying to connect Python to Scratch from another computer you will want to change the IP from '127.0.0.1' to the computer's IP which you will need to find out ( Search for a way to find the computer's IP for your specific Operating System ).
For the example above, there is a script in Scratch ( When I Receive "beat" broadcast: Play note "sensor variable note" ) and it's supposed to play a note off the piano ( or whatever instrument you set it to ).
Offline
midnightleopard wrote:
what is the >> operator?
Offline
LS97 wrote:
And where do we find scratchSock? I'm wondering if it's possible to use it in other languages such as C++ or VB...
scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
that's what it sets itself to at the start, not sure if that's what you mean.
Offline
what is the purpose of the bitshift in the program?
Offline
midnightleopard wrote:
what is the purpose of the bitshift in the program?
Everything in a computer is stored in bits and bytes (8 bits long). For example, a color can be stored in 3 bytes in binary:
10011010 00110101 1101100
which is 5053164 in decimal.
The left 8 bytes are red, the middle bits are green, and the right bits are blue. How are we supposed to get the green value out of that number? Bit shifting! It simply shifts the bits left or right by a certain number.
5053164 >> 8 is doing this:
10011010001101011101100
100110100011010|11101100 These extra bits are choped of the end.
100110100011010Now our number is 19738. We still don't have what we need though. We need to get rid of the bits to the left yet. Let's use some bit logic. :D How about bit AND with a mask of 0xFF. A mask will only let some of the bits stay on. 0xFF with only let the right 8 bits in our number stay on:
1111111 Our mask (0xFF is hex, and in decimal it is 255 which is 11111111 in binary)
|| | Bit AND compares all the bits like boolean values. The three '|'s are the bits that stay on
100110100011010
0011010 = 26 in decimalThe green value is 26! I think I just taught myself a lot about bits shifting. :D
EDIT: Ugh, blocks messed up my post.
Last edited by MathWizz (2011-12-17 09:51:37)
Offline
MathWizz wrote:
Everything in a computer is stored in bits and bytes (8 bits long). For example, a color can be stored in 3 bytes in binary:
Code:
10011010 00110101 1101100which is 5053164 in decimal.
The left 8 bytes are red, the middle bits are green, and the right bits are blue. How are we supposed to get the green value out of that number? Bit shifting! It simply shifts the bits left or right by a certain number.
5053164 >> 8 is doing this:Code:
10011010001101011101100 100110100011010|11101100 These extra bits are choped of the end. 100110100011010Now our number is 19738. We still don't have what we need though. We need to get rid of the bits to the left yet. Let's use some bit logic.
How about bit AND with a mask of 0xFF. A mask will only let some of the bits stay on. 0xFF with only let the right 8 bits in our number stay on:
Code:
1111111 Our mask (0xFF is hex, and in decimal it is 255 which is 11111111 in binary) || | Bit AND compares all the bits like boolean values. The three '|'s are the bits that stay on 100110100011010 0011010 = 26 in decimalThe green value is 26! I think I just taught myself a lot about bits shifting.
![]()
EDIT: Ugh, blocks messed up my post.
Thanks a lot! I have been attempting to reverse-engineer that function ever since scratch connections came out. I spent all morning learning about base changing.
Offline
could you explain the mask in more detail?
Offline
midnightleopard wrote:
could you explain the mask in more detail?
A bitwise "mask" operates on a neat feature of the bitwise and (&) operator. The and operator goes through the bits of two numbers, one at a time, and puts a 1 in the result if both bits are 1, and a 0 otherwise. It's very similar to a logical and, but it operates on bits rather than Booleans. For example:
101110100 & || | 011101110 = 001100100
Masks work by using the and operator with a constant operand, usually one that has a single '1' bit (for flags or options, which can then be combined with |) or a couple consecutive '1' bits. This lets one isolate a section of a number. This is useful for colors, because Squeak stores colors as a single 32-bit rgb number which has three 10-bit color components (red, green, and blue) embedded in it. To extract, for example, the green, one would first shift the number to the right to get rid of the red component:
00110101101011100101110100101110 (32 bits) >> 10 =
0011010110101110010111 (22 bits)Then one would use a mask containing all 0s but the first ten bits, which contain 1s:
0011010110101110010111 (22 bits) &
||| | |||
0000000000001111111111 (mask, 10 bits) =
0000000000001110010111 = 1110010111 (10 bits)That's the green component.
Last edited by nXIII (2011-12-17 13:00:46)
Offline
umm if the order is red, green, blue then why not just
colour = 100110101110001101011010110001; //then shift it ten bits to the right result = colour >> 10; //then shift that result ten to the left to isolate the middle ten green = colour << 10;
???
Offline
midnightleopard wrote:
umm if the order is red, green, blue then why not just
Code:
colour = 100110101110001101011010110001; //then shift it ten bits to the right result = colour >> 10; //then shift that result ten to the left to isolate the middle ten green = colour << 10;???
You will still end up with the red bits to the left.
Offline
MathWizz wrote:
midnightleopard wrote:
umm if the order is red, green, blue then why not just
Code:
colour = 100110101110001101011010110001; //then shift it ten bits to the right result = colour >> 10; //then shift that result ten to the left to isolate the middle ten green = colour << 10;???
You will still end up with the red bits to the left.
wouldn't it shift them off?
Offline