예제 #1
0
  def __init__(self, scratchIO_):
    self.__scratchIO = scratchIO_

    # Functions that can be parsed
    self.availableFunctions = ['config','read','write']

    # Set the defaults for the connection
    host = "localhost"
    port = 42001
    self.__aliases = {}

    # If the connection setting are given in the configuration file,
    # then update them.
    if self.__scratchIO.config != None:
      if self.__scratchIO.config.has_section("ScratchConnection"):
        host = self.__scratchIO.config.get("ScratchConnection","host")
        port = self.__scratchIO.config.getint("ScratchConnection","port")

    # Open a Scratch connection.
    print(" >> Connecting to Scratch on %s using port %d" % (host, port))
    try:
      self.scratchConnection = scratch.Scratch(host, port) 
    except scratch.ScratchError:
      print("ERROR: Cannot connect to Scratch.")
      print("       Start Scratch with remote sensors enabled before running this program.")
      sys.exit(1)
예제 #2
0
 def test_Init(self):
     """Verify scratch creates the directory if it doesn't exist."""
     new_scratchdir = os.path.join(self._scratchdir, 'testdir')
     assert not os.path.exists(new_scratchdir)
     # Only initialize the scratch to ensure it creates |new_scratchdir|
     scratch.Scratch(new_scratchdir)
     assert os.path.exists(new_scratchdir)
     os.rmdir(new_scratchdir)
def connect():
    try:
        return scratch.Scratch()
    except scratch.ScratchError:
        print _(
            "Error: Unable to connect to Scratch. Scratch may be not running or the remote sensor connections may be not enabled."
        )
        return None
def connect():
    try:
        #return scratch.Scratch(host='192.168.2.1', port=42001)
        return scratch.Scratch(host='192.168.11.24', port=42001)
    except scratch.ScratchError:
        print _(
            "Error: Unable to connect to Scratch. Scratch may be not running or the remote sensor connections may be not enabled."
        )
        return None
예제 #5
0
 def run(self):
     global s
     global scratchProgress
     while (s == None):
         try:
             s = scratch.Scratch()
         except Exception:
             time.sleep(1)
     scratchProgress.set("Connected")
예제 #6
0
def main():
    s = scratch.Scratch()
    capture = cv.CaptureFromCAM(0)
    cv.NamedWindow("Track", 1)

    while True:
        #capture frame
        frame_o = cv.QueryFrame(capture)
        frame = cv.CreateImage((frame_o.width * 3 / 8, frame_o.height * 3 / 8),
                               frame_o.depth, frame_o.nChannels)
        cv.Resize(frame_o, frame)
        cv.Smooth(frame, frame, cv.CV_GAUSSIAN, 3, 3)

        #Convert to HSV
        imgHSV = cv.CreateImage(cv.GetSize(frame), 8, 3)
        cv.CvtColor(frame, imgHSV, cv.CV_BGR2HSV)

        #Thresh
        imgThreshed = cv.CreateImage(cv.GetSize(frame), 8, 1)
        cv.InRangeS(imgHSV, cv.Scalar(0, 124, 221), cv.Scalar(10, 255, 256),
                    imgThreshed)
        cv.Smooth(imgThreshed, imgThreshed, cv.CV_GAUSSIAN, 3, 3)

        mat = cv.GetMat(imgThreshed)
        moments = cv.Moments(mat)

        moment10 = cv.GetSpatialMoment(moments, 1, 0)
        moment01 = cv.GetSpatialMoment(moments, 0, 1)
        area = cv.GetCentralMoment(moments, 0, 0)

        if area > 1000:
            posX = int(moment10 / area)
            posY = int(moment01 / area)

            if posX >= 0 and posY >= 0:
                print("X: " + str(posX) + ", Y: " + str(posY))
                cv.Rectangle(frame, (posX - 10, posY - 10),
                             (posX + 10, posY + 10), cv.RGB(0, 255, 0))
                s.sensorupdate({'X': posX})
                s.sensorupdate({'Y': posY})

        cv.ShowImage("Track", frame)
        k = cv.WaitKey(70)
        if k % 0x100 == 27:
            break
