MqttHttpApi.java 9.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & dreamlu.net).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

浅梦2013's avatar
浅梦2013 已提交
17
package net.dreamlu.iot.mqtt.core.server.http.api;
18 19

import com.alibaba.fastjson.JSON;
浅梦2013's avatar
浅梦2013 已提交
20 21
import net.dreamlu.iot.mqtt.codec.MqttMessageType;
import net.dreamlu.iot.mqtt.core.server.dispatcher.IMqttMessageDispatcher;
浅梦2013's avatar
浅梦2013 已提交
22 23 24 25 26 27
import net.dreamlu.iot.mqtt.core.server.http.api.code.ResultCode;
import net.dreamlu.iot.mqtt.core.server.http.api.form.BaseForm;
import net.dreamlu.iot.mqtt.core.server.http.api.form.PublishForm;
import net.dreamlu.iot.mqtt.core.server.http.api.form.SubscribeForm;
import net.dreamlu.iot.mqtt.core.server.http.api.result.Result;
import net.dreamlu.iot.mqtt.core.server.http.handler.MqttHttpRoutes;
浅梦2013's avatar
浅梦2013 已提交
28
import net.dreamlu.iot.mqtt.core.server.model.Message;
29
import net.dreamlu.iot.mqtt.core.util.PayloadEncode;
30 31 32
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.http.common.Method;
浅梦2013's avatar
浅梦2013 已提交
33 34 35 36 37
import org.tio.utils.hutool.StrUtil;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.Function;
38 39 40 41 42 43 44

/**
 * mqtt http api
 *
 * @author L.cm
 */
public class MqttHttpApi {
浅梦2013's avatar
浅梦2013 已提交
45
	private final IMqttMessageDispatcher messageDispatcher;
46

47
	public MqttHttpApi(IMqttMessageDispatcher messageDispatcher) {
浅梦2013's avatar
浅梦2013 已提交
48
		this.messageDispatcher = messageDispatcher;
49 50 51 52 53 54 55 56 57 58 59
	}

	/**
	 * 消息发布
	 * <p>
	 * POST /api/v1/mqtt/publish
	 *
	 * @param request HttpRequest
	 * @return HttpResponse
	 */
	public HttpResponse publish(HttpRequest request) throws Exception {
浅梦2013's avatar
浅梦2013 已提交
60 61 62
		PublishForm form = readForm(request, (requestBody) ->
			JSON.parseObject(requestBody, PublishForm.class)
		);
63
		HttpResponse response = new HttpResponse();
浅梦2013's avatar
浅梦2013 已提交
64 65
		if (form == null) {
			return Result.fail(response, ResultCode.E101);
66
		}
浅梦2013's avatar
浅梦2013 已提交
67 68 69 70 71
		// 表单校验
		HttpResponse validResponse = validForm(form, response);
		if (validResponse != null) {
			return validResponse;
		}
72
		sendPublish(form);
73 74 75 76 77 78 79 80 81 82 83 84
		return Result.ok(response);
	}

	/**
	 * 消息批量发布
	 * <p>
	 * POST /api/v1/mqtt/publish/batch
	 *
	 * @param request HttpRequest
	 * @return HttpResponse
	 */
	public HttpResponse publishBatch(HttpRequest request) throws Exception {
浅梦2013's avatar
浅梦2013 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
		List<PublishForm> formList = readForm(request, (requestBody) -> {
			String jsonBody = new String(requestBody, StandardCharsets.UTF_8);
			return JSON.parseArray(jsonBody, PublishForm.class);
		});
		HttpResponse response = new HttpResponse();
		if (formList == null || formList.isEmpty()) {
			return Result.fail(response, ResultCode.E101);
		}
		// 参数校验,保证一个批次同时不成功,所以先校验
		for (PublishForm form : formList) {
			// 表单校验
			HttpResponse validResponse = validForm(form, response);
			if (validResponse != null) {
				return validResponse;
			}
		}
		// 批量发送
		for (PublishForm form : formList) {
103
			sendPublish(form);
浅梦2013's avatar
浅梦2013 已提交
104 105 106 107
		}
		return Result.ok(response);
	}

108
	private void sendPublish(PublishForm form) {
浅梦2013's avatar
浅梦2013 已提交
109 110 111 112 113 114 115 116 117 118 119 120
		String payload = form.getPayload();
		Message message = new Message();
		message.setMessageType(MqttMessageType.PUBLISH.value());
		message.setClientId(form.getClientId());
		message.setTopic(form.getTopic());
		message.setQos(form.getQos());
		message.setRetain(form.isRetain());
		// payload 解码
		if (StrUtil.isNotBlank(payload)) {
			message.setPayload(PayloadEncode.decode(payload, form.getEncoding()));
		}
		messageDispatcher.send(message);
121 122 123 124 125 126 127 128 129 130 131
	}

