fix issue#44: HTTP API should add Qos parameter

This commit is contained in:
Ery Lee 2015-01-18 16:11:53 +08:00
parent 2f2e4ff3db
commit f637aa45c8
2 changed files with 38 additions and 14 deletions

View File

@ -124,7 +124,7 @@ eMQTT support http to publish message.
Example: Example:
``` ```
curl -v --basic -u user:passwd -d "topic=/a/b/c&message=hello from http..." -k http://localhost:8883/mqtt/publish curl -v --basic -u user:passwd -d "qos=1&retain=0&topic=/a/b/c&message=hello from http..." -k http://localhost:8883/mqtt/publish
``` ```
### URL ### URL
@ -135,10 +135,12 @@ HTTP POST http://host:8883/mqtt/publish
### Parameters ### Parameters
Name | Description Name | Description
-----|------------- --------|---------------
topic | MQTT Topic qos | QoS(0, 1, 2)
message | Text Message retain | Retain(0, 1)
topic | Topic
message | Message
## Design ## Design

View File

@ -43,15 +43,26 @@ handle(Req) ->
handle('POST', "/mqtt/publish", Req) -> handle('POST', "/mqtt/publish", Req) ->
Params = mochiweb_request:parse_post(Req), Params = mochiweb_request:parse_post(Req),
lager:info("~p~n", [Params]), lager:info("HTTP Publish: ~p~n", [Params]),
Topic = list_to_binary(get_value("topic", Params)), Qos = int(get_value("qos", "0")),
Message = list_to_binary(get_value("message", Params)), Retain = bool(get_value("retain", "0")),
emqtt_pubsub:publish(#mqtt_message { Topic = list_to_binary(get_value("topic", Params)),
topic = Topic, Message = list_to_binary(get_value("message", Params)),
payload = Message case {validate(qos, Qos), validate(topic, Topic)} of
}), {true, true} ->
Req:ok({"text/plan", "ok"}); emqtt_pubsub:publish(#mqtt_message {
qos = Qos,
retain = bool(Retain),
topic = Topic,
payload = Message
}),
Req:ok({"text/plan", <<"ok">>});
{false, _} ->
Req:respond({400, [], <<"Bad QoS">>});
{_, false} ->
Req:respond({400, [], <<"Bad Topic">>})
end;
handle(_Method, _Path, Req) -> handle(_Method, _Path, Req) ->
Req:not_found(). Req:not_found().
@ -69,3 +80,14 @@ authorized(Req) ->
user_passwd(BasicAuth) -> user_passwd(BasicAuth) ->
list_to_tuple(binary:split(base64:decode(BasicAuth), <<":">>)). list_to_tuple(binary:split(base64:decode(BasicAuth), <<":">>)).
validate(qos, Qos) ->
(Qos >= ?QOS_0) and (Qos =< ?QOS_2);
validate(topic, Topic) ->
emqtt_topic:validate({publish, Topic}).
int(S) -> list_to_integer(S).
bool("0") -> false;
bool("1") -> true.