From f637aa45c8a2cf8a244f16843026d4245c4d5c75 Mon Sep 17 00:00:00 2001 From: Ery Lee Date: Sun, 18 Jan 2015 16:11:53 +0800 Subject: [PATCH] fix issue#44: HTTP API should add Qos parameter --- README.md | 12 ++++++----- apps/emqtt/src/emqtt_http.erl | 40 +++++++++++++++++++++++++++-------- 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 02283797c..15f2609e8 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,7 @@ eMQTT support http to publish message. 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 @@ -135,10 +135,12 @@ HTTP POST http://host:8883/mqtt/publish ### Parameters -Name | Description ------|------------- -topic | MQTT Topic -message | Text Message +Name | Description +--------|--------------- +qos | QoS(0, 1, 2) +retain | Retain(0, 1) +topic | Topic +message | Message ## Design diff --git a/apps/emqtt/src/emqtt_http.erl b/apps/emqtt/src/emqtt_http.erl index e6aa3ccec..481293174 100644 --- a/apps/emqtt/src/emqtt_http.erl +++ b/apps/emqtt/src/emqtt_http.erl @@ -43,15 +43,26 @@ handle(Req) -> handle('POST', "/mqtt/publish", Req) -> Params = mochiweb_request:parse_post(Req), - lager:info("~p~n", [Params]), - Topic = list_to_binary(get_value("topic", Params)), - Message = list_to_binary(get_value("message", Params)), - emqtt_pubsub:publish(#mqtt_message { - topic = Topic, - payload = Message - }), - Req:ok({"text/plan", "ok"}); - + lager:info("HTTP Publish: ~p~n", [Params]), + Qos = int(get_value("qos", "0")), + Retain = bool(get_value("retain", "0")), + Topic = list_to_binary(get_value("topic", Params)), + Message = list_to_binary(get_value("message", Params)), + case {validate(qos, Qos), validate(topic, Topic)} of + {true, true} -> + 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) -> Req:not_found(). @@ -69,3 +80,14 @@ authorized(Req) -> user_passwd(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. +