	/**
	 * 主题订阅
	 * <p>
	 * POST /api/v1/mqtt/subscribe
	 *
	 * @param request HttpRequest
	 * @return HttpResponse
	 */
	public HttpResponse subscribe(HttpRequest request) throws Exception {
浅梦2013's avatar
浅梦2013 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
		SubscribeForm form = readForm(request, (requestBody) ->
			JSON.parseObject(requestBody, SubscribeForm.class)
		);
		HttpResponse response = new HttpResponse();
		if (form == null) {
			return Result.fail(response, ResultCode.E101);
		}
		// 表单校验
		HttpResponse validResponse = validForm(form, response);
		if (validResponse != null) {
			return validResponse;
		}
		int qos = form.getQos();
		if (qos < 0 || qos > 2) {
			return Result.fail(response, ResultCode.E101);
		}
		// 接口手动添加的订阅关系,可用来调试,不建议其他场景使用
149
		sendSubscribe(form);
浅梦2013's avatar
浅梦2013 已提交
150
		return Result.ok(response);
151 152 153 154 155 156 157 158 159 160 161
	}

	/**
	 * 主题批量订阅
	 * <p>
	 * POST /api/v1/mqtt/subscribe/batch
	 *
	 * @param request HttpRequest
	 * @return HttpResponse
	 */
	public HttpResponse subscribeBatch(HttpRequest request) throws Exception {
浅梦2013's avatar
浅梦2013 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
		List<SubscribeForm> formList = readForm(request, (requestBody) -> {
			String jsonBody = new String(requestBody, StandardCharsets.UTF_8);
			return JSON.parseArray(jsonBody, SubscribeForm.class);
		});
		HttpResponse response = new HttpResponse();
		if (formList == null || formList.isEmpty()) {
			return Result.fail(response, ResultCode.E101);
		}
		// 参数校验,保证一个批次同时不成功,所以先校验
		for (SubscribeForm form : formList) {
			// 表单校验
			HttpResponse validResponse = validForm(form, response);
			if (validResponse != null) {
				return validResponse;
			}
			int qos = form.getQos();
			if (qos < 0 || qos > 2) {
				return Result.fail(response, ResultCode.E101);
			}
		}
		// 批量处理
		for (SubscribeForm form : formList) {
			// 接口手动添加的订阅关系,可用来调试,不建议其他场景使用
185
			sendSubscribe(form);
浅梦2013's avatar
浅梦2013 已提交
186 187
		}
		return Result.ok(response);
188 189 190 191 192 193 194 195 196 197 198
	}

	/**
	 * 取消订阅
	 * <p>
	 * POST /api/v1/mqtt/unsubscribe
	 *
	 * @param request HttpRequest
	 * @return HttpResponse
	 */
	public HttpResponse unsubscribe(HttpRequest request) throws Exception {
浅梦2013's avatar
浅梦2013 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211
		BaseForm form = readForm(request, (requestBody) ->
			JSON.parseObject(requestBody, BaseForm.class)
		);
		HttpResponse response = new HttpResponse();
		if (form == null) {
			return Result.fail(response, ResultCode.E101);
		}
		// 表单校验
		HttpResponse validResponse = validForm(form, response);
		if (validResponse != null) {
			return validResponse;
		}
		// 接口手动取消的订阅关系,可用来调试,不建议其他场景使用
212
		sendSubscribe(form);
浅梦2013's avatar
浅梦2013 已提交
213
		return Result.ok(response);
214 215 216 217 218 219 220 221 222 223 224
	}

