控制过程 天猫精灵 -》 AliGenie平台 -》 Tomcat服务器 -》 OneNet -》 NodeMcu -》你要控制的设备
OAuth2授权部分 :
首先就是OAuth2认证部分 天猫精灵通过H5页面的账号去调用你的服务器校验是否正确 正确就返回Token相关数据 不正确就返回错误 这部分由于需要校验账号 就需要使用数据库部分 但是我通过网上其他代码简化了下 砍掉了数据库和校验的部分 直接返回Token 就是AliGenie请求过来后我们不校验账号 你说什么都是对的
代码分为几个类
不知道说什么了 直接上代码吧
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.prefs.Preferences;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import util.CodeFactory;
@WebServlet("/authorize")
public class Authorize extends HttpServlet{
/**
*
*/
public static Gson gson = new GsonBuilder().disableHtmlEscaping().create();
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
HttpSession session = req.getSession();
if ("yes".equals(req.getParameter("authorize"))){
String redirect_uri = (String) session.getAttribute("redirect_uri");
String state = (String) session.getAttribute("state");
String code = CodeFactory.getCode();
String client_id = (String) session.getAttribute("client_id");
redirect_uri = redirect_uri+"&code="+code+"&state="+state;
System.out.println(redirect_uri);
resp.setStatus(302);
resp.setHeader("location", redirect_uri);
}else if ("no".equals(req.getParameter("authorize"))){
resp.setHeader("refresh","2;url=/authorize");
resp.getWriter().write("授权失败
");
}else {
session.setAttribute("redirect_uri",req.getParameter("redirect_uri"));
session.setAttribute("state",req.getParameter("state"));
session.setAttribute("client_id",req.getParameter("client_id"));
System.out.println(req.getParameter("redirect_uri"));
System.out.println(req.getParameter("client_id"));
System.out.println(req.getParameter("response_type"));
System.out.println(req.getParameter("state"));
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import util.CodeFactory;
@WebServlet("/token")
public class GetToken extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public static Gson gson = new GsonBuilder().disableHtmlEscaping()//.serializeNulls().excludeFieldsWithoutExposeAnnotation() //������ʵ����û����@Exposeע�������
.create();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
System.out.println("***************GetToken******************");
BufferedReader br = req.getReader();
String str, wholeStr = "";
while((str = br.readLine()) != null){
wholeStr += str;
}
// System.out.println(wholeStr);
String[] par = wholeStr.split("&");
for (int i = 0; i < par.length; i++) {
System.out.println(par[i]);
}
String access_token = CodeFactory.getToken();
String refresh_token = CodeFactory.getToken();
HashMap< String, String> hashMap = new HashMap<>();
hashMap.put("access_token", access_token);
hashMap.put("refresh_token", refresh_token);
hashMap.put("expires", "259200");
resp.setContentType("application/json;charset=utf-8");
resp.getWriter().write( gson.toJson(hashMap));
System.out.println("***************GetToken******************");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@WebServlet("/readMessage")
public class ReadMessage extends HttpServlet {
private static final long serialVersionUID = 1L;
public static Gson gson = new GsonBuilder().disableHtmlEscaping().create();
/**
* @see HttpServlet#HttpServlet()
*/
public ReadMessage() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
BufferedReader br = request.getReader();
String str, wholeStr = "";
while((str = br.readLine()) != null){
wholeStr += str;
}
System.out.println(wholeStr);
Map map = request.getParameterMap();
for(String key:map.keySet()){
System.out.print(key+" : ");
String[] strings = map.get(key);
for (int i = 0; i < strings.length; i++) {
System.out.print(String.format(" [%s]", strings[i]));
}
System.out.println();
}
AliGenieBean readBean = gson.fromJson(wholeStr, AliGenieBean.class);
response.setContentType("application/json;charset=utf-8");
if("AliGenie.Iot.Device.Discovery".equals(readBean.getHeader().getNamespace())) {//发现设备 就是你需要把你的设备告诉天猫精灵
System.out.println("AliGenie Discovery");
AliGenieBean aliGenieBean = new AliGenieBean();
aliGenieBean.setHeader(new AliGenieBean.HeaderBean());
aliGenieBean.setPayload(new AliGenieBean.PayloadBean());
AliGenieBean.HeaderBean header = aliGenieBean.getHeader();
header.setNamespace("AliGenie.Iot.Device.Discovery");
header.setName("DiscoveryDevicesResponse");
header.setMessageId(readBean.getHeader().getMessageId());
header.setPayLoadVersion(1);
AliGenieBean.PayloadBean aPayloadBean = aliGenieBean.getPayload();
aPayloadBean.setDevices(new ArrayList());
List devices = aPayloadBean.getDevices();
AliGenieBean.PayloadBean.DevicesBean devicesBean = new AliGenieBean.PayloadBean.DevicesBean();
devicesBean.setDeviceId("34ea34cf2e81");
devicesBean.setDeviceName("风扇");
devicesBean.setDeviceType("fan");//这个决定你是什么设备 可到文档中心看其他支持的设备
devicesBean.setZone("床底下");//位置 比如门口的xxx 卧室的xxx
devicesBean.setBrand("美的");
devicesBean.setModel("风扇");
devicesBean.setIcon("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1552554552510&di=18b23705a5bdd45d3dd1e9cf84ded919&imgtype=0&src=http%3A%2F%2Fimages.669pic.com%2Felement_pic%2F91%2F91%2F78%2F50%2F146b9be2f1d8df2c5eb53ed677c3f401.jpg");
devicesBean.setProperties(new ArrayList());
devicesBean.setActions(new ArrayList());
AliGenieBean.PayloadBean.DevicesBean.PropertiesBean propertiesBean = new AliGenieBean.PayloadBean.DevicesBean.PropertiesBean();
propertiesBean.setName("windspeed"); //这里根据实际设备填写 比如风扇就填挡位 灯泡就是亮度相关的
propertiesBean.setValue("1");
devicesBean.getProperties().add(propertiesBean);
devicesBean.getActions().add("TurnOn");
devicesBean.getActions().add("TurnOff");
devicesBean.getActions().add("Query");
devices.add(devicesBean);
System.out.println(gson.toJson(aliGenieBean));
response.getWriter().append(gson.toJson(aliGenieBean));
}else if("AliGenie.Iot.Device.Control".equals(readBean.getHeader().getNamespace())) {//操作设备
//这里我们可以去调用OneNet的http接口 去控制ESP8266
}else if("AliGenie.Iot.Device.Query".equals(readBean.getHeader().getNamespace())) {//查询设备状态
System.out.println("AliGenie Query");
//这里我们可以去调用OneNet的http接口 去查询ESP8266状态并告诉天猫精灵
}else {
return;
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
记得导入相关jar包 关于天猫精灵部分的协议去看下AliGenie智能家居接入协议 https://doc-bot.tmall.com/docs/doc.htm?spm=0.7629140.0.0.395d1780pi4oYu&treeId=393&articleId=107454&docType=1
OneNet部分请参考我上一个博客 NodeMcu MQTT接入移动OneNet物联网平台(一)https://blog.csdn.net/oBaoChiChenMo/article/details/87996899
口才差也不知道说什么了 不明白留言吧