-
Notifications
You must be signed in to change notification settings - Fork 17
/
scratchrsc.rb
78 lines (66 loc) · 1.62 KB
/
scratchrsc.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#
# scratchrsc.rb is based on the one file library(http://pastebin.com/XCqPeeyW)
# created by Scratcher logiblocs(http://scratch.mit.edu/users/logiblocs/).
#
# it uses the Remote Sensor Connections protocol (http://wiki.scratch.mit.edu/wiki/Remote_Sensors_Protocol) to talk to Scratch over sockets
require "socket"
require "scanf"
class RSCWatcher
def initialize(host="127.0.0.1")
puts "initialize"
@socket = TCPSocket.open(host, 42001)
onConnect
end
def sendCommand(cmd)
i = cmd.length
@socket.write [i].pack("I").reverse + cmd
end
def socket
@socket
end
def handle_command
message = @socket.recv(@socket.recv(4).reverse.unpack("I")[0])
if message.include? "sensor-update"
split = message.split
a = ""
split.length.times do |i|
unless i == 0
if i % 2 == 1
a = split[i]
end
if i % 2 == 0
on_sensor_update a.gsub(/"/, ''), split[i].gsub(/"/, '')
end
end
end
end
if message.include? "broadcast"
puts message
split = message.split
if split.length == 2
__on_broadcast split[1].gsub(/"/, '')
end
end
end
def __on_broadcast(name)
method = "broadcast_#{name}"
if self.respond_to? method
self.send method
else
on_broadcast(name)
end
end
def on_broadcast(name)
end
def on_sensor_update(name, value)
end
def broadcast(name)
sendCommand("broadcast \"#{name}\"")
end
def sensor_update(name,value)
sendCommand("sensor-update \"#{name}\" \"#{value}\"")
end
private
def onConnect
end
end