player stage tutorial manual 2.1

35
How to Use Player/Stage Jennifer Owen July 10, 2009 This document is intended as a guide for anyone learning Player/Stage for the first time. It explains the process of setting up a new simulation environment and how to then make your simulation do something, using a case study along the way. Whilst it is aimed at Player/Stage users, those just wishing to use Player on their robot may also find sections of this document useful (particularly the parts about coding with Player). If you have any questions about using Player/Stage there is a guide to getting help from the Player comunity here: http://playerstage.sourceforge.net/wiki/Getting_help 1 Contents 1 Introduction 3 1.1 A Note on Installing Player/Stage ................. 3 2 The Basics 3 2.1 Important File Types ........................ 3 2.2 Interfaces, Drivers and Devices ................... 4 3 Building a World 5 3.1 Building an Empty World ...................... 7 3.1.1 Models ............................ 8 3.1.2 Describing the Player/Stage Window ............ 11 3.1.3 Making a Basic Worldfile .................. 12 3.2 Building a Robot ........................... 13 3.2.1 Sensors and Devices ..................... 13 3.2.2 An Example Robot ...................... 17 3.3 Building Other Stuff ......................... 27 4 Writing a Configuration (.cfg) File 31 4.1 Device Addresses - key:host:robot:interface:index ......... 33 4.2 Putting the Configuration File Together .............. 34 5 Getting Your Simulation To Run Your Code 36 5.1 Connecting to the Server and Proxies With Your Code ...... 37 5.1.1 Setting Up Connections: an Example. ........... 39 5.2 Interacting with Proxies ....................... 40 5.2.1 Position2dProxy ....................... 40 5.2.2 SonarProxy .......................... 42 5.2.3 LaserProxy .......................... 43 5.2.4 RangerProxy ......................... 43 5.2.5 BlobfinderProxy ....................... 44 5.2.6 GripperProxy ......................... 45 5.2.7 SimulationProxy ....................... 46 5.2.8 General Useful Commands ................. 47 5.3 Using Proxies: A Case Study .................... 47 5.3.1 The Control Architecture .................. 48 5.3.2 Beginning the Code ..................... 48 5.3.3 Wander ............................ 49 5.3.4 Obstacle Avoidance ..................... 51 5.3.5 Move To Item ......................... 52 5.3.6 Collect Item .......................... 54 5.4 Simulating Multiple Robots ..................... 56 6 Useful Links 58 7 Appendices 59 2

Upload: zulkarnainzainudin

Post on 02-Dec-2014

131 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Player Stage Tutorial Manual 2.1

How

toU

seP

layer/Stage

Jen

nifer

Ow

en

July

10,2009

This

document

isintended

asa

guidefor

anyonelearning

Player/Stage

forthe

firsttim

e.It

explainsthe

processofsetting

upa

newsim

ulationenvironm

entand

howto

thenm

akeyour

simulation

dosom

ething,using

acase

studyalong

thew

ay.W

hilstit

isaim

edat

Player/Stage

users,those

justw

ishingto

useP

layeron

theirrobot

may

alsofind

sectionsofthis

document

useful(particularlythe

partsabout

codingw

ithP

layer).Ifyou

haveany

questionsabout

usingP

layer/Stagethere

isa

guideto

gettinghelp

fromthe

Player

comunity

here:

http://playerstage.sourceforge.net/wiki/Getting_help

1

Conte

nts

1In

troduction

31.1

AN

oteon

InstallingP

layer/Stage.

..

..

..

..

..

..

..

..

3

2T

he

Basics

32.1

Important

File

Types

..

..

..

..

..

..

..

..

..

..

..

..

32.2

Interfaces,D

riversand

Devices

..

..

..

..

..

..

..

..

..

.4

3B

uild

ing

aW

orld5

3.1B

uildingan

Em

ptyW

orld.

..

..

..

..

..

..

..

..

..

..

.7

3.1.1M

odels.

..

..

..

..

..

..

..

..

..

..

..

..

..

.8

3.1.2D

escribingthe

Player/Stage

Window

..

..

..

..

..

..

113.1.3

Making

aB

asicW

orldfile.

..

..

..

..

..

..

..

..

.12

3.2B

uildinga

Robot

..

..

..

..

..

..

..

..

..

..

..

..

..

.13

3.2.1Sensors

andD

evices.

..

..

..

..

..

..

..

..

..

..

133.2.2

An

Exam

pleR

obot.

..

..

..

..

..

..

..

..

..

..

.17

3.3B

uildingO

therStuff

..

..

..

..

..

..

..

..

..

..

..

..

.27

4W

riting

aC

onfigu

ration(.cfg)

File

314.1

Device

Addresses

-key:host:robot:interface:index

..

..

..

..

.33

4.2P

uttingthe

Configuration

File

Together

..

..

..

..

..

..

..

34

5G

etting

You

rSim

ulation

To

Run

You

rC

ode

365.1

Connecting

tothe

Serverand

Proxies

With

Your

Code

..

..

..

375.1.1

SettingU

pC

onnections:an

Exam

ple..

..

..

..

..

..

395.2

Interactingw

ithP

roxies.

..

..

..

..

..

..

..

..

..

..

..

405.2.1

Position2dP

roxy.

..

..

..

..

..

..

..

..

..

..

..

405.2.2

SonarProxy

..

..

..

..

..

..

..

..

..

..

..

..

..

425.2.3

LaserP

roxy.

..

..

..

..

..

..

..

..

..

..

..

..

.43

5.2.4R

angerProxy

..

..

..

..

..

..

..

..

..

..

..

..

.43

5.2.5B

lobfinderProxy

..

..

..

..

..

..

..

..

..

..

..

.44

5.2.6G

ripperProxy

..

..

..

..

..

..

..

..

..

..

..

..

.45

5.2.7Sim

ulationProxy

..

..

..

..

..

..

..

..

..

..

..

.46

5.2.8G

eneralU

sefulC

omm

ands.

..

..

..

..

..

..

..

..

475.3

Using

Proxies:

AC

aseStudy

..

..

..

..

..

..

..

..

..

..

475.3.1

The

Control

Architecture

..

..

..

..

..

..

..

..

..

485.3.2

Beginning

theC

ode.

..

..

..

..

..

..

..

..

..

..

485.3.3

Wander

..

..

..

..

..

..

..

..

..

..

..

..

..

..

495.3.4

Obstacle

Avoidance

..

..

..

..

..

..

..

..

..

..

.51

5.3.5M

oveTo

Item.

..

..

..

..

..

..

..

..

..

..

..

..

525.3.6

Collect

Item.

..

..

..

..

..

..

..

..

..

..

..

..

.54

5.4Sim

ulatingM

ultipleR

obots.

..

..

..

..

..

..

..

..

..

..

56

6U

sefulLin

ks

58

7A

ppen

dices

59

2

Page 2: Player Stage Tutorial Manual 2.1

1In

troductio

n

Player/Stage

isa

robotsim

ulationtool,

itcom

prisesof

oneprogram

,P

layer,w

hichis

aH

ardware

Abstraction

Layer.T

hatm

eansthat

ittalks

tothe

bitsof

hardware

onthe

robot(like

aclaw

ora

camera)

andlets

youcontrolthem

with

yourcode,m

eaningyou

don’tneed

tow

orryabout

howthe

variousparts

oftherobot

work.

Stageis

aplugin

toP

layerw

hichlistens

tow

hatP

layeris

tellingit

todo

andturns

theseinstructions

intoa

simulation

ofyour

robot.It

alsosim

ulatessensor

dataand

sendsthis

toP

layerw

hichin

turnm

akesthe

sensordata

availableto

yourcode.

Asim

ulationthen,

iscom

posedof

threeparts:

•Y

ourcode.

This

talksto

Player.

•P

layer.T

histakes

yourcode

andsends

instructionsto

arobot.

Fromthe

robotit

getssensor

dataand

sendsit

toyour

code.

•Stage.

Stageinterfaces

with

Player

inthe

same

way

asa

robot’shardw

arew

ould.It

receivesinstructions

fromP

layerand

moves

asim

ulatedrobot

ina

simulated

world,it

getssensor

datafrom

therobot

inthe

simulation

andsends

thisto

Player.

Together

Player

andStage

arecalled

Player/Stage,and

theym

akea

simulation

ofyour

robots.T

heseinstructions

will

befocussing

onhow

touse

Player/Stage

tom

akea

simulation,

buthopefully

thisw

illstill

bea

usefulresource

foranyone

justusing

Player

(which

isthe

same

thingbut

ona

realrobot,without

anysim

ulationsoftw

are).

1.1

AN

ote

on

Insta

lling

Pla

yer/

Sta

ge

Instructionson

howto

installPlayer/Stage

ontoyour

computer

aren’treally

thefocus

ofthisdocum

ent.It

isvery

difficult

though.Ifyou’re

luckythe

installwill

work

firsttim

ebut

thereare

alot

ofdependencies

which

may

needinstalling.

InLinux

thereare

theinstall

programm

es“synaptic”

or“aptitude”

which

will

installa

packageand

alsoget

itsdependencies,

butthese

aren’tcom

mon

toall

Linux

distributions.T

hereis

anotherinstall

programcalled

“apt-get”but

thisw

on’tinstall

dependenciesfor

you.For

computers

runningU

buntuthere

isa

reasonableset

ofinstructions

here:

http://www.control.aau.dk/~tb/wiki/index.php/Installing_Player_

and_Stage_in_Ubuntu

Alternatively,

youtry

thesuggestions

onthe

Player

“gettinghelp”

page:

http://playerstage.sourceforge.net/wiki/Getting_help

2T

he

Basics

2.1

Importa

nt

File

Types

InP

layer/Stagethere

are3

kindsof

filethat

youneed

tounderstand

toget

goingw

ithP

layer/Stage:

3

•a

.world

file

•a

.cfg(configuration)

file

•a

.inc(include)

file

The

.world

filetells

Player/Stage

what

thingsare

availableto

putin

thew

orld.In

thisfile

youdescribe

yourrobot,

anyitem

sw

hichpopulate

thew

orldand

thelayout

ofthe

world.

The

.incfile

follows

thesam

esyntax

andform

atof

a.w

orldfile

butit

canbe

included.So

ifthere

isan

object

inyour

world

thatyou

might

want

touse

inother

worlds,such

asa

modelof

arobot,

puttingthe

robotdescription

ina

.incfile

justm

akesit

easierto

copyover,

italso

means

thatif

youever

want

tochange

yourrobot

descriptionthen

youonly

needto

doit

inone

placeand

yourm

ultiplesim

ulationsare

changedtoo.

The

.cfgfile

isw

hatP

layerreads

toget

alltheinform

ationabout

therobot

thatyou

aregoing

touse.T

hisfile

tellsP

layerw

hichdrivers

itneeds

touse

inorder

tointeract

with

therobot,

ifyou’re

usinga

realrobot

thesedrivers

arebuilt

into

Player

1,alternatively,

ifyou

want

tom

akea

simulation,

thedriver

isalw

aysStage

(thisis

howP

layeruses

Stagein

thesam

ew

ayit

usesa

robot:it

thinksthat

itis

ahardw

aredriver

andcom

municates

with

itas

such).T

he.cfg

filetells

Player

howto

talkto

thedriver,

andhow

tointerpret

anydata

fromthe

driverso

thatit

canbe

presentedto

yourcode.

Items

describedin

the.w

orldfile

shouldbe

describedin

the.cfg

fileifyou

want

yourcode

tobe

ableto

interactw

iththat

item(such

asa

robot),ifyoudon’t

needyour

codeto

interactw

iththe

itemthen

thisisn’t

necessary.T

he.cfg

filedoes

allthis

specificationusing

interfacesand

drivers,w

hichw

illbe

discussedin

thefollow

ingsection.

2.2

Inte

rface

s,D

rivers

and

Device

s

•D

riversare

piecesof

codethat

talkdirectly

tohardw

are.T

heseare

builtin

toP

layerso

itis

notim

portantto

knowhow

tow

ritethese

asyou

beginto

learnP

layer/Stage.T

hedrivers

arespecific

toa

pieceof

hardware

so,say,

alaser

driverw

illbe

differentto

acam

eradriver,

andalso

differentto

adriver

fora

differentbrand

oflaser.

This

isthe

same

asthe

way

thatdrivers

forgraphics

cardsdiffer

foreach

make

andm

odelofcard.

Drivers

produceand

readinform

ationw

hichconform

sto

an“interface”.

•Interfaces

area

setw

ayfor

adriver

tosend

andreceive

information

fromP

layer.Like

drivers,interfacesare

alsobuilt

into

Player

andthere

isa

biglist

ofthemin

theP

layerm

anual 2.T

heyspecify

thesyntax

andsem

anticsof

howdrivers

andP

layerinteract.

•A

deviceis

adriver

thatis

boundto

aninterface

sothat

Player

cantalk

toit

directly.T

hism

eansthat

ifyou

arew

orkingon

areal

robotthat

youcan

interactw

itha

realdevice(laser,gripper,cam

eraetc)

onthe

realrobot,

ina

simulated

robotyou

caninteract

with

theirsim

ulations.

The

officialdocum

entationactually

describesthese

3things

quitew

ellwith

anexam

ple.1O

ryou

can

dow

nlo

ad

or

write

your

ow

ndriv

ers,but

I’mnot

goin

gto

talk

about

how

todo

this

here.

2http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

Pla

yer-2

.1.0

/pla

yer/

gro

up

interfa

ces.htm

l

4

Page 3: Player Stage Tutorial Manual 2.1

Consider

thelaser

interface.T

hisinterface

definesa

format

inw

hicha

planarrange-sensor

canreturn

rangereadings

(basicallya

listofranges,w

ithsom

em

eta-data).T

helaser

interfaceis

justthat:

aninterface.

You

can’tdo

anythingw

ithit.

Now

considerthe

sicklms200

driver.T

hisdriver

controlsa

SICK

LM

S200,w

hichis

particularplanar

rangesensor

thatis

popularin

mobile

robotapplications.

The

sicklms200

driverknow

show

tocom

municate

with

theSIC

KLM

S200over

aserial

lineand

retrieverange

datafrom

it.B

utyou

don’tw

antto

accessthe

rangedata

insom

eSIC

K-specific

format.

Sothe

driveralso

knows

howto

translatethe

retrieveddata

tom

akeit

conformto

theform

atdefined

bythe

laserinterface.

The

sicklms200

drivercan

bebound

tothe

laserinterface

...tocreate

adevice,

which

might

havethe

following

address:localhost:6665:laser:0T

hefields

inthis

addresscorrespond

tothe

entriesin

theplayer

devaddrt

structure:host,

robot,interface,

andindex.

The

hostand

robotfields

(localhostand

6665)indicate

where

thedevice

islocated.

The

interfacefield

indicatesw

hichinterface

thedevice

supports,andthus

howit

canbe

used.B

ecauseyou

might

havem

orethan

onelaser,

theindex

fieldallow

syou

topick

among

thedevices

thatsupport

thegiven

interfaceand

arelocated

onthe

givenhost:robot

Other

laserson

thesam

ehost:robot

would

beassigned

differentindexes.

The

lastparagraph

theregets

abit

technical,but

don’tw

orry.P

layertalks

toparts

ofthe

robotusing

ports(the

defaultport

is6665),

ifyou’re

usingStage

thenP

layerand

Stagecom

municate

throughthese

ports(even

ifthey’rerunning

onthe

same

computer).

All

thisline

doesis

tellP

layerw

hichport

tolisten

toand

what

kindof

datato

expect.In

theexam

pleit’s

laserdata

which

isbeing

transmitted

onport

6665ofthe

computer

thatP

layeris

runningon

(localhost).Y

oucould

justas

easilyconnect

toanother

computer

byusing

itsIP

addressinstead

of“localhost”.

The

specificsof

writing

adevice

addressin

thisw

ayw

illbe

describedin

section4.

3B

uild

ing

aW

orld

First

we

willrun

aw

orldand

configurationfile

thatcom

esbundled

with

Stage.In

yourbash

shellnavigate

tothe

Stage/worlds

folder,by

default(in

Linux

atleast)

thisis

/usr/local/share/stage/worlds.

Once

inthe

correctfolder

typethe

following

comm

andto

runthe

“simple

world”

thatcom

esw

ithP

layer/Stage:

playersimple.cfg

Assum

ingP

layer/Stageis

installedproperly

youshould

nowhave

aw

indowopen

which

looksfigure

1.A

tthis

stageyou

candrag

anddrop

therobot

aroundits

world

with

yourm

ouse,butyou

canalso

tele-operatethe

robotusing

theP

layerV

iewer

program.

Ina

separateterm

inalw

hilstthe

Player/Stage

simulation

window

isstill

open,type:

playerv--position2d--laser

5

Figure

1:T

hesim

ple.cfgw

orldafter

beingrun

6

Page 4: Player Stage Tutorial Manual 2.1

Figure

2:T

hesim

ple.cfgw

orldseen

with

Player

View

er

Figure

3:H

owto

Rem

oteC

ontrol(tele-operate)

theStage

Robot

The

--position2d

and--laser

optionstell

theplayerv

(Player

View

er)pro-

gramthat

youw

antto

lookat

thepositional

dataand

thelaser

datathat

isavailable

tothe

robot.T

hisshould

opena

window

which

lookslike

figure2.

To

beable

torem

otecontrol

therobot

youclick

Device→

position2d:0→C

omm

andas

shown

infigure

3.A

cross-hairshould

appearover

therobot

inthe

Player

View

erw

indow,

which

ifyou

dragaround

will

causethe

robotto

move

inthe

Player/Stage

simulation

(figure1).

3.1

Build

ing

an

Em

pty

World

As

youcan

seein

