Étude 11-1: Get the Weather

In this étude, you will create a weather server using the gen_server OTP behavior.This server will handle requests using a four-letter weather station identifier and will return a brief summary of the weather. You may also ask the server for a list of most recently accessed weather stations.

Here is some sample output:

1> c(weather).
{ok,weather}
2> weather:start_link().
{ok,<0.42.0>}
3> gen_server:call(weather, "KSJC").
{ok,[{location,"San Jose International Airport, CA"},
     {observation_time_rfc822,"Mon, 18 Feb 2013 13:53:00 -0800"},
     {weather,"Overcast"},
     {temperature_string,"51.0 F (10.6 C)"}]}
4> gen_server:call(weather, "KITH").
{ok,[{location,"Ithaca / Tompkins County, NY"},
     {observation_time_rfc822,"Mon, 18 Feb 2013 16:56:00 -0500"},
     {weather,"A Few Clouds"},
     {temperature_string,"29.0 F (-1.6 C)"}]}
5> gen_server:call(weather,"NONE").
{error,404}
6> gen_server:cast(weather, "").
Most recent requests: ["KITH","KSJC"]

Obtaining Weather Data

To retrieve a web page, you must first call inets:start/0; you will want to do this in your init/1 code. Then, simply call httpc:request(url), where url is a string containing the URL you want. In this case, you will use the server provided by National Oceanic and Atmospheric Administration. This server accepts four-letter weather station codes and returns an XML file summarizing the current weather at that station. You request this data with a URL in the form

http://w1.weather.gov/xml/current_obs/NNNN.xml

where NNNN ...

Get Études for Erlang now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.