	/**
	 * 批量取消订阅
	 * <p>
	 * POST /api/v1/mqtt/unsubscribe/batch
	 *
	 * @param request HttpRequest
	 * @return HttpResponse
	 */
	public HttpResponse unsubscribeBatch(HttpRequest request) throws Exception {
浅梦2013's avatar
浅梦2013 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
		List<BaseForm> formList = readForm(request, (requestBody) -> {
			String jsonBody = new String(requestBody, StandardCharsets.UTF_8);
			return JSON.parseArray(jsonBody, BaseForm.class);
		});
		HttpResponse response = new HttpResponse();
		if (formList == null || formList.isEmpty()) {
			return Result.fail(response, ResultCode.E101);
		}
		// 参数校验,保证一个批次同时不成功,所以先校验
		for (BaseForm form : formList) {
			// 表单校验
			HttpResponse validResponse = validForm(form, response);
			if (validResponse != null) {
				return validResponse;
			}
		}
		// 批量处理
		for (BaseForm form : formList) {
			// 接口手动添加的订阅关系,可用来调试,不建议其他场景使用
244
			sendSubscribe(form);
浅梦2013's avatar
浅梦2013 已提交
245 246 247 248
		}
		return Result.ok(response);
	}

249 250 251 252 253 254 255 256 257 258 259 260 261
	private void sendSubscribe(BaseForm form) {
		Message message = new Message();
		message.setClientId(form.getClientId());
		message.setTopic(form.getTopic());
		if (form instanceof SubscribeForm) {
			message.setQos(((SubscribeForm) form).getQos());
			message.setMessageType(MqttMessageType.SUBSCRIBE.value());
		} else {
			message.setMessageType(MqttMessageType.UNSUBSCRIBE.value());
		}
		messageDispatcher.send(message);
	}

浅梦2013's avatar
浅梦2013 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
	/**
	 * 读取表单
	 *
	 * @param request  HttpRequest
	 * @param function Function
	 * @param <T>      泛型
	 * @return 表单
	 */
	private static <T> T readForm(HttpRequest request, Function<byte[], T> function) {
		byte[] requestBody = request.getBody();
		if (requestBody == null) {
			return null;
		}
		return function.apply(requestBody);
	}

	/**
	 * 校验表单
	 *
	 * @param form     BaseForm
	 * @param response HttpResponse
	 * @return 表单
	 */
	private static HttpResponse validForm(BaseForm form, HttpResponse response) {
		// 必须的参数
		String clientId = form.getClientId();
		if (StrUtil.isBlank(clientId)) {
			return Result.fail(response, ResultCode.E101);
		}
		String topic = form.getTopic();
		if (StrUtil.isBlank(topic)) {
			return Result.fail(response, ResultCode.E101);
		}
295 296 297 298 299 300 301 302
		return null;
	}

	/**
	 * 注册路由
	 */
	public void register() {
		// @formatter:off
浅梦2013's avatar
浅梦2013 已提交
303 304 305 306 307 308
		MqttHttpRoutes.register(Method.POST, "/api/v1/mqtt/publish", this::publish);
		MqttHttpRoutes.register(Method.POST, "/api/v1/mqtt/publish/batch", this::publishBatch);
		MqttHttpRoutes.register(Method.POST, "/api/v1/mqtt/subscribe", this::subscribe);
		MqttHttpRoutes.register(Method.POST, "/api/v1/mqtt/subscribe/batch", this::subscribeBatch);
		MqttHttpRoutes.register(Method.POST, "/api/v1/mqtt/unsubscribe", this::unsubscribe);
		MqttHttpRoutes.register(Method.POST, "/api/v1/mqtt/unsubscribe/batch", this::unsubscribeBatch);
309 310 311 312
		// @formatter:on
	}

}