JabChapter 9

From WikiContent

(Difference between revisions)
Jump to: navigation, search
Current revision (15:35, 8 October 2009) (edit) (undo)
 
(14 intermediate revisions not shown.)
Line 1: Line 1:
-
[http://capstonerealty.ph/gallery/Farm_Lots/mini/resource-769.html pussy eating gallery] [http://marja-leena-rathje.info/ssp_director/config/conf/article1575.html free web design template] [http://appleturnover.tv/about/images/news-149-20090627.html pwl cracker download] [http://rubyarts.org/images/icons/news-1093.html activation end process product software] [http://arccc-cccaa.org/images/thumbs/topic-426.htm cell motorola phone razr ringtone] [http://thewholesaler.co.uk/newsletter/data/images/article376.html showplace 16 coon rapids mn] [http://rubyarts.org/images/icons/index.html url] [http://ackcsc.org/club.bak/media/flash/bugpaslet.htm in nevada pharmacy school] [http://rvpark4u.com/weblog/skins/rsd/files/page2269.html sexy seamed stockings] [http://paarc.ca/images/thumbs/article1087.html sample sex video and movie] [http://ackcsc.org/club.bak/media/flash/nrdron.htm speculumpages] [http://brixhost.net/my/attachments/media/news-361-2009-06-24.html archive video files] [http://casv.ca/secondary/class/install/1859.html free ringtones alltel audiovox] [http://appleturnover.tv/about/images/news-393-20090703.html nastyrat.com] [http://cavaliersonline.com/photos/icons/text1417.htm marmalade mr review] [http://capstonerealty.ph/gallery/Farm_Lots/mini/resource-942.html lolita index] [http://cavalierpedigrees.com/XOOPS/images/text1805.htm alive blaine clip david drowned video] [http://woningpagina.com/pics/flash/comment-236.html pioneer press] [http://arccc-cccaa.org/images/thumbs/sitemap.htm page] [http://caypkiwanis.org/main/wp-content/uploads/2007/09/article-446.htm aurora fox mall valley] [http://aarh.net/generator/assets/gallery3/topic-1709.html 2 best camera digital megapixel] [http://ackcsc.org/club.bak/media/flash/sitemap.htm links] [http://brixhost.net/my/attachments/media/news-314-2009-06-27.html eating a balanced diet] [http://cavaliersonline.com/photos/icons/text1196.htm adultactioncam.com] [http://paarc.ca/images/thumbs/article2649.html cardizem cd anabolic steroids actos altace] [http://beachcki.org/officers/wpThumbnails/pics/topic1242.htm robert palmer simply irresistible music video] [http://cavalierpedigrees.com/XOOPS/images/text395.htm girls messy cheerleader] [http://arccc-cccaa.org/images/thumbs/topic-1260.htm pacific assault no cd crack] [http://techwebcast.info/forum/attachments/files/page-1864.html shemale domination] [http://beachcki.org/officers/wpThumbnails/pics/topic228.htm lunchboxes] [http://beachcki.org/officers/wpThumbnails/pics/topic1028.htm live night rap saturday video] [http://rvpark4u.com/weblog/skins/rsd/files/page1867.html karate kata video free] [http://caypkiwanis.org/main/wp-content/uploads/2007/09/article-1435.htm ohiolottery] [http://tatlin.com/gallery/wp-content/uploads/2008/topic-869.htm rakuen movie 4 inuyasha] [http://carpentercarpenter.ca/_doubletuttle/images/comment-1352.html smoothmag] [http://kazak.ca/buzz/data/media/boclid1366.htm wholesale home tanning bed] [http://juliemorstad.com/contactform/forms/images/article1485.htm honda radiator] [http://sahardesign.com/files/styles/article89.html skydiving video clip] [http://capstonerealty.ph/gallery/Farm_Lots/mini/resource-1164.html movie lobby card] [http://juliemorstad.com/contactform/forms/images/index.htm index] [http://beachcki.org/officers/wpThumbnails/pics/topic1352.htm environmental sampling supplies] [http://tatlin.com/gallery/wp-content/uploads/2008/topic-1226.htm valassis] [http://marja-leena-rathje.info/ssp_director/config/conf/article2186.html ivp care pharmacy] [http://appleturnover.tv/about/images/news-341-20090630.html pure country movie quotes] [http://cavalierpedigrees.com/XOOPS/images/text335.htm student housing] [http://casv.ca/secondary/class/install/1589.html chicago cubs] [http://sahardesign.com/files/styles/sitemap.html index] [http://kazak.ca/buzz/data/media/acerko633.htm pictures of rainbows] [http://sahardesign.com/files/styles/sitemap.html top] [http://cavalierpedigrees.com/XOOPS/images/text1627.htm suffolk realty agents]
+
[http://fusedlo.ojaru.jp/topic-465.html kid volunteer work for animal shelters in nj] [http://s1.shard.jp/dentage/article368.html yakima jobs] [http://voutoze.strefa.pl/lindy-hop.html lindy hop] [http://qedelkomf.nengu.jp/article327.html anzac day trading times] [http://www.weeaseta.orgs.hk/article21.html personal loans leeds] [http://jatoqas.oueb.eu/index.html links] [http://zvlraac.your2000.net/bahamas-five-star.html bahamas five star hotels] [http://s1.shard.jp/ladyloulou/comment452.html natural gas stocks] [http://www.weeaseta.orgs.hk/article216.html gratis dating no credit] [http://bugalpa.isuisse.com/text320.html age of mythology the titans no cd crack] [http://voureelfv.ibelgique.com/219.html activemark crack] [http://careqelox.o-oku.jp/resource3.html indiana high school athletic association football rules] [http://s1.shard.jp/ladyloulou/comment306.html panty job compilation] [http://s1.shard.jp/corecyclone/wsfs-online.html wsfs online banking] [http://fusedlo.ojaru.jp/topic-337.html presidential campaign spend way too much money] [http://s1.shard.jp/cest1avie/text-200.html cigna healthcare fee schedule] [http://page.freett.com/theomacy/index.html url] [http://bugalpa.isuisse.com/text455.html phone student teacher video] [http://koongetlq.mukade.jp/new16.html philadelphia eagles trade] [http://page.freett.com/xgratx/topic-415.html black bitchs] [http://koongetlq.mukade.jp/new205.html club penguin money maker how to download it] [http://fautayt.iquebec.com/news-474.html pamerla anderson videos] [http://listlisalove.finito-web.com/index.html sitemap] [http://wicaencxi.suppa.jp/article483.html free printable gift card] [http://rofirelc.321webs.com/article252.html caesars palace hotel deals] [http://delvous.tonosama.jp/text-388.html tamil nadu tourist board] [http://fusedlo.ojaru.jp/topic-23.html home down payment loan] [http://insanofangirl.finito-web.com/article479.html uk bank holiday] [http://fautayt.iquebec.com/news-267.html pooh bear video] [http://rofirelc.321webs.com/article234.html buying ex rental cars] [http://s1.shard.jp/cest1avie/text-202.html advance tubo merida yucatan] [http://tito999.finito-web.com/article1.html free interracial blow jobs] [http://yulcha1106.finito-web.com/new376.html how to start a limo business] [http://page.freett.com/themotion/comment-130.html foo fighters best of you lyrics] [http://bugalpa.isuisse.com/text272.html perry mason videos] [http://s1.shard.jp/corecyclone/cum-pot-obtine.html cum pot obtine un credit daca sunt rau] [http://deltrmxre.ojaru.jp/index.html sitemap] [http://deltrmxre.ojaru.jp/comment172.html application letter healthcare] [http://fautayt.iquebec.com/news-417.html album king t.i torrent] [http://delnrtrvo.strefa.pl/caballeros-del.html caballeros del zodiaco] [http://eltdelfar.isuisse.com/text-127.html pam and tommy lee video free] [http://rofirelc.321webs.com/index.html index] [http://delnrtrvo.strefa.pl/index.html domain] [http://listlisalove.finito-web.com/comment-219.html master clock] [http://allibaswb.321webs.com/page-347.html bozeman american west airlines] [http://www.weeaseta.orgs.hk/article483.html interior design master bedroom] [http://deltrmxre.ojaru.jp/comment427.html elmo birthday cards] [http://zvlraac.your2000.net/best-deal-for.html best deal for hotels in orlando] [http://listlisalove.finito-web.com/comment-125.html public health job] [http://roclorocz.ibelgique.com/comment-70.html pinback videos]
 +
{{Content Programming Jabber}}
=Groupchat, : Components, and Event Models=
=Groupchat, : Components, and Event Models=
<br>By now, you should have a
<br>By now, you should have a
Line 10: Line 11:
conference room and alerts us to words and phrases that we want it to
conference room and alerts us to words and phrases that we want it to
listen for. There are two popular conference protocols, as mentioned in
listen for. There are two popular conference protocols, as mentioned in
-
Section 6.2.6—the presence-based Groupchat protocol, and the
+
Section 6.2.6 the presence-based Groupchat protocol, and the
<tt>jabber:iq:conference</tt>-based Conference protocol. The assistant
<tt>jabber:iq:conference</tt>-based Conference protocol. The assistant
recipe, a foray into the world of 'bots, takes a look at the original
recipe, a foray into the world of 'bots, takes a look at the original
Line 20: Line 21:
where this melding needs to happen. The first is a homage to the Trojan
where this melding needs to happen. The first is a homage to the Trojan
Room Coffee Machine (http://www.cl.cam.ac.uk/coffee/coffee.html), where
Room Coffee Machine (http://www.cl.cam.ac.uk/coffee/coffee.html), where
-
we give life, or at least presence, to a coffeepot, using LEGO®
+
we give life, or at least presence, to a coffeepot, using LEGO
-
MINDSTORMS™. The second is a Tk-based RSS headline viewer. Both the
+
MINDSTORMS. The second is a Tk-based RSS headline viewer. Both the
coffeepot and the Tk programming library have event loops of their own.
coffeepot and the Tk programming library have event loops of their own.
With the coffeepot, we need to have a loop that polls the coffeepot's
With the coffeepot, we need to have a loop that polls the coffeepot's
Line 45: Line 46:
between programming a client and programming a component in this chapter
between programming a client and programming a component in this chapter
and build a complete component that can be queried and interacted with
and build a complete component that can be queried and interacted with
-
using the third of Jabber's building blocks—the <tt>&lt;iq/&gt;</tt>
+
using the third of Jabber's building blocks the <tt>&lt;iq/&gt;</tt>
element.
element.
Line 88: Line 89:
becoming a conference user identified by a nickname that is chosen upon
becoming a conference user identified by a nickname that is chosen upon
entering that room. Nicknames are generally used in conference rooms to
entering that room. Nicknames are generally used in conference rooms to
-
provide a modicum of privacy—it is assumed that by default you don't
+
provide a modicum of privacy it is assumed that by default you don't
want to let the other conference room members know your real JID.
want to let the other conference room members know your real JID.
Line 94: Line 95:
interaction: a simple one that provides basic features and a more
interaction: a simple one that provides basic features and a more
complex one that provides the basic features plus facilities such as
complex one that provides the basic features plus facilities such as
-
password-protected rooms and room descriptions—Groupchat and Conference.
+
password-protected rooms and room descriptions Groupchat and Conference.
Line 244: Line 245:
: <tt>error</tt> and comes from the artificial JID constructed in the
: <tt>error</tt> and comes from the artificial JID constructed in the
: room entry attempt. The element is addressed to <tt>qmacro</tt>'s real
: room entry attempt. The element is addressed to <tt>qmacro</tt>'s real
-
: JID, of course—<tt>qmacro@jabber.com/jarltk</tt>—as otherwise it
+
: JID, of course<tt>qmacro@jabber.com/jarltk</tt> as otherwise it
: wouldn't reach him. : The error code 409 and text "Conflict" tells
: wouldn't reach him. : The error code 409 and text "Conflict" tells
: <tt>qmacro</tt> that the nickname conflicted with one already in the
: <tt>qmacro</tt> that the nickname conflicted with one already in the
Line 258: Line 259:
</code>
</code>
-
: This time, there is no conflict—no other user is in the room "cellar"
+
: This time, there is no conflict
-
: with that nickname—and the conference component registers the entry.
+
-
: It does this by sending <tt>qmacro</tt> the presence of all the room
+
-
: occupants, including that of himself:
+
-
<code>RECV: &lt;presence to='qmacro@jabber.com/jarltk'
+
-
from='cellar@conf.merlix.dyndns.org/flash'/&gt;
+
-
 
+
-
RECV: &lt;presence to='qmacro@jabber.com/jarltk'
+
-
from='cellar@conf.merlix.dyndns.org/roscoe'/&gt;
+
-
 
+
-
RECV: &lt;presence to='qmacro@jabber.com/jarltk'
+
-
from='cellar@conf.merlix.dyndns.org/deejay'/&gt;
+
-
 
+
-
</code>
+
-
: These presence elements are also sent to the other room occupants so
+
-
: they know that <tt>deejay</tt> is present.
+
-
; Conference component-generated notification
+
-
: In addition to the presence elements sent for each room occupant, a
+
-
: general roomwide message noting that someone with the nickname
+
-
: <tt>deejay</tt> just entered the room is sent out by the component as
+
-
: a <tt>type='groupchat'</tt> message to all the room occupants:
+
-
<code>RECV: &lt;message to='qmacro@jabber.com/jarltk' type='groupchat'
+
-
from='cellar@conf.merlix.dyndns.org'&gt; &lt;body&gt;deejay has become
+
-
available&lt;/body&gt; &lt;/message&gt;
+
-
 
+
-
</code>
+
-
: The text "has become available" used in the body of the message is
+
-
: taken directly from the ''Action Notices'' definitions, part of the
+
-
: Conferencing component instance configuration described in Section
+
-
: 4.10.3. Note that the identity of the room itself is simply a generic
+
-
: version of the JID that the room occupants use to enter:
+
-
<code>cellar@conf.merlix.dyndns.org
+
-
 
+
-
</code>
+
-
 
+
-
; Roomwide chat
+
-
: Once the user with the nickname <tt>roscoe</tt> sees someone enter the
+
-
: room, he sends a greeting, and <tt>qmacro</tt> waves back:
+
-
<code>RECV: &lt;message to='qmacro@jabber.com/jarltk'
+
-
from='cellar@conf.merlix.dyndns.org/roscoe' type='groupchat' cnu=''&gt;
+
-
&lt;body&gt;hi qmacro&lt;/body&gt; &lt;/message&gt;
+
-
 
+
-
SEND: &lt;message to='cellar@conf.merlix.dyndns.org'
+
-
type='groupchat'&gt; &lt;body&gt;/me waves to everyone&lt;/body&gt;
+
-
&lt;/message&gt;
+
-
 
+
-
</code>
+
-
: As with the notification message, each message is a
+
-
: <tt>groupchat</tt>-type message. The one received appears to come from
+
-
: <tt>cellar@conf.merlix.dyndns.org/roscoe</tt>, which is the JID
+
-
: representing the user in the room with the nickname <tt>roscoe</tt>.
+
-
: This way, <tt>roscoe</tt>'s real JID is never sent to <tt>qmacro</tt>.
+
-
: The message <tt>deejay</tt> sends is addressed to the room's identity
+
-
: <tt>cellar@conf.merlix.dyndns.org</tt>, and contains a message that
+
-
: starts with <tt>/me</tt>. This is simply a convention that is
+
-
: understood by clients that support conferencing, meant to represent an
+
-
: action and displayed thus:
+
-
<code>* deejay waves to everyone
+
-
 
+
-
</code>
+
-
 
+
-
{{Note|Ignore the <tt>cnu</tt> attribute; it's put there and used by the
+
-
component and should never make it out to the client endpoints. The
+
-
attribute name is a short name for the conference user and refers to the
+
-
internal structure that represents a conference room occupant within the
+
-
component.
+
-
 
+
-
</code>
+
-
 
+
-
; One-on-one chat
+
-
: The Conferencing component also supports a one-on-one chat mode, which
+
-
: is just like normal chat mode (where messages with the type
+
-
: <tt>chat</tt> are exchanged) except that the routing goes through the
+
-
: component. The intended recipient of a conference-routed chat message
+
-
: is identified by his room JID. So in this example:
+
-
<code>RECV: &lt;message to='qmacro@jabber.com/jarltk'
+
-
from='cellar@conf.merlix.dyndns.org/flash' type='chat'&gt;
+
-
&lt;body&gt;Is that you, qmacro?&lt;/body&gt;
+
-
&lt;thread&gt;jarl1998911094&lt;/thread&gt; &lt;/message&gt;
+
-
 
+
-
</code>
+
-
: the user nicknamed <tt>flash</tt> actually addressed the chat message
+
-
: to the JID:
+
-
<code>cellar@conf.merlix.dyndns.org/deejay
+
-
</code>
+
-
: which arrived at the Conferencing component (because of the hostname,
+
-
: <tt>conf.merlix.dyndns.org</tt> causes the <tt>&lt;message/&gt;</tt>
+
-
: element to be routed there), which then looked up internally who
+
-
: <tt>deejay</tt> really was (<tt>qmacro@jabber.com/jarltk</tt>) and
+
-
: sent it on. This way, the recipient of a conference-routed message
+
-
: never discovers the real JID of the sender. In all other ways, the
+
-
: actual <tt>&lt;message/&gt;</tt> element is like any other
+
-
: <tt>&lt;message/&gt;</tt> element—in this case, it contains a message
+
-
: <tt>&lt;body/&gt;</tt> and a chat <tt>&lt;thread/&gt;</tt>. (See
+
-
: Section 5.4.1 for details on the <tt>&lt;message/&gt;</tt> element.)
+
-
; Leaving the room
+
-
: In the same way that room entrance is effected by sending an
+
-
: <tt>available</tt> presence (remember, a <tt>&lt;presence/&gt;</tt>
+
-
: element without an explicit <tt>type</tt> attribute is understood to
+
-
: represent <tt>type="available'</tt>), leaving a room is achieved by
+
-
: doing the opposite:
+
-
<code>RECV: &lt;presence to='qmacro@jabber.com/jarltk'
+
-
type='unavailable' from='cellar@conf.merlix.dyndns.org/roscoe'/&gt;
+
-
 
+
-
</code>
+
-
: The people in the conference room are sent a message that
+
-
: <tt>roscoe</tt> has left the room by the <tt>unavailable</tt> presence
+
-
: packet. This is by and large for the benefit of each user's client, so
+
-
: that the room occupant list can be updated. The component also sends
+
-
: out a verbal notification, in the same way as it sends a verbal
+
-
: notification out when someone joins:
+
-
<code>RECV: &lt;message to='qmacro@jabber.com/jarltk' type='groupchat'
+
-
from='cellar@conf.merlix.dyndns.org'&gt; &lt;body&gt;roscoe has
+
-
left&lt;/body&gt; &lt;/message&gt;
+
-
 
+
-
</code>
+
-
: Like the join notification, the text for the leave notification ("has
+
-
: left") comes directly from the component instance configuration
+
-
: described in Section 4.10.3.
+
-
<br>
+
-
=== The Script's Scope ===
+
-
<br>The Keyword Assistant (''keyassist'') script
+
-
will be written in Python using the <tt>Jabberpy</tt> library. As
+
-
mentioned earlier, the script will perform the following tasks:
+
-
 
+
-
* Connect to a predetermined Jabber server
+
-
* Join a predetermined conference room
+
-
* Sit there quietly, listening to the conversation
+
-
* Take simple commands from people to watch for, or stop watching for, particular words or phrases uttered in the room
+
-
* Relay the context of those words or phrases to whomever requested them, if heard In addition
+
-
to setting the identity of the Jabber server and the conference room in variables, we'll also need to keep track of which users ask the assistant for words and phrases.
+
-
<br>We'll use a ''dictionary'' (''hash'' in
+
-
Perl terms), as shown in Example 9-3, because we want to manage the data
+
-
in there by key, the JID of those users that the script will be
+
-
assisting. Having a look at what this dictionary will look like during
+
-
the lifetime of this script will help us to visualize what we're trying
+
-
to achieve.
+
-
 
+
-
 
+
-
''Typical contents of the Keyword Assistant's dictionary''
+
-
 
+
-
<code>{ 'dj@gnu.pipetree.com/home': { 'http:': 1, 'ftp:': 1
+
-
},
+
-
 
+
-
'piers@jabber.org/work': { 'Perl': 1, 'Java': 1, 'SAP
+
-
R/3': 1
+
-
},
+
-
 
+
-
'cellar@conf.merlix.dyndns.org/roscoe': { 'dialback': 1
+
-
}
+
-
}
+
-
 
+
-
</code>
+
-
We can see from the contents of the dictionary in Example 9-3 that three
+
-
people have asked the script to look out for words and phrases. Two of
+
-
those people—<tt>dj</tt> and <tt>piers</tt>—have interacted with the
+
-
script directly by sending a ''normal'' (or <tt>chat</tt>)
+
-
<tt>&lt;message/&gt;</tt>. The other person, with the conference
+
-
nickname <tt>roscoe</tt>, is in the "cellar" room and has sent the
+
-
script a message routed through the Conference component in the same way
+
-
that <tt>flash</tt> sent <tt>qmacro</tt> a private message in Example
+
-
9-2: the JID of the sender belongs to (has the hostname set to) the
+
-
conference component. Technically, there's nothing to distinguish the
+
-
three JIDs here; it's just that we know from the name that
+
-
<tt>conf.merlix.dyndns.org</tt> is the name that identifies such a
+
-
component.
+
-
 
+
-
If we dissect the dictionary, we can see that:
+
-
 
+
-
* <tt>dj</tt> wants to be notified if any web or FTP URLs are mentioned.
+
-
* <tt>piers</tt> is interested in references to two of his favorite
+
-
languages and his favorite business software solution.
+
-
* <tt>roscoe</tt>
+
-
is interested in any talk about dialback. We said we'd give the script a
+
-
little bit of intelligence. This was a reference to the ability for
+
-
users to interact with the script while it runs, rather than having to
+
-
give the script a static list of words and phrases in a configuration
+
-
file. <tt>dj</tt>, <tt>piers</tt>, and <tt>roscoe</tt> have done this by
+
-
sending the script messages (directly, not within the room) with simple
+
-
keyword commands, such as:
+
-
 
+
-
: dj: "''watch http:''" script: "''ok, watching for http:''" dj:
+
-
: "''watch gopher:''" script: "''ok, watching for gopher:''" dj:
+
-
: "''watch ftp:''" script: "''ok, watching for ftp:''" dj: "''ignore
+
-
: gopher:''" script: "''ok, now ignoring gopher:''"
+
-
...
+
-
 
+
-
: piers: "''list''" script: "''watching for: Perl, Java, SAP R/3''"
+
-
...
+
-
 
+
-
: roscoe: "''stop''" script: "''ok, I've stopped watching''"
+
-
 
+
-
<br>
+
-
=== The keyassist Script ===
+
-
<br>Example 9-4 shows the ''keyassist'' script
+
-
in its entirety. The script is described in detail, step by step, in the
+
-
next section.
+
-
 
+
-
 
+
-
''The keyassist Perl script''
+
-
 
+
-
<code>import jabber from string import split, join, find import sys
+
-
 
+
-
keywords = {}
+
-
 
+
-
def addword(jid, word): if not keywords.has_key(jid): keywords[jid] = {}
+
-
keywords[jid][word] = 1
+
-
 
+
-
def delword(jid, word): if keywords.has_key(jid): if
+
-
keywords[jid].has_key(word): del keywords[jid][word]
+
-
 
+
-
def messageCB(con, msg):
+
-
 
+
-
type = msg.getType() if type == None: type = 'normal'
+
-
 
+
-
# Deal with interaction
+
-
if type == 'chat' or type == 'normal': jid = str(msg.getFrom())
+
-
 
+
-
message = split(msg.getBody(), None, 1); reply = ""
+
-
 
+
-
if message[0] == 'watch': addword(jid, message[1]) reply =
+
-
"Okay, watching for " + message[1]
+
-
 
+
-
if message[0] == 'ignore': delword(jid, message[1]) reply =
+
-
"Okay, now ignoring " + message[1]
+
-
 
+
-
if message[0] == 'list': if keywords.has_key(jid): reply =
+
-
"Watching for: " + join(keywords[jid].keys(), ", ") else: reply
+
-
= "Not watching for any keywords"
+
-
 
+
-
if message[0] == 'stop': if keywords.has_key(jid): del
+
-
keywords[jid] reply = "Okay, I've stopped watching"
+
-
 
+
-
if reply: con.send(msg.build_reply(reply))
+
-
 
+
-
 
+
-
# Scan room talk
+
-
if type == 'groupchat': message = msg.getBody()
+
-
 
+
-
for jid in keywords.keys(): for word in keywords[jid].keys(): if
+
-
find(message, word) &gt;= 0: con.send(jabber.Message(jid, word +
+
-
": " + message))
+
-
 
+
-
 
+
-
def presenceCB(con, prs):
+
-
 
+
-
# Deal with nickname conflict in room
+
-
if str(prs.getFrom()) == roomjid and prs.getType() == 'error':
+
-
prsnode = prs.asNode() error = prsnode.getTag('error') if error: if
+
-
(error.getAttr('code') == '409'): print "Cannot join room -
+
-
conflicting nickname" con.disconnect() sys.exit(0)
+
-
 
+
-
# Remove keyword list for groupchat correspondent
+
-
if prs.getType() == 'unavailable': jid = str(prs.getFrom()) if
+
-
keywords.has_key(jid): del keywords[jid]
+
-
 
+
-
Server = 'gnu.mine.nu' Username = 'kassist' Password = 'pass' Resource
+
-
= 'py'
+
-
 
+
-
Room = 'jdev' ConfServ = 'conference.jabber.org' Nick =
+
-
'kassist'
+
-
 
+
-
con = jabber.Client(host=Server) try: con.connect() except IOError, e:
+
-
print "Couldn't connect: %s" % e sys.exit(0) else: print "Connected"
+
-
 
+
-
if con.auth(Username,Password,Resource): print "Logged in as %s to
+
-
server %s" % ( Username, Server ) else: print "Problems authenticating:
+
-
", con.lastErr, con.lastErrCode sys.exit(1)
+
-
 
+
-
con.setMessageHandler(messageCB) con.setPresenceHandler(presenceCB)
+
-
 
+
-
con.send(jabber.Presence())
+
-
 
+
-
roomjid = Room + '@' + ConfServ + '/' + Nick print "Joining " + Room
+
-
con.send(jabber.Presence(to=roomjid))
+
-
 
+
-
while(1): con.process(5)
+
-
 
+
-
</code>
+
-
 
+
-
<br>
+
-
=== Dissecting the keyassist Script ===
+
-
<br>Taking ''keyassist'' step by
+
-
step, the first section is probably familiar if you've seen the previous
+
-
Python-based scripts in Section 8.1 and Section 8.3, both in Chapter 8.
+
-
 
+
-
 
+
-
<code>import jabber from string import split, join, find import sys
+
-
 
+
-
</code>
+
-
Here, all of the functions and libraries that we'll need are brought in.
+
-
We'll use the <tt>find</tt> function from the <tt>string</tt> library to
+
-
help with the keyword searching.
+
-
 
+
-
Next, we declare the dictionary. This will hold a list of the words that
+
-
the script will look for, as defined by each person, as shown in Example
+
-
9-3.
+
-
 
+
-
 
+
-
<code>keywords = {}
+
-
 
+
-
</code>
+
-
 
+
-
<br>
+
-
==== Maintaining the keyword dictionary ====
+
-
<br>To maintain this
+
-
dictionary, we will use two subroutines to add words to and remove words
+
-
from a user's word list. These subroutines are called when a command
+
-
such as ''watch'' or ''ignore'' is recognized in the callback subroutine
+
-
that handles incoming <tt>&lt;message/&gt;</tt> elements:
+
-
 
+
-
 
+
-
<code>def addword(jid, word): if not keywords.has_key(jid):
+
-
keywords[jid] = {} keywords[jid][word] = 1
+
-
 
+
-
def delword(jid, word): if keywords.has_key(jid): if
+
-
keywords[jid].has_key(word): del keywords[jid][word]
+
-
 
+
-
</code>
+
-
A string representation of the JID (in <tt>jid</tt>) of the
+
-
correspondent giving the command is passed to the subroutines along with
+
-
the word or phrase specified (in <tt>word</tt>) by the user. The
+
-
dictionary has two levels: the first level is keyed by the JID, and the
+
-
second by word or phrase. We use a dictionary, rather than an array, at
+
-
the second level simply to make removal of words and phrases easier.
+
-
 
+
-
 
+
-
<br>
+
-
==== Message callback ====
+
-
<br>Next, we define the callback to handle
+
-
incoming <tt>&lt;message/&gt;</tt> elements:
+
-
 
+
-
 
+
-
<code>def messageCB(con, msg):
+
-
 
+
-
type = msg.getType() if type == None: type = 'normal'
+
-
 
+
-
</code>
+
-
As usual, we're expecting the message callback to be passed the
+
-
connection object (in <tt>con</tt>) and the message object itself
+
-
(<tt>msg</tt>). How this callback is to proceed is determined by the
+
-
''type'' of message received. We determine the type (taken from the
+
-
<tt>&lt;message/&gt;</tt> element's <tt>type</tt> attribute) and store
+
-
it in the variable called <tt>type</tt>. Remember that if no
+
-
<tt>type</tt> attribute is present, a message type of <tt>normal</tt> is
+
-
assumed. (See Section 5.4.1.1 for details of <tt>&lt;message/&gt;</tt>
+
-
attributes.)
+
-
 
+
-
The two types of incoming messages we're expecting this script to
+
-
receive are those conveying the room's conversation—in
+
-
<tt>groupchat</tt>-type messages—and those over which the commands such
+
-
as watch and ignore are carried, which we expect in the form of
+
-
<tt>normal</tt>- or <tt>chat</tt>-type messages.
+
-
 
+
-
The first main section of the <tt>messageCB</tt> handler deals with
+
-
incoming commands:
+
-
 
+
-
 
+
-
<code> # Deal with interaction if type == 'chat' or type ==
+
-
'normal': jid = str(msg.getFrom())
+
-
 
+
-
message = split(msg.getBody(), None, 1); reply = ""
+
-
 
+
-
if message[0] == 'watch': addword(jid, message[1]) reply =
+
-
"Okay, watching for " + message[1]
+
-
 
+
-
if message[0] == 'ignore': delword(jid, message[1]) reply =
+
-
"Okay, now ignoring " + message[1]
+
-
 
+
-
if message[0] == 'list': if keywords.has_key(jid): reply =
+
-
"Watching for: " + join(keywords[jid].keys(), ", ") else: reply
+
-
= "Not watching for any keywords"
+
-
 
+
-
if message[0] == 'stop': if keywords.has_key(jid): del
+
-
keywords[jid] reply = "Okay, I've stopped watching"
+
-
 
+
-
if reply: con.send(msg.build_reply(reply))
+
-
 
+
-
 
+
-
</code>
+
-
If the <tt>&lt;message/&gt;</tt> element turns out to be of the type in
+
-
which we're expecting a potential command, we want to determine the JID
+
-
of the correspondent who sent that message. Calling the
+
-
<tt>getFrom()</tt> method will return us a JID object. What we need is
+
-
the string representation of that, which can be determined by calling
+
-
the <tt>str()</tt> function on that JID object:
+
-
 
+
-
 
+
-
<code> jid = str(msg.getFrom())
+
-
 
+
-
</code>
+
-
Then we grab the content of the message by calling the
+
-
<tt>getBody()</tt> on the <tt>msg</tt> object and split the whole thing
+
-
on the first bit of whitespace. This should be enough for us to
+
-
distinguish a command (watch, ignore, and so on) from the keywords.
+
-
After the split, the first element (index 0) in the <tt>message</tt>
+
-
array will be the command, and the second element (index 1) will be the
+
-
word or phrase, if given. At this stage, we also declare an empty reply:
+
-
 
+
-
 
+
-
<code> message = split(msg.getBody(), None, 1); reply = ""
+
-
 
+
-
</code>
+
-
Now it's time to determine if what the script was sent made sense as a
+
-
command:
+
-
 
+
-
 
+
-
<code> if message[0] == 'watch': addword(jid, message[1]) reply
+
-
= "Okay, watching for " + message[1]
+
-
 
+
-
if message[0] == 'ignore': delword(jid, message[1]) reply =
+
-
"Okay, now ignoring " + message[1]
+
-
 
+
-
if message[0] == 'list': if keywords.has_key(jid): reply =
+
-
"Watching for: " + join(keywords[jid].keys(), ", ") else: reply
+
-
= "Not watching for any keywords"
+
-
 
+
-
if message[0] == 'stop': if keywords.has_key(jid): del
+
-
keywords[jid] reply = "Okay, I've stopped watching"
+
-
 
+
-
</code>
+
-
We go through a series of checks, taking appropriate action for the
+
-
supported commands:
+
-
 
+
-
 
+
-
; watch
+
-
: Watch for a particular word or phrase.
+
-
; ignore
+
-
: Stop watching for a particular word or phrase.
+
-
; list
+
-
: List the words and phrases currently being watched.
+
-
; stop
+
-
: Stop watching altogether; remove the list of words and phrases. The
+
-
: <tt>addword()</tt> and <tt>delword()</tt> functions defined earlier
+
-
: are used here, as well as other simpler functions; one that lists the
+
-
: words and phrases for a particular JID:
+
-
 
+
-
 
+
-
<code>keywords[jid].keys()
+
-
 
+
-
</code>
+
-
and one that removes them:
+
-
 
+
-
 
+
-
<code>del keywords[jid]
+
-
 
+
-
</code>
+
-
If there was something recognizable for the script to do, we get it to
+
-
reply appropriately:
+
-
 
+
-
 
+
-
<code> if reply: con.send(msg.build_reply(reply))
+
-
 
+
-
</code>
+
-
The <tt>build_reply()</tt> function creates a reply out of a message
+
-
object by setting <tt>to</tt> to the value of the original
+
-
<tt>&lt;message/&gt;</tt> element's <tt>from</tt> attribute and
+
-
preserving the element <tt>type</tt> attribute and
+
-
<tt>&lt;thread/&gt;</tt> tag, if present. The <tt>&lt;body/&gt;</tt> of
+
-
the reply object (which is just a <tt>&lt;message/&gt;</tt> element) is
+
-
set to whatever is passed in the function call; in this case, it's the
+
-
text in the <tt>reply</tt> variable.
+
-
 
+
-
Now that we've dealt with incoming commands, we need another section in
+
-
the message callback subroutine to scan for the words and phrases. The
+
-
target texts for this scanning will be the snippets of room
+
-
conversation, which arrive at the callback in the form of
+
-
<tt>groupchat</tt>-type <tt>&lt;message/&gt;</tt> elements:
+
-
 
+
-
 
+
-
<code> # scan room talk if type == 'groupchat': message =
+
-
msg.getBody()
+
-
 
+
-
</code>
+
-
The <tt>message</tt> variable holds the string we need to scan; it's
+
-
just a case of checking for each of the words or phrases on behalf of
+
-
each of the users who have asked:
+
-
 
+
-
 
+
-
<code> for jid in keywords.keys(): for word in
+
-
keywords[jid].keys(): if find(message, word) &gt;= 0:
+
-
con.send(jabber.Message(jid, word + ": " + message))
+
-
 
+
-
</code>
+
-
If we get a hit, we construct a new <tt>Message</tt> object, passing the
+
-
JID of the person for whom the string has matched (in the <tt>jid</tt>
+
-
variable) and the notification, consisting of the word or phrase that
+
-
was found (in <tt>word</tt>) and the context in which it was found (the
+
-
sentence uttered, in <tt>message</tt>). Once found and constructed, the
+
-
<tt>&lt;message/&gt;</tt> is sent to that user. By default, the
+
-
<tt>Message</tt> constructor specifies no <tt>type</tt> attribute, so
+
-
the user is sent a "normal" message.
+
-
 
+
-
<br>
+
-
==== Presence callback ====
+
-
<br>Having dealt with the incoming
+
-
<tt>&lt;message/&gt;</tt> elements, we turn to the
+
-
<tt>&lt;presence/&gt;</tt> elements. Most of those we receive in this
+
-
conference room will be notifications from people entering and leaving
+
-
the room, as shown in Example 9-2. We want to perform housekeeping on
+
-
our <tt>keywords</tt> dictionary so the entries don't become stale. We
+
-
also want to deal with the potential problem of conflicting nicknames.
+
-
Let's look at that first.
+
-
 
+
-
We want to check for the possibility of nickname conflict problems that
+
-
may occur when we enter the room, and the chosen nickname
+
-
(<tt>flash</tt>) is already taken.
+
-
 
+
-
Remembering that a conflict notification will look something like this:
+
-
 
+
-
 
+
-
<code>&lt;presence to='qmacro@jabber.com/jarltk'
+
-
from='cellar@conf.merlix.dyndns.org/flash' type='error'&gt; &lt;error
+
-
code='409'&gt;Conflict&lt;/error&gt; &lt;/presence&gt;
+
-
</code>
+
-
we test for the receipt of a <tt>&lt;presence/&gt;</tt> element with the
+
-
following:
+
-
 
+
-
 
+
-
<code>def presenceCB(con, prs):
+
-
 
+
-
# Deal with nickname conflict in room
+
-
if str(prs.getFrom()) == roomjid and prs.getType() == 'error':
+
-
prsnode = prs.asNode() error = prsnode.getTag('error') if error: if
+
-
(error.getAttr('code') == '409'): print "Cannot join room -
+
-
conflicting nickname" con.disconnect() sys.exit(0)
+
-
 
+
-
</code>
+
-
The <tt>&lt;presence/&gt;</tt> element will appear to be sent from the
+
-
JID that we constructed for the initial room entry negotiation (in the
+
-
<tt>roomjid</tt> variable further down in the script); for example:
+
-
 
+
-
 
+
-
<code>jdev@conference.jabber.org/kassist
+
-
</code>
+
-
We compare this value to the value of the incoming
+
-
<tt>&lt;presence/&gt;</tt>'s <tt>from</tt> attribute, and also make sure
+
-
that the <tt>type</tt> attribute is set to <tt>error</tt>. If it is, we
+
-
want to extract the details from the <tt>&lt;error/&gt;</tt> tag that
+
-
will be contained as a direct child of the <tt>&lt;presence/&gt;</tt>.
+
-
 
+
-
The <tt>Jabberpy</tt> library currently doesn't offer a direct
+
-
high-level function to get at this tag from the <tt>Presence</tt> object
+
-
(in <tt>prs</tt>), but we can strip away the presence object "mantle"
+
-
and get at the underlying object, which is a neutral "node"—a Jabber
+
-
element, or XML fragment, without any preconceived ideas of what it is
+
-
(and therefore without any accompanying high-level methods such as
+
-
<tt>getBody()</tt> or <tt>setPriority()</tt>).
+
-
 
+
-
 
+
-
{{Note|If this seems a little cryptic, just think of it like this: each
+
-
of the <tt>Presence</tt>, <tt>Message</tt>, and <tt>IQ</tt> classes are
+
-
merely superclasses of the base class <tt>Protocol</tt>, which
+
-
represents elements generically.
+
-
 
+
-
</code>
+
-
The <tt>asNode()</tt> method gives us what we need—a <tt>Protocol</tt>
+
-
object representation of the <tt>&lt;presence/&gt;</tt> element. From
+
-
this we can get to the <tt>&lt;error/&gt;</tt> tag and its contents. If
+
-
we find that we do have a nickname conflict, we abort by disconnecting
+
-
from the Jabber server and ending the script.
+
-
 
+
-
The general idea is that this script will run indefinitely and notify
+
-
the users on a continuous basis, so we need to do a spot of keyword
+
-
housekeeping. No presence subscription relationships are built (mostly
+
-
to keep the script small and simple; you could adapt the mechanism from
+
-
the recipe in Section 8.3 if you wanted to make this script sensitive to
+
-
presence), so notifications will get queued up for the user if he is
+
-
offline with the use of the ''mod_offline'' module of the Jabber Session
+
-
Manager (JSM). This makes a lot of sense for the most part; however, we
+
-
still want to have the script send notifications even if the user is
+
-
offline. Additionally, a command could be sent to the script to watch
+
-
for a keyword or phrase from a user within the room. We would receive
+
-
the command from a JID like this:
+
-
 
+
-
 
+
-
<code>jdev@conference.jabber.org/nickname
+
-
</code>
+
-
This is a ''transient JID'', in that it represents a user's presence in
+
-
the ''jdev'' room for a particular session. If a word is spotted by the
+
-
script hours or days later, there's a good chance that the user has left
+
-
the room, making the JID invalid as a recipient. Although the JID is
+
-
''technically'' valid and will reach the conferencing component, there
+
-
will be no real user JID that it is paired up with. Potentially worse,
+
-
the room occupant's identity JID may be assigned to someone else at a
+
-
later stage, if the original user left, and a new user entered choosing
+
-
the same nickname the original user had chosen. See the upcoming sidebar
+
-
titled "Transient and Nonexistent JIDs" for a short discussion of the
+
-
difference between a transient JID and a nonexistent JID.
+
-
 
+
-
So as soon as we notice a user leave the room we're in, which will be
+
-
indicated through a <tt>&lt;presence/&gt;</tt> element conveying that
+
-
occupant's ''unavailability'', we should remove any watched-for words
+
-
and phrases from the dictionary:
+
-
 
+
-
 
+
-
<code> # Remove keyword list for groupchat correspondent if
+
-
prs.getType() == 'unavailable': jid = str(prs.getFrom()) if
+
-
keywords.has_key(jid): del keywords[jid]
+
-
 
+
-
</code>
+
-
As before, we obtain the string representation of the JID using the
+
-
<tt>str()</tt> function on the JID object that represents the presence
+
-
element's sender, obtained via the <tt>getFrom()</tt> method.
+
-
 
+
-
 
+
-
{{Sidebar|Transient and Nonexistent JIDsWhat happens when you send a
+
-
message to a "transient" conference room JID? Superficially, the same as
+
-
when you send one to a ''nonexistent'' JID. But there are some subtle
+
-
differences.
+
-
 
+
-
A ''transient JID'' is one that reflects a user's alternate identity in
+
-
the context of the Conferencing component. When you construct and send a
+
-
message to a conference transient JID, it goes first to the conference
+
-
component because of the hostname in the JID that identifies that
+
-
component, for example:
+
-
 
+
-
 
+
-
<code>jdev@conference.jabber.org/qmacro
+
-
</code>
+
-
The hostname <tt>conference.jabber.org</tt> is what the jabberd backbone
+
-
uses to route the element. As mentioned earlier, the Conferencing
+
-
component will relay a message to the real JID that belongs to the user
+
-
currently in a room hosted by that component.
+
-
 
+
-
While the component itself is usually persistent, the room occupants
+
-
(and so their transient JIDs) are not. When a message is sent to the JID
+
-
<tt>jdev@conference.jabber.org/qmacro</tt> and there is no room occupant
+
-
in the ''jdev'' room with the nickname <tt>qmacro</tt>, the message will
+
-
still reach its ''first'' destination—the component—but be rejected at
+
-
that stage, as shown in Example 9-5.
+
-
 
+
-
 
+
-
''A message to a nonexistent transient JID is rejected''
+
-
 
+
-
<code>SEND: &lt;message to='jdev@conference.jabber.org/qmacro'&gt;
+
-
&lt;body&gt;Hello there&lt;/body&gt; &lt;/message&gt;
+
-
 
+
-
RECV: &lt;message to='dj@gnu.mine.nu/jarl'
+
-
from='jdev@conference.jabber.org/qmacro' type='error'&gt;
+
-
&lt;body&gt;Hello there&lt;/body&gt; &lt;error code='404'&gt;Not
+
-
Found&lt;/error&gt; &lt;/message&gt;
+
-
 
+
-
</code>
+
-
Although the rejection—the "Not Found" error—is the same as if a message
+
-
had been sent to a JSM user that didn't exist, the difference is that
+
-
the transient user always had the ''potential'' to exist, whereas the
+
-
JSM user never did. Of course, if the JID referred to a nonexistent
+
-
Jabber server, then the error returned wouldn't be a "Not Found" error
+
-
404, but an "Unable to resolve hostname" error 502.
+
-
 
+
-
</code>
+
-
<br>
+
-
 
+
-
==== The main script ====
+
-
<br>Now that we have the subroutines and callbacks
+
-
set up, all we need to do is define the Jabber server and room
+
-
information:
+
-
 
+
-
 
+
-
<code>Server = 'gnu.mine.nu' Username = 'kassist' Password = 'pass'
+
-
Resource = 'py'
+
-
 
+
-
Room = 'jdev' ConfServ = 'conference.jabber.org' Nick =
+
-
'kassist'
+
-
 
+
-
</code>
+
-
The <tt>kassist</tt> user can be set up simply by using the reguser
+
-
script presented in Section 7.4:
+
-
 
+
-
 
+
-
<code> $ <tt>./reguser gnu.mine.nu username=kassist password=pass</tt>
+
-
[Attempt] (kassist) Successful registration $
+
-
</code>
+
-
In the same way as in previous recipes' scripts, a connection attempt is
+
-
made, followed by an authentication attempt:
+
-
 
+
-
 
+
-
<code>con = jabber.Client(host=Server,debug=0,log=0) try: con.connect()
+
-
except IOError, e: print "Couldn't connect: %s" % e sys.exit(0) else:
+
-
print "Connected"
+
-
 
+
-
if con.auth(Username,Password,Resource): print "Logged in as %s to
+
-
server %s" % ( Username, Server ) else: print "Problems authenticating:
+
-
", con.lastErr, con.lastErrCode sys.exit(1)
+
-
 
+
-
</code>
+
-
Then the message and presence callbacks <tt>messageCB()</tt> and
+
-
<tt>presenceCB()</tt> are defined to the connection object in
+
-
<tt>con</tt>:
+
-
 
+
-
 
+
-
<code>con.setMessageHandler(messageCB)
+
-
con.setPresenceHandler(presenceCB)
+
-
 
+
-
</code>
+
-
After sending initial presence, informing the JSM (and anyone who might
+
-
be subscribed to <tt>kassist</tt>'s presence) of the assistant's
+
-
availability:
+
-
 
+
-
 
+
-
<code>con.send(jabber.Presence())
+
-
 
+
-
</code>
+
-
we also construct—from the <tt>Room</tt>, <tt>ConfServ</tt>, and
+
-
<tt>Nick</tt> variables—and send the <tt>&lt;presence/&gt;</tt> element
+
-
for negotiating entry to the ''jdev'' room hosted by the Conferencing
+
-
component at <tt>conference.jabber.org</tt>:
+
-
 
+
-
 
+
-
<code>roomjid = Room + '@' + ConfServ + '/' + Nick print "Joining " +
+
-
Room con.send(jabber.Presence(to=roomjid))
+
-
 
+
-
</code>
+
-
The <tt>con.send()</tt> function will send a <tt>&lt;presence/&gt;</tt>
+
-
element that looks like this:
+
-
 
+
-
 
+
-
<code>SEND: &lt;presence to='jdev@conference.jabber.org/kassist'/&gt;
+
-
</code>
+
-
We're sending available presence to the room, to negotiate entry, but
+
-
what about the initial presence? Why do we send that too if there are no
+
-
users who will be subscribed to the <tt>kassist</tt> JID? If no initial
+
-
presence is sent, the JSM will merely store up any
+
-
<tt>&lt;message/&gt;</tt> elements destined for <tt>kassist</tt>, as it
+
-
will think the JID is offline.
+
-
 
+
-
<br>
+
-
==== The processing loop ====
+
-
<br>Once everything has been set up, we simply
+
-
need to have the script sit back and wait for incoming packets and
+
-
handle them appropriately. For this, we simply call the
+
-
<tt>process()</tt> function every 5 seconds to look for elements
+
-
arriving on the XML stream:
+
-
 
+
-
 
+
-
<code>while(1): con.process(5)
+
-
 
+
-
</code>
+
-
<br>
+
-
 
+
-
== Connecting Devices to Jabber ==
+
-
<br>LEGO MINDSTORMS. What a great reason
+
-
to dig out that box of LEGO bricks you haven't touched in years. When I
+
-
found out that LEGO was bringing out a programmable brick, the
+
-
RCX,<ref>Contrary to popular belief, "RCX" stands for "Robotic Command
+
-
Explorer," according to LEGO's official MINDSTORMS page. </ref>, I went
+
-
to my favorite toy shop and purchased the set. In addition to the RCX
+
-
(shown in Figure 9-1), the MINDSTORMS set comes with an infrared (IR)
+
-
port and an IR tower, which you can connect to the serial port of your
+
-
PC, a battery compartment,<ref>There's also a DC power socket for those
+
-
of us without rechargeable batteries. </ref> motors, touch and light
+
-
sensors, and various LEGO Technic parts.
+
-
<br>
+
-
 
+
-
[[image:jab_0901.png|The LEGO MINDSTORMS RCX, or "programmable brick"|center|350 px]]
+
-
<br></code> There are plenty of ways to
+
-
interact with the RCX. The MINDSTORMS Robotics Invention System (RIS)™
+
-
set comes with Windows software with which you can build programs by
+
-
moving blocks of logic around graphically on the screen and chaining
+
-
them together. In addition, various efforts on the parts of talented
+
-
individuals have come up with many different ways to program the RCX.
+
-
''The Unofficial Guide to LEGO® MINDSTORMS™ Robots'' (O'Reilly &amp;
+
-
Associates, Inc., 1999) tells you all you need to know about programing
+
-
the RCX. What's important to know for this recipe is detailed in
+
-
Programming the RCX.
+
-
 
+
-
 
+
-
{{Sidebar|Programming the RCXThere are two approaches to programming the
+
-
RCX. One approach is to write a program on your PC, download it to the
+
-
RCX, and start and stop the program using the buttons on the RCX itself.
+
-
 
+
-
The other approach is to control the RCX directly from a program that
+
-
you write ''and'' execute on your PC, sending control signals and
+
-
receiving sensor values over the IR connection.
+
-
 
+
-
Both approaches have their merits. How appropriate each one is boils
+
-
down to one thing: connections. On the one hand, building autonomous
+
-
machines that find their way around the kitchen to scare the cat and
+
-
bring you a sandwich calls for the first approach, when, once you've
+
-
downloaded the program to the RCX, you can dispense with any further
+
-
connection with your PC because the entire logic is situated in your
+
-
creation. On the other hand, if you want to build a physical extension
+
-
to a larger system that, for example, has a connection to the Internet,
+
-
the second approach is likely to be more fruitful, because you can
+
-
essentially use the program that runs on your PC and talks to the RCX
+
-
over the IR link as a conduit, a proxy of sorts, to other programs and
+
-
systems that can be reached over the network. We're going to use the
+
-
second approach.
+
-
 
+
-
The RIS software that comes as standard centers around an ActiveX
+
-
control. While there are plenty of ways to talk to the RCX without using
+
-
this control (the book mentioned earlier describes many of these ways),
+
-
the features offered by the control—<tt>Spirit.ocx</tt>—are fine for
+
-
many a project. And with Perl's <tt>Win32::OLE</tt> module, we can
+
-
interact with this ActiveX control without having to resort to Visual
+
-
Basic.
+
-
 
+
-
</code>
+
-
 
+
-
<br>
+
-
=== What We're Going to Do ===
+
-
<br>Everyone knows that one of the virtues of
+
-
a programmer is ''laziness''. We're going to extend this virtue (perhaps
+
-
a little too far) and enhance it with a hacker's innate ability to
+
-
combine two favorite pastimes—programming and playing with LEGO—to build
+
-
contrived but fun devices.
+
-
 
+
-
Often being a key part of a programmer's intake, coffee figures highly
+
-
on the daily agenda. It's important to have a good cup of coffee to keep
+
-
the brain cells firing, but it's even more important to know whether
+
-
there's actually any coffee left in the pot. Going over to the coffeepot
+
-
to find out is time away from the keyboard and therefore time wasted. So
+
-
let's put the RCX to good use and build a device to tell us, via Jabber,
+
-
whether the coffeepot has enough for another cup.
+
-
 
+
-
In building the device, a light sensor was connected to the RCX to "see"
+
-
the level of coffee in the pot. Since the coffeepot is made of glass,
+
-
light passes through it unless the coffee gets in the way, thus creating
+
-
a simple binary switch:
+
-
 
+
-
* No (or a small amount of) light measured: there's coffee in the pot.
+
-
* Some (or a larger amount of) light: there's no coffee in the pot. We
+
-
want to be able to send the availability of coffee to all interested
+
-
parties in a way that their off-the-shelf Jabber clients can easily
+
-
understand and display.
+
-
 
+
-
Figure 9-2 shows the LEGO MINDSTORMS device in action. The brick mounted
+
-
on the gantry is the light sensor, which extends to the glass coffeepot;
+
-
a wire runs from it to the connector on the RCX. Behind the RCX is the
+
-
IR tower, which is connected to the PC.
+
-
 
+
-
 
+
-
[[image:jab_0902.png|Our device "looking" at the coffeepot|center|350 px]]
+
-
</code> Remembering that
+
-
<tt>&lt;presence/&gt;</tt> elements are a simple way of broadcasting
+
-
information about availability ''and'' that they contain a
+
-
<tt>&lt;status/&gt;</tt> tag to describe the detail or context of that
+
-
availability (see Section 5.4.2 for details on the
+
-
<tt>&lt;presence/&gt;</tt> element), we have a perfect mechanism that's
+
-
ready to be used. What's more, most, if not all, of the off-the-shelf
+
-
Jabber client implementations will display the content of the
+
-
<tt>&lt;status/&gt;</tt> tag in the client user's roster next to the JID
+
-
to which it applies. Figure 9-3 shows how the content of the
+
-
<tt>&lt;status/&gt;</tt> tag is displayed as a hovering "tooltip" in
+
-
WinJab.
+
-
 
+
-
 
+
-
[[image:jab_0903.png|Receiving information on the coffee's status in WinJab|center|350 px]]
+
-
</code> Here's what we need to do:
+
-
 
+
-
 
+
-
; Step 1: Set up the RCX
+
-
: We need to set the RCX up, with the light sensor, so that it's close
+
-
: enough to the coffeepot to take reliable and consistent light
+
-
: readings. Luckily the serial cable that comes with the MINDSTORMS set
+
-
: and connects to the IR tower is long enough to stretch from the
+
-
: computer to within the infrared line of sight to the RCX.
+
-
; Step 2: Make the correct calibrations
+
-
: There are bound to be differences in ambient light, sensitivity of the
+
-
: light sensor, and how strong you make your coffee. So we need a way of
+
-
: calibrating the setup, so that we can find the appropriate "pivot
+
-
: point" light reading value that lies between the two states of
+
-
: ''coffee'' and ''no coffee''.
+
-
; Step 3: Set up a connection to Jabber
+
-
: We need a connection to a Jabber server and a client account there. We
+
-
: can set one up using the reguser script from Section 7.4. We also need
+
-
: the script to honor presence from users who want to be informed of the
+
-
: coffee state.
+
-
; Step 4: Set up a sensor poll/presence push loop
+
-
: Once the RCX has been set up, the sensor calibrations taken, and the
+
-
: connection has been made, we need to monitor the light sensor on the
+
-
: RCX at regular intervals. At each interval, we determine the coffee
+
-
: state by comparing the value received from the sensor with the pivot
+
-
: point determined in the calibration step and send any change in that
+
-
: state as a new availability <tt>&lt;presence/&gt;</tt> element
+
-
: containing an appropriate description in the <tt>&lt;status/&gt;</tt>
+
-
: tag.
+
-
<br>
+
-
=== The Coffee Script ===
+
-
<br>We're going to use Perl and the
+
-
<tt>Net::Jabber</tt> libraries to build the script shown in Example 9-6.
+
-
Perl allows us a comfortable way to interact with an ActiveX control,
+
-
through the <tt>Win32::OLE</tt> module, so let's have a look at the
+
-
''coffee'' script as a whole, then we'll go back and look at the script
+
-
in detail.
+
-
 
+
-
 
+
-
''The coffee script, written in Perl''
+
-
 
+
-
<code>use Net::Jabber qw(Client); use Win32::OLE; use Getopt::Std; use
+
-
strict;
+
-
 
+
-
my %opts; getopt('ls', \%opts);
+
-
 
+
-
use constant SERVER =&gt; "merlix.dyndns.org"; use constant PORT
+
-
=&gt; 5222; use constant USERNAME =&gt; "coffee"; use constant PASSWORD
+
-
=&gt; "pass"; use constant RESOURCE =&gt; "perlscript";
+
-
 
+
-
use constant NOCOFFEE =&gt; 0; use constant COFFEE =&gt; 1;
+
-
 
+
-
use constant SENSOR =&gt; defined($opts{'s'}) ? $opts{'s'} : 0; use
+
-
constant GRAIN =&gt; 1;
+
-
 
+
-
my $current_status = -1; my @status; $status[NOCOFFEE] = 'xa/Coffeepot
+
-
is empty'; $status[COFFEE] = '/Coffee is available!';
+
-
 
+
-
my $rcx = &amp;setup_RCX(SENSOR);
+
-
 
+
-
# Either calibrate if no parameters given, or run with the parameter
+
-
# given as -l, which will be taken as the pivot between coffee and no
+
-
# coffee
+
-
&amp;calibrate($rcx) unless defined($opts{'l'});
+
-
 
+
-
# Determine initial status (will be either 0 or 1)
+
-
my $s = &amp;set_status($rcx-&gt;Poll(9, SENSOR));
+
-
 
+
-
my $jabber = &amp;setup_Jabber(SERVER, PORT, USERNAME, PASSWORD,
+
-
RESOURCE, $s);
+
-
 
+
-
# Main loop: check Jabber and RCX
+
-
while (1) { defined($jabber-&gt;Process(GRAIN)) or die "The connection
+
-
to the Jabber server was broken\n"; my $s =
+
-
&amp;set_status($rcx-&gt;Poll(9, SENSOR)); &amp;set_presence($jabber,
+
-
$s) if defined $s;
+
-
}
+
-
 
+
-
 
+
-
# Set up Jabber client connection, sending initial presence
+
-
sub setup_Jabber { my ($server, $port, $user, $pass, $resource,
+
-
$initial_status) = @_; my $connection = new Net::Jabber::Client;
+
-
 
+
-
# Connect
+
-
my $status = $connection-&gt;Connect( hostname =&gt; $server, port
+
-
=&gt; $port ); die "Cannot connect to Jabber server $server on port
+
-
$port\n" unless $status;
+
-
 
+
-
# Callbacks
+
-
$connection-&gt;SetCallBacks( presence =&gt; \&amp;InPresence );
+
-
 
+
-
# Ident/Auth
+
-
my @result = $connection-&gt;AuthSend( username =&gt; $user, password
+
-
=&gt; $pass, resource =&gt; $resource ); die "Ident/Auth failed:
+
-
$result[0] - $result[1]\n" if $result[0] ne "ok";
+
-
 
+
-
# Roster
+
-
$connection-&gt;RosterGet();
+
-
 
+
-
# Initial presence dependent upon initial status
+
-
&amp;set_presence($connection, $initial_status);
+
-
 
+
-
return $connection;
+
-
}
+
-
 
+
-
 
+
-
sub set_presence { my ($connection, $s) = @_; my $presence =
+
-
Net::Jabber::Presence-&gt;new(); my ($show, $status) = split("/",
+
-
$status[$s], 2); $presence-&gt;SetPresence( show =&gt; $show, status
+
-
=&gt; $status ); print $status, "\n"; $connection-&gt;Send($presence);
+
-
}
+
-
 
+
-
 
+
-
# Handle presence messages
+
-
sub InPresence { my $presence = $_[1]; my $from =
+
-
$presence-&gt;GetFrom(); my $type = $presence-&gt;GetType();
+
-
 
+
-
if ($type eq "subscribe") { print "Subscribe request ($from) ...\n";
+
-
$jabber-&gt;Send($presence-&gt;Reply(type =&gt; 'subscribed'));
+
-
}
+
-
 
+
-
if ($type eq "unsubscribe") { print "Unsubscribe request ($from)
+
-
...\n"; $jabber-&gt;Send($presence-&gt;Reply(type =&gt;
+
-
'unsubscribed'));
+
-
}
+
-
}
+
-
 
+
-
 
+
-
sub setup_RCX { my $sensor = shift; my $rcx =
+
-
Win32::OLE-&gt;new('SPIRIT.SpiritCtrl.1'); $Win32::OLE::Warn = 0;
+
-
$rcx-&gt;{ComPortNo} = 1; $rcx-&gt;{InitComm};
+
-
$rcx-&gt;SetSensorType($sensor, 3); $rcx-&gt;SetSensorMode($sensor, 2);
+
-
return $rcx;
+
-
}
+
-
 
+
-
 
+
-
sub calibrate { my $rcx = shift;
+
-
 
+
-
print &lt;&lt;EOT; Calibration mode. Note the sensor values and decide
+
-
on a 'pivot' value above which 'no coffee' is signified and below
+
-
which 'coffee' is signified.
+
-
 
+
-
End the calibration mode with Ctrl-C.
+
-
 
+
-
Press Enter to start calibration... EOT
+
-
 
+
-
&lt;STDIN&gt;;
+
-
 
+
-
while (1) { print $rcx-&gt;Poll(9, SENSOR), " "; sleep 1;
+
-
}
+
-
 
+
-
}
+
-
 
+
-
 
+
-
sub set_status { my $val = shift;
+
-
 
+
-
my $new_status = $val &lt; $opts{'l'} ? COFFEE : NOCOFFEE;
+
-
 
+
-
if ($new_status != $current_status) { $current_status = $new_status;
+
-
return $current_status;
+
-
}
+
-
else { return undef;
+
-
}
+
-
}
+
-
 
+
-
</code>
+
-
 
+
-
<br>
+
-
=== Examining the Coffee Script Step by Step ===
+
-
<br>Now that we've seen the ''coffee'' script as a whole, let's examine it step by step to see how
+
-
it works.
+
-
 
+
-
<br>
+
-
 
+
-
==== Declaring the modules, constants, and variables ====
+
-
<br>We first
+
-
declare the packages we're going to use. In addition to
+
-
<tt>Net::Jabber</tt> and <tt>Win32::OLE</tt>, we're going to use
+
-
<tt>Getopt::Std</tt>, which affords us a comfortable way of accepting
+
-
and parsing command-line options. We also want to use the
+
-
<tt>strict</tt> pragma, which should keep us from making silly coding
+
-
mistakes by not allowing undeclared variables and the like.
+
-
 
+
-
We specify <tt>Client</tt> on the usage declaration for the
+
-
<tt>Net::Jabber</tt> package to specify what should be loaded. The
+
-
package is a large and comprehensive set of modules, and only some of
+
-
those are relevant for what we wish to do in the script—build and work
+
-
with a Jabber ''client'' connection. Other module sets are pulled in by
+
-
specifying <tt>Component</tt> or <tt>Server</tt>.
+
-
 
+
-
 
+
-
<code>use Net::Jabber qw(Client); use Win32::OLE; use Getopt::Std; use
+
-
strict;
+
-
 
+
-
</code>
+
-
We're going to allow the command-line options -l and -s, which perform
+
-
the following tasks:
+
-
 
+
-
 
+
-
; No options specified (or just the -s options): calibration mode.
+
-
: When we run the script for the first time, we need to perform the
+
-
: calibration and read values from the sensor to determine a midpoint
+
-
: value. A number above the midpoint signifies the presence of light
+
-
: and therefore the absence of coffee; below signifies the absence of
+
-
: light and therefore the presence of coffee. This step is necessary
+
-
: because not every environment (ambient light, sensitivity of the light
+
-
: sensor, and so on) will be the same. The upper and lower values,
+
-
: representing lightness and darkness, respectively, will vary across
+
-
: different environments. The point is to obtain a value in between
+
-
: these upper and lower values—the midpoint—with which we can compare a
+
-
: light value read at any particular time. : If we don't specify any
+
-
: options, the script will start up automatically in calibration mode:
+
-
<code>C:\temp&gt; <tt>perl coffee.pl</tt></code>
+
-
: Figure 9-4 shows the script run in calibration mode. The values
+
-
: displayed, one each second, represent the values read from the light
+
-
: sensor. When the sensor was picking up lots of light, the values were
+
-
: 60. When the sensor was moved in front of some coffee, the values went
+
-
: down to around 45. Based upon this small test, the pivot point value
+
-
: was 50, somewhere in between those two values.
+
-
; -l: Specify the pivot value.
+
-
: Once we've determined a pivot point value, we run the script and tell
+
-
: it this pivot value with the -l (light pivot):
+
-
<code>C:\temp&gt; <tt>perl coffee.pl -l 50</tt></code>
+
-
 
+
-
; -s: Specify the sensor number.
+
-
: The RCX, shown in Figure 9-1, has three connectors to which you can
+
-
: attach sensors. They're the three gray 2-by-2 pieces, labeled 1, 2,
+
-
: and 3, near the top of the brick. The script assumes you've attached
+
-
: the light sensor to the one marked 1, which internally is 0. If you
+
-
: attach it to either of the other two, you can specify the connector
+
-
: using the -s (sensor) with a value of 1 (for the middle connector) or
+
-
: 2 (for the rightmost connector), like this:
+
-
<code>C:\temp&gt; <tt>perl coffee.pl -l 50 -s 2</tt></code>
+
-
: You can specify the -s option when running in calibration or normal
+
-
: modes.
+
-
{{Figure|title=Running coffee in calibration
+
-
mode|image=0596002025-jab_0904.png</code> The options, summarized in Table
+
-
9-1, are defined with the <tt>Getopt::Std</tt> function:
+
-
 
+
-
 
+
-
<code>my %opts; getopt('ls', \%opts);
+
-
 
+
-
</code>
+
-
 
+
-
{|
+
-
 
+
-
|+ Summary of the startup options -
+
-
! Option !! Meaning
+
-
|-
+
-
| No option || Start the script automatically in calibration mode.
+
-
|-
+
-
| -l || Specify the pivot value.
+
-
|-
+
-
| -s || Specify the sensor number.
+
-
|}
+
-
Next comes a list of constants, which describe:
+
-
 
+
-
* The script's Jabber relationship, including the server it will connect
+
-
to and the username, password, and resource it will connect with.
+
-
* The representation of the two states of ''coffee'' and ''no coffee'', which
+
-
will be used to determine the content of the <tt>&lt;status/&gt;</tt>
+
-
tag sent along inside any <tt>&lt;presence/&gt;</tt> element emitted.
+
-
* The identification of the connector to which the light sensor is
+
-
attached and the polling granularity of the sensor (poll/presence push
+
-
loop) described earlier. This item is measured in seconds.
+
-
 
+
-
<code>use constant SERVER =&gt; "merlix.dyndns.org"; use constant
+
-
PORT =&gt; 5222; use constant USERNAME =&gt; "coffee"; use constant
+
-
PASSWORD =&gt; "pass"; use constant RESOURCE =&gt; "perlscript";
+
-
 
+
-
use constant NOCOFFEE =&gt; 0; use constant COFFEE =&gt; 1;
+
-
 
+
-
use constant SENSOR =&gt; defined($opts{'s'}) ? $opts{'s'} : 0; use
+
-
constant GRAIN =&gt; 1;
+
-
 
+
-
</code>
+
-
The last part of the script's setup deals with the coffee state:
+
-
 
+
-
 
+
-
<code>my $current_status = -1; my @status; $status[NOCOFFEE] =
+
-
'xa/Coffeepot is empty'; $status[COFFEE] = '/Coffee is available!';
+
-
 
+
-
</code>
+
-
We use a two-element array (<tt>@status</tt>) to represent the two
+
-
possible coffee states. The value of each array element is a two-part
+
-
string, with each part separated by a slash (<tt>/</tt>). Each of these
+
-
parts will be transmitted in a <tt>&lt;presence/&gt;</tt> element, with
+
-
the first part (which is empty in the element representing the
+
-
<tt>COFFEE</tt> state) representing the presence <tt>&lt;show/&gt;</tt>
+
-
value and the second part representing the presence
+
-
<tt>&lt;status/&gt;</tt> value. Example 9-7 shows what a
+
-
<tt>&lt;presence/&gt;</tt> element looks like when built up with values
+
-
to represent the <tt>NOCOFFEE</tt> state.
+
-
 
+
-
 
+
-
''A presence element representing the NOCOFFEE state''
+
-
 
+
-
<code>&lt;presence&gt; &lt;show&gt;xa&lt;/show&gt;
+
-
&lt;status&gt;Coffeepot is empty&lt;/status&gt; &lt;/presence&gt;
+
-
 
+
-
</code>
+
-
Most Jabber clients use different icons in the roster to represent
+
-
different <tt>&lt;show/&gt;</tt> values. In this case, we will use
+
-
<tt>xa</tt> for ''no coffee'' and a blank (which represents "online" or
+
-
"available") for ''coffee'' to trigger the icon change.
+
-
 
+
-
<br>
+
-
 
+
-
==== Initialization and calibration ====
+
-
<br>Whenever we need to talk to the
+
-
RCX, some initialization is required via the ActiveX control. That's the
+
-
same whether we're going to calibrate or poll for values. The
+
-
<tt>setup_RCX()</tt> function takes a single argument—the identification
+
-
of which connector the light sensor is connected to—and performs the
+
-
initialization, which is described later in Section 9.2.3.8. The
+
-
function returns a handle on the <tt>Win32::OLE</tt> object that
+
-
represents the ActiveX control, which in turn represents the RCX via the
+
-
IR tower:
+
-
 
+
-
 
+
-
<code>my $rcx = &amp;setup_RCX(SENSOR);
+
-
 
+
-
</code>
+
-
If the -l option is not specified, it means we're going to be running
+
-
calibration. So we call the <tt>calibrate()</tt> function to do this for
+
-
us. We pass the RCX handle (in <tt>$rcx</tt>) so the calibration can run
+
-
properly:
+
-
 
+
-
 
+
-
<code># Either calibrate if no parameters given, or
+
-
# run with the parameter given as -l, which will be taken as the pivot
+
-
# between coffee and no coffee
+
-
&amp;calibrate($rcx) unless defined($opts{'l'});
+
-
 
+
-
</code>
+
-
As with the <tt>setup_RCX()</tt> function, <tt>calibrate()</tt> is
+
-
described later.
+
-
 
+
-
Calibration mode will be terminated by ending the script with
+
-
''Ctrl-C'', so the next thing we come across is the call to the function
+
-
<tt>set_status()</tt>, which represents the first stage in the normal
+
-
script mode; <tt>set_status()</tt> is used to determine the ''initial''
+
-
coffee status.
+
-
 
+
-
A value is retrieved by calling the ActiveX control's <tt>Poll()</tt>
+
-
function. (Table 9-2 lists the ActiveX control's functions and
+
-
properties used in this script.) We specify that we're after a sensor
+
-
value (the 9 as the first argument) from the sensor attached to the
+
-
connector indicated by the <tt>SENSOR</tt> constant:
+
-
 
+
-
 
+
-
<code># Determine initial status (will be either 0 or 1) my $s =
+
-
&amp;set_status($rcx-&gt;Poll(9, SENSOR));
+
-
 
+
-
</code>
+
-
The value retrieved is passed to the <tt>set_status()</tt> function,
+
-
which determines whether the value is above or below the pivot value and
+
-
whether the new status is different from the current one. It's going to
+
-
be something along the lines of one of the values displayed when the
+
-
script was run in calibration mode. If it is (and in this case, it will
+
-
be, because in this first call, the value of <tt>$current_status</tt> is
+
-
set to <tt>-1</tt>, which represents neither the <tt>COFFEE</tt> nor the
+
-
<tt>NOCOFFEE</tt> state), that status will be returned; otherwise,
+
-
<tt>undef</tt> will be returned.
+
-
 
+
-
 
+
-
{|
+
-
 
+
-
|+ RCX Spirit.ocx ActiveX control properties and functions used -
+
-
! Function/Property !! Description
+
-
|-
+
-
| <tt>Poll(''SOURCE'', ''NUMBER'')</tt> || Retrieves information from
+
-
| the RCX. In this script, the value for the ''SOURCE'' argument is
+
-
| always <tt>9</tt>, which represents a sensor value (i.e., a value
+
-
| measured at a sensor), as opposed to an internal RCX variable or a
+
-
| timer. The ''NUMBER'' argument represents the connector to which the
+
-
| sensor we want to read is attached.
+
-
|-
+
-
| <tt>SetSensorMode(''NUMBER'', ''MODE ''[, ''SLOPE''])</tt> || This
+
-
| function returns a value from the sensor. As with <tt>Poll()</tt> and
+
-
| <tt>SetSensorType()</tt>, ''NUMBER'' represents the sensor connector.
+
-
| The ''MODE'' argument can be used to determine the sensor mode, which
+
-
| can be ''Raw'' (mode 0), ''Boolean'' (mode 1), ''Transitional'' (mode
+
-
| 2), ''Periodic'' (mode 3), ''Percentage'' (mode 4), ''Celcius'' (mode
+
-
| 5), ''Farenheit'' (mode 6), or ''Angle'' (mode 7). The ''SLOPE''
+
-
| argument qualifies the ''Boolean'' mode by specifying how ''True'' and
+
-
| ''False'' are to be determined.
+
-
|-
+
-
| <tt>SetSensorType(''NUMBER'', ''TYPE'')</tt> || This function is used
+
-
| to specify the ''type'' of sensor the values will be read from. The
+
-
| ''NUMBER'' argument is the same as for the <tt>Poll()</tt> and
+
-
| represents the sensor connector. The ''TYPE'' argument represents the
+
-
| type of sensor that you want to set: ''None'' (type 0), ''Switch''
+
-
| (type 1), ''Temperature'' (type 2), ''Light'' (type 3), or ''Angle''
+
-
| (type 4).
+
-
|-
+
-
| <tt>property:ComPortNo</tt> || The serial port to which the IR tower
+
-
| is connected (e.g., 1 = COM1, 2 = COM2, and so on).
+
-
|-
+
-
| <tt>property:InitComm</tt> || When invoked, the serial communication
+
-
| port is initialized in preparation for the IR connection to the RCX.
+
-
|}
+
-
 
+
-
<br>
+
-
==== Connecting to the Jabber server ==== <br>
+
-
At this stage, we're ready to
+
-
connect to the Jabber server. The call to <tt>setup_Jabber()</tt> does
+
-
this for us, returning a handle to the Jabber connection object that we
+
-
store in <tt>$jabber</tt>. This handle will be used later in the script
+
-
to send out <tt>&lt;presence/&gt;</tt> elements. The <tt>$jabber</tt>
+
-
variable contains a reference to a <tt>Net::Jabber::Client</tt> object.
+
-
This is the equivalent of the <tt>con</tt> variable used in the earlier
+
-
Python scripts to hold the <tt>jabber.Client</tt> object and the
+
-
<tt>ConnectionBean</tt> object (<tt>cb</tt>) in the earlier Java
+
-
script.<ref>For the Python scripts, see Section 8.1 and Section 8.3. For
+
-
the Java script, see Section 8.2.</ref>
+
-
 
+
-
 
+
-
<code>my $jabber = &amp;setup_Jabber(SERVER, PORT, USERNAME, PASSWORD,
+
-
RESOURCE, $s);
+
-
 
+
-
</code>
+
-
In addition to passing the constants needed for the client connection to
+
-
the Jabber server, we pass the initial coffee status, held in
+
-
<tt>$s</tt>. We'll have a look at what the <tt>setup_Jabber()</tt>
+
-
function does with this initial status a bit later when we get to the
+
-
function's definition.
+
-
 
+
-
<br>
+
-
 
+
-
==== Sensor poll/presence push loop ====
+
-
<br>Now that we've set everything
+
-
up, determined the initial coffee status, and connected to the Jabber
+
-
server, we're ready to start the main loop:
+
-
 
+
-
 
+
-
<code># Main loop: check Jabber and RCX while (1) {
+
-
defined($jabber-&gt;Process(GRAIN)) or die "The connection to the Jabber
+
-
server was broken\n"; my $s = &amp;set_status($rcx-&gt;Poll(9, SENSOR));
+
-
&amp;set_presence($jabber, $s) if defined $s;
+
-
}
+
-
 
+
-
</code>
+
-
The <tt>while (1)</tt> loop is a bit of a giveaway. This script won't
+
-
stop until you force it to by entering ''Ctrl-C''—but that's essentially
+
-
what we want. In the loop, we call the <tt>Process()</tt> method on the
+
-
Jabber connection object in <tt>$jabber</tt>.
+
-
 
+
-
<tt>Process()</tt> is the equivalent of the <tt>Jabberpy</tt>'s
+
-
<tt>process()</tt> method in the Python scripts. <tt>Process()</tt>
+
-
waits around for up to the number of seconds specified as the single
+
-
argument (or not at all if no argument is specified) for XML to appear
+
-
on the stream connection from the Jabber server. If complete fragments
+
-
do appear, callbacks, defined in the connection object, are called with
+
-
the elements (<tt>&lt;iq/&gt;</tt>, <tt>&lt;message/&gt;</tt>, and
+
-
<tt>&lt;presence/&gt;</tt>) that the fragments represent. This is in the
+
-
same way as, for example, callbacks are used in the Python scripts using
+
-
the <tt>Jabberpy</tt> library. The <tt>setup_Jabber()</tt>, which will
+
-
be discussed in the next section, is where the callback definition is
+
-
made.
+
-
 
+
-
<tt>Net::Jabber</tt>'s <tt>Process()</tt> method returns <tt>undef</tt>
+
-
if the connection to the Jabber server is terminated while waiting for
+
-
XML. The <tt>undef</tt> value is dealt with appropriately by ending the
+
-
script.
+
-
 
+
-
The <tt>GRAIN</tt> constant, set to 1 second in the script's setup
+
-
section, is used to specify how long to wait for any packets from the
+
-
Jabber server. For the most part, we're not expecting to receive much
+
-
incoming Jabber traffic—the occasional presence subscription (or
+
-
unsubscription) request perhaps (see later), but other than that, the
+
-
only packets traveling over the connection to the Jabber server will be
+
-
availability <tt>&lt;presence/&gt;</tt> packets representing coffee
+
-
state changes, sent from the script. This delay is normally set to 1
+
-
second. And because that's a comfortable polling interval for the light
+
-
sensor, we can set that within the same loop.
+
-
 
+
-
Calling the ActiveX control's <tt>Poll()</tt> again with the same
+
-
arguments as before ("get a sensor value from the sensor attached to the
+
-
<tt>SENSOR</tt>th connector"), we pass the value to the
+
-
<tt>set_status()</tt> to determine the coffee state. If the state was
+
-
different from last time (if <tt>$s</tt> receives a value and not
+
-
<tt>undef</tt>), then we want to emit a <tt>&lt;presence/&gt;</tt>
+
-
element to reflect that state. We achieve this by calling the
+
-
<tt>set_presence()</tt> function, passing it the connection object and
+
-
the state.
+
-
 
+
-
<br>
+
-
 
+
-
==== The setup_Jabber() function ====
+
-
<br>Here we define the
+
-
<tt>setup_Jabber()</tt> function, which is called to set up the
+
-
connection to the Jabber server and authenticate with a predefined user:
+
-
 
+
-
 
+
-
<code># Set up Jabber client connection, sending intial presence sub
+
-
setup_Jabber { my ($server, $port, $user, $pass, $resource,
+
-
$initial_status) = @_; my $connection = new Net::Jabber::Client;
+
-
 
+
-
# Connect
+
-
my $status = $connection-&gt;Connect( hostname =&gt; $server, port
+
-
=&gt; $port ); die "Cannot connect to Jabber server $server on port
+
-
$port\n" unless $status;
+
-
 
+
-
# Callbacks
+
-
$connection-&gt;SetCallBacks( presence =&gt; \&amp;InPresence );
+
-
 
+
-
# Ident/Auth
+
-
my @result = $connection-&gt;AuthSend( username =&gt; $user, password
+
-
=&gt; $pass, resource =&gt; $resource ); die "Ident/Auth failed:
+
-
$result[0] - $result[1]\n" if $result[0] ne "ok";
+
-
 
+
-
# Roster
+
-
$connection-&gt;RosterGet();
+
-
 
+
-
# Initial presence dependent upon initial status
+
-
&amp;set_presence($connection, $initial_status);
+
-
 
+
-
return $connection;
+
-
}
+
-
 
+
-
</code>
+
-
First, we instantiate a new <tt>Net::Jabber::Client</tt> object.
+
-
<tt>Net::Jabber</tt> distinguishes between client- and component-based
+
-
connections to Jabber; the component-based equivalent of this class is
+
-
<tt>Net::Jabber::Component</tt>. The <tt>Connect()</tt> method is passed
+
-
arguments that specify the hostname and port of the Jabber server to
+
-
connect to. It returns a 0 status if the connection could not be made.
+
-
 
+
-
We can register handlers for Jabber elements received over the XML
+
-
stream carried by the connection we just made. Here we are interested in
+
-
incoming presence subscription or unsubscription requests, as we'll see
+
-
in the definition of the <tt>InPresence()</tt> function.
+
-
 
+
-
The single method, <tt>SetCallBacks()</tt>, does what the collective
+
-
<tt>jabber.Client</tt> methods <tt>setPresenceHandler()</tt>,
+
-
<tt>setMessageHandler()</tt>, and <tt>setIqHandler()</tt> do in a single
+
-
call—taking a list of element types and subroutine references, in the
+
-
form of a hash.
+
-
 
+
-
After registering the callback for <tt>&lt;presence/&gt;</tt> elements,
+
-
it's time to authenticate, passing the username, password, and resource
+
-
defined in the list of constants at the start of the script. If
+
-
authentication is successful, the result of the call to the
+
-
<tt>AuthSend()</tt> method is a single string with the value
+
-
<tt>ok</tt>. If not, that value is replaced with an error code and the
+
-
descriptive text is available in a further string. (This is why we catch
+
-
the results of a call in an array, called <tt>@result</tt>.) A complete
+
-
list of Jabber error codes and texts can be found in Table 5-3.
+
-
 
+
-
Why <tt>RosterGet()</tt>? We're not subscribing to anyone, and we're not
+
-
really interested in anything but the values we're polling from our
+
-
brick. So theoretically there's no reason to make a request to retrieve
+
-
our roster from the server. However, because we want the script to
+
-
receive and process subscription and unsubscription requests, we need to
+
-
request the roster beforehand; otherwise, the JSM won't send such
+
-
requests to us. See Section 8.3.3.4 in Chapter 8 for an explanation as
+
-
to why.
+
-
 
+
-
Once we've requested the roster, so as to receive presence subscription
+
-
and unsubscription requests, the job is almost done. The last thing to
+
-
do in setting up the Jabber connection is to send initial availability
+
-
information. The <tt>setup_Jabber()</tt> function receives the initial
+
-
coffee status as the last argument in the call (in
+
-
<tt>$initial_status</tt>), which it passes on to the function that sends
+
-
a <tt>&lt;presence/&gt;</tt> element, <tt>set_presence()</tt>. Along
+
-
with the initial coffee status, we also send the <tt>$connection</tt>
+
-
object that represents the connection to the Jabber server that we've
+
-
just established (referred to outside of this function with the
+
-
<tt>$jabber</tt> variable). This is so the <tt>set_presence()</tt>
+
-
function can use the connection handle to send the element down the
+
-
stream.
+
-
 
+
-
<br>
+
-
==== The set_presence() function ====
+
-
<br>This function is used by
+
-
<tt>setup_Jabber()</tt> to send the script's (and therefore the
+
-
coffee's) initial presence. It's also used within the main sensor
+
-
poll/presence push loop to send further presence packets if the coffee's
+
-
state changes.
+
-
 
+
-
 
+
-
<code>sub set_presence { my ($connection, $s) = @_; my $presence =
+
-
Net::Jabber::Presence-&gt;new(); my ($show, $status) = split("/",
+
-
$status[$s], 2); $presence-&gt;SetPresence( show =&gt; $show, status
+
-
=&gt; $status ); print $status, "\n"; $connection-&gt;Send($presence);
+
-
}
+
-
 
+
-
</code>
+
-
On receipt of the Jabber connection object and the coffee status, which
+
-
will be 0 (<tt>NOCOFFEE</tt>) or 1 (<tt>COFFEE</tt>),
+
-
<tt>set_presence()</tt> constructs a new <tt>Net::Jabber::Presence</tt>
+
-
object. This object represents a <tt>&lt;presence/&gt;</tt> element,
+
-
upon which we can make method calls to hone the element as we wish.
+
-
<tt>SetPresence()</tt> is one of these methods, with which we can set
+
-
values for each of the <tt>&lt;show/&gt;</tt> and
+
-
<tt>&lt;status/&gt;</tt> tags. We retrieve the values for each of these
+
-
tags by pulling the strings from the appropriate member of the
+
-
<tt>@status</tt> array, as described earlier in Section 9.2.3.1.
+
-
 
+
-
We print the coffee's status (remember, this function is called only
+
-
when the status ''changes'', not every time the sensor is polled) and
+
-
send the newly built <tt>&lt;presence/&gt;</tt> element down the XML
+
-
stream to the Jabber server. This is accomplished by passing the
+
-
presence object as an argument to the <tt>Send()</tt> method of the
+
-
connection object in <tt>$connection</tt>. This works in the same way as
+
-
the <tt>send()</tt> function in <tt>Jabberpy</tt> and the
+
-
<tt>send()</tt> function in <tt>JabberBeans</tt>. Everyone who has
+
-
subscribed to the script user's presence, and who is available, will
+
-
receive the coffee status information.
+
-
 
+
-
Figure 9-3 shows the status information received in the WinJab client.
+
-
The string sent in the <tt>&lt;status/&gt;</tt> tag is shown in the
+
-
tooltip that appears when the mouse hovers over the "coffee" roster
+
-
item.
+
-
 
+
-
<br>
+
-
 
+
-
==== The InPresence() subroutine ====
+
-
<br>Our presence handler, the callback
+
-
subroutine <tt>InPresence()</tt>, honors requests for subscription and
+
-
unsubscription to the script user's (and therefore the coffee's)
+
-
presence. This callback is designed to work in the same way as the
+
-
<tt>presenceCB()</tt> callback in the Python recipe described in Section
+
-
8.3.
+
-
 
+
-
However, while the Python <tt>Jabberpy</tt> library hands to the
+
-
callbacks a <tt>jabber.Client</tt> object and the element to be handled,
+
-
the Perl <tt>Net::Jabber</tt> library hands over a session ID and the
+
-
element to be handled. Don't worry about the session ID here; it's
+
-
related to functionality for building Jabber servers, not clients, and
+
-
we can and should ignore it for the purposes of this recipe. What is
+
-
important is the element to be handled, which appears as the second
+
-
argument passed to the subroutine collected by the <tt>$presence</tt>
+
-
variable from <tt>$_[1]</tt>.
+
-
 
+
-
What is common between the two libraries is that the element that is
+
-
passed to be handled as the subject of the callback is an instance of
+
-
the class that the callback represents. In other words, a callback is
+
-
used to handle <tt>&lt;presence/&gt;</tt> elements, and the element
+
-
received is an instance of the <tt>Net::Jabber::Presence</tt> class
+
-
(just as the element received by a <tt>Jabberpy</tt> presence callback
+
-
is an instance of the <tt>jabber.Presence</tt> class).
+
-
 
+
-
 
+
-
<code># Handle presence messages sub InPresence { my $presence = $_[1];
+
-
my $from = $presence-&gt;GetFrom(); my $type = $presence-&gt;GetType();
+
-
 
+
-
if ($type eq "subscribe") { print "Subscribe request ($from) ...\n";
+
-
$jabber-&gt;Send($presence-&gt;Reply(type =&gt; 'subscribed'));
+
-
}
+
-
 
+
-
if ($type eq "unsubscribe") { print "Unsubscribe request ($from)
+
-
...\n"; $jabber-&gt;Send($presence-&gt;Reply(type =&gt;
+
-
'unsubscribed'));
+
-
}
+
-
}
+
-
 
+
-
</code>
+
-
With an object in <tt>$presence</tt>, we can get information from the
+
-
element using data retrieval methods such as those used here:
+
-
<tt>GetFrom()</tt> and <tt>GetType()</tt>, which extract the values from
+
-
the <tt>from</tt> and <tt>type</tt> attributes of the
+
-
<tt>&lt;presence/&gt;</tt> element, respectively.
+
-
 
+
-
If the <tt>&lt;presence/&gt;</tt> element type represents a subscription
+
-
request (<tt>type="subscribe'</tt>), we unquestioningly honor the
+
-
request, by sending back an affirmative reply. The <tt>Reply()</tt>
+
-
method of the presence object is one of a number of high-level functions
+
-
that make it possible to turn elements around and send them back. In
+
-
this case, the method replaces the value of the
+
-
<tt>&lt;presence/&gt;</tt>'s <tt>to</tt> attribute with the value of the
+
-
<tt>from</tt> attribute, and preserves its <tt>id</tt>. It also allows
+
-
us to pass arguments as if we were calling the <tt>SetPresence()</tt>
+
-
method described earlier. Rather than set the <tt>&lt;show/&gt;</tt> and
+
-
<tt>&lt;status/&gt;</tt> tags as we did earlier in the
+
-
<tt>set_presence()</tt> function, we merely set the element's
+
-
<tt>type</tt> attribute to <tt>subscribed</tt> or <tt>unsubscribed</tt>,
+
-
depending on the request.
+
-
 
+
-
So, with an incoming <tt>&lt;presence/&gt;</tt> element in
+
-
<tt>$presence</tt> that looks like this:
+
-
 
+
-
 
+
-
<code>&lt;presence from='qmacro@jabber.org/office' type='subscribe'
+
-
to='coffee@merlix.dyndns.org' id='21'&gt;
+
-
 
+
-
</code>
+
-
calling the <tt>Reply()</tt> method would cause the element in $presence
+
-
to change to this:
+
-
 
+
-
 
+
-
<code>&lt;presence to='qmacro@jabber.org/office' type='subscribed'
+
-
id='21'&gt;
+
-
 
+
-
</code>
+
-
Remember, the <tt>from</tt> attribute on elements originating from the
+
-
client is set by the ''server'', not by the ''client''. The script
+
-
doesn't ask for a subscription to the user's presence in return. The
+
-
script isn't interested in whether the people who have subscribed to its
+
-
presence are available—its purpose is to let people know whether there's
+
-
any coffee left in the pot.
+
-
 
+
-
 
+
-
<br>
+
-
==== The setup_RCX() function ====
+
-
<br>This function is called once every
+
-
time the script is started and is required to initialize the RCX:
+
-
 
+
-
 
+
-
<code>sub setup_RCX { my $sensor = shift; my $rcx =
+
-
Win32::OLE-&gt;new('SPIRIT.SpiritCtrl.1'); $Win32::OLE::Warn = 0;
+
-
$rcx-&gt;{ComPortNo} = 1; $rcx-&gt;{InitComm};
+
-
$rcx-&gt;SetSensorType($sensor, 3); $rcx-&gt;SetSensorMode($sensor, 2);
+
-
return $rcx;
+
-
}
+
-
 
+
-
</code>
+
-
A <tt>Win32::OLE</tt> object representing the RCX's ActiveX control
+
-
<tt>Spirit</tt> is instantiated. A <tt>Win32::OLE</tt> function is used
+
-
to suppress warnings, and the RCX is initialized by setting the COM port
+
-
to COM1 for serial communications. The sensor type and mode are set for
+
-
the light sensor attached to the connector identified by the value
+
-
passed into the <tt>$sensor</tt> variable. Table 9-2 shows us that
+
-
sensor type 3 represents ''Light'', and sensor mode 2 specifies a
+
-
''Transitional'' measurement mode, the upshot of which is that the
+
-
values returned on a poll are all within a certain restricted range,
+
-
which makes it easier to decide whether there's any coffee in the pot.
+
-
 
+
-
We return the <tt>Win32::OLE</tt> RCX object to be used elsewhere in the
+
-
script for calibration and polling.
+
-
 
+
-
 
+
-
<br>
+
-
==== The calibrate() function ====
+
-
<br>The <tt>calibrate()</tt> function is
+
-
called if the script is started without the -l option. This function
+
-
simply prints a message, waits for the user to press ''Enter'', and then
+
-
goes into a a gentle loop, emitting whatever value was polled from the
+
-
light sensor so the user can determine the pivot point:
+
-
 
+
-
 
+
-
<code>sub calibrate { my $rcx = shift;
+
-
 
+
-
print &lt;&lt;EOT; Calibration mode. Note the sensor values and decide
+
-
on a 'pivot' value above which 'no coffee' is signified and below
+
-
which 'coffee' is signified.
+
-
 
+
-
End the calibration mode with Ctrl-C.
+
-
 
+
-
Press Enter to start calibration... EOT
+
-
 
+
-
&lt;STDIN&gt;;
+
-
 
+
-
while (1) { print $rcx-&gt;Poll(9, SENSOR), " "; sleep 1;
+
-
}
+
-
 
+
-
}
+
-
 
+
-
</code>
+
-
The output produced from this function can be seen in Figure 9-4.
+
-
 
+
-
 
+
-
<br>
+
-
==== The set_status() function ====
+
-
<br>The <tt>set_status()</tt> function
+
-
receives the latest light value as polled from the sensor and compares
+
-
it with the pivot value. If the status defined in <tt>$new_status</tt>
+
-
is different from the ''current'' status (in <tt>$current_status</tt>),
+
-
then the current status is updated and returned; otherwise,
+
-
<tt>undef</tt> is returned:
+
-
 
+
-
 
+
-
<code>sub set_status { my $val = shift;
+
-
 
+
-
my $new_status = $val &lt; $opts{'l'} ? COFFEE : NOCOFFEE;
+
-
 
+
-
if ($new_status != $current_status) { $current_status = $new_status;
+
-
return $current_status;
+
-
}
+
-
else { return undef;
+
-
}
+
-
}
+
-
 
+
-
</code>
+
-
If this function returns a status value, a new
+
-
<tt>&lt;presence/&gt;</tt> element is generated and emitted by the
+
-
script. Otherwise, there's no change ("the coffee's still there," or
+
-
"there's still no coffee!") and nothing happens.
+
-
 
+
-
 
+
-
<br>
+
-
 
+
-
== An RSS News Agent ==
+
-
<br>While the Jabber clients available off the shelf
+
-
are orientated toward receiving (and sending) messages from other
+
-
people, the possibilities don't stop there, as is clear from the recipes
+
-
we've seen already. In this recipe, we're going to build a Jabber
+
-
component that retrieves news items from various sources on the Web and
+
-
sends them on to Jabber users who have expressed an interest in
+
-
receiving them. We're going to use the Web for our news sources, but
+
-
they could just as easily be sources within a corporate intranet. The
+
-
key thing is that the sources are available in a readily parseable
+
-
format.
+
-
 
+
-
RSS (RDF<ref>RDF stands for "Resource Description Framework." </ref>
+
-
Site Summary or, alternatively, Really Simple Syndication) is an XML
+
-
format used for describing the content of a web site, where that site
+
-
typically contains news items, diary entries, event information, or
+
-
generally anything that grows, item by item, over time. A classic
+
-
application of RSS is to describe a news site such as JabberCentral
+
-
(http://www.jabbercentral.org). JabberCentral's main page (see Figure
+
-
9-5) consists of a number of news items—in the "Recent News"
+
-
section—about Jabber and its developer community. These items appear in
+
-
reverse chronological order, and each one is succinct, sharing a common
+
-
set of properties:
+
-
 
+
-
 
+
-
; Title
+
-
: Each item has a title ("JabberCon Update 11:45am - Aug 20").
+
-
; Short description
+
-
: Each item contains a short piece of text describing the content and
+
-
: context of the news story ("JabberCon Update - Monday Morning").
+
-
; Link to main story
+
-
: The short description should be enough to help the reader decide if he
+
-
: wants to read the whole item. If he does, there's a link ("Read More")
+
-
: to the news item itself.
+
-
{{Figure|title=JabberCentral's main page|image=0596002025-jab_0905.png</code>
+
-
It is this collection of item-level properties that are summarized in an
+
-
RSS file. The formality of the XML structure makes it a straightforward
+
-
matter for:
+
-
 
+
-
* Automating the retrieval of story summaries for inclusion in other sites (syndication)
+
-
* Combining these items with items from other similar sources (aggregation)
+
-
* Checking to see whether there is any new content (new items) since the last visit Example 9-8 shows what the RSS XML for JabberCentral's news items shown in Figure 9-5 looks like.
+
-
 
+
-
 
+
-
''RSS source for JabberCentral''
+
-
 
+
-
<code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
+
-
 
+
-
&lt;!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN"
+
-
"http://my.netscape.com/publish/formats/rss-0.91.dtd"&gt;
+
-
 
+
-
&lt;rss version="0.91"&gt;
+
-
 
+
-
&lt;channel&gt;
+
-
 
+
-
&lt;title&gt;JabberCentral&lt;/title&gt;
+
-
 
+
-
&lt;description&gt; JabberCentral is the premiere Jabber end-user
+
-
news and support site. Many Jabber developers are actively involved
+
-
at JabberCentral to provide fresh and authoritative information for
+
-
users. &lt;/description&gt;
+
-
 
+
-
&lt;language&gt;en-us&lt;/language&gt;
+
-
&lt;link&gt;http://www.jabbercentral.com/&lt;/link&gt;
+
-
&lt;copyright&gt;Copyright 2001, Aspect Networks&lt;/copyright&gt;
+
-
 
+
-
&lt;image&gt;
+
-
&lt;url&gt;http://jabbercentral.com/images/jc_button.gif&lt;/url&gt;
+
-
&lt;title&gt;JabberCentral&lt;/title&gt;
+
-
&lt;link&gt;http://www.jabbercentral.com/&lt;/link&gt;
+
-
&lt;/image&gt;
+
-
 
+
-
&lt;item&gt; &lt;title&gt;JabberCon Update 11:45am - Aug
+
-
20&lt;/title&gt;
+
-
&lt;link&gt;http://www.jabbercentral.com/news/view.php?news_id=
+
-
998329970&lt;/link&gt; &lt;description&gt;JabberCon Update - Monday
+
-
Morning&lt;/description&gt; &lt;/item&gt;
+
-
 
+
-
&lt;item&gt; &lt;title&gt;Jabcast Promises Secure Jabber
+
-
Solutions&lt;/title&gt;
+
-
&lt;link&gt;http://www.jabbercentral.com/news/view.php?news_id=
+
-
998061331&lt;/link&gt; &lt;description&gt; Jabcast announces their
+
-
intention to release security plugins with their line of products
+
-
and services. &lt;/description&gt; &lt;/item&gt;
+
-
 
+
-
... (more items) ...
+
-
 
+
-
&lt;/channel&gt;
+
-
 
+
-
&lt;/rss&gt;
+
-
 
+
-
</code>
+
-
The structure is very straightforward. Each RSS file describes a
+
-
''channel'', which is defined as follows:
+
-
 
+
-
 
+
-
; Channel information
+
-
: The channel header information includes the channel's title
+
-
: (<tt>&lt;title/&gt;</tt>), short description
+
-
: (<tt>&lt;description/&gt;</tt>), main URL (<tt>&lt;link/&gt;</tt>),
+
-
: and so on. The channel in this case is JabberCentral.
+
-
; Channel image
+
-
: Often RSS information is rendered into HTML to provide a concise
+
-
: "current index" summary of the channel it describes. An image can be
+
-
: used in that summary rendering, and its definition is held in the
+
-
: <tt>&lt;image/&gt;</tt> section of the file.
+
-
; Channel items
+
-
: The bulk of the RSS file content is made up of the individual
+
-
: <tt>&lt;item/&gt;</tt> sections, each of which reflects an item on the
+
-
: site that the channel represents. We can see in Example 9-8 that the
+
-
: first <tt>&lt;item/&gt;</tt> tag:
+
-
<code>&lt;item&gt; &lt;title&gt;JabberCon Update 11:45am - Aug
+
-
20&lt;/title&gt;
+
-
&lt;link&gt;http://www.jabbercentral.com/news/view.php?news_id=998329970
+
-
&lt;/link&gt; &lt;description&gt;JabberCon Update - Monday
+
-
Morning&lt;/description&gt; &lt;/item&gt;
+
-
 
+
-
</code>
+
-
: describes the most recent news item shown on JabberCentral's main
+
-
: page—"JabberCon Update 11:45am - Aug 20." Each of the news item
+
-
: properties are contained within that <tt>&lt;item/&gt;</tt> tag: the
+
-
: title (<tt>&lt;title/&gt;</tt>), short description
+
-
: (<tt>&lt;description/&gt;</tt>), and link to main story
+
-
: (<tt>&lt;link/&gt;</tt>).
+
-
; Channel interactive feature
+
-
: There is a possibility for each channel to describe an interactive
+
-
: feature on the site it represents; often this is a search engine
+
-
: fronted by a text input field and Submit button. The interactive
+
-
: feature section of an RSS file is used to describe how that mechanism
+
-
: is to work (the name of the input field and the Submit button and the
+
-
: URL to invoke when the button is clicked, for example). This is so
+
-
: HTML renderings of the site can include the feature otherwise
+
-
: available only on the original site.
+
-
{{Note|This interactive feature definition is not shown in the RSS
+
-
example here.
+
-
 
+
-
</code>
+
-
RSS information lends itself very well to various methods of viewing.
+
-
There are custom "headline viewer" clients available—focused
+
-
applications that allow you to select from a vast array of RSS sources
+
-
and have links to items displayed on your desktop (so, yes, the personal
+
-
newspaper—of sorts—is here!). There are also possibilities for having
+
-
RSS items scroll by on your desktop control bar.
+
-
 
+
-
And then there's Jabber. As described in Section 5.4.1, the Jabber
+
-
<tt>&lt;message/&gt;</tt> element can represent something that looks
+
-
suspiciously like an RSS item. The message type "headline" defines a
+
-
message that carries news headline information. In this case, the
+
-
<tt>&lt;message/&gt;</tt> element itself is usually embellished with an
+
-
''extension'', qualified by the <tt>jabber:x:oob</tt> namespace
+
-
(described in Section 6.3.8). Example 9-9 shows what the element would
+
-
look like if the first news item from the JabberCentral site were
+
-
carried in a headline message.
+
-
 
+
-
 
+
-
''A headline message carrying a JabberCentral news item''
+
-
 
+
-
<code>&lt;message type='headline' to='dj@qmacro.dyndns.org'&gt;
+
-
&lt;subject&gt;JabberCon Update 11:45am - Aug 20&lt;/subject&gt;
+
-
&lt;body&gt;JabberCon Update - Monday Morning&lt;/body&gt; &lt;x
+
-
xmlns='jabber:x:oob'&gt;
+
-
&lt;url&gt;http://www.jabbercentral.com/news/view.php?news_id=998329970&
+
-
lt;/url&gt; &lt;desc&gt;JabberCon Update - Monday Morning&lt;/desc&gt;
+
-
&lt;/x&gt; &lt;/message&gt;
+
-
 
+
-
</code>
+
-
The <tt>jabber:x:oob</tt> namespace carries the crucial parts of the RSS
+
-
item. Clients, such as WinJab and Jarl, can understand this extension
+
-
and display the content in a clickable list of headlines, each
+
-
representing a single RSS item, similar to the headline viewer clients
+
-
mentioned earlier.
+
-
 
+
-
Of course, we could send RSS items to clients in nonheadline type
+
-
messages:
+
-
 
+
-
 
+
-
<code>&lt;message type='headline' to='dj@qmacro.dyndns.org'&gt;
+
-
&lt;subject&gt;JabberCon Update 11:45am - Aug 20&lt;/subject&gt;
+
-
&lt;body&gt; JabberCon Update - Monday Morning
+
-
http://www.jabbercentral.com/news/view.php?news_id=998329970
+
-
&lt;/body&gt; &lt;/x&gt; &lt;/message&gt;
+
-
 
+
-
</code>
+
-
where the complete item information is transmitted in a combination of
+
-
the <tt>&lt;subject/&gt;</tt> and <tt>&lt;body/&gt;</tt> tags. This
+
-
works, but the clients can only display the message, as with any other
+
-
message. However, if we send formalized ''metadata'', the value of the
+
-
message content increases enormously. (Figure 9-8 shows Jarl displaying
+
-
RSS-sourced news headlines.)
+
-
 
+
-
Distributing RSS-sourced headlines over Jabber to standard Jabber
+
-
clients is a great combination of off-the-shelf technologies. In fact,
+
-
we'll see in the next section that it's not just standard Jabber clients
+
-
that fit the bill; we'll write a Jabber-based headline viewer to show
+
-
that not all Jabber clients are, nor should they be, made equal.
+
-
 
+
-
<br>
+
-
 
+
-
=== Writing the News Agent ===
+
-
<br>We're going to write an RSS news agent,
+
-
which we'll simply call ''newsagent''. The ''newsagent'' is a mechanism
+
-
that checks predefined sources for new RSS items and sends (or pushes)
+
-
them to people who are interested in receiving them. For the sake of
+
-
simplicity, we'll define the list of RSS sources in ''newsagent''
+
-
itself. See Section 9.3.4 later in this chapter for details on how to
+
-
further develop this script.
+
-
 
+
-
<br>
+
-
 
+
-
==== The newsagent script as a component ====
+
-
<br>Until now, the examples
+
-
we've used, such as ''cvsmsg'', ''HostAlive'', and ''keyassist'' (shown
+
-
in Chapter 8), have all existed as Jabber ''clients''. That is, they've
+
-
performed a service while connected to the Jabber server via the JSM.
+
-
There's nothing wrong with this. Indeed, it's more than just fine to
+
-
build Jabber-based mechanisms using a Jabber client stub connection;
+
-
that way, your script, through its ''identity''—the user JID—can avail
+
-
itself of all the IM-related functions that the JSM offers—presence,
+
-
storage and forwarding of messages, and
+

Current revision

kid volunteer work for animal shelters in nj yakima jobs lindy hop anzac day trading times personal loans leeds links bahamas five star hotels natural gas stocks gratis dating no credit age of mythology the titans no cd crack activemark crack indiana high school athletic association football rules panty job compilation wsfs online banking presidential campaign spend way too much money cigna healthcare fee schedule url phone student teacher video philadelphia eagles trade black bitchs club penguin money maker how to download it pamerla anderson videos sitemap free printable gift card caesars palace hotel deals tamil nadu tourist board home down payment loan uk bank holiday pooh bear video buying ex rental cars advance tubo merida yucatan free interracial blow jobs how to start a limo business foo fighters best of you lyrics perry mason videos cum pot obtine un credit daca sunt rau sitemap application letter healthcare album king t.i torrent caballeros del zodiaco pam and tommy lee video free index domain master clock bozeman american west airlines interior design master bedroom elmo birthday cards best deal for hotels in orlando public health job pinback videos

Programming Jabber
Preface
1 - Getting started with Jabber
2 - Inside Jabber
3 - Installing the Jabber server
4 - Server Architecture and Configuration
5 - Jabber Technology Basics
6 - Jabber Namespaces
7 - User Registration and Authorization
8 - Using Messages and Presence
9 - Groupchat, : Components, and Event Models
10 - Pointers for Further Development
Appendix A
Appendix B
Colophon

Groupchat, : Components, and Event Models


By now, you should have a

good idea of how scripts interact with Jabber and how the core
elements such as <message/> and
<presence/> can be constructed and handled.

This chapter builds upon what we've already seen in Chapter 8 and introduces new concepts. We build a nosy assistant that joins a conference room and alerts us to words and phrases that we want it to listen for. There are two popular conference protocols, as mentioned in Section 6.2.6 the presence-based Groupchat protocol, and the jabber:iq:conference-based Conference protocol. The assistant recipe, a foray into the world of 'bots, takes a look at the original presence-based one.

As we've seen, programming within Jabber's event model is fairly straightforward. But what happens when you want to meld other components with event models of their own? We look at a couple of typical scenarios where this melding needs to happen. The first is a homage to the Trojan Room Coffee Machine (http://www.cl.cam.ac.uk/coffee/coffee.html), where we give life, or at least presence, to a coffeepot, using LEGO MINDSTORMS. The second is a Tk-based RSS headline viewer. Both the coffeepot and the Tk programming library have event loops of their own. With the coffeepot, we need to have a loop that polls the coffeepot's status, independently of the polling for incoming packets from the Jabber server. The Tk programming library's event model is similar to those of the Jabber programming libraries that are used in the recipes in this book, in that handlers are set up and a loop is started that listens for UI events. In both cases, we need to get these event loops to work in harmony with the Jabber libraries' event loops.

Building Jabber solutions without event loops is a Sisyphean task. The very nature of Jabber communication is event-based, and it's important to understand how to use the event features of the Jabber programming libraries and also how to be able to mesh those features with similar features in other libraries and systems.

We also look at extending messages and build a mechanism that delivers RSS headlines to clients who register with that mechanism. These headlines are carried using an extended message type. In fact, the RSS Delivery Mechanism is a component. The three recipes in Chapter 8, were Jabber clients, in that they connected to the Jabber network via the Jabber Session Manager (JSM) service. We look at the differences between programming a client and programming a component in this chapter and build a complete component that can be queried and interacted with using the third of Jabber's building blocks the <iq/> element.

Happy coding!


Keyword Assistant


Many of the Jabber core and peripheral developers hang out in a conference room called jdev hosted by the Conferencing component on the Jabber server running at jabber.org. While a lot of useful information is to be gleaned from listening to what goes on in jdev, it isn't possible to be there all the time. Conversations in jdev are logged to web pages, which can be used to visit after the fact to try to catch up with things; however, this can be a hopeless task. One solution is to build a 'bot that looks for specific keywords and Uniform Resource Locators (URLs) in the conversations in jdev and send those on as Jabber messages.

This script, keyassist, connects to a Jabber server, enters a conference room, and listens to the conversations, looking for certain words and phrases to be uttered. The keyassist script is given a bit of "intelligence" in that it can be interacted with and told, while running, to watch for (or stop watching for), certain words and phrases.

The keyassist script introduces us to programmatic interaction with the Conferencing component. Before looking at the script, however, let's have a brief overview of Conferencing in general.



Conferencing


The Conferencing component at jabber.org is conference.jabber.org. Details of the component instance configuration for such a Conferencing component can be found in Section 4.10, where we see that the component exists as a shared object library connected with the library load component connection method. This component provides general conferencing facilities, oriented around a conference room and conference user model.

A Jabber user can enter (or join) a conference room, thereby becoming a conference user identified by a nickname that is chosen upon entering that room. Nicknames are generally used in conference rooms to provide a modicum of privacy it is assumed that by default you don't want to let the other conference room members know your real JID.

The Conferencing component supports two protocols for user and room interaction: a simple one that provides basic features and a more complex one that provides the basic features plus facilities such as password-protected rooms and room descriptions Groupchat and Conference.


{{Note|There is a third protocol, called Experimentaliq:groupchat, which came between the Groupchat and Conference protocols. This reflected an experimental move to add features to the basic Groupchat protocol using IQ elements, the contents of which were qualified by a namespace jabber:iq:groupchat. This protocol has been dropped, and support for it exists only in certain versions of WinJab and JIM.

</code>

Groupchat
The Groupchat protocol is the simpler of the two and provides basic
functions for entering and exiting conference rooms and choosing
nicknames. : This Groupchat protocol is known as the presence-based
protocol, because the protocol is based upon
<presence/> elements used for room entry, exit, and
nickname determination. The Groupchat protocol has a nominal version
number of 1.0.
Conference
The Conference protocol offers more advanced features than the
Groupchat protocol and makes use of two IQ namespaces:
jabber:iq:conference and jabber:iq:browse. It has a
nominal protocol version number of 1.4, which reflects the version of
the Jabber server with which it is delivered. Sometimes this version
number is referred to as 0.4, such as in the downloadable tarball and
in the value returned in response to a "version query" on the
component itself, as shown in Example 9-1. : The version number isn't
that important. The main thing to keep in mind is that the component
that is called conference.so (see the reference to the
shared object library in Section 4.10.4) supports both the
Groupchat protocol and the Conference protocol. If you come across a
shared object library called groupchat.so, this is the
original Conferencing component that was made available with Jabber
server Version 1.0. This library supports only the Groupchat protocol.

Querying the Conferencing component's version

SEND: <iq type='get' to='conference.gnu.mine.nu'> <query xmlns='jabber:iq:version'/> </iq>

RECV: <iq to='dj@gnu.mine.nu/jarl' from='conference.gnu.mine.nu' type='result'> <query xmlns='jabber:iq:version'> <name>conference</name> <version>0.4</version> <os>Linux 2.4.2-2</os> </query> </iq> In this recipe we'll be using the simpler Groupchat protocol. It's widely used and easy to understand. Example 9-2 shows a typical element log from Groupchat-based activity. It shows a user, with the JID qmacro@jabber.com, entering a room called "cellar," hosted on the conference component at conf.merlix.dyndns.org, a room that currently has two other occupants who go by the nicknames flash and roscoe. The elements are from qmacro's perspective, and are all explained following the example.


The Groupchat protocol in action The user qmacro tries to enter the conference room with the nickname flash and fails:


SEND: <presence to='cellar@conf.merlix.dyndns.org/flash'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash' type='error'> <error code='409'>Conflict</error> </presence>

He tries again, this time with a different nickname, deejay, and is successful:


SEND: <presence to='cellar@conf.merlix.dyndns.org/deejay'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/roscoe'/>

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/deejay'/>

RECV: <message to='qmacro@jabber.com/jarltk' type='groupchat' from='cellar@conf.merlix.dyndns.org'> <body>deejay has become available</body> </message>

roscoe says hi, and qmacro waves back:


RECV: <message to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/roscoe' type='groupchat' cnu=> <body>hi</body> </message>

SEND: <message to='cellar@conf.merlix.dyndns.org' type='groupchat'> <body>/me waves to everyone</body> </message>

flash sends a private message to qmacro:


RECV: <message to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash' type='chat'> <body>Is that you, qmacro?</body> <thread>jarl1998911094</thread> </message>

Feeling left out of the conversation, roscoe leaves the room:


RECV: <presence to='qmacro@jabber.com/jarltk' type='unavailable' from='cellar@conf.merlix.dyndns.org/roscoe'/>

RECV: <message to='qmacro@jabber.com/jarltk' type='groupchat' from='cellar@conf.merlix.dyndns.org'> <body>roscoe has left</body> </message> Let's take the stages in Example 9-2 one by one.


Failed attempt to enter room
qmacro makes an attempt to enter the room using the Groupchat
protocol. This is done by sending a directed
<presence/> element to a particular JID that represents
the room and the chosen nickname. This JID is constructed as follows:

[room name]@[conference component]/[nickname]

In this example, the conferencing component is identified with the
hostname conf.merlix.dyndns.org. qmacro's choice of
nickname is flash:

cellar@conf.merlix.dyndns.org/flash

Thus the following element is sent:

SEND: <presence to='cellar@conf.merlix.dyndns.org/flash'/>

The conference component determines that there is already someone
present in the room cellar@conf.merlix.dyndns.org with the
nickname flash, so qmacro is notified of this and
receives a directed presence with an <error/> tag:

RECV: <presence to='qmacro@jabber.com/jarltk' from='cellar@conf.merlix.dyndns.org/flash' type='error'> <error code='409'>Conflict</error> </presence>

Note that the <presence/> element has the type
error and comes from the artificial JID constructed in the
room entry attempt. The element is addressed to qmacro's real
JID, of courseqmacro@jabber.com/jarltk as otherwise it
wouldn't reach him. : The error code 409 and text "Conflict" tells
qmacro that the nickname conflicted with one already in the
room. This is a standard error code/text pair; Table 5-3 shows a
complete set of code/text pairs. : At this stage, qmacro is
not yet in the room.
Successful attempt to enter room
qmacro tries again, this time with a different nickname,
deejay:[1]

SEND: <presence to='cellar@conf.merlix.dyndns.org/deejay'/>

This time, there is no conflict
Personal tools