section3,w

henw

etellP

layerto

builda

world

we

onlygive

itthe

.cfgfile

asan

input.T

his.cfg

fileneeds

totell

usw

hereto

findour

.world

file,which

isw

hereallthe

itemsin

thesim

ulationare

described.To

explainhow

tobuild

aStage

world

containingnothing

butw

allsw

ew

illuse

anexam

ple.To

startbuilding

anem

ptyw

orldw

eneed

a.cfg

file.First

createa

document

calledempty.cfg

andcopy

thefollow

ingcode

intoit:

driver

(name"stage"

plugin"libstageplugin"

provides["simulation:0"]

7

#loadthenamedfileintothesimulator

worldfile"empty.world"

)The

configurationfile

syntaxis

describedin

section4,

butbasically

what

ishappening

hereis

thatyour

configurationfile

istelling

Player

thatthere

isa

drivercalled

stage

inthe

libstageplugin

library,and

thisw

illgive

Player

dataw

hichconform

sto

thesimulation

interface.To

buildthe

simulation

Player

needsto

lookin

thew

orldfilecalled

empty.world

which

isstored

inthe

same

folderas

this.cfg.

Ifit

was

storedelsew

hereyou

would

haveto

includea

filepath,for

example

./worlds/empty.world.

Lines

thatbegin

with

thehash

symbol

