Sniff is a "Scratch-like" programming language that's designed to help Scratchers move gently from Scratch to more conventional languages. They can start writing programs, without having to learn a new language because Sniff is based on Scratch. They learn a little more about variables, compiling, syntax errors (!), and they can have fun controlling real hardware while they're doing it.

Wednesday, 11 February 2015

Accessing web data in Sniff

In the last post we saw how you could make a simple web server using the Sniff ethernet device library. This time we'll show you the other side of the exchange - how to pull data down from a web server.

make ethernet device
make message string
make networkConnected boolean
make networkPort number
make networkPeer string

when start
.set networkPort to 80
.set networkPeer to ""
..tell ethernet to "connect"
..say join "Connected to:" networkPeer
..set message to "GET /index.html HTTP/1.0\r\n\r\n"
..tell ethernet to "send"
..repeat until not networkConnected
...tell ethernet to "receive"
...if not message = ""
....say message 
.. say "disconnected"
..wait 10 secs

It turns out there's not a lot too it. Set networkPeer to be the name of the other machine, and networkPort to be the port on that machine you want to talk to. In this case we're connecting to port 80 on

To make things happen we just tell ethernet to "connect", and we're off! We send a "GET" request to the server asking for a page, then read back the reply. We can just keep reading until the other end has finished sending the data, and we're done.

When I run this code I see a reply back saying that the page has moved to something more obscure - probably related to google maintaining different versions of the page. Normally your web browser would follow this up, and  pull down the redirected page.

It's actually a pretty good thing we hit the redirect, as modern web pages tend to be big and messy. We probably don't want to use this code so pull down full html feeds, but its pretty ideal for accessing custom data feeds. You can put a file on a server somewhere, and have Sniff code running on embedded devices phone home periodically for example to get config updates.

The identical code will run on Arduino with the proviso that we've used Ethernet Config to set an address for the board (as we did last time), we include an SPI device, and that we specify the server as an ip address rather than as a hostname, as we don't have DNS available.

No comments:

Post a Comment