예제 #7
0
    def setUp(self):
        """Setup each test.

    Prepare a Scratch on a temp directory & prepare a convenience entry.
    """
        super(TestScratch, self).setUp()
        self._scratchdir = tempfile.mkdtemp()
        self._scratch = scratch.Scratch(self._scratchdir)
        self._dport = 31234
        self._dserials = ['9', '17']
        self._dpid = 1827
        # Commonly used test entry
        self._entry = {
            'pid': self._dpid,
            'serials': self._dserials,
            'port': self._dport,
            'active': False
        }
예제 #8
0
# -*- coding: utf-8 -*-

import scratch
import subprocess

# ScratchのIPアドレス
s = scratch.Scratch(host='192.168.11.20')
s.connect()


def listen():
    while True:
        try:
            yield s.receive()
        except scratch.ScratchError:
            s.disconnect()
            raise StopIteration
        except KeyboardInterrupt:
            print "Scratch: Disconnected from Scratch"
            s.disconnect()
            break


for msg in listen():
    if msg[0] == 'broadcast':
        # デバッグ用
        print msg
    elif msg[0] == 'sensor-update':
        if 'shell' in msg[1]:
            val = msg[1]['shell']
            cmd = str(val)
예제 #9
0
# DEALINGS IN THE SOFTWARE.
import sys, rmap, threading, time, math, socket, scratch, subprocess, datetime
import rmapcfg
from PiStorms import PiStorms

debug = False
device_dict = rmap.dict
read_dict = rmap.read_dict
command_array = []
command_array1 = []
string_message = ""
psm = PiStorms()
lasttime = int(round(time.time() * 1000))
# Connect to Scratch
try:
    s = scratch.Scratch(host=rmapcfg.host, port=rmapcfg.port)
    if s.connected:
        rmap.rmap_print("Connected")
except scratch.ScratchError:
    rmap.rmap_print(
        "Scratch is either not opened or remote sensor connections aren't enabled"
    )

# Broadcast 'READY' to Scratch
try:
    s.broadcast('READY')
    time.sleep(.5)
except NameError:
    #pass
    print "Did not send Ready"
예제 #10
0
#ThingPeriod=float( conf.get("period","thing_sampling"))






### connect to scratch
#
print("conneting to scratch")
hostip=conf.get("setting","host")

print(hostip)

s=scratch.Scratch(host=hostip)


################
#
# local DBの設定
#

key = [("cnt","int"),("time","text"),("d0","real"),("d1","real"),("d2","real")]
#key={"cnt":"int","time":"text","temp":"real","humid":"real","th_avez":"real","th_std":"real","pressure":"real","rawdata":"text"}
print(conf.get("setting","dbfile"))
db=sql_lib.miyadb(conf.get("setting","dbfile"),key)

#dbの中身を削除する
db.clear()
db.init_table2()
예제 #11
0
#!/usr/bin/env python
import scratch, sys
scratch.Scratch().sensorupdate({sys.argv[1]: sys.argv[2]})
예제 #12
0
 def __init__(self, attribs):
     self.server_address = attribs["server_address"]
     self.server_port = attribs.get("server_port", 42001)
     self.scratch_connection = scratch_ex.Scratch(self.server_address,
                                                  port=self.server_port)
예제 #13
0
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#

import scratch
from subprocess import call
import sys

# Connect to Scratch host; by default on local host
hostname = 'localhost'
if len(sys.argv) == 2:
    hostname = sys.argv[1]
s = scratch.Scratch(host=hostname)


# Receive and queue Scratch messages
def listen():
    while True:
        try:
            yield s.receive()
        except scratch.ScratchError:
            raise StopIteration


# Now you can iterate over all the messages from Scratch
for msg in listen():
    # Can be sensor-update or broadcast
    if msg[0] != 'broadcast':
# -*- coding: utf-8 -*-

import scratch

