It emits an infrared command specified by a protocol type (
protocol
), the length
of the code measured in bits (
bits
), and the code value to be sent (
value
).
Depending on the name of the protocol, the method delegates all the real work
to our
IRsend
instance.
handle_command
implements one of the most difficult aspects of our
InfraredProxy
—it
parses the URL addressed by the HTTP request:
RemoteControl/InfraredProxy/infrared_proxy.cpp
bool InfraredProxy::handle_command(char* line) {
Line 1
strsep(&line, " ");
-
char* path = strsep(&line, " ");
-
-
char* args[3];
5
for (char** ap = args; (*ap = strsep(&path, "/")) != NULL;)
-
if (**ap != '\0')
-
if (++ap >= &args[3])
-
break;
-
const int bits = atoi(args[1]);
10
const long value = strtoul(args[2], NULL, 16);
-
return send_ir_data(args[0], bits, value);
-
}
-
To understand what this method does, you have to understand how HTTP
requests work. If you wander up to your web browser’s address bar and enter
a URL like
http://192.168.2.42/SAMSUNG/32/E0E040BF
, your browser will send an HTTP
request that looks like this:
GET /SAMSUNG/32/E0E040BF HTTP/1.1
host: 192.168.2.42
The first line is a
GET
request, and
handle_command
expects a string containing
such a request. It extracts all the information encoded in the given path
(
/SAMSUNG/32/E0E040BF
) and uses it to emit an infrared signal. Parsing the
information is tricky, but using C’s
strsep
function, it’s not too difficult.
strsep
separates strings delimited by certain characters. It expects a string containing
several separated strings and a string containing all delimiters. To get the
separated strings, you have to call
strsep
repeatedly until it returns NULL.
That is, whenever you invoke
strsep
, it returns the next string or NULL.
We use
strsep
in two different contexts. In the first case, we extract the path
from the
GET
command: we strip off the string “GET” and the string “HTTP/1.1.”
Both are separated from the path by a blank character. In line 2, we call
strsep
to remove the “GET” at the beginning of the string. We don’t even store the
function’s return value, because we know it’s “GET” anyway.
report erratum • discuss
Building an Infrared Proxy • 219
www.it-ebooks.info