(#)

arecom

ments.

When

youbuild

asim

ulation,any

simulation,

inStage

theabove

chunkofcode

shouldalw

aysbe

thefirst

thingthe

configurationfile

says.O

bviouslythe

name

ofthe

worldfile

shouldbe

changeddepending

onw

hatyou

calledit

though.N

owa

basicconfiguration

filehas

beenw

ritten,itis

time

totellP

layer/Stagew

hatto

putinto

thissim

ulation.T

hisis

donein

the.w

orldfile.

3.1.1M

odels

Aw

orldfileis

basicallyjust

alist

ofm

odelsthat

describesall

thestuff

inthe

simulation.

This

includesthe

basicenvironm

ent,robotsand

otherob

jects.T

hebasic

typeofm

odeliscalled

“model”,and

youdefine

am

odelusingthe

following

syntax:

definemodel_namemodel

(#parameters

)This

tellsP

layer/Stagethat

youare

defining

amodel

which

youhave

calledmodel_name,

andall

thestuff

inthe

roundbrackets

areparam

etersof

them

odel.To

beginto

understandP

layer/Stagem

odelparam

eters,let’s

lookat

themap.inc

filethat

comes

with

Stage,this

isused

todescribe

thebasic

envi-ronm

entin

thesim

ulation(e.g.

walls

therobots

canbum

pinto):

definemapmodel

(#sombre,sensible,artistic

color"black"

#mostmapswillneedaboundingbox

boundary1

gui_nose1

gui_grid1

gui_movemask0

gui_outline0

fiducial_return0

gripper_return0

8

Page 5: Player Stage Tutorial Manual 2.1

)We

cansee

fromthe

firstline

thatthey

aredefining

amodel

calledmap.

•color:

Tells

Player/Stage

what

colourto

renderthis

model,

inthis

caseit

isgoing

tobe

black.

•boundary:

Whether

ornot

thereis

abounding

boxaround

them

odel.T

hisis

anexam

pleof

abinary

parameter,w

hichm

eansthe

ifthe

number

nextto

itis

0then

itis

false,ifitis

1or

overthen

it’strue.

Sohere

we

DO

havea

boundingbox

aroundour

“map”

modelso

therobot

can’tw

anderout

ofour

map.

•gui_nose:

thistells

Player/Stage

thatit

shouldindicate

which

way

them

odelisfacing.

Figure

4show

sthe

differencebetw

eena

map

with

anose

andone

without.

•gui_grid:

thisw

illsuperim

posea

gridover

them

odel.Figure

5show

sa

map

with

agrid.

•gui_movemask:

thisindicates

whether

itshould

bepossible

todrag

anddrop

them

odel.H

ereit

is0,

soyou

cannotm

ovethe

map

model

onceP

layer/Stagehas

beenrun.

Insection

3w

henthe

Player/Stage

example

simple.cfg

was

runit

was

possibleto

dragand

dropthe

robotbecause

itsgui_movemask

variablew

asset

to1.

•gui_outline:

indicatesw

hetheror

notthe

model

shouldbe

outlined.T

hism

akesno

differenceto

am

ap,but

itcan

beuseful

when

making

models

ofitem

sw

ithinthe

world.

•fiducial_return:

anyparam

eterof

theform

some

sensorreturn

de-scribes

howthat

kindof

sensorshould

reactto

them

odel.“F

iducial”is

akind

ofrobot

sensorw

hichw

illbe

describedlater

insection

3.2.1.Setting

fiducial_return

to0

means

thatthe

map

cannotbe

detectedby

afiducial

sensor.

•gripper_return:

Like

fiducial_return,gripper_return

tellsP

layer/Stagethat

yourm

odelcanbe

detectedby

therelevant

sensor,ieit

canbe

grippedby

agripper.

This

parameter

alsoindicates

whether

them

odelcan

bepushed.

Here

gripper_return

isset

to0

sothe

map

cannotbe

pushedby

arobot

andit

cannotbe

grippedby

agripper.

To

make

useof

themap.inc

filew

eput

thefollow

ingcode

intoour

world

file:

include"map.inc"

This

insertsthe

map.inc

fileinto

ourw

orldfile

where

theinclude

lineis.

This

assumes

thatyour

worldfile

andmap.inc

fileare

inthe

same

folder,ifthey

arenot

thenyou’llneed

toinclude

thefilepath

inthe

quotes.O

ncethis

isdone

we

canm

odifyour

definitionof

them

apm

odelto

beused

inthe

simulation.

Forexam

ple:

9

Figure

4:T

heleft

pictureshow

san

empty

map

without

anose.

The

rightpicture

shows

thesam

em

apw

itha

noseto

indicateorientation,

thisis

thehorizontal

linefrom

thecentre

ofthe

map

tothe

right,it

shows

thatthe

map

isactually

facingto

theright.

Figure

5:A

nem

ptym

apw

ithgui

gridenabled.

With

guigrid

disabledthis

would

justbe

anem

ptyw

hitesquare.10

Page 6: Player Stage Tutorial Manual 2.1

Figure

6:T

heleft

image

isour

”helloworld.png”

bitmap,the

rightim

ageis

what

Player/Stage

interpretsthat

bitmap

as.T

heblack

areasare

walls,

therobot

canm

oveeveryw

hereelse.

map

(bitmap"bitmaps/helloworld.png"

size[125]

)What

thism

eansis

thatw

eare

usingthe

model“m

ap”,andm

akingsom

eextra

definitions;both

“bitmap”

and“size”

areparam

etersof

aP

layer/Stagem

odel.H

erew

eare

tellingP

layer/Stagethat

we

defineda

bunchof

parameters

fora

typeof

model

called“m

ap”(contained

inm

ap.inc)and

noww

e’reusing

this“m

ap”m

odeldefinition

andadding

afew

extraparam

eters.

•bitmap:

thisis

thefilepath

toa

bitmap,w

hichcan

betype

bmp,jpeg,gif

orpng.

Black

areasin

thebitm

aptell

them

odelw

hatshape

tobe,

non-black

areasare

notrendered,this

isillustrated

infigure

6.In

them

ap.incfile

we

toldthe

map

thatits

“color”w

ouldbe

black.T

hisparam

eterdoes

notaffect

howthe

bitmaps

areread,

Player/Stage

will

always

lookfor

blackin

thebitm

ap,the

“color”param

eterjust

altersw

hatcolour

them

apis

renderedin

thesim

ulation.

•size:

This

isthe

sizein

metres

ofthe

simulation.

All

sizesyou

givein

thew

orldfile

arein

metres,

andthey

representthe

actualsize

ofthings.

Ifyouhave

3mx

4mrobot

testingarena

which

youw

antto

simulate

thenthe

sizehere

is[3.0

4.0].T

hefirst

number

isthe

sizein

thex

dimension,

thesecond

isthe

ydim

ension.

Afull

listof

model

parameters

andtheir

descriptionscan

befound

inthe

official

Stagem

anual 3.M

ostof

theuseful

parameters

havealready

beende-

scribedhere,

however

thereare

afew

othertypes

ofm

odelw

hichare

relevantto

buildingsim

ulationsof

robots,these

will

bedescribed

laterin

section3.2.

3.1.2D

escribin

gth

eP

layer/Stage

Win

dow

The

worldfile

alsocan

beused

todescribe

thesim

ulationw

indowthat

Player/Stage

creates.P

layer/Stagew

illautom

aticallym

akea

window

forthe

simulation

if

3http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

stage-3

.0.1

/gro

up

model.h

tml

11

youdon’t

putany

window

detailsin

thew

orldfile,how

ever,it

isoften

usefulto

putthis

information

inanyw

ay.T

hisprevents

alarge

simulation

frombeing

toobig

forthe

window

,or

toincrease

ordecrease

thesize

ofthe

simulation.

Like

am

odel,aw

indowis

aninbuilt,high-levelentity

with

lotsofparam

eters.U

nlikem

odelsthough,

therecan

beonly

onew

indowin

asim

ulationand

onlya

fewof

itsparam

etersare

reallyneeded.

The

simulation

window

isdescribed

with

thefollow

ingsyntax:

window

(parameters...

)

The

two

most

important

parameters

forthe

window

aresize

andscale.

•size:

This

isthe

sizethe

simulation

window

will

bein

pixels.Y

ouneed

todefine

boththe

width

andheight

ofthe

window

usingthe

following

syntax:size[widthheight].

•scale:

This

ishow

many

metres

ofthe

simulated

environment

eachpixel

shows.

The

biggerthis

number

is,the

smaller

thesim

ulationbecom

es.T

heoptim

umvalue

forthe

scaleis

map

siz

ew

indow

siz

eand

itshould

berounded

upwards

slightlyso

thesim

ulationis

alittle

smaller

thanthe

window

it’sin.

Afull

listof

window

parameters

canbe

foundin

theStage

manual

under“W

orldGU

I”4.

3.1.3M

akin

ga

Basic

World

file

We

havealready

discussedthe

basicsof

worldfile

building:m

odelsand

thew

indow.

There

arejust

afew

more

parameters

todescribe

which

don’tbelong

ineither

am

odelora

window

descriptionw

hichshould

bedefined

andthen

thew

orldfilecan

bebuilt.

•size:

At

thislevel

thisrepresents

howbig,

inm

etres,the

whole

simula-

tionenvironm

entw

illbe.

This

iscom

pletelyseparate

fromthe

map

sizebecause

itcould

belarger

andthere

might

beseveral

differentm

apsrun-

ningin

thesam

esim

ulation(so

more

thanone

simulation

couldbe

runat

once).G

enerallythough

thisjust

needsto

bethe

same

asthe

map

size.T

hisparam

eterm

ustbe

includedin

thew

orldfileotherw

isethe

simulation

won’t

work.

•interval_sim:

This

ishow

many

simulated

milliseconds

thereare

be-tw

eeneach

updateof

thesim

ulationw

indow,the

defaultis

100m

illisec-onds.

•interval_real:

This

ishow

many

realm

illisecondsthere

arebetw

eeneach

updateof

thesim

ulationw

indow.

Balancing

thisparam

eterand

theinterval\_sim

parameter

controlsthe

speedofthe

simulation.

Again,the

defaultvalue

is100

milliseconds,

boththese

intervalparam

eterdefaults

arefairly

sensible,so

it’snot

always

necessaryto

redefinethem

.4http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

stage-3

.0.1

/gro

up

world

gui.h

tml

12

Page 7: Player Stage Tutorial Manual 2.1

The

Stagem

anualcontains

alist

ofthe

high-levelw

orldfileparam

eters5.

Finally,

we

areable

tow

ritea

worldfile!

include"map.inc"

#sizeofthewholesimulation

size[1515]

#configuretheGUIwindow

window

(size[700.0700.0]

#15/700roundedupabit

scale0.025

)#loadanenvironmentbitmap

map

(bitmap"bitmaps/cave.png"

size[1515]

)Ifw

esave

theabove

codeas

empty.w

orld(correcting

anyfilepaths

ifnecessary)

we

canrun

itscorresponding

empty.cfg

file(see

section3.1)

toget

thesim

ulationshow

nin

figure7.

3.2

Build

ing

aR

obot

InP

layer/Stagea

robotis

justa

slightlyadvanced

kindof

model,

allthe

pa-ram

etersdescribed

insection

3.1.1can

stillbe

applied.

3.2.1Sen

sorsan

dD

evices

There

aresix

built-inkinds

ofm

odelthat

helpw

ithbuilding

arobot,

theyare

usedto

definethe

sensorsand

actuatorsthat

therobot

has.T

heseare

associatedw

itha

setof

model

parameters

which

defineby

which

sensorsthe

model

canbe

detected(these

arethe

_returns

mentioned

earlier).E

achof

thesebuilt

inm

odelsacts

asan

interface(see

section2.2)

between

thesim

ulationand

Player.

Ifyour

robothas

oneof

thesekinds

ofsensor

onit,

thenyou

needto

usethe

relevantm

odeltodescribe

thesensor,otherw

iseStage

andP

layerw

on’tbe

ableto

passthe

databetw

eeneach

other.It

ispossible

tow

riteyour

own

interfaces,but

thestuff

alreadyincluded

inP

layer/Stageshould

besuffi

cientfor

most

people’sneeds.

Afull

listof

interfacesthat

Player

supportscan

befound

inthe

Player

manual 6

althoughonly

thefollow

ingare

supportedby

thecurrent

distributionof

Stage(version

3.0.1).U

nlessotherw

isestated,

thesem

odelsuse

theP

layerinterface

thatshares

itsnam

e:5http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

stage-3

.0.1

/gro

up

world

.htm

l6http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

Pla

yer-2

.1.0

/pla

yer/

gro

up

interfa

ces.htm

l

13

Figure

7:O

urE

mpty

World.

camera

7T

hecam

eram

odeladds

acam

erato

therobot

model

andallow

syour

codeto

interactw

iththe

simulated

camera.

The

camera

parameters

areas

follows:

•resolution[xy]:

theresolution,

inpixels,

ofthe

camera’s

image.

•range[minmax]:

them

inimum

andm

aximum

rangethat

thecam

eracan

detect

•fov[xy]:

thefield

ofview

ofthe

camera

indegrees.

•pantilt[pantilt]:

thehorizontalangle

thecam

eracan

move

through(pan)

andthe

verticalangle

(tilt).So

forinstance

pantilt[9020]

al-low

sthe

camera

tom

ove45 ◦

leftand

45 ◦right

and10 ◦

upand

10 ◦dow

n.

blob

finder

8T

hissim

ulatescolour

detectionsoftw

arethat

canbe

runon

theim

agefrom

therobot’s

camera.

Itis

notnecessary

toinclude

am

odelof

thecam

erain

yourdescription

ofthe

robotif

youw

antto

usea

blobfinder,the

blobfinderw

illwork

onits

own.

The

blobfindercan

onlyfind

am

odelifits

blob_return

parameter

istrue.

The

parameters

forthe

blobfinderare

describedin

theStage

manual,

butthe

most

usefulones

arehere:

•colors_count<int>:

thenum

berof

differentcolours

theblobfinder

candetect

7http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

stage-3

.0.1

/gro

up

model

cam

era.h

tml

8http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

stage-3

.0.1

/gro

up

model

blo

bfinder.h

tml

14

Page 8: Player Stage Tutorial Manual 2.1

•colors[]:

thenam

esof

thecolours

itcan

detect.T

hisis

givento

theblobfinder

definitionin

theform

["black""blue""cyan"].

These

colournam

esare

fromthe

builtin

X11

colourdatabase

rgb.txt.T

hisis

builtin

toLinux. 9

•image[xy]:

thesize

ofthe

image

fromthe

camera,

inpixels.

•range<float>:

The

maxim

umrange

thatthe

camera

candetect,in

me-

tres.

•fov<float>:

fieldof

viewof

theblobfinder

inR

AD

IAN

S.

Itis

important

tonote

thatthe

syntaxfor

theblobfinder

model

isdifferent

inStage

versions2.X

.Xand

3.X.X

.T

heabove

parameters

arespecific

toStage

3.X.X

,in

Stage2.X

.Xthey

havedifferent

names

butdo

thesam

ething:

•channel_count<int>:

same

ascolors

count.

•channels[]:

same

ascolors

[].

•image[xy]:

same

asin

Stage3.X

.X.

•range_max<float>:

same

asrange

•ptz[pan_angletilt_anglezoom_angle]:

controlsthe

areasthat

thecam

eracan

lookat.

This

works

likepantilt

ofthe

camera

model,

thezoom_angle

isthe

fieldof

viewin

DEG

REES.

Additionally,

inStage

2.X.X

blobfinderis

achild

ofa

deprecatedm

odelcalled

ptz.A

llthisbasically

means

isthat

when

youdefine

yourblobfinder

modelyou

needto

usethis

syntaxinstead:

definemodel_nameptz

(blobfinder

(#parameters

))fiducialfi

nder

10

Afiducialis

afixed

pointin

anim

age,sothe

fiducialfindersim

ulatesim

ageprocessing

software

thatlocates

fixedpoints

inan

image.

The

fiducialfinderis

ableto

locateob

jectsin

thesim

ulationw

hosefiducial_return

parameter

isset

totrue.

Stagealso

allows

youto

specifydifferent

typesof

fiducialusing

thefiducial_key

parameter

ofa

model.

This

means

thatyou

canm

akethe

robotsable

totell

thedifference

between

differentfiducials

byw

hatkey

theytransm

it.T

hefiducialfinder

andthe

conceptof

fiducial_keys

isproperly

explainedin

theStage

manual.

9rg

b.tx

tca

nnorm

ally

be

found

at/usr/

share/

X11/rg

b.tx

tassu

min

git’s

pro

perly

insta

lled,

altern

ativ

elya

Google

search

for

“rg

b.tx

t”w

illgiv

eyou

the

docu

men

t.10http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

stage-3

.0.1

/gro

up

model

fiducia

l.htm

l

15

ranger

11

This

simulates

anykind

ofobstacle

detectiondevice

(e.g.sonars

orinfra-red

sensors).T

hesecan

locatem

odelsw

hoseranger_return

istrue.

Using

aranger

model

youcan

defineany

number

ofranger

devicesand

applythem

alltoa

singlerobot.

Unlike

theother

typesof

modelthis

doesn’tuse

theinterface

with

itsnam

ebut

insteadthe

sonar

interface,there

ism

oreabout

thisin

section4.2.

The

parameters

forthe

ranger

model

andtheir

inputsare

describedin

theStage

manual,

butbasically:

•scount<int>:

The

number

ofranger

sensorsin

thisranger

model

•spose[ranger_number][xyyaw]:

Tells

thesim

ulatorw

herethe

rangersare

placedaround

therobot.

How

tow

ritethe

[xyyaw]

datais

explainedin

section3.2.2.

•ssize[xy]:

howbig

thesensors

are.

•sview[minmaxfov]:

definesthe

maxim

umand

minim

umdistances

thatcan

besensed

andalso

thefield

ofview

indegrees.

laser12

Alaser

isa

specialcaseofranger

sensorw

hichonly

allows

oneranger

(sothere’s

noneofthe

scount,

spose

stuff),but

ithas

avery

largefield

ofview.

Ifa

model

hasits

laser_return

parameter

enabledthen

alaser

candetect

it.D

etailsabout

laserparam

eterscan

befound

inthe

Stagem

anual,how

everthe

most

usefulparam

etersare:

•range_min:

The

minim

umrange

ofthe

laser.

•range_max:

them

aximum

rangeof

thelaser.

•fov:

thefield

ofview

ofthe

laser.In

Stage3.X

.Xthis

isin

radians,in

Stage2.X

.Xit

isin

degrees.

gripper

13

The

gripperm

odelis

asim

ulationof

thegripper

youget

ona

Pioneer

robot. 14

Ifyou

puta

gripperon

yourrobot

model

itm

eansthat

yourrobot

isable

topick

upob

jectsand

move

themaround

within

thesim

ulation.T

heonline

Stagem

anualsays

thatgrippers

aredeprecated

inStage

3.X.X

,how

everthis

isnot

actuallythe

caseand

grippersare

veryuseful

ifyou

want

yourrobot

tobe

ableto

manipulate

andm

oveitem

s.T

heparam

etersyou

canuse

tocustom

isethe

gripperm

odelare:

•size[xy]:

The

xand

ydim

ensionsof

thegripper.

•pose[xyyaw]:

Where

thegripper

isplaced

onthe

robot.11http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

stage-3

.0.1

/gro

up

model

ranger.h

tml

12http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

stage-3

.0.1

/gro

up

model

laser.h

tml

13http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

Sta

ge-2

.0.0

/gro

up

model

grip

per.h

tml

14T

he

Pio

neer

grip

pers

looks

like

abig

blo

ckon

the

front

ofth

ero

bot

with

two

big

sliders

that

close

aro

und

an

object.

16

Page 9: Player Stage Tutorial Manual 2.1

position

15

The

positionm

odelsim

ulatesthe

robot’sodom

etry,this

isw

henthe

robotkeeps

trackofw

hereit

isby

recordinghow

many

times

itsw

heelsspin

andthe

angleit

turns.T

hisrobot

modelis

them

ostim

portantofallbecause

itallow

sthe

robotm

odeltobe

embodied

inthe

world,m

eaningit

cancollide

with

anythingw

hichhas

itsobstacle_return

parameter

setto

true.T

heposition

model

usesthe

position2d

interface,w

hichis

essentialfor

Player

becauseit

tellsP

layerw

herethe

robotactually

isin

thew

orld.T

hem

ostusefulparam

etersof

theposition

model

are:

•drive:

Tells

theodom

etryhow

therobot

isdriven.

This

isusually

“diff”

which

means

therobot

iscontrolled

bychanging

thespeeds

oftheleft

andright

wheels

independently.O

therpossible

valuesare

“car”w

hichm

eansthe

robotuses

avelocity

anda

steeringangle,

or“om

ni”w

hichm

eansit

cancontrol

howit

moves

alongthe

xand

yaxes

ofthe

simulation.

•localization:

tellsthe

modelhow

itshould

recordthe

odometry

“odom”

ifthe

robotcalculates

itas

itm

ovesalong

or“gps”

forthe

robotto

haveperfect

knowledge

aboutw

hereit

isin

thesim

ulation.

•odom_error[xyangle]:

The

amount

oferrorthat

therobot

willm

akein

theodom

etryrecordings.

•mass<int>:

How

heavythe

robotis.

3.2.2A

nExam

ple

Rob

ot

To

demonstrate

howto

builda

model

ofa

robotin

Player/Stage

we

will

buildour

own

example.

First

we

will

describethe

physicalproperties

ofthe

robot,such

assize,

shapeand

mass.

Then

we

will

addsensors

ontoit

sothat

itcan

interactw

ithits

environment.

The

Rob

ot’sB

ody

Let’s

sayw

ew

antto

model

arubbish

collectingrobot

called“B

igbob”.T

hefirst

thingw

eneed

todo

isdescribe

itsbasic

shape,todo

thisyou

needto

knowyour

robot’sdim

ensionsin

metres.

Figure

8show

sthe

basicshape

ofB

igbobdraw

nonto

some

cartesiancoordinates,

thecoordinates

ofthe

cornersof

therobot

havebeen

recorded.W

ecan

thenbuild

thism

odelusing

thepolygons

model

parameter

16:

definebigbobposition

(#theshapeofBigbob

polygons1

polygon[0].points6

polygon[0].point[0][00]

polygon[0].point[1][01]

polygon[0].point[2][0.751]

polygon[0].point[3][10.75]

polygon[0].point[4][10.25]

15http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

stage-3

.0.1

/gro

up

model

positio

n.h

tml

16In

this

exam

ple

we’re

usin

gpoly

gons

with

the

positio

nm

odel

type

but

we

could

equally

use

itw

ithoth

erm

odel

types.

17

Figure

8:T

hebasic

shapew

ew

antto

make

Bigbob,

theunits

onthe

axesare

inm

etres.

polygon[0].point[5][0.750]

)Inthe

firstline

ofthis

codew

estate

thatw

eare

definingaposition

model

calledbigbob.

Next

polygons1

saysthat

thism

odelw

illbe

builtout

ofone

polygon.T

hefollow

inglines

goon

todescribe

theshape

ofthis

polygon;polygon[0].points6

saysthat

thepolygon

has6

cornersand

polygon[number].point[number][xy]

givesthe

coordinatesofeach

cornerofthe

polygonin

turn.It

isim

portantto

goaround

therobot

doingeach

cornerin

turn(either

clockwise

oranti-clockw

ise)otherw

iseP

layer/Stagew

on’tproperly

renderthe

polygon.N

owin

thesam

ew

ayas

we

builtthe

bodyw

ecan

addon

some

teethfor

Bigbob

tocollect

rubbishbetw

een:

definebigbobposition

(#actualsize

size[1.251]

#theshapeofBigbob

polygons3

#body

polygon[0].points6

polygon[0].point[0][00]

polygon[0].point[1][01]

polygon[0].point[2][0.751]

polygon[0].point[3][10.75]

18

Page 10: Player Stage Tutorial Manual 2.1

Figure

9:T

henew

shapeof

Bigbob.

polygon[0].point[4][10.25]

polygon[0].point[5][0.750]

#firsttooth

polygon[1].points4

polygon[1].point[0][10.75]

polygon[1].point[1][1.250.75]

polygon[1].point[2][1.250.625]

polygon[1].point[3][10.625]

#secondtooth

polygon[2].points4

polygon[2].point[0][10.375]

polygon[2].point[1][1.250.375]

polygon[2].point[2][1.250.25]

polygon[2].point[3][10.25]

)

To

declarethe

sizeof

therobot

youuse

thesize[widthheight]

parame-

ter,thisw

illcausethe

polygondescribed

tobe

scaledto

fitinto

abox

which

iswidthxheight

insize.

The

defaultsize

is1

x1

metre,so

becausethe

additionof

rubbish-collectingteeth

made

Bigbob

longer,the

sizeparam

eterw

asneeded

tostop

Player/Stage

fromm

akingthe

robotsm

allerthan

itshould

be.In

thisw

ayw

ecould

havespecified

thepolygon

coordinatesto

be4

times

thedistance

apartand

thendeclared

itssize

tobe

1.25x1

metres,and

we

would

havegot

arobot

thesize

we

wanted.

Fora

robotas

largeas

Bigbob

thisis

notreally

important,but

itcould

beusefulw

henbuilding

models

ofvery

smallrobots.

Itshould

benoted

thatit

doesn’tactually

matter

where

inthe

cartesiancoordi-

natesystem

youplace

thepolygon,

insteadof

startingat

(0,0)

itcould

justas

easilyhave

startedat

(-1000,12345).

With

thepolygon

parameter

we

just

19

Figure

10:A

cartesiangrid

showing

howangles

aredescribed.

describethe

shapeof

therobot,

notits

sizeor

locationin

them

ap.Y

oum

ayhave

noticedthat

infigures

8and

9B

igbobis

facingto

theright

ofthe

grid.W

henyou

placeany

itemin

aP

layer/Stagesim

ulationthey

are,by

default,facingto

theright

handside

ofthesim

ulation.Figure

5show

sthat

thegrids

usea

typicalCartesian

coordinatesystem

,andso

ifyou

want

toalter

thedirection

anob

jectin

thesim

ulationis

pointing(its

“yaw”)

anyangles

yougive

usethe

x-axisas

areference,

justlike

vectorsin

aC

artesiancoordinate

system(see

figure10)

andso

thedefault

yawis

0 ◦.T

hisis

alsow

hyin

section3.1

thegui_nose

shows

them

apis

facingto

theright.

Figure

11show

sa

fewexam

plesof

robotsw

ithdifferent

yaws.

By

default,Player/Stage

assumes

therobot’s

centreofrotation

isat

itsgeo-

metric

centrebased

onw

hatvalues

aregiven

tothe

robot’ssize

parameter.

Big-

bob’ssize

is1.25x1

soP

layer/Stagew

illplace

itscentre

at(0.625,0.5),

which

means

thatB

igbob’sw

heelsw

ouldbe

closerto

itsteeth.

Insteadlet’s

saythat

Bigbob’s

centreof

rotationis

inthe

middle

ofits

main

body(show

nin

figure8)

which

putsthe

centreof

rotationat

(0.5,0.5).

To

changethis

inrobot

model

youuse

theorigin[x-offsety-offsetz-offset]

comm

and:

definebigbobposition

(#actualsize

size[1.251]

#centreofrotationoffset

origin[0.12500]

#theshapeofBigbob

polygons3

...

...

...

)

Finally

we

will

specifythe

mass

anddrive

ofB

igbob,these

areboth

pa-ram

etersof

theposition

model

andhave

beendescribed

earlier.

20

Page 11: Player Stage Tutorial Manual 2.1

Figure

11:Starting

fromthe

topright

robotand

working

anti-clockwise,

theyaw

sof

theserobots

are0,

90,-45

and200.

definebigbobposition

(#actualsize

size[1.251]

#centreofrotationoffset

origin[0.12500]

#theshapeofBigbob

polygons3

...

...

...

#positonalthings

mass10.0

drive"diff"

)The

Rob

ot’sSen

sorsN

owthat

Bigbob’s

bodyhas

beenbuilt

let’sm

oveon

tothe

sensors.W

ew

illput

sonarand

blobfindingsensors

ontoB

igbobso

thatit

candetect

walls

andsee

colouredblobs

itcan

interpretas

rubbishto

collect.W

ew

illalso

puta

laserbetw

eenB

igbob’steeth

sothat

itcan

detectw

henan

itempasses

inbetw

eenthem

.W

ew

illstart

with

thesonars.

The

firstthing

todo

isto

definea

model

forthe

sonararray

thatis

goingto

beattached

toB

igbob:

21

Figure

12:T

heposition

ofB

igbob’ssonars

(inred)

relativeto

itsorigin.

The

originis

marked

with

across,som

eofthe

distancesfrom

theorigin

tothe

sensorshave

beenm

arked.T

herem

ainingdistances

canbe

doneby

inspection.

definebigbobs_sonarsranger

(#parameters...

)Here

we

tellP

layer/Stagethat

we

will

define

aset

ofsonar

sensorscalled

bigbobs_sonars

andw

e’reusing

them

odeltype

ranger

totell

Player/Stage

thatthis

isa

model

ofsom

eranging

devices.Let’s

putfour

sonarson

Bigbob,

oneon

thefront

ofeach

tooth,and

oneon

thefront

leftand

thefront

rightcorners

ofits

body.W

henbuilding

Bigbob’s

bodyw

ew

ereable

touse

anylocation

ona

coor-dinate

gridthat

we

wanted

andcould

declareour

shapepolygons

tobe

anydistance

apartw

ew

antedso

longas

we

resizedthe

model

with

size.

Incon-

trast,sensors-allsensors

notjust

rangers-m

ustbe

positionedaccording

tothe

robot’sorigin

andactual

size.To

work

outthe

distancesin

metres

ithelps

todo

adraw

ingof

where

thesensors

willgo

onthe

robotand

theirdistances

fromthe

robot’sorigin.

When

we

worked

outthe

shapeofB

igbob’sbody

we

usedits

actualsize,sow

ecan

usethe

same

drawings

againto

work

outthe

distancesof

thesensors

fromthe

originas

shown

infigure

12.N

oww

eknow

howm

anysensors

we

want,

andtheir

coordinatesrelative

tothe

originw

ecan

beginto

buildour

modelof

thesonar

array.H

erew

ew

illusethe

scount

andspose

parameters

mentioned

in3.2.1.

The

valuesfor

spose

are[xyyaw],

remem

berthat

yawis

indegrees

andis

measured

relativeto

thex

axis.

definebigbobs_sonarsranger

(#numberofsonars

22

Page 12: Player Stage Tutorial Manual 2.1

scount4

#definetheposeofeachtransducer[xposyposheading]

spose[0][0.750.18750]#frlefttooth

spose[1][0.75-0.18750]#frrighttooth

spose[2][0.250.530]#leftcorner

spose[3][0.25-0.5-30]#rightcorner

)

The

processofw

orkingout

where

thesensors

gorelative

tothe

originofthe

robotis

them

ostcom

plicatedpart

ofdescribing

thesensor,the

restis

easy.To

definethe

size,range

andfield

ofview

ofthe

sonarsw

ejust

consultthe

sonardevice’s

datasheet.

definebigbobs_sonarsranger

(#numberofsonars

scount4

#definetheposeofeachtransducer[xposyposheading]

spose[0][0.750.18750]#frlefttooth

spose[1][0.75-0.18750]#frrighttooth

spose[2][0.250.530]#leftcorner

spose[3][0.25-0.5-30]#rightcorner

#definethefieldofviewofeachtransducer

#[range_minrange_maxview_angle]

sview[0.32.010]

#definethesizeofeachtransducer[xsizeysize]inmetres

ssize[0.010.05]

)

Now

thatB

igbob’ssonars

aredone

we

will

attacheda

blobfinder:

definebigbobs_eyesblobfinder

(#parameters

)

Bigbob

isa

rubbish-collectorso

herew

eshould

tellitw

hatcolour

ofrubbishto

lookfor.

Let’s

saythat

theintended

applicationof

Bigbob

isin

anorange

juicefactory

andhe

picksup

anystray

orangesor

juicecartons

thatfallon

thefloor.

Oranges

areorange,and

juicecartons

are(let’s

say)dark

blueso

Bigbob’s

blobfinderw

illlook

forthese

two

colours:

definebigbobs_eyesblobfinder

(#numberofcolourstolookfor

colors_count2

23

#whichcolourstolookfor

colors["orange""DarkBlue"]

)Then

we

definethe

propertiesofthe

camera,again

thesecom

efrom

adatasheet:

definebigbobs_eyesblobfinder

(#numberofcolourstolookfor

colors_count2

#whichcolourstolookfor

colors["orange""DarkBlue"]

#cameraparameters

image[160120]#resolution

range5.00

fov3.14159/3#60degrees=pi/3radians

)InStage

2.X.X

thefollow

ingcode

shouldbe

usedinstead:

#bigbob’sblobfinder

definebigbobs_eyesptz

(blobfinder

(#numberofcolourstolookfor

channels_count2

#whichcolourstolookfor

channels["orange""DarkBlue"]

#cameraparameters

image[160120]#resolution

range_max5.00

ptz[0060]

))

The

lastsensor

thatneeds

addingto

Bigbob

isthe

laser,which

willbe

usedto

detectw

henevera

pieceof

rubbishhas

beencollected.

Following

thesam

eprinciples

asfor

ourprevious

sensorm

odelsw

ecan

createa

descriptionof

thislaser:

definebigbobs_laserlaser

(range_min0.0

#distancebetweenteethinmetres

range_max0.25

24

Page 13: Player Stage Tutorial Manual 2.1

Figure

13:T

heposition

ofB

igbob’slaser

(inred)

andits

distance,in

metres,

relativeto

itsorigin

(marked

with

across).

fov3.14159/9#20degrees=pi/9radians

#fov20#usethislineinsteadofaboveifusingstage2.X.X

pose[0.6250.125270]

size[0.0250.025]

)With

thislaser

we’ve

setits

maxim

umrange

tobe

thedistance

between

teeth,and

thefield

ofview

isarbitrarily

setto

20 ◦.W

ehave

calculatedthe

laser’spose

inexactly

thesam

ew

ayas

thesonars

spose,

bym

easuringthe

distancefrom

thelaser’s

centreto

therobot’s

centreof

rotation,thelaser’s

yawis

setto

270 ◦so

thatit

pointsacross

Bigbob’s

teeth.W

ealso

setthe

sizeof

thelaser

tobe

2.5cmsquare

sothat

itdoesn’t

obstructthe

gapbetw

eenB

igbob’steeth.

Now

thatw

ehave

arobot

bodyand

sensorm

odelsall

we

needto

dois

putthem

togetherand

placethem

inthe

world.

To

addthe

sensorsto

thebody

we

needto

goback

tothe

bigbobposition

model:

definebigbobposition

(#actualsize

size[1.251]

#centreofrotationoffset

origin[0.12500]

#theshapeofBigbob

polygons3

...

...

...

25

#positonalthings

mass10.0

drive"diff"

#sensorsattachedtobigbob

bigbobs_sonars()

bigbobs_eyes()

bigbobs_laser()

)The

extraline

bigbobs_sonars()

addsthe

sonarm

odelcalledbigbobs_sonars()

ontothe

bigbob

model,

likewise

forbigbobs_eyes()

andbigbobs_laser().

After

thisfinalstep

we

nowhave

acom

pletem

odelofourrobot

bigbob,thefull

codefor

which

canbe

foundin

appendixA

.Atthis

pointit’s

worthw

hileto

copythis

intoa

.incfile,

sothat

them

odelcould

beused

againin

othersim

ulationsor

worlds.

To

putour

Bigbob

model

intoour

empty

world

(seesection

3.1.3)w

eneed

toadd

therobot

toour

worldfile

empty.w

orld:

include"map.inc"

include"bigbob.inc"

#sizeofthewholesimulation

size[1515]

#configuretheGUIwindow

window

(size[700.000700.000]

scale0.025

)#loadanenvironmentbitmap

map

(bitmap"bitmaps/cave.png"

size[1515]

)bigbob

(name"bob1"

pose[-5-645]

color"red"

)Here

we’ve

putall

thestuff

thatdescribes

Bigbob

intoa

.incfile

bigbob.inc,

andw

henw

einclude

this,all

thecode

fromthe

.incfile

isinserted

intothe

26

Page 14: Player Stage Tutorial Manual 2.1

.world

file.T

hesection

hereis

where

we

puta

versionof

thebigbob

modelinto

ourw

orld:

bigbob

(name"bob1"

pose[-5-645]

color"green"

)Bigbob

isa

model

description,by

notincluding

anydefine

stuffin

thetop

linethere

itm

eansthat

we

arem

akingan

instantiationof

thatm

odel,w

iththe

namebob1.

Using

anob

ject-orientedprogram

ming

analogy,bigbob

isour

class,and

bob1

isour

object

ofclass

bigbob.

The

pose[xyyaw]

parameter

works

inthe

same

was

asspose[xyyaw]

does.T

heonly

differencesare

thatthe

coordinatesuse

thecentre

ofthe

simulation

asa

referencepoint

andpose

letsus

specifythe

initialposition

andheading

ofthe

entirebob1

model,

notjust

onesensor

within

thatm

odel.Finally

we

specifyw

hatcolour

bob1

shouldbe,

bydefault

thisis

red.T

hepose

andcolor

parameters

couldhave

beenspecified

inour

bigbobm

odelbut

byleaving

themout

itallow

sus

tovary

thecolour

andposition

ofthe

robotsfor

eachdifferent

robotof

typebigbob,so

we

coulddeclare

multiple

robotsw

hichare

thesam

esize,shape

andhave

thesam

esensors,but

arerendered

byP

layer/Stagein

differentcolours

andare

initialisedat

differentpoints

inthe

map.

When

we

runthe

newem

pty.world

with

Player/Stage

we

seeour

Bigbob

robotis

occupyingthe

world,

asshow

nin

figure14.

The

darkm

arkon

topof

therobot

isthe

blobfindercam

era.

3.3

Build

ing

Oth

er

Stu

ff

We

establishedin

section3.2.2

thatB

igbobw

orksin

aorange

juicefactory

collectingoranges

andjuice

cartons.N

oww

eneed

tobuild

models

torepresent

theoranges

andjuice

cartonsso

thatB

igbobcan

interactw

iththings.

We’ll

startby

buildinga

model

ofan

orange:

defineorangemodel

(#parameters...

)The

firstthing

todefine

isthe

shapeof

theorange.

The

polygons

parameter

isone

way

ofdoing

this,w

hichw

ecan

useto

builda

blockyapproxim

ationof

acircle.

An

alternativeto

thisis

touse

bitmap

which

we

previouslysaw

beingused

tocreate

am

ap.W

hatthe

bitmap

comm

andactually

doesis

takein

apicture,

andturn

itinto

aseries

ofpolygons

which

areconnected

togetherto

make

am

odelthe

same

shapeas

thepicture.

This

isillustrated

infigure

15.To

getrid

ofthe

blocks’outlinesadd

gui_outline0

tothe

modeldescription,

with

thelarge

ghostin

figure15

it’snot

som

uchofa

problem,but

with

smaller

models,like

anorange,the

blackoutlines

preventthe

model’s

colourfrom

beingvisible.

27

Figure

14:O

urbob1

robotplaced

inthe

empty

world.

Figure

15:T

heleft

image

isthe

originalpicture,

theright

image

isits

Player/Stage

interpretation.

28

Page 15: Player Stage Tutorial Manual 2.1

Figure

16:./bitm

aps/circle.png

Figure

17:T

heorange

model

renderedin

thesam

eP

layer/Stagew

indowas

Bigbob.

defineorangemodel

(bitmap"bitmaps/circle.png"

size[0.150.15]

color"orange"

gui_outline0

gripper_return1

)Inthis

codew

edescribe

am

odelcalled

orange

which

usesa

bitmap

todefine

itsshape

andrepresents

anob

jectw

hichis

15cmby

15cmand

colouredorange.

The

gripper_return

parameter

isa

specialtype

ofreturn

becauseit

means

thatthe

modelcan

begrabbed

bya

robot’sgripper

butit

alsom

eansthe

object

canbe

pusheda

littlebit

inthe

simulation.

We

want

ourorange

model

tobe

pushableso,even

thoughB

igbobhas

nogripper,the

orange’sgripper_return

parameter

isset

totrue.

Figure

17show

sour

orangem

odelnext

toB

igbob.B

uildinga

juicecarton

model

issim

ilarlyquite

easy:

definecartonmodel

(#acartonisretangular

#somakeasquareshapeandusesize[]

polygons1

polygon[0].points4

polygon[0].point[0][00]

polygon[0].point[1][01]

polygon[0].point[2][11]

polygon[0].point[3][10]

#averagecartonsizeis~20cmx10cmx5cm

size[0.10.2]

color"DarkBlue"

gripper_return1

)

29

We

canuse

thepolygons

comm

andsince

juicecartons

areboxy,w

ithboxy

thingsit’s

slightlyeasier

todescribe

theshape

with

polygon

thandraw

inga

bitmap

andusing

that.

Now

thatw

ehave

describedbasic

orange

andcarton

models

it’stim

eto

putsom

eoranges

andcartons

intothe

simulation.

This

isdone

inthe

same

way

asour

example

robotw

asput

intothe

world:

orange

(name"orange1"

pose[-2-50]

)carton

(name"carton1"

pose[-3-50]

)We

createdm

odelsoforanges

andcartons,and

noww

eare

declaringthat

therew

illbean

instanceofthese

models

(calledorange1

andcarton1

respectively)at

thegiven

positions.U

nlikew

iththe

robot,we

declaredthe

color

ofthem

odelsin

thedescription

sow

edon’t

needto

dothat

here.If

we

didhave

differentcolours

foreach

orangeor

cartonthen

itw

ouldm

essup

theblobfinding

onB

igbobbecause

therobot

isonly

searchingfor

orangeand

darkblue.

At

thispoint

itw

ouldbe

usefulif

we

couldhave

more

thanjust

oneorange

orcarton

inthe

world

(Bigbob

would

notbe

verybusy

ifthere

wasn’t

much

topick

up),it

turnsout

thatthis

isalso

prettyeasy:

orange(name"orange1"pose[-1-50])

orange(name"orange2"pose[-2-50])

orange(name"orange3"pose[-3-50])

orange(name"orange4"pose[-4-50])

carton(name"carton1"pose[-2-40])

carton(name"carton2"pose[-2-30])

carton(name"carton3"pose[-2-20])

carton(name"carton4"pose[-2-10])

Up

untilnow

we

havebeen

describingm

odelsw

itheach

parameter

ona

newline,

thisis

justa

way

ofm

akingit

more

readablefor

theprogram

mer

–especially

ifthere

area

lotof

parameters.

Ifthere

areonly

afew

parameters

oryou

want

torepeat

thecode

(asw

e’vedone

here)it

canall

beput

ontoone

line.H

erew

edeclare

thatthere

will

befour

orange

models

inthe

simulation

with

thenam

esorange1

toorange4,w

ealso

needto

specifydifferent

posesfor

them

odelsso

theyaren’t

allon

topof

eachother.

Properties

thatthe

orangem

odelshave

incom

mon

(suchas

shape,colour

orsize)

shouldall

bein

them

odeldefinition.

The

fullw

orldfileis

includedin

appendixB

,this

includesthe

orangeand

cartonm

odelsas

wellas

thecode

forputting

themin

thesim

ulation.Figure

18show

sthe

populatedP

layer/Stagesim

ulation.

30

Page 16: Player Stage Tutorial Manual 2.1

Figure

18:T

heB

igbobrobot

placedin

thesim

ulationalong

with

junkfor

itto

pickup.

4W

riting

aC

onfigura

tion

(.cfg)

File

As

mentioned

earlier,P

layeris

ahardw

areabstraction

layerw

hichconnects

yourcode

tothe

robot’shardw

are.It

doesthis

byacting

asa

Server/Client

typeprogram

where

yourcode

andthe

robot’ssensors

areclients

toa

Player

serverw

hichthen

passesthe

dataand

instructionsaround

tow

hereit

allneedsto

go.T

hisstuff

will

beproperly

explainedin

section5,

itall

soundsm

orecom

plicatedthan

itis

becauseP

layer/Stagetakes

careof

allthe

difficult

stuff.T

heconfiguration

fileis

neededin

orderto

tellthe

Player

serverw

hichdrivers

touse

andw

hichinterfaces

thedrivers

will

beusing.

Foreach

model

inthe

simulation

ordevice

onthe

robotthat

youw

antto

interactw

ith,you

will

needto

specifya

driver.T

hisis

fareasier

thanw

ritingw

orldfileinform

ation,and

follows

thesam

egeneral

syntax.T

hedriver

specificationis

inthe

form:

driver

(name"driver_name"

provides[device_address]

#otherparameters...

)The

name

andprovides

parameters

arem

andatoryinform

ation,without

themP

layerw

on’tknow

which

driverto

use(given

byname)

andw

hatkind

ofin-

formation

iscom

ingfrom

thedriver

(provides).

The

name

parameter

isnot

31

arbitrary,itm

ustbe

thenam

eofone

ofPlayer’s

inbuiltdrivers

17

thathave

beenw

rittenfor

Player

tointeract

with

arobot

device.A

listof

supporteddriver

names

isin

theP

layerM

anual 18,

althoughw

henusing

Stagethe

onlyone

thatis

neededis"stage".

The

provides

parameter

isa

littlem

orecom

plicatedthan

name.

Itis

herethat

youtellP

layerw

hatinterface

touse

inorder

tointerpret

information

givenout

bythe

driver(often

thisis

sensorinform

ationfrom

arobot),any

information

thata

driverprovides

canbe

usedby

yourcode.

Fora

Stagesim

ulatedrobot

the"stage"

drivercan

providethe

interfacesto

thesensors

discussedin

section3.2.1.

Each

interfaceshares

thesam

enam

eas

thesensor

model,so

forexam

plearanger

model

would

usethe

ranger

interfaceto

interactw

ithP

layerand

soon

(theonly

exceptionto

thisbeing

theposition

model

which

usesthe

position2d

interface).T

heP

layerm

anualcontains

alist

ofall

thedifferent

interfacesthat

canbe

used19,the

most

usefuloneshave

alreadybeen

mentioned

insection

3.2.1,although

thereare

otherstoo

numerable

tolist

here.T

heinput

tothe

provides

parameter

isa

“deviceaddress”,w

hichspecifies

which

TC

Pport

aninterface

toa

robotdevice

canbe

found,section4.1

hasm

oreinform

ationabout

deviceaddresses.

This

usesthe

key:host:robot:interface:indexform

separatedby

white

space.

provides["key:host:robot:interface:index"

"key:host:robot:interface:index"

"key:host:robot:interface:index"

...]

After

thetw

om

andatoryparam

eters,thenext

most

usefuldriverparam

eterismodel.

This

isonly

usedif"stage"

isthe

driver,ittells

Player

which

partic-ular

model

inthe

worldfile

isproviding

theinterfaces

forthis

particulardriver.

Adifferent

driveris

neededfor

eachm

odelthat

youw

antto

use.M

odelsthat

aren’trequired

todo

anything(such

asa

map,or

inthe

example

ofsection

3.3oranges

andboxes)

don’tneed

tohave

adriver

written

forthem

.T

herem

ainingdriver

parameters

arerequires

andplugin.

The

requires

isused

fordrivers

thatneed

inputinform

ationsuch

as"vfh",

ittells

thisdriver

where

tofind

thisinform

ationand

which

interfaceit

uses.T

herequires

pa-ram

eteruses

thesam

ekey:host:robot:interface:index

syntaxas

theprovides

parameter.

Finally

theplugin

parameter

isused

totell

Player

where

tofind

allthe

information

aboutthe

driverbeing

used.E

arlierw

em

adea

.cfgfile

inorder

tocreate

asim

ulationof

anem

pty(or

atleast

unmoving)

world,

the.cfg

fileread

asfollow

s:

driver

(name"stage"

plugin"libstageplugin"

provides["simulation:0"]

17It

isalso

possib

leto

build

yourow

ndriv

ersfo

ra

hard

ware

dev

icebutth

isdocu

men

tw

on’t

go

into

how

todo

this

beca

use

it’snot

relevant

toP

layer/

Sta

ge.

18http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

Pla

yer-2

.1.0

/pla

yer/

gro

up

driv

ers.htm

l19http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

Pla

yer-2

.1.0

/pla

yer/

gro

up

interfa

ces.htm

l

32

Page 17: Player Stage Tutorial Manual 2.1

#loadthenamedfileintothesimulator

worldfile"empty.world"

)This

hasto

bedone

atthe

beginningof

theconfiguration

filebecause

ittells

Player

thatthere

isa

drivercalled

"stage"

thatw

e’regoing

touse

andthe

codefor

dealingw

iththis

drivercan

befound

inthe

libstageplugin

plugin.T

hisneeds

tobe

specifiedfor

Stagebecause

Stageis

anadd-on

forP

layer,fordrivers

thatare

builtinto

Player

bydefault

theplugin

doesn’tneed

tobe

specified.

4.1

Device

Addre

sses

-key:h

ost:ro

bot:in

terfa

ce:in

dex

Adevice

addressis

usedto

tellP

layerw

herethe

driveryou

arem

akingw

illpresent

(orreceive)

information

andw

hichinterface

touse

inorder

toread

thisinform

ation.T

hisis

astring

inthe

formkey:host:robot:interface:index

where

eachfield

isseparated

bya

colon.

•key:

The

Player

manual

statesthat:

“The

purposeof

thekey

fieldis

toallow

adriver

thatsupports

multiple

interfacesof

thesam

etype

tom

apthose

interfacesonto

different

devices”[1].T

hisis

adriver

levelthingand

hasa

lotto

dow

iththe

name

ofthedriver

thatyou

areusing,generally

for"stage"

thekey

doesn’tneed

tobe

used.If

you’reusing

Player

without

Stagethen

thereis

ausefulsection

aboutdevice

addresskeys

inthe

Player

manual 2

0.

•host:

This

isthe

addressofthe

hostcom

puterw

herethe

deviceis

located.W

itha

robotit

couldbe

theIP

addressof

therobot.

The

defaulthost

is“localhost”

which

means

thecom

puteron

which

Player

isrunning.

•robot:

thisis

theT

CP

portthrough

which

Player

shouldexpect

toreceive

datafrom

theinterface

usuallya

singlerobot

andall

itsnecessary

inter-faces

areassigned

toone

port.T

hedefault

portused

is6665,ifthere

were

two

robotsin

thesim

ulationthe

portscould

be6665

and6666

althoughthere’s

norule

sayingw

hichnum

berports

youcan

orcan’t

use.

•interface:

The

interfaceto

usein

orderto

interactw

iththe

data.T

hereis

nodefault

valuefor

thisoption

becauseit

isa

mandatory

field.

•index:

Ifarobot

hasm

ultipledevices

ofthesam

etype,for

instanceit

has2

cameras

togive

therobot

depthperception,

eachdevice

usesthe

same

interfacebut

givesslightly

differentinform

ation.T

heindex

fieldallow

syou

togive

aslightly

differentaddress

toeach

device.So

two

cameras

couldbe

camera:0

andcamera:1.

This

isvery

differentfrom

thekey

fieldbecause

havinga

“driverthat

supportsm

ultipleinterfaces

ofthe

same

type”is

NO

Tthe

same

ashaving

multiple

devicesthat

usethe

same

interface.A

gainthere

isno

defaultindex,

asthis

isa

mandatory

fieldin

thedevice

address,but

youshould

use0

asthe

indexif

thereis

onlyone

ofthat

kindof

device.

Ifyou

want

touse

anyof

thedefault

valuesit

canjust

beleft

outof

thedevice

address.So

we

coulduse

thedefault

hostand

robotport

andspecify

(forexam

-ple)

alaser

interfacejust

bydoing

"laser:0".

How

ever,if

youw

antto

specify20http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

Pla

yer-2

.1.0

/pla

yer/

gro

up

tuto

rial

config.h

tml#

dev

icekey

33

fieldsat

thebeginning

ofthedevice

addressbut

notin

them

iddlethen

thesepa-

ratingcolons

shouldrem

ain.For

example

ifwe

hada

hostat

"127.0.0.1"

with

alaser

interfacethen

we

would

specifythe

addressas

"127.0.0.1::laser:0",

therobot

fieldis

empty

butthe

colonsaround

itare

stillthere.Y

oum

aynotice

thatthe

keyfield

herew

asleft

offas

before.

4.2

Puttin

gth

eC

onfigura

tion

File

Togeth

er

We

haveexam

inedthe

comm

andsnecessary

tobuild

adriver

fora

modelin

thew

orldfile,nowit

isjust

acase

ofputtingthem

alltogether.To

demonstrate

thisprocess

we

will

builda

configurationfile

forthe

worldfile

developedin

section3.

Inthis

world

we

want

ourcode

tobe

ableto

interactw

iththe

robot,so

inour

configurationfile

we

needto

specifya

driverfor

thisrobot.

driver

(#parameters...

)

The

inbuiltdriver

thatP

layer/Stageuses

forsim

ulationsis

called"stage"

sothe

drivernam

eis"stage".

driver

(name"stage"

)The

Bigbob

robotuses

position,

laser,

blobfinder

andranger

sensors.T

hesecorrespond

tothe

position2d,

laser,

blobfinder

andinterfaces

re-spectively.

The

ranger

sensoris

aspecialcase

becausethe

rangerinterface

hasnot

currentlybeen

implem

ented(for

versionsStage

3.0.1or

earlier).To

work

aroundthis

you’llneedto

usethe

sonar

interfacesinstead

(thereis

apparentlyan

IRinterface

which

couldbe

usedinstead

ofranger,

butit

doesn’tseem

tow

orkon

eitherStage

2or

Stage3).

We

want

ourcode

tobe

ableto

readfrom

thesesensors,

sow

eneed

todeclare

interfacesfor

themand

tellP

layerw

hereto

findeach

device’sdata,

forthis

we

usethe

configurationfile’s

provides

parameter.

This

requiresthat

we

constructdevice

addressesfor

eachsensor;

torem

indourselves,

thisis

inthe

key:host:robot:interface:indexform

at.W

earen’t

usingany

fancydrivers,so

we

don’tneed

tospecify

akey.

We

arerunning

ourrobot

ina

simulation

onthe

same

computer

asour

Player

sever,so

thehost

name

islocalhost

which

isthe

default,so

we

alsodon’t

needto

specifya

host.T

herobot

isa

TC

Pport

toreceive

robotinform

ationover,

pickingw

hichport

touse

ispretty

arbitrarybut

what

usuallyhappens

isthat

thefirst

robotuses

thedefault

port6665

andsubsequent

robotsuse

6666,6667,6668etc.

There

isonly

onerobot

inour

simulation

sow

ew

illuseport

6665for

alloursensor

information

fromthis

robot.W

eonly

haveone

sensorofeach

type,soour

devicesdon’t

needseparate

indices.W

hatw

ouldhappen

ifw

edid

haveseveral

sensorsof

thesam

etype

(likesay

two

cameras)

isthat

we

putthe

firstdevice

atindex

0and

subsequentdevices

usingthe

same

interfacehave

index1,

then2,

then3

andso

on. 21

Finally

we

21T

here

are

lots

ofra

nger

senso

rsin

our

model

but

when

we

created

the

robot’s

senso

rsin

section

3.2

.2w

eput

them

all

into

the

sam

era

nger

model.

So

as

far

as

the

configura

tion

file

34

Page 18: Player Stage Tutorial Manual 2.1

useinterfaces

appropriateto

thesensors

therobot

has,soin

ourexam

plethese

arethe

position,

laser,

blobfinder

interfacesand

forour

ranger

devicesw

ew

illuse

sonar.

Putting

allthis

togetherunder

theprovides

parameter

givesus:

driver

(name"stage"

provides["6665:position2d:0"

"6665:sonar:0"

"6665:blobfinder:0"

"6665:laser:0"]

)The

deviceaddresses

canbe

onthe

same

lineas

eachother

orseparate

lines,just

solong

asthey’re

separatedby

some

formof

white

space.T

helast

thingto

doon

ourdriver

isthe

model"model_name"

parameter

which

needsto

bespecified

becausew

eare

usingP

layer/Stage.T

histells

thesim

ulationsoftw

arethat

anythingyou

dow

iththis

driverw

illaffect

them

odel"model_name"

inthe

simulation.

Inthe

simulation

we

builtw

enam

edour

robotm

odel“bob1”,

soour

finaldriver

forthe

robotw

illbe:

driver

(name"stage"

provides["6665:position2d:0"

"6665:sonar:0"

"6665:blobfinder:0"

"6665:laser:0"]

model"bob1"

)Ifour

simulation

hadm

ultipleB

igbobrobots

in,the

configurationfile

driversw

ouldbe

verysim

ilarto

oneanother.

Ifw

ecreated

asecond

robotin

ourw

orldfileand

calledit

“bob2”then

thedriver

would

be:

driver

(name"stage"

provides["6666:position2d:0"

"6666:sonar:0"

"6666:blobfinder:0"

"6666:laser:0"]

model"bob2"

)Notice

thatthe

portnum

berand

model

name

arethe

onlydifferences

becausethe

robotshave

allthe

same

sensors.

isco

ncern

edth

ereis

only

one

ragin

gdev

iceusin

geith

erth

eso

nar

or

IRin

terface,

beca

use

all

the

separa

tera

nger

dev

icesare

lum

ped

togeth

erin

toth

isone

model.

We

don’t

need

todecla

reea

chra

nger

on

an

index

ofits

ow

n.

35

Adriver

ofthis

kindcan

bebuilt

forany

model

thatis

inthe

worldfile,

notjust

therobots.

Forinstance

am

apdriver

canbe

made

which

usesthe

map

interfaceand

will

allowyou

toget

size,origin

andoccupancy

dataabout

them

ap.T

heonly

requirement

isthat

ifyou

want

todo

something

tothe

modelw

ithyour

codethen

youneed

tobuild

adriver

forit

inthe

configurationfile.

Finally

when

we

putthe

bitw

hichdeclares

thestage

driver(this

partis

compulsory

forany

simulation

configurationfile)

togetherw

ithour

driversfor

therobot

we

endup

with

ourfinal

configurationfile:

driver

(name"stage"

plugin"libstageplugin"

provides["simulation:0"]

#loadthenamedfileintothesimulator

worldfile"worldfile_name.world"

)driver

(name"stage"

provides["6665:position2d:0"

"6665:sonar:0"

"6665:blobfinder:0"

"6665:laser:0"]

model"bob1"

)5G

ettin

gY

our

Sim

ula

tion

To

Run

Your

Code

To

learnhow

tow

ritecode

forP

layeror

Player/Stage

ithelps

tounderstand

thebasic

structureof

howP

layerw

orks.P

layeruses

aServer/C

lientstructure

inorder

topass

dataand

instructionsbetw

eenyour

codeand

therobot’s

hardware.

Player

isa

server,anda

hardware

device22

onthe

robotis

subscribedas

aclient

tothe

servervia

athing

calleda

proxy.T

he.cfg

fileassociated

with

yourrobot

(oryour

simulation)

takescare

oftelling

theP

layerserver

which

devicesare

attachedto

it,sow

henw

erun

thecom

mand

playersome_cfg.cfg

thisstarts

upthe

Player

serverand

connectsall

thenecessary

hardware

devicesto

theserver.

Figure

19show

sa

basicblock

diagramof

thestructure

ofP

layerw

henim

plemented

ona

robot.In

Player/Stage

thesam

ecom

mand

will

startthe

Player

serverand

loadup

thew

orldfilein

asim

ulationw

indow,

thisruns

onyour

computer

andallow

syour

codeto

interactw

iththe

simulation

ratherthan

hardware.

Figure

20show

sa

basicblock

diagramofthe

Player/Stage

structure.Y

ourcode

must

alsosubscribe

tothe

Player

serverso

thatit

canaccess

theseproxies

andhence

controltherobot.

Player

hasfunctions

andclasses

which

will

22rem

ember,

adev

iceis

apiece

ofhard

ware

thatuses

adriv

erw

hich

confo

rmsto

an

interfa

ce.See

section

2.2

36

Page 19: Player Stage Tutorial Manual 2.1

Figure

19:T

heserver/client

controlstructure

ofP

layerw

henused

ona

robot.T

herem

aybe

severalproxies

connectedto

theserver

atany

time.

doall

thisfor

you,but

youstill

needto

actuallycall

thesefunctions

with

yourcode

andknow

howto

usethem

.P

layeris

compatable

with

C,C

++

orP

ythoncode,how

everin

thism

anualw

ew

illonlyreally

beusing

C+

+because

itis

thesim

plestto

understand.T

heprocess

ofw

ritingP

layercode

ism

ostlythe

same

foreach

differentlanguage

though.T

heP

layerand

Player

proxyfunctions

havedifferent

names

foreach

language,but

work

inm

oreor

lessthe

same

way,

soeven

ifyou

don’tplan

onusing

C+

+or

Stagethis

sectionw

illstill

containhelpful

information.

Before

beginninga

projectit

ishighly

recomm

endedthat

forany

programs

otherthan

basicexam

plesyou

shouldalw

aysw

rapyour

Player

comm

andsaround

yourow

nfunctions

andclasses

sothat

allyourcode’s

interactionsw

ithP

layerare

kepttogether

thesam

efile.

This

isn’ta

requirement

ofP

layer,it’s

justgood

practice.For

example,ifyou

upgradeP

layeror

ifforsom

ereason

yourrobot

breaksand

acertain

functionno

longerw

orksyou

onlyhave

tochange

partof

afile

insteadof

searchingthrough

allyourcode

forplaces

where

Player

functionshave

beenused.

Finally,

inorder

tocom

pileyour

programyou

usethe

following

comm

ands(in

Linux):

g++-oexample0`pkg-config--cflagsplayerc++`example0.cc`pkg-config

--libsplayerc++`

That

will

compile

aprogram

toa

filecalled

example0

fromthe

C+

+code

fileexample0.cc.

Ifyou

arecoding

inC

insteadthen

usethe

following

com-

mand:

gcc-oexample0`pkg-config--cflagsplayerc`example0.c`pkg-config

--libsplayerc`

5.1

Connectin

gto

the

Serv

erand

Pro

xie

sW

ithY

ourC

ode

The

firstthing

todo

within

yourcode

isto

includethe

Player

headerfile.

Assum

ingP

layer/Stageis

installedcorrectly

onyour

machine

thenthis

canbe

37

Figure

20:T

heserver/client

controlstructure

ofP

layer/Stagew

henused

asa

simulator.

There

may

beseveral

proxiesconnected

tothe

serverat

anytim

e.

donew

iththe

line#include<libplayerc++/playerc++.h>

(ifyou’re

usingC

thentype

#include<libplayerc/playerc.h>

instead).N

extw

eneed

toestablish

aP

layerC

lient,which

willinteract

with

theP

layerserver

foryou.

To

dothis

we

usethe

line:

PlayerClientclient_name(hostname,port);

What

thisline

doesis

declarea

newob

jectw

hichis

aP

layerClient

calledclient_name

which

connectsto

theP

layerserver

atthe

givenaddress.

The

hostname

andport

islike

thatdiscussed

insection

4.1.If

yourcode

isrun-

ningon

thesam

ecom

puter(or

robot)as

theP

layerserver

youw

ishto

connectto

thenthe

hostname

is“localhost”

otherwise

itw

illbe

theIP

addressof

thecom

puteror

robot.T

heport

isan

optionalparam

eterusually

onlyneeded

forsim

ulations,it

will

bethe

same

asthe

portyou

gavein

the.cfg

file.T

hisis

onlyuseful

ifyour

simulation

hasm

orethan

onerobot

inand

youneed

yourcode

toconnect

toboth

robots.So

ifyou

gaveyour

firstrobot

port6665

andthe

secondone

6666(like

inthe

example

ofsection

4.2)then

youw

ouldneed

two

PlayerC

lients,oneconnected

toeach

robot,andyou

would

dothis

with

thefollow

ingcode:

PlayerClientrobot1("localhost",6665);

PlayerClientrobot2("localhost",6666);

Ifyou

areonly

usingone

robotand

inyour

.cfgfile

yousaid

thatit

would

operateon

port6665

thenthe

portparam

eterto

theP

layerClient

classis

notneeded.O

ncew

ehave

establisheda

PlayerC

lientw

eshould

connectour

codeto

thede-

viceproxies

sothat

we

canexchange

information

with

them.

Which

proxiesyou

canconnect

yourcode

tois

dependenton

what

youhave

putin

yourconfigura-

tionfile.

Forinstance

ifyourconfiguration

filesays

yourrobot

isconnected

toa

laserbut

nota

camera

youcan

connectto

thelaser

devicebut

notthe

camera,

evenif

therobot

(orrobot

simulation)

hasa

camera

onit.

38

Page 20: Player Stage Tutorial Manual 2.1

Proxies

takethe

name

oftheinterface

which

thedrivers

useto

talkto

Player.

Let’s

takepart

ofthe

Bigbob

example

configurationfile

fromsection

4.2:

driver

(name"stage"

provides["6665:position2d:0"

"6665:sonar:0"

"6665:blobfinder:0"

"6665:laser:0"]

)Here

we’ve

toldthe

Player

serverthat

our“robot”

hasdevices

which

usethe

position2d,sonar,

blobfinderand

laserinterfaces.

Inour

codethen,

we

shouldconnect

tothe

position2d,sonar,

blobfinderand

laserproxies

likeso:

Position2dProxypositionProxy_name(&client_name,index);

SonarProxy

sonarProxy_name(&client_name,index);

BlobfinderProxyblobProxy_name(&client_name,index);

LaserProxy

laserProxy_name(&client_name,index);

Afulllist

ofwhich

proxiesP

layersupports

canbe

foundin

theP

layerm

anual 23,

theyall

followthe

conventionof

beingnam

edafter

theinterface

theyuse.

Inthe

abovecase

xProxy_name

isthe

name

youw

antto

giveto

theproxy

object,

client_name

isthe

name

yougave

theP

layerClient

object

earlierand

index

isthe

indexthat

thedevice

was

givenin

yourconfiguration

file(probably

0).

5.1.1Settin

gU

pC

onnection

s:an

Exam

ple.

Foran

example

ofhowto

connectto

theP

layersever

anddevice

proxiesw

ew

illuse

theexam

pleconfiguration

filedeveloped

insection

4.2.For

conveniencethis

isreproduced

below:

driver

(name"stage"

plugin"libstageplugin"

provides["simulation:0"]

#loadthenamedfileintothesimulator

worldfile"worldfile_name.world"

)driver

(name"stage"

provides["6665:position2d:0"

"6665:sonar:0"

"6665:blobfinder:0"

23http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

Pla

yer-2

.1.0

/pla

yer/

classP

layerC

c1

1C

lientP

roxy.h

tml

39

"6665:laser:0"]

model"bob1"

)To

setup

aP

layerClient

andthen

connectto

proxieson

thatserver

we

canuse

principlesdiscussed

inthis

sectionto

developthe

following

code:

#include<stdio.h>

#include<libplayerc++/playerc++.h>

intmain(intargc,char*argv[])

{/*needtodothislineinc++only*/

usingnamespacePlayerCc;

PlayerClient

robot("localhost");

Position2dProxyp2dProxy(&robot,0);

SonarProxy

sonarProxy(&robot,0);

BlobfinderProxyblobProxy(&robot,0);

LaserProxy

laserProxy(&robot,0);

//somecontrolcode

return0;

}5.2

Inte

ractin

gw

ithP

roxie

s

As

youm

ayexpect,

eachproxy

isspecialised

towards

controllingthe

deviceit

connectsto.

This

means

thateach

proxyw

illhavedifferent

comm

andsdepend-

ingon

what

itcontrols.

InP

layerversion

2.1.0there

are38

differentproxies

which

youcan

chooseto

use,many

ofwhich

arenot

applicableto

Player/Stage.

This

manualw

illnotattem

ptto

explainthem

all,afulllist

ofavaliable

proxiesand

theirfunctions

isin

theP

layerm

anual 24,although

thereturns,param

etersand

purposeof

theproxy

functionis

notalw

aysexplained.

The

following

fewproxies

areprobably

them

ostuseful

toanyone

usingP

layeror

Player/Stage.

5.2.1Position

2dP

roxy

The

Position2dP

roxyis

thenum

berone

most

usefulproxy

thereis.

Itcontrols

therobot’s

motors

andkeeps

trackof

therobot’s

odometry

(where

therobot

thinksit

isbased

onhow

farits

wheels

havem

oved).

Get/S

etSpeed

The

SetSpeed

comm

andis

usedto

tellthe

robot’sm

otorshow

fastto

turn.T

hereare

two

differentSetSpeed

comm

andsthat

canbe

called,one

isfor

robotsthat

canm

ovein

anydirection

andthe

otheris

forrobots

with

differentialor

car-likedrives.

•SetSpeed(doubleXSpeed,doubleYSpeed,doubleYawSpeed)

24http

://pla

yersta

ge.so

urcefo

rge.n

et/doc/

Pla

yer-2

.1.0

/pla

yer/

classP

layerC

c1

1C

lientP

roxy.h

tml

40

Page 21: Player Stage Tutorial Manual 2.1

Figure

21:A

roboton

acartesian

grid.T

hisshow

sw

hatdirections

theX

andY

speedsw

illcause

therobot

tom

ovein.

Apositive

yawspeed

will

turnthe

robotin

thedirection

ofthe

+arrow

,a

negativeyaw

speedis

thedirection

ofthe

-arrow

.

•SetSpeed(doubleXSpeed,doubleYawSpeed)

•SetCarlike(doubleXSpeed,doubleDriveAngle)

Figure

21show

sw

hichdirection

thex,

yand

yawspeeds

arein

relationto

therobot.

The

xspeed

isthe

rateat

which

therobot

moves

forward

andthe

yspeed

isthe

robot’sspeed

sideways,both

areto

begiven

inm

etresper

second.T

hey

speedw

illonly

beuseful

ifthe

robotyou

want

tosim

ulateor

controlis

aball,since

robotsw

ithw

heelscannot

move

sideways.

The

yawspeed

controlshow

fastthe

robotis

turningand

isgiven

inradians

persecond,

Player

hasan

inbuiltglobal

functioncalled

dtor()

which

convertsa

number

indegrees

intoa

number

inradians

which

couldbe

usefulw

hensetting

theyaw

speed.If

youw

antto

simulate

orcontrol

arobot

with

adifferential

drivesystem

thenyou’ll

needto

convertleft

andright

wheel

speedsinto

aforw

ardspeed

anda

turningspeed

beforesending

itto

theproxy.

Forcar-like

drivesthere

isthe

SetCarlike

which,

againis

theforw

ardspeed

inm

/sand

thedrive

anglein

radians.T

heGetSpeed

comm

andsare

essentiallythe

reverseof

theSetSpeed

com-

mand.

Insteadof

settinga

speedthey

returnthe

currentspeed

relativeto

therobot

(sox

isthe

forward

speed,yaw

isthe

turningspeed

andso

on).

•GetXSpeed:

forward

speed(m

etres/sec).

•GetYSpeed:

sideways

(perpendicular)speed

(metres/sec).

•GetYawSpeed:

turningspeed

(radians/sec).

Get

Pos

This

functioninteracts

with

therobot’s

odometry.

Itallow

syou

tom

onitorw

herethe

robotthinks

itis.

Coordinate

valuesare

givenrelative

toits

startingpoint,

andyaw

sare

relativeto

itsstarting

yaw.

•GetXPos():

givescurrent

xcoordinate

relativeto

itsx

startingposition.

41

•GetYPos():

givescurrent

ycoordinate

relativeto

itsy

startingposition.

•GetYaw():

givescurrent

yawrelative

toits

startingyaw

.

Insection

3.2.1,w

especified

whether

itw

ouldrecord

odometry

bym

easur-ing

howm

uchits

wheels

haveturned,

orw

hetherthe

robotw

ouldhave

perfectknow

ledgeofits

currentcoordinates

(bydefault

therobot

doesnot

recordodom

-etry

atall).

Ifyou

setthe

robotto

recordodom

etryusing

itsw

heelsthen

thepositions

returnedby

theseget

comm

andsw

illbecom

eincreasingly

inaccurateas

thesim

ulationgoes

on.If

youw

antto

logyour

robotsposition

asit

moves

around,thesefunctions

alongw

iththe

perfectodom

etry25

settingcan

beused.

SetM

otorEnab

le()T

hisfunction

takesa

booleaninput,telling

Player

whether

toenable

them

otorsor

not.If

them

otorsare

disabledthen

therobot

will

notm

oveno

matter

what

comm

andsare

givento

it,ifthe

motors

areenabled

thenthe

motors

will

always

work,

thisis

notso

desirableif

therobot

ison

adesk

orsom

ethingand

islikely

toget

damaged.

Hence

them

otorsbeing

enabledis

optional.Ifyou

areusing

Player/Stage,then

them

otorsw

illalways

beenabled

andthis

comm

anddoesn’t

needto

berun.

How

ever,if

yourcode

isever

likelyto

bem

ovedonto

arealrobot

andthe

motors

arenot

explicitlyenabled

inyour

code,then

youm

ayend

upspending

along

time

tryingto

work

outw

hyyour

robotis

notw

orking.

5.2.2Son

arProx

y

The

sonarproxy

canbe

usedto

receivethe

distancefrom

thesonar

toan

obstaclein

metres.

To

dothis

youuse

thecom

mand:

•sonarProxy_name[sonar_number]

Where

sonarProxy_name

isthe

SonarProxy

object

andsonar_number

isthe

number

ofthe

ranger.In

Player/Stage

thesonar

numbers

come

fromthe

orderin

which

youdescribed

theranger

devicesin

thew

orldfile.In

section3.2.2

we

describedthe

rangersensors

forthe

Bigbob

robotlike

so:

definebigbobs_sonarsranger

(#numberofsonars

scount4

#definetheposeofeachtransducer[xposyposheading]

spose[0][0.750.18750]#frlefttooth

spose[1][0.75-0.18750]#frrighttooth

spose[2][0.250.530]#leftcorner

spose[3][0.25-0.5-30]#rightcorner

)Inthis

example

sonarProxy_name[0]

givesus

thedistance

fromthe

lefttooth

rangerto

anobstacle,

sonarProxy_name[1]

givesthe

distancefrom

thefront

righttooth

toan

obstacle,andso

on.Ifno

obstacleis

detectedthen

thefunction

will

returnw

hateverthe

ranger’sm

aximum

rangeis.

25See

section

3.2

.1fo

rhow

togiv

eth

ero

bot

perfect

odom

etry.

42

Page 22: Player Stage Tutorial Manual 2.1

Figure

22:H

owlaser

anglesare

referenced.In

thisdiagram

thelaser

ispointing

tothe

rightalong

thedotted

line,theangle

θis

theangle

ofa

laserscan

point,in

thisexam

pleθ

isnegative.

5.2.3LaserP

roxy

Alaser

isa

specialcase

ofranger

device,it

makes

regularlyspaced

rangem

ea-surem

entsturning

froma

minim

umangle

toa

maxim

umangle.

Each

measure-

ment,

orscan

point,is

treatedas

beingdone

with

aseparate

ranger.W

hereangles

aregiven

theyare

givenw

ithreference

tothe

laser’scentre

front(see

figure22).

•GetCount:

The

number

oflaser

scanpoints

thatthe

laserm

easures.

•laserProxy_name[laser_number]

The

rangereturned

bythe

laser_number

th

scanpoint.

Scanpoints

arenum

beredfrom

them

inimum

angleat

index0,

tothe

maxim

umangle

atindex

GetCount().

•GetBearing[laser_number]:

This

getsthe

angleof

thelaser

scanpoint.

•GetRange[laser_number]:

returnsthe

rangem

easuredby

thescan

pointlaser_number.

This

isthe

same

asdoing

laserProxy_name[laser_number].

•MinLeft:

Gives

them

inimum

rangereturned

bya

scanpoint

onthe

lefthand

sideof

thelaser.

•MinRight:

Gives

them

inimum

rangereturned

bya

scanpoint

onthe

righthand

sideof

thelaser.

5.2.4R

angerP

roxy

The

RangerP

roxyis

aproxy

form

oregeneral

ranging,it

supportsthe

sonar,laser

andIR

proxies.It

hasthe

same

functionas

theSonarP

roxyin

thatyou

canuse

thecode

rangerProxy_name[ranger_number]

toreturn

thedistance

fromranger

ranger_number

toan

obstacle.It

alsohas

many

ofthe

same

functions

43

Figure

23:A

laserscanner.

The

minim

umangle

isthe

angleof

therightm

ostlaser

scan,them

aximum

angleis

theleftm

ostlaser

scan.θ

isthe

scanresolution

ofthe

laser,it

isthe

anglebetw

eeneach

laserscan,

givenin

0.01degrees.

asthe

LaserP

roxy,such

asa

minim

umangle

anda

maxim

umangle

anda

scanningresolution,m

ostlythese

arefor

retrievingdata

abouthow

therangers

arearranged

orw

hatsize

theranging

devicesare.

5.2.5B

lobfinderP

roxy

The

blobfinderm

oduleanalyses

acam

eraim

agefor

areasof

adesired

colourand

returnsan

arrayof

thestructure

playerc_blobfinder_blob_t,this

isthe

structureused

tostore

blobdata.

First

we

willcover

howto

getthis

datafrom

theblobfinder

proxy,then

we

will

discussthe

datastored

inthe

structure.

•GetCount:

Returns

thenum

berof

blobsseen.

•blobProxy_name[blob_number]:

This

returnsthe

blobstructure

datafor

theblob

with

theindex

blob_number.

Blobs

aresorted

byindex

inthe

orderthat

theyappear

inthe

image

fromleft

toright.

This

canalso

beachieved

with

theB

lobfinderProxy

functionGetBlob(blob_number).

Once

we

receivethe

blobstructure

fromthe

proxyw

ecan

extractdata

we

need.T

heplayerc_blobfinder_blob_t

structurecontains

thefollow

ingfields:

•color:

The

colourof

theblob

itdetected.

This

isgiven

asa

hexadecimal

value.

•area:

The

areaof

theblob’s

boundingbox.

•x:

The

horizontalcoordinateofthe

geometric

centreofthe

blob’sbounding

box(see

figure24).

•y:

The

verticalcoordinate

ofthe

geometric

centreof

theblob’s

boundingbox

(seefigure

24).

•left:

The

horizontalcoordinateofthe

lefthand

sideofthe

blob’sbound-

ingbox

(seefigure

24).

44

Page 23: Player Stage Tutorial Manual 2.1

Figure

24:W

hatthe

fieldsin

playercblobfinder

blobt

mean.

The

blobon

theleft

hasa

geometric

centreat

(x,y),

theblob

onthe

righthas

abounding

boxw

iththe

topleft

cornerat

(left,top)

pixels,and

alow

erright

coordinateat

(right,bottom

)pixels.

Coordinates

aregiven

with

referenceto

thetop

leftcorner

ofthe

image.

•right:

The

horizontalcoordinate

ofthe

righthand

sideof

theblob’s

boundingbox

(seefigure

24).

•top:

The

verticalcoordinate

ofthe

topside

ofthe

blob’sbounding

box(see

figure24).

•bottom:

The

verticalcoordinateofthe

bottomside

oftheblob’s

boundingbox

(seefigure

24).

5.2.6G

ripperP

roxy

The

GripperP

roxyallow

syou

tocontrolthe

gripper,oncethe

gripperis

holdingan

item,the

simulated

robotw

illcarry

itaround

wherever

itgoes.

Without

agripper

youcan

onlyjostle

anitem

inthe

simulation

andyou

would

haveto

manually

tellthe

simulation

what

todo

with

anitem

.T

heG

ripperProxy

canalso

tellyou

ifan

itemis

between

thegripper

teethbecause

thegripper

model

hasinbuilt

beams

which

candetect

ifthey

arebroken.

•GetBeams:

This

comm

andw

illtellyouif

thereis

anitem

insidethe

grip-per.

Ifit

isa

valueabove

0then

thereis

anitem

tograb.

•GetState:

This

will

tellyou

whether

thegripper

isopened

orclosed.

Ifthe

comm

andreturns

a1

thenthe

gripperis

open,ifitreturns

2then

thegripper

isclosed.

•Open:

Tells

thegripper

toopen.

This

willcause

anyitem

sthat

were

beingcarried

tobe

dropped.

45

•Close:

Tells

thegripper

toclose.

This

will

causeit

topick

upanything

between

itsteeth.

5.2.7Sim

ulation

Prox

y

The

simulation

proxyallow

syour

codeto

interactw

ithand

changeaspects

ofthe

simulation,

suchas

anitem

’spose

orits

colour.

Get/S

etP

roperty

To

changea

propertyofan

itemin

thesim

ulationw

euse

thefollow

ingfunction:

SetProperty(char*item_name,char*property,void*value,size_tvalue_len)

•item_name:

thisis

thenam

ethat

yougave

tothe

object

inthe

worldfile,it

couldbe

anym

odelthatyou

havedescribed

inthe

worldfile.

Forexam

ple,in

section3.2.2

inthe

worldfile

we

declareda

Bigbob

typerobot

which

we

called“bob1”

sothe

item_name

forthat

object

is“bob1”.

Similarly

insection

3.3w

ebuilt

some

models

oforanges

andcalled

the“orange1”

to“orange4”

sothe

itemnam

efor

oneofthese

would

be“orange1”.

Anything

thatis

am

odelinyour

worldfile

canbe

alteredby

thisfunction,you

justneed

tohave

named

it,nodrivers

needto

bedeclared

inthe

configurationfile

forthis

tow

orkeither.

We

didn’tw

ritedrivers

forthe

orangesbut

we

couldstill

altertheir

propertiesthis

way.

•property:

There

areonly

certainproperties

abouta

model

thatyou

canchange.

You

specifyw

hichone

youw

antw

itha

string.Since

theproperties

youcan

changeare

fixedthen

thesestrings

arepredefined

(seestage.hh):

–"_mp_color":

The

colourof

theitem

.

–"_mp_watts":

The

number

ofw

attsthe

itemneeds.

–"_mp_mass":

The

mass

ofthe

item.

–"_mp_fiducial_return":

setsw

hetherthe

itemis

detectableto

thefiducial

finderon

arobot.

–"_mp_laser_return":

setsw

hetherthe

itemis

detectableto

thelaser

ona

robot.

–"_mp_obstacle_return":

setsw

hetherthe

robotcan

collidew

iththe

item.

–"_mp_ranger_return":

setsw

hetherthe

itemis

detectableto

therangers

ona

robot.

–"_mp_gripper_return":

setsw

hetherthe

itemcan

begripped

bya

gripperor

jostledby

therobot

collidingw

ithit.

•value:

The

valueyou

want

toassign

tothe

property.For

thereturn

parameters

thiscan

simply

bea

0or

a1,for

thew

attsand

mass

itcan

bea

numerical

value.For

thecolour

ofthe

itemthis

isauint32_t

8digit

longhexadecim

alnum

ber.T

hefirst

2digits

arethe

alphavalue

ofthe

colour,the

secondtw

oare

itsred

value,the

nexttw

oare

itsgreen

valueand

thefinaltw

oare

theblue

colourvalue.

Sored,for

instance,would

beuint32

tred

=0xffff0000,green

would

be0xff00ff00

andblue

is0xff0000ff.

Anice

shadeof

yellowm

ightbe

0xffffcc11.

46

Page 24: Player Stage Tutorial Manual 2.1

•value_len:

isthe

sizeof

thevalue

yougave

inbytes.

This

caneasily

befound

with

theC

orC

++

sizeof()

operator.

Similarly

thefollow

ingfunction

canbe

usedto

getproperty

information:

GetProperty(char*item_name,char*property,void*value,size_tvalue_len)

Insteadofsetting

thegiven

propertyofthe

item,this

willw

riteit

tothe

mem

oryblock

pointedto

by*value.

Get/S

etPose

The

item’s

poseis

aspecialcase

oftheG

et/SetProperty

func-tion,because

itis

likelythat

someone

would

want

tom

ovean

itemin

thew

orldthey

createda

specialfunction

todo

it.SetPose2d(char*item_name,doublex,doubley,doubleyaw)

Inthis

caseitem_name

isas

with

Get/SetP

roperty,butw

ecan

directlyspecify

itsnew

coordinatesand

yaw(coordinates

andyaw

sare

givenw

ithreference

tothe

map’s

origin).GetPose2d(char*item_name,double&x,double&y,double&yaw)

This

islike

SetPose2d

onlythis

time

itw

ritesthe

coordinatesand

yawto

thegiven

addressesin

mem

ory.

5.2.8G

eneral

Usefu

lC

omm

ands

Read

()To

make

theproxies

updatew

ithnew

sensordata

we

needto

tellthe

playerserver

toupdate,w

ecan

dothis

usingthe

PlayerC

lientob

jectw

hichw

eused

toconnect

tothe

server.A

llw

ehave

todo

isrun

thecom

mand

playerClient_name.Read()

everytim

ethe

dataneeds

updating(w

hereplayer-

Client

name

isthe

name

yougave

theP

layerClient

object).

Untilthis

comm

andis

run,the

proxiesand

anysensor

information

fromthem

will

beem

pty.T

hedevices

ona

typicalrobot

areasynchronous

andthe

devicesin

aP

layer/Stagesim

ulationare

alsoasynchronous,so

runningthe

Read()

comm

andw

on’talw

aysupdate

everythingat

thesam

etim

e,so

itm

aytake

severalcalls

beforesom

elarge

datastructures

(suchas

acam

eraim

age)gets

updated.

GetG

eom()

Most

oftheproxies

havea

functioncalled

GetGeom

orGetGeometry

orRequestGeometry,or

words

tothat

effect.W

hatthese

functionsdo

istellthe

proxyretrieve

information

aboutthe

device,usually

itssize

andpose

(relativeto

therobot).

The

proxiesdon’t

knowthis

bydefault

sincethis

information

isspecific

tothe

robotor

theP

layer/Stagerobot

model.

Ifyour

codeneeds

toknow

thiskind

ofinform

ationabout

adevice

thenthe

proxym

ustrun

thiscom

mand

first.

5.3

Usin

gP

roxie

s:A

Case

Stu

dy

To

demonstrate

howto

write

codeto

controla

Player

deviceor

Player/Stage

simulation

we

will

usethe

example

robot“B

igbob”developed

insections

3.2and

4w

hichcollects

orangesand

juicecartons

froma

factoryfloor.

Inprevious

sectionsw

ehave

developedthe

Stagem

odelfor

thisrobot

andits

environment

andthe

configurationfile

tocontrol

it.N

oww

ecan

beginto

puteverything

togetherto

createa

working

simulation

ofthis

robot.

47

Figure

25:T

hestate

transitionsthat

theB

igbobrubbish

collectingrobot

will

follow.

5.3.1T

he

Con

trolA

rchitectu

re

To

collectrubbish

we

havethree

basicbehaviours:

•W

andering:to

searchfor

rubbish.

•M

ovingtow

ardsitem

:for

when

anitem

isspotted

andthe

robotw

antsto

collectit

•C

ollectingitem

:for

dealingw

ithcollecting

items.

The

robotw

illalso

avoidobstacles

butonce

thisis

doneit

will

switch

backto

itsprevious

behaviour.T

hecontrol

will

followthe

statetransitions

shown

infigure

25.

5.3.2B

eginnin

gth

eC

ode

Insection

5.1.1w

ediscussed

howto

connectto

theP

layerserver

andproxies

attachedto

theserver,

anddeveloped

thefollow

ingcode:

#include<stdio.h>

#include<libplayerc++/playerc++.h>

intmain(intargc,char*argv[])

{/*needtodothislineinc++only*/

usingnamespacePlayerCc;

PlayerClient

robot("localhost");

48

Page 25: Player Stage Tutorial Manual 2.1

Position2dProxyp2dProxy(&robot,0);

SonarProxy

sonarProxy(&robot,0);

BlobfinderProxyblobProxy(&robot,0);

LaserProxy

laserProxy(&robot,0);

//somecontrolcode

return0;

}Using

ourknow

ledgeof

theproxies

discussedin

section5.2

we

canbuild

con-trolling

codeon

topof

thisbasic

code.Firstly,it

isgood

practiceto

enablethe

motors

andrequest

thegeom

etryfor

alltheproxies.

This

means

thatthe

robotw

illmove

andthat

ifwe

needto

knowabout

thesensing

devicesthe

proxiesw

illhave

thatinform

ationavailable.

//enablemotors

p2dProxy.SetMotorEnable(1);

//requestgeometries

p2dProxy.RequestGeom();

sonarProxy.RequestGeom();

laserProxy.RequestGeom();

//blobfinderdoesn’thavegeometry

Once

thingsare

initialisedw

ecan

enterthe

main

controlloop.A

tthis

pointw

eshould

tellthe

robotto

readin

datafrom

itsdevices

tothe

proxies.

while(true)

{robot.Read();

//controlcode

}5.3.3W

ander

firstw

ew

illinitialisea

coupleof

variablesw

hichw

illbethe

forward

speedand

theturning

speedof

therobot,

we’ll

putthis

with

theproxy

initialisations.

Position2dProxyp2dProxy(&robot,0);

SonarProxy

sonarProxy(&robot,0);

BlobfinderProxyblobProxy(&robot,0);

LaserProxy

laserProxy(&robot,0);

doubleforwardSpeed,turnSpeed;

Let’s

saythat

Bigbob’s

maxim

umspeed

is1

metre/second

andit

canturn

90 ◦a

second.W

ew

illwrite

asm

allsubfunctionto

randomly

assignforw

ardand

turningspeeds

between

0and

them

aximum

speeds.

voidWander(double*forwardSpeed,double*turnSpeed)

{intmaxSpeed=1;

49

intmaxTurn=90;

doublefspeed,tspeed;

//fspeedisbetween0and10

fspeed=rand()%11;

//(fspeed/10)isbetween0and1

fspeed=(fspeed/10)*maxSpeed;

tspeed=rand()%(2*maxTurn);

tspeed=tspeed-maxTurn;

//tspeedisbetween-maxTurnand+maxTurn

*forwardSpeed=fspeed;

*turnSpeed=tspeed;

}Inthe

controlloop

we

includea

callto

thisfunction

andthen

setthe

resultingspeeds

tothe

motors.

while(true)

{//readfromtheproxies

robot.Read();

//wander

Wander(&forwardSpeed,&turnSpeed);

//setmotors

p2dProxy.SetSpeed(forwardSpeed,dtor(turnSpeed));

}

At

presentthe

motors

arebeing

updatedevery

time

thiscontrol

loopex-

ecutes,and

thisleads

tosom

eerratic

behaviourfrom

therobot.

Using

thesleep()26

comm

andw

ew

illtell

thecontrol

loopto

wait

onesecond

between

eachexecution.

At

thispoint

we

shouldalso

seedthe

randomnum

bergenerator

with

thecurrent

time

sothat

thew

anderbehaviour

isn’texactly

thesam

eeach

time.

Forthe

sleepcom

mand

we

willneed

toinclude

unistd.h

andto

seedthe

randomnum

bergenerator

with

thecurrent

systemtim

ew

ew

illneedto

includetime.h.

#include<stdio.h>

#include<unistd.h>

#include<time.h>

#include<libplayerc++/playerc++.h>

voidWander(double*forwardSpeed,double*turnSpeed)

{//wandercode...

}

26sleep

()is

asta

ndard

Cfu

nctio

nand

isin

cluded

inth

eunistd

.hhea

der.

50

Page 26: Player Stage Tutorial Manual 2.1

intmain(intargc,char*argv[])

{/*needtodothislineinc++only*/

usingnamespacePlayerCc;

//connecttoproxies

doubleforwardSpeed,turnSpeed;

srand(time(NULL));

//enablemotors

//requestgeometries

while(true)

{//readfromtheproxies

robot.Read();

//wander

Wander(&forwardSpeed,&turnSpeed);

//setmotors

p2dProxy.SetSpeed(forwardSpeed,dtor(turnSpeed));

sleep(1);

}}5.3.4

Obstacle

Avoid

ance

Now

we

needto

write

asubfunction

thatchecks

thesonars

forany

obstaclesand

amends

them

otorspeeds

accordingly.

voidAvoidObstacles(double*forwardSpeed,double*turnSpeed,\

SonarProxy&sp)

{//willavoidobstaclescloserthan40cm

doubleavoidDistance=0.4;

//willturnawayat60degrees/sec

intavoidTurnSpeed=60;

//leftcornerissonarno.2

//rightcornerissonarno.3

if(sp[2]<avoidDistance)

{*forwardSpeed=0;

//turnright

*turnSpeed=(-1)*avoidTurnSpeed;

return;

}elseif(sp[3]<avoidDistance)

51

{*forwardSpeed=0;

//turnleft

*turnSpeed=avoidTurnSpeed;

return;

}elseif((sp[0]<avoidDistance)&&\

(sp[1]<avoidDistance))

{//backoffalittlebit

*forwardSpeed=-0.2;

*turnSpeed=avoidTurnSpeed;

return;

}return;//donothing

}This

isa

verybasic

obstacleavoidance

subfunctionw

illupdatethe

motor

speedsonly

ifthere

isan

obstacleto

avoid.If

we

callthisfunction

justbefore

sendingdata

tothe

motors

thenit

will

overwrite

anyother

behavioursso

thatthe

obstaclew

illbe

avoided.O

ncethe

obstacleis

nolonger

inthe

way

thenthe

robotw

illcontinueas

itw

as,thisw

illallowus

totransition

fromany

behaviourinto

obstacleavoidance

andthen

backagain,

asper

therequirem

entof

ourcontrol

structure.A

llw

eneed

todo

nowis

callthis

functionin

ourcontrol

loop:

while(true)

{//readfromtheproxies

robot.Read();

//wander

Wander(&forwardSpeed,&turnSpeed);

//avoidobstacles

AvoidObstacles(&forwardSpeed,&turnSpeed,sonarProxy);

//setmotors

p2dProxy.SetSpeed(forwardSpeed,dtor(turnSpeed));

sleep(1);

}5.3.5M

oveTo

Item

Forthis

statew

ew

antthe

robotto

move

towards

ablob

thatit

hasspotted.

There

may

beseveral

blobsin

itsview

atonce,

sow

e’lltell

therobot

tom

oveto

thelargest

onebecause

it’sprobably

theclosest

tothe

robot.T

hefollow

ingsubfunction

findsthe

largestblob

andturns

therobot

sothat

theblob’s

centreis

nearthe

centreof

theim

age.T

herobot

will

thenm

ovetow

ardsthe

blob.

52

Page 27: Player Stage Tutorial Manual 2.1

voidMoveToItem(double*forwardSpeed,double*turnSpeed,\

BlobfinderProxy&bfp)

{inti,centre;

intnoBlobs=bfp.GetCount();

playerc_blobfinder_blob_tblob;

intturningSpeed=10;

/*numberofpixelsawayfromtheimagecentreablob

canbetobeinfrontoftherobot*/

intmargin=10;

intbiggestBlobArea=0;

intbiggestBlob=0;

//findthelargestblob

for(i=0;i<noBlobs;i++)

{//getblobfromproxy

playerc_blobfinder_blob_tcurrBlob=bfp[i];

if(currBlob.area>biggestBlobArea)

{biggestBlob=i;

biggestBlobArea=currBlob.area;

}}blob=bfp[biggestBlob];

//findcentreofimage

centre=bfp.GetWidth()/2;

//adjustturntocentretheblobinimage

/*iftheblob’scentreiswithinsomemarginoftheimage

centrethenmoveforwards,otherwiseturnsothatitis

centred.*/

//blobtotheleftofcentre

if(blob.x<centre-margin)

{*forwardSpeed=0;

//turnleft

*turnSpeed=turningSpeed;

}//blobtotherightofcentre

elseif(blob.x>centre+margin)

{*forwardSpeed=0;

//turnright

*turnSpeed=-turningSpeed;

}

53

//otherwisegostraightahead

else

{*forwardSpeed=0.5;

*turnSpeed=0;

}return;

}

We

want

therobot

totransition

tothis

statew

heneveran

itemis

seen,so

we

puta

conditionalstatem

entin

ourcontrol

looplike

so:

if(blobProxy.GetCount()==0)

{//wander

Wander(&forwardSpeed,&turnSpeed);

}else

{//movetowardstheitem

MoveToItem(&forwardSpeed,&turnSpeed,blobProxy);

}5.3.6C

ollectItem

This

behaviourw

illbethe

most

difficult

tocode

becauseStage

doesn’tsupport

pushableob

jects(the

requiredphysics

isfar

toocom

plex),what

happensinstead

isthat

therobot

runsover

theob

jectand

justjostles

ita

bit.A

sa

work-around

tothis

problemw

ew

illhaveto

somehow

findout

which

itemis

between

Bigbob’s

teethso

thatw

ecan

findits

“name”

andthen

changethat

item’s

pose(for

which

we

needthe

item’s

name)

sothat

itis

nolonger

inthe

simulation.

Inessence,

insteadof

havingour

roboteat

rubbishand

storeit

within

itsbody,

what

we

aredoing

ism

akingthe

laserzap

therubbish

outof

existence.W

ecan

findthe

name

ofanitem

between

Bigbob’s

teethby

crossreferencing

therobot’s

posew

iththe

locationsof

theitem

sin

thew

orldto

findout

which

itemis

nearestthe

robot’slaser.

The

firststep

isto

createa

listof

allthe

items

inthe

world,

theirnam

esand

theirposes

atinitialisation.

Sincew

eknow

thenam

esof

theitem

sare

“orange1”to

“orange4”and

“carton1”to

“carton4”,w

ecan

findtheir

posesw

itha

simple

callto

asim

ulationproxy.

We’llhave

toconnect

tothe

simulation

proxyw

ithour

codefirst

usingthe

lineSimulationProxysimProxy(&robot,0);,then

we

canaccess

thisinform

ationand

putit

intoa

struct.

structItem

{charname[16];

doublex;

doubley;

}typedefitem_t;

We

canpopulate

thestructure

with

information

usingthe

following

code:

54

Page 28: Player Stage Tutorial Manual 2.1

item_titemList[8];

voidRefreshItemList(item_t*itemList,SimulationProxy&simProxy)

{inti;

//gettheposesoftheoranges

for(i=0;i<4;i++)

{charorangeStr[]="orange%d";

sprintf(itemList[i].name,orangeStr,i+1);

doubledummy;

//dummyvariable,don’tneedyaws.

simProxy.GetPose2d(itemList[i].name,\

itemList[i].x,itemList[i].y,dummy);

}//gettheposesofthecartons

for(i=4;i<8;i++)

{charcartonStr[]="carton%d";

sprintf(itemList[i].name,cartonStr,i-3);

doubledummy;

//dummyvariable,don’tneedyaws.

simProxy.GetPose2d(itemList[i].name,\

itemList[i].x,itemList[i].y,dummy);

}return;

}Where

itemList

isan

item_t

arrayof

length8.

Next

we

canbegin

the“C

ollectItem

”behaviour,w

hichw

illbetriggered

bysom

ethingbreaking

thelaser

beam.

When

thishappens

we

will

checkthe

areaaround

Bigbob’s

teeth,as

indicatedby

figure26.

We

knowthe

distancefrom

thecentre

ofthis

searchcircle

toB

igbob’sorigin

(0.625m)

andthe

radiusof

thesearch

circle(0.375m

),we

canget

therobot’s

exactpose

with

thefollow

ingcode.

doublex,y,yaw;

simProxy.GetPose2d("bob1",x,y,yaw);

Cross

referencingthe

robot’sposition

with

theitem

positionsis

am

atterof

trigonometry,

we

won’t

reproducethe

codehere,

butthe

fulland

finalcode

developedfor

theB

igbobrubbish

collectingrobot

isincluded

inappendix

D.

The

method

we

usedis

tofind

theE

uclidiandistance

ofthe

items

tothe

circlecentre,

andthe

smallest

distanceis

theitem

we

want

todestroy.

We

made

asubfunction

calledFindItem

thatreturns

theindex

oftheitem

tobe

destroyed.N

owthat

we

canfind

theitem

todestroy

it’sfairly

simple

totrigger

oursubfunction

when

thelaser

isbroken

sow

ecan

findand

destroyan

item.

if(laserProxy[90]<0.25)

{

55

Figure

26:W

hereto

lookfor

items

which

may

havepassed

throughB

igbob’slaser.

intdestroyThis;

/*firstparamisthelistofitemsintheworld

secondislengthofthislist

thirdparameteristhesimulationproxywith

theposeinformationinit*/

destroyThis=FindItem(itemList,8,simProxy);

//moveitoutofthesimulation

simProxy.SetPose2d(itemList[destroyThis].name,-10,-10,0);

RefreshItemList(itemList,simProxy);

}The

laserhas

180points,so

pointnum

ber90

isthe

onew

hichis

perpendicularto

Bigbob’s

teeth.T

hispoint

returnsa

maxim

umof

0.25,so

ifits

rangew

asto

fallbelow

thisthen

something

haspassed

throughthe

laserbeam

.W

ethen

findthe

itemclosest

tothe

robot’steeth

andm

ovethat

itemto

coordinate(−

10,−10)

soit

isno

longervisible

oraccessible.

Finally

we

havea

working

simulation

ofa

rubbishcollecting

robot!T

hefull

codelisting

isincluded

inappendix

D,the

simulation

world

andconfiguration

filesare

inappendices

Band

Crespectively.

5.4

Sim

ula

ting

Multip

leR

obots

Our

robotsim

ulationcase

studyonly

shows

howto

simulate

asingle

robotin

aP

layer/Stageenvironm

ent.It’s

highlylikely

thata

simulation

might

want

more

thanone

robotin

it.In

thissituation

youw

illneed

tobuild

am

odelof

everyrobot

youneed

inthe

worldfile,

andthen

itsassociated

driverin

theconfiguration

file.Let’s

takea

lookat

ourw

orldfilefor

thecase

study,we’lladd

56

Page 29: Player Stage Tutorial Manual 2.1

anew

model

ofa

newB

igbobrobot

called“bob2”:

bigbob

(name"bob1"

pose[-5-645]

color"green"

)bigbob

(name"bob2"

pose[56225]

color"yellow"

)Ifthereare

multiple

robotsin

thesim

ulation,thestandard

practiceis

toput

eachrobot

onits

own

port(see

section4.1).

To

implem

entthis

inthe

configurationfile

we

needto

tellP

layerw

hichport

tofind

oursecond

roboton:

driver(name"stage"

provides["6665:position2d:0""6665:sonar:0"

"6665:blobfinder:0""6665:laser:0"]

model"bob1")

driver(name"stage"

provides["6666:position2d:0""6666:sonar:0"

"6666:blobfinder:0""6666:laser:0"]

model"bob2")

Ifyou

planon

simulating

alarge

number

ofrobots

thenit

isprobably

worth

writing

ascript

togenerate

thew

orldand

configurationfiles.

When

Player/Stage

isstarted,

theP

layerserver

automatically

connectsto

alltheused

portsin

yoursim

ulationand

youcontrolthe

robotsseparately

with

differentP

layerClient

objects

inyour

code.For

instance:

//firstrobot

PlayerClientrobot1("localhost",6665);

Position2dProxyp2dprox1(&robot1,0);

SonarProxysprox1(&robot1,0);

//secondrobot

PlayerClientrobot2("localhost",6666);

Position2dProxyp2dprox2(&robot2,0);

SonarProxysprox2(&robot2,0);

Each

Player

Client

representsa

robot,thisis

why

when

youconnect

toa

proxythe

PlayerC

lientis

aconstructor

parameter.

Each

robothas

aproxy

foreach

ofits

devices,no

robotsshare

aproxy,

soit

isim

portantthat

yourcode

connectsto

everyproxy

ofevery

robotin

orderto

readthe

sensorinform

ation.H

owyou

handlethe

extraP

layerClients

andproxies

isdependent

onthe

scaleof

thesim

ulationand

yourow

npersonalcoding

preferences.It’s

agood

idea,ifthere’s

57

more

thanm

aybe2

robotsin

thesim

ulation,tom

akea

robotclass

which

dealsw

ithconnecting

toproxies

andthe

server,and

processesall

theinform

ationinternally

tocontrol

therobot.

Then

youcan

createan

instanceof

thisclass

foreach

simulated

robot27

andallthe

simulated

robotsw

illrunthe

same

code.A

nalternative

tousing

aport

foreach

robotis

touse

thesam

eport

buta

differentindex.

This

will

onlyw

orkif

therobots

areall

thesam

e(or

atleast

usethe

same

interfaces,although

differentrobots

couldbe

runon

adifferent

ports)and

therobots

onlyuse

oneindex

foreach

ofits

devices.For

example,

theB

igbobrobot

usesinterfaces

andindexes:

position2d:0,sonar:0,blobfinder:0and

laser:0so

itnever

usesm

orethan

oneindex.

Ifw

econfigured

two

Bigbob

robotsto

usethe

same

portbut

adifferent

indexour

configurationfile

would

belike

this:

driver(name"stage"

provides["6665:position2d:0""6665:sonar:0"

"6665:blobfinder:0""6665:laser:0"]

model"bob1")

driver(name"stage"

provides["6665:position2d:1""6665:sonar:1"

"6665:blobfinder:1""6665:laser:1"]

model"bob2")

Inour

codew

ecould

thenestablish

theproxies

usingonly

oneP

layerClient:

PlayerClientrobot("localhost",6665);

//firstrobot

Position2dProxyp2dprox1(&robot,0);

SonarProxysprox1(&robot,0);

//secondrobot

Position2dProxyp2dprox2(&robot,1);

SonarProxysprox2(&robot,1);

//sharedSimultionproxy...

SimulationProxysim(&robot,0);

The

main

advantageof

configuringthe

robotsw

armthis

way

isthat

itallow

sus

toonly

haveone

simulation

proxyw

hichis

sharedby

allrobots.T

hisis

goodsince

thereis

onlyever

onesim

ulationw

indowthat

youcan

interactw

ithand

som

ultiplesim

ulationproxies

areunnecessary.

6U

sefu

lLin

ks

•P

layer2.1.0

Manual

http://playerstage.sourceforge.net/doc/Player-2.1.0/player/

27obvio

usly

the

robot’s

port

num

ber

would

need

tobe

apara

meter

oth

erwise

they

’llall

connect

toth

esa

me

port

and

conseq

uen

tlyth

esa

me

robot.

58

Page 30: Player Stage Tutorial Manual 2.1

•Stage

3.0.1M

anualhttp://playerstage.sourceforge.net/doc/stage-3.0.1/

•Stage

2.0.0M

anualhttp://playerstage.sourceforge.net/doc/Stage-2.0.0/

•A

llP

layerP

roxiesin

Chttp://playerstage.sourceforge.net/doc/Player-2.1.0/player/group_

_playerc__proxies.html

•A

llP

layerP

roxiesin

C+

+http://playerstage.sourceforge.net/doc/Player-2.1.0/player/namespacePlayerCc.

html

•Interfaces

usedby

Player

http://playerstage.sourceforge.net/doc/Player-2.1.0/player/group_

_interfaces.html

Refe

rence

s

[1]B

rianG

erkey,R

ichardV

aughan,and

Andrew

How

ard.P

layerm

anual:D

e-vice

addresses.http://playerstage.sourceforge.net/doc/Player-2.1.

0/player/group__tutorial__config.html#device_addresses.

7A

ppendice

s

Appendix

A.G

enera

lSta

ge

ModelofB

igbob

#bigbob.inc

#modelfortherobot"Bigbob"

#Author:JenniferOwen

#Bigbob’ssonars

definebigbobs_sonarsranger

(#numberofsonars

scount4

#definetheposeofeachtransducer[xposyposheading]

spose[0][0.750.18750]#frlefttooth

spose[1][0.75-0.18750]#frrighttooth

spose[2][0.250.530]#leftcorner

spose[3][0.25-0.5-30]#rightcorner

#definethefieldofviewofeachtransducer

#[range_minrange_maxview_angle]

sview[0.32.010]

#definethesizeofeachtransducer

#[xsizeysize]inmeters

59

ssize[0.010.05]

)#bigbob’sblobfinder

definebigbobs_eyesptz

(blobfinder

(#numberofcolourstolookfor

channels_count2

#whichcolourstolookfor

channels["orange""DarkBlue"]

#cameraparameters

image[160120]#resolution

range_max5.00

ptz[0060]

))#bigbob’slaser

definebigbobs_laserlaser

(range_min0.0

#distancebetweenteethinmetres

range_max0.25

#doesnotneedtobebig

fov20

pose[0.6250.125270]

size[0.0250.025]

)#bigbob’sbody

definebigbobposition

(#actualsize

size[1.2511]

#Bigbob’scentreofrotationisoffsetfromitscentreofarea

origin[0.12500]

#estimatedmassinKG

mass15.0

#theshapeofBigbob

60

Page 31: Player Stage Tutorial Manual 2.1

polygons3

polygon[0].points6

polygon[0].point[0][00]

polygon[0].point[1][01]

polygon[0].point[2][0.751]

polygon[0].point[3][10.75]

polygon[0].point[4][10.25]

polygon[0].point[5][0.750]

polygon[1].points4

polygon[1].point[0][10.75]

polygon[1].point[1][1.250.75]

polygon[1].point[2][1.250.625]

polygon[1].point[3][10.625]

polygon[2].points4

polygon[2].point[0][10.375]

polygon[2].point[1][1.250.375]

polygon[2].point[2][1.250.25]

polygon[2].point[3][10.25]

#differentialsteeringmodel

drive"diff"

#sensorsattachedtobigbob

bigbobs_sonars()

bigbobs_eyes()

bigbobs_laser()

)Appendix

B.

World

file

,C

onta

inin

gR

obot

and

Item

sin

World

#populatedworldforBigbobrobot

#Author:JenniferOwen

include"map.inc"

include"bigbob.inc"

#sizeofthewholesimulation

size[1515]

#configuretheGUIwindow

window

(size[700.000700.000]

scale0.025

61

)#loadanenvironmentbitmap

map

(bitmap"bitmaps/cave.png"

size[1515]

)bigbob

(name"bob1"

pose[-5-645]

color"green"

)defineorangemodel

(#thisisapictureofablackcircle

bitmap"bitmaps/circle.png"

size[0.150.15]

color"orange"

gui_outline0

gripper_return1

)definecartonmodel

(#acartonisretangular

#somakeasquareshapeandusesize[]

polygons1

polygon[0].points4

polygon[0].point[0][00]

polygon[0].point[1][01]

polygon[0].point[2][11]

polygon[0].point[3][10]

#averagelitrecartonsizeis~20cmx10cmx5cm

size[0.10.2]

color"DarkBlue"

gripper_return1

)orange(name"orange1"pose[-1-50])

orange(name"orange2"pose[-2-50])

orange(name"orange3"pose[-3-50])

62

Page 32: Player Stage Tutorial Manual 2.1

orange(name"orange4"pose[-4-50])

carton(name"carton1"pose[-2-40])

carton(name"carton2"pose[-2-30])

carton(name"carton3"pose[-2-20])

carton(name"carton4"pose[-2-10])

Appendix

C.C

onfigura

tion

file

for

Big

bob

World

#Desc:PlayersampleconfigurationfileforcontrollingStagedevices

#Author:

JenniferOwen

#Date:22/05/2009

driver

(name"stage"

plugin"libstageplugin"

provides["simulation:0"]

#loadthenamedfileintothesimulator

worldfile"robots_and_junk.world"

)#themainbob1robot

driver

(name"stage"

provides[

"6665:position2d:0"

"6665:sonar:0"

"6665:blobfinder:0"

"6665:laser:0"

]model"bob1"

)Appendix

D.C

ontro

lling

Code

for

Big

bob

Robot

Sim

ula

-tio

n

#include<stdio.h>

#include<unistd.h>

#include<time.h>

#include<libplayerc++/playerc++.h>

63

structItem

{charname[16];

doublex;

doubley;

}typedefitem_t;

usingnamespacePlayerCc;

/**

Randomlyassignsnewspeedsintothegivenaddresses.

Thisfunctionwillalwayswritetothegivenaddresses.

@param*forwardSpeedtheaddressoftheforwardspeed

variableyouwantthisfunctiontochange.

@param*turnSpeedtheaddressoftheturnspeedvariable

youwantthisfunctiontochange.

*/voidWander(double*forwardSpeed,double*turnSpeed)

{intmaxSpeed=1;

intmaxTurn=90;

doublefspeed,tspeed;

//fspeedisbetween0and10

fspeed=rand()%11;

//(fspeed/10)isbetween0and1

fspeed=(fspeed/10)*maxSpeed;

tspeed=rand()%(2*maxTurn);

tspeed=tspeed-maxTurn;

*forwardSpeed=fspeed;

*turnSpeed=tspeed;

}/**

Checkssonarsforobstaclesandupdatesthegivenaddresses

withwheelspeeds.Thisfunctionwillwritetotheaddresses

onlyifthereisanobstaclepresent.Verybasicobstacleavoidanceonly.

@param*forwardSpeedtheaddressoftheforwardspeedvariable

youwantthisfunctiontochange.

@param*turnSpeedtheaddressoftheturnspeedvariableyou

wantthisfunctiontochange.

@param&spThesonarproxythatyouwantthisfunctiontomonitor.

*/voidAvoidObstacles(double*forwardSpeed,double*turnSpeed,\

SonarProxy&sp)

64

Page 33: Player Stage Tutorial Manual 2.1

{//willavoidobstaclescloserthan40cm

doubleavoidDistance=0.4;

//willturnawayat60degrees/sec

intavoidTurnSpeed=60;

//leftcornerissonarno.2

//rightcornerissonarno.3

if(sp[2]<avoidDistance)

{*forwardSpeed=0;

//turnright

*turnSpeed=(-1)*avoidTurnSpeed;

printf("avoidingobstacle\n");

return;

}elseif(sp[3]<avoidDistance)

{*forwardSpeed=0;

//turnleft

*turnSpeed=avoidTurnSpeed;

printf("avoidingobstacle\n");

return;

}elseif((sp[0]<avoidDistance)&&\

(sp[1]<avoidDistance))

{//backoffalittlebit

*forwardSpeed=-0.2;

*turnSpeed=avoidTurnSpeed;

printf("avoidingobstacle\n");

return;

}return;//donothing

}/**

Ifblobshavebeendetectedthisfunctionwillturntherobot

towardsthelargestblob.Thiswillbetheclosestblob(hopefully!).

Ifcalledthisfunctionwillalwaysoverwriteinformationinthe

givenaddresses.

@param*forwardSpeedtheaddressoftheforwardspeedvariable

youwantthisfunctiontochange.

@param*turnSpeedtheaddressoftheturnspeedvariableyou

wantthisfunctiontochange.

@param&bfpTheblobfinderproxythatyouwantthisfunction

tomonitor.

*/

65

voidMoveToItem(double*forwardSpeed,double*turnSpeed,\

BlobfinderProxy&bfp)

{inti,centre;

intnoBlobs=bfp.GetCount();

playerc_blobfinder_blob_tblob;

intturningSpeed=10;

/*numberofpixelsawayfromtheimagecentreablob

canbetobeinfrontoftherobot*/

intmargin=10;

intbiggestBlobArea=0;

intbiggestBlob=0;

//findthelargestblob

for(i=0;i<noBlobs;i++)

{//getblobfromproxy

playerc_blobfinder_blob_tcurrBlob=bfp[i];

if(currBlob.area>biggestBlobArea)

{biggestBlob=i;

biggestBlobArea=currBlob.area;

}}blob=bfp[biggestBlob];

//findcentreofimage

centre=bfp.GetWidth()/2;

//adjustturntocentretheblobinimage

/*iftheblob’scentreiswithinsomemarginoftheimage

centrethenmoveforwards,otherwiseturnsothatitis

centred.*/

//blobtotheleftofcentre

if(blob.x<centre-margin)

{*forwardSpeed=0;

//turnleft

*turnSpeed=turningSpeed;

}//blobtotherightofcentre

elseif(blob.x>centre+margin)

{*forwardSpeed=0;

//turnright

*turnSpeed=-turningSpeed;

}

66

Page 34: Player Stage Tutorial Manual 2.1

//otherwisegostraightahead

else

{*forwardSpeed=0.5;

*turnSpeed=0;

}return;

}/**

Fillstheitemlistarraywiththenamesandpositionsofitems

inthesimulation

@paramitemListthisistheitemlistwhichcontainsthenames

andpositionsofalltheitemsinthesimulation.

@paramsimProxythesimulationproxyforthePlayer/Stagesimulation.

*/

voidRefreshItemList(item_t*itemList,SimulationProxy&simProxy)

{inti;

//gettheposesoftheoranges

for(i=0;i<4;i++)

{charorangeStr[]="orange%d";

sprintf(itemList[i].name,orangeStr,i+1);

doubledummy;

//dummyvariable,don’tneedyaws.

simProxy.GetPose2d(itemList[i].name,\

itemList[i].x,itemList[i].y,dummy);

}//gettheposesofthecartons

for(i=4;i<8;i++)

{charcartonStr[]="carton%d";

sprintf(itemList[i].name,cartonStr,i-3);

doubledummy;

//dummyvariable,don’tneedyaws.

simProxy.GetPose2d(itemList[i].name,\

itemList[i].x,itemList[i].y,dummy);

}return;

}

67

/**

Findsaniteminthesimulationwhichisneartherobot’steeth.

@paramitemListthisistheitemlistwhichcontainsthenamesand

positionsofalltheitemsinthesimulation.

@paramlistLengthThenumberofitemsinthesimulation

@paramsimthesimulationproxyforthePlayer/Stagesimulation.

@returnreturnstheindexoftheiteminthearraywhichiswithin

therobot’steeth.Ifnoitemisfoundthenthiswillreturn-1.

*/intFindItem(item_t*itemList,intlistLength,SimulationProxy&sim)

{doubleradius=0.375;

doubledistBotToCircle=0.625;

doublerobotX,robotY,robotYaw;

doublecircleX,circleY;

//findtherobot...

sim.GetPose2d((char*)"bob1",robotX,robotY,robotYaw);

/*nowwefindthecentreofthesearchcircle.

thisisdistBotToCirclemetresfromtherobot’sorigin

alongitsyaw*/

/*horizontaloffsetfromrobotorigin*/

circleX=distBotToCircle*cos(robotYaw);

/*verticaloffsetfromrobotorigin*/

circleY=distBotToCircle*sin(robotYaw);

//findactualcentrerelativetosimulation.

circleX=robotX+circleX;

circleY=robotY+circleY;

/*tofindwhichitemsarewithinthiscirclewe

findtheirEuclidiandistancetothecirclecentre.

Findtheclosestoneandifit’sdistanceissmallerthan

thecircleradiusthenreturnitsindex*/

doublesmallestDist=1000000;

intclosestItem=0;

inti;

for(i=0;i<listLength;i++)

{doublex,y,dist;

x=circleX-itemList[i].x;

y=circleY-itemList[i].y;

//findeuclidiandistance

68

Page 35: Player Stage Tutorial Manual 2.1

dist=(x*x)+(y*y);

dist=sqrt(dist);

if(dist<smallestDist)

{smallestDist=dist;

closestItem=i;

}}returnclosestItem;

}intmain(intargc,char*argv[])

{/*needtodothislineinc++only*/

usingnamespacePlayerCc;

PlayerClient

robot("localhost",6665);

Position2dProxyp2dProxy(&robot,0);

SonarProxy

sonarProxy(&robot,0);

BlobfinderProxyblobProxy(&robot,0);

LaserProxy

laserProxy(&robot,0);

SimulationProxysimProxy(&robot,0);

doubleforwardSpeed,turnSpeed;

item_titemList[8];

RefreshItemList(itemList,simProxy);

srand(time(NULL));

//enablemotors

p2dProxy.SetMotorEnable(1);

//requestgeometries

p2dProxy.RequestGeom();

sonarProxy.RequestGeom();

laserProxy.RequestGeom();

//blobfinderdoesn’thavegeometry

/*heresothatlaserProxy[90]doesn’tsegfaultonfirstloop*/

robot.Read();

while(true)

{//readfromtheproxies

69

robot.Read();

if(blobProxy.GetCount()==0)

{//wander

printf("wandering\n");

Wander(&forwardSpeed,&turnSpeed);

}else

{//movetowardstheitem

printf("movingtoitem\n");

MoveToItem(&forwardSpeed,&turnSpeed,blobProxy);

}if(laserProxy[90]<0.25)

{intdestroyThis;

destroyThis=FindItem(itemList,8,simProxy);

//moveitoutofthesimulation

printf("collectingitem\n");

simProxy.SetPose2d(itemList[destroyThis].name,-10,-10,0);

RefreshItemList(itemList,simProxy);

}//avoidobstacles

AvoidObstacles(&forwardSpeed,&turnSpeed,sonarProxy);

//setmotors

p2dProxy.SetSpeed(forwardSpeed,dtor(turnSpeed));

sleep(1);

}}

70