# scratch1のIPアドレス
s = scratch.Scratch(host='192.168.11.20')
s.connect()

# scratch2のIPアドレス
s2 = scratch.Scratch(host='localhost')
s2.connect()


def listen():
    while True:
        try:
            yield s.receive()
        except scratch.ScratchError:
            s.disconnect()
            s2.disconnect()
            raise StopIteration
        except KeyboardInterrupt:
            print "Scratch: Disconnected from Scratch"
            s.disconnect()
            s2.disconnect()
            break


for msg in listen():
    if msg[0] == 'broadcast':
        # デバッグ用
예제 #15
0
    def run(self):
        while (True):
            message = s.receive()
            broadcasts = message['broadcast']
            sensors = message['sensor-update']
            if 'rumble' in broadcasts:
                wm.rumble = 1
                time.sleep(2)
                wm.rumble = 0
            if 'leds' in sensors:
                if sensors['leds'] >= 0 & sensors['leds'] <= 16:
                    wm.led = sensors['leds']


print("Connecting to Scratch")
s = scratch.Scratch(host='192.168.2.1')
s.connect(poll=False)

print("Press button 1 + 2 on your Wiimote.")
time.sleep(1)

s.sensorupdate({"CLASSIC_L_STICK_MAX": cwiid.CLASSIC_L_STICK_MAX})
s.sensorupdate({"CLASSIC_R_STICK_MAX": cwiid.CLASSIC_R_STICK_MAX})
s.sensorupdate({"IR_X_MAX": cwiid.IR_X_MAX})
s.sensorupdate({"IR_Y_MAX": cwiid.IR_Y_MAX})

wm = cwiid.Wiimote()
print("Wiimote connected.")
time.sleep(1)

wm.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC | cwiid.RPT_NUNCHUK | cwiid.RPT_IR
예제 #16
0
#!/usr/bin/env python

import rospy
import scratch
from threading import Thread
from robairmain.msg import MotorsCmd
from std_msgs.msg import Int8
from std_msgs.msg import Bool

client = scratch.Scratch(host='0.0.0.0', port=42001)
mcmd = MotorsCmd()

angleHead = 180
last_angleHead = 100

last_speedL = 0
last_speedR = 0


def callback_bumper_rear(data):
    rospy.loginfo(data.data)
    client.sensorupdate({'bumper_rear': data.data})


def callback_bumper_front(data):
    rospy.loginfo(data.data)
    client.sensorupdate({'bumper_front': data.data})


def callback_touch_left(data):
    rospy.loginfo(data.data)
예제 #17
0
#original
import sys
sys.path.append("../")

import common.sql_lib as sql_lib

import common.thingspeak as thingspeak
#import common.fswebcamtest as fswebcamtest

import sensor.grove_d6t as d6t_lib
import sensor.sht30_lib as sht30
import sensor.omron_2smpd_lib as omron_2smpd_lib

import scratch
import numpy
s=scratch.Scratch(host="192.168.11.28")
#s.connection()
a=0

configfile="./scratch.ini"
conf=configparser.ConfigParser()

if os.path.exists(configfile):
    conf.read(configfile)
else:
    conf.add_section("setting")
    conf.set("setting","D6T_type","8L")
#    conf.set("setting","dbfile","./hotel.db")
#    conf.set("setting","log","./log/")
#    conf.set("setting","camera","yes")
    conf.add_section("thingspeak")
예제 #18
0
# -*- coding: utf-8 -*-
import subprocess
import bluetooth
import scratch
import signal
import time
import re

#identyfikator usługi bluetooth
uuid = "00001101-0000-1000-8000-00805F9B34FB"
isRunning = True  #stan naszej aplikacji
isConnected = False  #stan połaczenia

core = scratch.Scratch()  #podłączenie się do scratcha
core.sensorupdate({'bt-recv': -1
                   })  #ustawienie początkowej wartości sesora "bt-recv" na -1

