def __init__(self, path): # needs /etc/dbus-1/system.d/openroberta.conf bus_name = dbus.service.BusName('org.openroberta.lab', bus=dbus.SystemBus()) dbus.service.Object.__init__(self, bus_name, path) logger.info('object registered') self.status('disconnected') self.hal = Hal(None, None) self.hal.clearDisplay() self.thread = None
class Service(dbus.service.Object): """OpenRobertab-Lab dbus service The status state machines is a follows: +-> disconnected | | | v +- connected | | | v +- registered | ^ | v +- executing """ def __init__(self, path): # needs /etc/dbus-1/system.d/openroberta.conf bus_name = dbus.service.BusName('org.openroberta.lab', bus=dbus.SystemBus()) dbus.service.Object.__init__(self, bus_name, path) logger.info('object registered') self.status('disconnected') self.hal = Hal(None, None) self.hal.clearDisplay() self.thread = None @dbus.service.method('org.openroberta.lab', in_signature='s', out_signature='s') def connect(self, address): logger.info('connect(%s)' % address) # start thread, connecting to address self.thread = Connector(address, self) self.thread.daemon = True self.thread.start() self.status('connected') return self.thread.params['token'] @dbus.service.method('org.openroberta.lab') def disconnect(self): logger.info('disconnect()') # end thread, can take up to 15 seconds (the timeout to return) self.thread.running = False; self.thread.join() self.thread = None self.status('disconnected') @dbus.service.signal('org.openroberta.lab', signature='s') def status(self, status): logger.info('status changed: %s' % status)
from ev3dev import ev3 as ev3dev import math import os class BreakOutOfALoop(Exception): pass class ContinueLoop(Exception): pass _brickConfiguration = { 'wheel-diameter': 5.6, 'track-width': 18.0, 'actors': { }, 'sensors': { }, } hal = Hal(_brickConfiguration) item = [0, 0, 0] item2 = [True, True, True] item3 = ["1", "2", "3"] item4 = ['white', 'white', 'white'] item5 = [None, None, None] item6 = 0 item7 = True item8 = "123" item9 = 'white' item10 = None def run(): global item, item2, item8, item7, item9, item4, item3, item10, item6, item5 item[0] = 0 item[-1 -0] = 0
class BreakOutOfALoop(Exception): pass class ContinueLoop(Exception): pass _brickConfiguration = { 'wheel-diameter': 5.6, 'track-width': 18.0, 'actors': {}, 'sensors': { '1': Hal.makeTouchSensor(ev3dev.INPUT_1), '2': Hal.makeGyroSensor(ev3dev.INPUT_2), '3': Hal.makeColorSensor(ev3dev.INPUT_3), '4': Hal.makeUltrasonicSensor(ev3dev.INPUT_4), }, } hal = Hal(_brickConfiguration) def run(): while True: if (0 == 0) and True: break hal.waitFor(15) hal.waitFor(500) while True:
def main(): logger = logging.getLogger('robertalab') logger.info('--- starting ---') params = { 'macaddr': '70:1e:bb:88:89:bc', 'firmwarename': 'ev3dev', 'menuversion': version.split('-')[0], } headers = {'Content-Type': 'application/json'} try: with open('.robertalab.json') as cfg_file: cfg = json.load(cfg_file) except IOError as e: cfg = { 'target': 'http://lab.open-roberta.org/', # address and port of server } os.system('setterm -cursor off') hal = Hal(None, None) updateConfiguration(params) drawUI(hal, params) registered = False while not hal.isKeyPressed('back'): try: if registered: params['cmd'] = 'push' timeout = 15 else: params['cmd'] = 'register' timeout = 330 params['brickname'] = socket.gethostname() params['battery'] = getBatteryVoltage() # TODO: what about /api/v1/pushcmd logger.info('sending: %s' % params['cmd']) req = urllib2.Request('%s/pushcmd' % cfg['target'], headers=headers) response = urllib2.urlopen(req, json.dumps(params), timeout=timeout) reply = json.loads(response.read()) logger.info('response: %s' % json.dumps(reply)) cmd = reply['cmd'] if cmd == 'repeat': hal.drawText('registered', 0, 2) if not registered: hal.playFile(2) registered = True elif cmd == 'abort': break elif cmd == 'download': hal.drawText('executing ...', 0, 3) # TODO: url is not part of reply :/ # TODO: we should receive a digest for the download (md5sum) so that # we can verify the download req = urllib2.Request('%s/download' % cfg['target'], headers=headers) response = urllib2.urlopen(req, json.dumps(params), timeout=timeout) logger.info('response: %s' % json.dumps(reply)) hdr = response.info().getheader('Content-Disposition') filename = '/tmp/%s' % hdr.split('=')[1] if hdr else 'unknown' with open(filename, 'w') as prog: prog.write(response.read()) logger.info('code downloaded to: %s' % filename) # new process #res = subprocess.call(["python", filename], env={"PYTHONPATH":"$PYTONPATH:."}) #logger.info('execution result: %d' % res) # eval from file, see http://bugs.python.org/issue14049 # NOTE: all the globals in the generated code will override gloabls we use here! try: execfile(filename, globals(), globals()) logger.info('execution finished') except: logger.exception("Ooops:") drawUI(hal, params) hal.drawText('registered', 0, 2) elif cmd == 'update': # FIXME: # fetch new files (menu/hal) # then restart: # os.execv(__file__, sys.argv) # check if we need to close files (logger?) pass else: logger.warning('unhandled command: %s' % cmd) except urllib2.HTTPError as e: logger.error("HTTPError(%s): %s" % (e.code, e.reason)) break except urllib2.URLError as e: # [Errno 111] Connection refused> logger.error("URLError: %s" % e.reason) break except socket.timeout: pass except: logger.exception("Ooops:") os.system('setterm -cursor on') logger.info('--- done ---') logging.shutdown()
#!/usr/bin/env python3 from roberta.ev3 import Hal from roberta.BlocklyMethods import BlocklyMethods from ev3dev import ev3 as ev3dev import math import traceback _brickConfiguration = { 'wheel-diameter': 5.6, 'track-width': 18.0, 'actors': { 'RIGHT':Hal.makeLargeMotor(ev3dev.OUTPUT_A, 'on', 'foreward', 'right'), 'LEFT':Hal.makeLargeMotor(ev3dev.OUTPUT_D, 'on', 'foreward', 'left'), }, 'sensors': { 'color': Hal.makeColorSensor(ev3dev.INPUT_2), # 'distance': Hal.makeUltrasonicSensor(ev3dev.INPUT_2), 'touchLeft': Hal.makeTouchSensor(ev3dev.INPUT_4), 'touchRight': Hal.makeTouchSensor(ev3dev.INPUT_1), }, } hal = Hal(_brickConfiguration) def rotate(direction): hal.rotateDirectionAngle('LEFT', 'RIGHT', False, direction, 20, 80) angle = 5 right = False
def main(): logger = logging.getLogger('robertalab') logger.info('--- starting ---') params = { 'macaddr': '70:1e:bb:88:89:bc', 'firmwarename': 'ev3dev', 'menuversion': version.split('-')[0], } headers = { 'Content-Type': 'application/json' } try: with open('.robertalab.json') as cfg_file: cfg = json.load(cfg_file) except IOError as e: cfg = { 'target': 'http://lab.open-roberta.org/', # address and port of server } os.system('setterm -cursor off') hal = Hal(None, None) updateConfiguration(params) drawUI(hal, params) registered = False while not hal.isKeyPressed('back'): try: if registered: params['cmd'] = 'push' timeout = 15 else: params['cmd'] = 'register' timeout = 330 params['brickname'] = socket.gethostname() params['battery'] = getBatteryVoltage() # TODO: what about /api/v1/pushcmd logger.info('sending: %s' % params['cmd']) req = urllib2.Request('%s/pushcmd' % cfg['target'], headers=headers) response = urllib2.urlopen(req, json.dumps(params), timeout=timeout) reply = json.loads(response.read()) logger.info('response: %s' % json.dumps(reply)) cmd = reply['cmd'] if cmd == 'repeat': hal.drawText('registered', 0, 2) if not registered: hal.playFile(2) registered = True elif cmd == 'abort': break elif cmd == 'download': hal.drawText('executing ...', 0, 3) # TODO: url is not part of reply :/ # TODO: we should receive a digest for the download (md5sum) so that # we can verify the download req = urllib2.Request('%s/download' % cfg['target'], headers=headers) response = urllib2.urlopen(req, json.dumps(params), timeout=timeout) logger.info('response: %s' % json.dumps(reply)) hdr = response.info().getheader('Content-Disposition') filename = '/tmp/%s' % hdr.split('=')[1] if hdr else 'unknown' with open(filename, 'w') as prog: prog.write(response.read()) logger.info('code downloaded to: %s' % filename) # new process #res = subprocess.call(["python", filename], env={"PYTHONPATH":"$PYTONPATH:."}) #logger.info('execution result: %d' % res) # eval from file, see http://bugs.python.org/issue14049 # NOTE: all the globals in the generated code will override gloabls we use here! try: execfile(filename, globals(), globals()) logger.info('execution finished') except: logger.exception("Ooops:") drawUI(hal, params) hal.drawText('registered', 0, 2) elif cmd == 'update': # FIXME: # fetch new files (menu/hal) # then restart: # os.execv(__file__, sys.argv) # check if we need to close files (logger?) pass else: logger.warning('unhandled command: %s' % cmd) except urllib2.HTTPError as e: logger.error("HTTPError(%s): %s" % (e.code, e.reason)) break except urllib2.URLError as e: # [Errno 111] Connection refused> logger.error("URLError: %s" % e.reason) break except socket.timeout: pass except: logger.exception("Ooops:") os.system('setterm -cursor on') logger.info('--- done ---') logging.shutdown()
class BreakOutOfALoop(Exception): pass class ContinueLoop(Exception): pass _brickConfiguration = { 'wheel-diameter': 5.6, 'track-width': 18.0, 'actors': {}, 'sensors': { '4': Hal.makeInfraredSensor(ev3dev.INPUT_4), '2': Hal.makeSoundSensor(ev3dev.INPUT_2), }, } hal = Hal(_brickConfiguration) ___numberVar = 0 ___booleanVar = True ___stringVar = "" ___colourVar = 'white' ___connectionVar = None ___numberList = [0, 0] ___booleanList = [True, True] ___stringList = ["", ""] ___colourList = ['white', 'white'] ___connectionList = [___connectionVar, ___connectionVar]
from __future__ import absolute_import from roberta.ev3 import Hal from roberta.BlocklyMethods import BlocklyMethods from ev3dev import ev3 as ev3dev import math class BreakOutOfALoop(Exception): pass class ContinueLoop(Exception): pass _brickConfiguration = { 'wheel-diameter': 5.6, 'track-width': 18.0, 'actors': { }, 'sensors': { '1':Hal.makeIRSeekerSensor(ev3dev.INPUT_1), '2':Hal.makeCompassSensor(ev3dev.INPUT_2), }, } hal = Hal(_brickConfiguration) def run(): while True: if hal.getHiTecCompassSensorValue('2', ANGLE) < 30: break hal.waitFor(15) while True: if hal.getHiTecCompassSensorValue('2', COMPASS) < 30: break hal.waitFor(15) while True:
#!/usr/bin/python from __future__ import absolute_import from roberta.ev3 import Hal from ev3dev import ev3 as ev3dev import math import os class BreakOutOfALoop(Exception): pass class ContinueLoop(Exception): pass _brickConfiguration = { 'wheel-diameter': 5.6, 'track-width': 18.0, 'actors': { 'B':Hal.makeLargeMotor(ev3dev.OUTPUT_B, 'on', 'foreward'), }, 'sensors': { '1':Hal.makeTouchSensor(ev3dev.INPUT_1), '2':Hal.makeGyroSensor(ev3dev.INPUT_2), '3':Hal.makeColorSensor(ev3dev.INPUT_3), '4':Hal.makeUltrasonicSensor(ev3dev.INPUT_4), }, } hal = Hal(_brickConfiguration) ___numberVar = 0 ___booleanVar = True ___stringVar = "" ___colourVar = 'white' ___connectionVar = None
import traceback class BreakOutOfALoop(Exception): pass class ContinueLoop(Exception): pass _brickConfiguration = { 'wheel-diameter': 5.6, 'track-width': 18.0, 'actors': { 'B': Hal.makeLargeMotor(ev3dev.OUTPUT_A, 'on', 'foreward', 'right'), 'C': Hal.makeLargeMotor(ev3dev.OUTPUT_D, 'on', 'foreward', 'left'), }, 'sensors': { '3': Hal.makeColorSensor(ev3dev.INPUT_1), '4': Hal.makeUltrasonicSensor(ev3dev.INPUT_4), }, } hal = Hal(_brickConfiguration) right = True angle = 5 def run(): global angle, right
class BreakOutOfALoop(Exception): pass class ContinueLoop(Exception): pass _brickConfiguration = { 'wheel-diameter': 5.6, 'track-width': 18.0, 'actors': {}, 'sensors': { '2': Hal.makeCompassSensor(ev3dev.INPUT_2), '3': Hal.makeHTColorSensorV2(ev3dev.INPUT_3), '4': Hal.makeIRSeekerSensor(ev3dev.INPUT_4), }, } hal = Hal(_brickConfiguration) ___numberVar = 0 ___booleanVar = True ___stringVar = "" ___colourVar = 'white' ___connectionVar = None ___numberList = [0, 0] ___booleanList = [True, True] ___stringList = ["", ""] ___colourList = ['white', 'white']
import math class BreakOutOfALoop(Exception): pass class ContinueLoop(Exception): pass _brickConfiguration = { 'wheel-diameter': 5.6, 'track-width': 18.0, 'actors': { 'B': Hal.makeLargeMotor(ev3dev.OUTPUT_B, 'on', 'foreward'), 'C': Hal.makeLargeMotor(ev3dev.OUTPUT_C, 'on', 'foreward'), }, 'sensors': {}, } hal = Hal(_brickConfiguration) def run(): for k0 in range(0, 10, 1): hal.driveDistance('C', 'B', False, 'foreward', 30, 20) def main(): try: run()
mm = MediumMotor(OUTPUT_B) sound = Sound() opts = '-a 200 -s 130 -v' text = 'Saluton amikoj, mi estas Robi! mi sxatas muziki kaj danci' sound.speak(text, espeak_opts=opts+'eo') class BreakOutOfALoop(Exception): pass class ContinueLoop(Exception): pass _brickConfiguration = { 'wheel-diameter': 5.6, 'track-width': 18.0, 'actors': { 'A':Hal.makeLargeMotor(ev3dev.OUTPUT_A, 'on', 'foreward', 'right'), 'D':Hal.makeLargeMotor(ev3dev.OUTPUT_D, 'on', 'foreward', 'left'), } } hal = Hal(_brickConfiguration) def s3(): mm.on(20) hal.rotateDirectionRegulated('D', 'A', False, 'right', 30) hal.playTone(float(220), float(250)) hal.stopMotors('D', 'A') mm.off() mm.on(-20) hal.regulatedDrive('D', 'A', False, 'foreward', 30) hal.playTone(float(246.942), float(250)) hal.stopMotors('D', 'A')