btServer = bluetooth.BluetoothSocket(
    bluetooth.RFCOMM
)  #utworzenie gniazda nasłuchującego na połączenie bluetooth
btClient = None  #przechowuje połaczenie z klientem

btServer.bind(("", 1))  #ustawiamy nasłuchiwanie na kanał 1
btServer.listen(1)  #ustawiamy maksymalną ilość jednoczesnych połączeń na jedno

#rozgłaszamy naszą usługę
bluetooth.advertise_service(
    btServer,
    "Raspberry Pi",
    service_id=uuid,
    service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
import serial
from time import sleep
import scratch


scr = scratch.Scratch()
PORT = "/dev/ttyACM3"
BAUD = 115200

s = serial.Serial(PORT)
s.baudrate = BAUD
s.parity   = serial.PARITY_NONE
s.databits = serial.EIGHTBITS
s.stopbits = serial.STOPBITS_ONE
s.readline()

while True:
    data = s.readline().decode('UTF-8')
    data_list = data.rstrip().split(' ')
    try:
        x, y, z, a, b = data_list
    except:
        pass

    scr.sensorupdate({'x' : x})
    scr.sensorupdate({'y' : y})
    scr.sensorupdate({'z' : z})
    scr.sensorupdate({'a' : a})
    scr.sensorupdate({'b' : b})    
    
s.close()
예제 #20
0
파일: GPIO.py 프로젝트: zhjmyx/OLINUXINO
def main():

    usage = "usage: %prog [options] arg1 ...."
    parser = optparse.OptionParser(usage=usage)
    parser.add_option("-v",
                      "--verbose",
                      action="store_true",
                      dest="verbose",
                      default=False,
                      help="Print extra messages")
    parser.add_option("--host",
                      type="str",
                      dest="host",
                      default="127.0.0.1",
                      help="Scratch host")
    parser.add_option("--port",
                      type="int",
                      dest="port",
                      default=42001,
                      help="Scratch port")

    #parse options
    (options, args) = parser.parse_args()

    #check verbose mode
    DEBUG = parser.values.verbose

    #get HOST_IP
    HOST = parser.values.host

    #get HOST_PORT
    PORT = parser.values.port

    if (DEBUG):
        print("Initializating GPIOs..."),
    try:
        gpio.init()

        #Configure inputs
        gpio.setcfg(gpio.PIN9, gpio.INP)  #input 1
        gpio.setcfg(gpio.PIN8, gpio.INP)  #input 2
        gpio.setcfg(gpio.PIN7, gpio.INP)  #input 3
        gpio.setcfg(gpio.PIN6, gpio.INP)  #input 4

        #Configure outputs
        gpio.setcfg(gpio.PIN29, gpio.OUT)  #output 1
        gpio.setcfg(gpio.PIN30, gpio.OUT)  #output 2
        gpio.setcfg(gpio.PIN31, gpio.OUT)  #output 3
        gpio.setcfg(gpio.PIN32, gpio.OUT)  #output 4
        gpio.setcfg(gpio.PIN33, gpio.OUT)  #output 5
        gpio.setcfg(gpio.PIN34, gpio.OUT)  #output 6
        gpio.setcfg(gpio.PIN35, gpio.OUT)  #output 7
        gpio.setcfg(gpio.PIN36, gpio.OUT)  #output 8
        gpio.setcfg(gpio.PIN37, gpio.OUT)  #output 9
        gpio.setcfg(gpio.PIN38, gpio.OUT)  #output 10
        gpio.setcfg(gpio.PIN39, gpio.OUT)  #output 11

        #Set all outputs LOW
        gpio.output(gpio.PIN29, gpio.LOW)
        gpio.output(gpio.PIN30, gpio.LOW)
        gpio.output(gpio.PIN31, gpio.LOW)
        gpio.output(gpio.PIN32, gpio.LOW)
        gpio.output(gpio.PIN33, gpio.LOW)
        gpio.output(gpio.PIN34, gpio.LOW)
        gpio.output(gpio.PIN35, gpio.LOW)
        gpio.output(gpio.PIN36, gpio.LOW)
        gpio.output(gpio.PIN37, gpio.LOW)
        gpio.output(gpio.PIN38, gpio.LOW)
        gpio.output(gpio.PIN39, gpio.LOW)

        if (DEBUG):
            print("Done")
    except Exception:
        if (DEBUG):
            print("Fail")
        else:
            print("Failed to initialize ports")
        sys.exit()

    if (DEBUG):
        print("Connecting to SCRATCH @ [" + str(HOST) + ":" + str(PORT) +
              "]..."),
    try:
        s = scratch.Scratch(host=str(HOST), port=PORT)
        if (DEBUG):
            print("Done")
    except Exception:
        if (DEBUG):
            print("Fail")
        else:
            print("Failed to connect to SCRATCH.")
        sys.exit()

    for msg in listen(s):
        if (DEBUG):
            print("New message received: " + str(msg))
        if msg[0] == 'broadcast':
            if msg[1] == 'INPUT1':
                i = gpio.input(gpio.PIN9)
                s.sensorupdate({'INPUT1': i})
            elif msg[1] == 'INPUT2':
                i = gpio.input(gpio.PIN8)
                s.sensorupdate({'INPUT2': i})
            elif msg[1] == 'INPUT3':
                i = gpio.input(gpio.PIN7)
                s.sensorupdate({'INPUT3': i})
            elif msg[1] == 'INPUT4':
                i = gpio.input(gpio.PIN6)
                s.sensorupdate({'INPUT4': i})

        #Handle outputs
        elif msg[0] == 'sensor-update':

            g = msg[1]
            keys = g.viewkeys()
            for key in keys:
                #         if(DEBUG):
                #            print("Key: " + str(key) + "\tValue: " + str(g[key]))

                #Catch message for OUTPUT1
                if key == 'OUTPUT1':
                    pin = gpio.PIN29
                elif key == 'OUTPUT2':
                    pin = gpio.PIN30
                elif key == 'OUTPUT3':
                    pin = gpio.PIN31
                elif key == 'OUTPUT4':
                    pin = gpio.PIN32
                elif key == 'OUTPUT5':
                    pin = gpio.PIN33
                elif key == 'OUTPUT6':
                    pin = gpio.PIN34
                elif key == 'OUTPUT7':
                    pin = gpio.PIN35
                elif key == 'OUTPUT8':
                    pin = gpio.PIN36
                elif key == 'OUTPUT9':
                    pin = gpio.PIN37
                elif key == 'OUTPUT10':
                    pin = gpio.PIN38
                elif key == 'OUTPUT11':
                    pin = gpio.PIN39

                #toggle GPIO
                if g[key] == 1:
                    if (DEBUG):
                        print(str(key) + ": HIGH..."),
                    try:
                        gpio.output(pin, gpio.HIGH)
                        if (DEBUG):
                            print("Done")
                    except Exception:
                        if (DEBUG):
                            print("Fail")
                        else:
                            print("Failed to set " + str(key))
                elif g[key] == 0:
                    if (DEBUG):
                        print(str(key) + ": LOW..."),
                    try:
                        gpio.output(pin, gpio.LOW)
                        if (DEBUG):
                            print("Done")
                    except Exception:
                        if (DEBUG):
                            print("Fail")
                        else:
                            print("Failed to clear " + str(key))
                else:
                    print(str(key) + ": Invalid output state!")

    return 0
예제 #21
0
import scratch
import time
import numpy

s = scratch.Scratch(host="192.168.11.56")

s.connect()
a = 0

while True:
    try:
        a = numpy.random.randint(50)
        s.sensorupdate({"temp": a})
        s.sensorupdate({"detect": "yes"})
        time.sleep(1)
        buf = s.receive()
        if buf[0] == "broadcast":
            print buf[1]

    except KeyboardInterrupt:
        print "Disconnected"
        break

s.disconnect()
예제 #22
0
#----------------------------------
num_of_pos_1 = 0
num_of_pos_2 = 0
Motor_1_on = 0
Motor_2_on = 0
positions = 0
m1 = 0
m2 = 0
start_time = 0
flag = 0
dt = []
pp = []

# IP of the Remote Computer Running SCRATCH
#s = scratch.Scratch(host='192.168.1.21',port=42001)
s = scratch.Scratch(host='192.168.2.2', port=42001)
#s = scratch.Scratch(host='10.67.166.171',port=42001)
#s = scratch.Scratch(host='192.168.11.192',port=42001)

print("We are ready now ...")
#while True:
for msg in listen():
    if msg[0] == 'broadcast':
        # Handle broadcast messages received from Scratch

        # Move Forward
        if msg[1][0:2] == 'GO':
            if msg[1][2:9] == 'FORWARD':
                pwr = float(msg[1][14:])
                M1.forward(speed=int((pwr + 0.0) * 5))
                M2.forward(speed=int((pwr + 0.1) * 5))
예제 #23
0
import matplotlib.pyplot as plt
import scratch

sc = scratch.Scratch()

x = []
y = []
plt.ylim(0, 3.5)
lines, = plt.plot(x, y)

stopflag = False
while stopflag == False:
    message = sc.receive()

    for k, v in message['sensor-update'].items():
        print(k, v)
        if k == 'data':
            a = v.split(' ')
            x = []
            y = []
            for i in range(1, len(a), 2):
                x.append(int(a[i + 1]) / 1000.0)
                y.append(int(a[i]) / 4095.0 * 3.3)

            sortedx = sorted(x)
            trigpos = round((len(sortedx) * 10) / 100)
            trigx = sortedx[trigpos]
            x = [p - trigx for p in x]

            lines.set_data(x, y)
            if len(x) >= 2:
예제 #24
0
 def startScratchClient(self):
     self.scratchInterface = scratch.Scratch()
     self.scratchInterface.connect()
예제 #25
0
	PPR = 18 # [p/rev] encoder Pulses Per wheel Revolution
	pulses = PPR*revs # [p] encoder pulses required to move dist cm.
	#print 'pulses',pulses
	return pulses

fw_version=fw_ver()
print "GoPiGo Scratch: Current firmware version:",fw_ver()
if fw_version > 1.2:
	pass
else:
	print "GoPiGo Scratch: Please Install the new firmware for the GoPiGo (v1.2+) to use GoPiGo with Scratch. \nPress enter to exit"
	raw_input()
	sys.exit()

try:
	s = scratch.Scratch()
	if s.connected:
		print "GoPiGo Scratch: Connected to Scratch successfully"
	#else:
	#sys.exit(0)
except scratch.ScratchError:
	print "GoPiGo Scratch: Scratch is either not opened or remote sensor connections aren't enabled"
	#sys.exit(0)

class myThread (threading.Thread):	 
	def __init__(self, threadID, name, counter):
		threading.Thread.__init__(self)
		self.threadID = threadID
		self.name = name
		self.counter = counter
	def run(self):
        logger.error("Error: %s", e)
        logger.error("Exiting ... bye")
        sys.exit(1)

    #SCRIPTPATH = os.path.split(os.path.realpath(__file__))[0]
    #logger.debug("PATH:%s", SCRIPTPATH)
    numAttempts = MAXATTEMPTS
    cycle_trace = 'start'

    while True:
        try:
            if cycle_trace == 'start':
                # open the socket trying each 3 seconds
                logger.info('Trying to connect...')
                time.sleep(3)
                s = scratch.Scratch(host)
                the_socket = s.socket
                logger.info('Connected!')
                listener = ScratchListener(s)
                sender = ScratchSender(s)
                cycle_trace = 'running'
                logger.info("Running....")
                listener.start()
                sender.start()

            if cycle_trace == 'disconnected':
                logger.info("Scratch disconnected")
                cleanup_threads((listener, sender))
                logger.debug("Thread cleanup done after disconnect")
                s4ahGC.resetAllPins()
                logger.debug("Pin Reset Done")