基于JavaWeb平台的常用物联网硬件接口对接代码总结文档_田超凡

基于JavaWeb平台的常用物联网硬件接口对接代码总结文档

                                                                                                                                           20190612 田超凡

                                                                     知网用户_进击的猿宝宝(田超凡)为原作者,转载请注明原作者

1.基于嵌入式语言Arduino和C++的传感器监测代码

改造后的C++ h头文件:

//

//    FILE: dht.h

//  AUTHOR: Rob Tillaart

// VERSION: 0.1.20

// PURPOSE: DHT Temperature & Humidity Sensor library for Arduino

//     URL: http://arduino.cc/playground/Main/DHTLib

//

// HISTORY:

// see dht.cpp file

//

 

#ifndef dht_h

#define dht_h

 

#if ARDUINO < 100

#include <WProgram.h>

#include <pins_arduino.h>  // fix for broken pre 1.0 version - TODO TEST

#else

#include <Arduino.h>

#endif

 

#define DHT_LIB_VERSION "0.1.20"

 

#define DHTLIB_OK                   0

#define DHTLIB_ERROR_CHECKSUM       -1

#define DHTLIB_ERROR_TIMEOUT        -2

#define DHTLIB_ERROR_CONNECT        -3

#define DHTLIB_ERROR_ACK_L          -4

#define DHTLIB_ERROR_ACK_H          -5

 

#define DHTLIB_DHT11_WAKEUP         18

#define DHTLIB_DHT_WAKEUP           1

 

#define DHTLIB_DHT11_LEADING_ZEROS  1

#define DHTLIB_DHT_LEADING_ZEROS    6

 

// max timeout is 100 usec.

// For a 16 Mhz proc 100 usec is 1600 clock cycles

// loops using DHTLIB_TIMEOUT use at least 4 clock cycli

// so 100 us takes max 400 loops

// so by dividing F_CPU by 40000 we "fail" as fast as possible

#define DHTLIB_TIMEOUT 400 // (F_CPU/40000)

 

class dht

{

public:

    // return values:

    // DHTLIB_OK

    // DHTLIB_ERROR_CHECKSUM

    // DHTLIB_ERROR_TIMEOUT

    // DHTLIB_ERROR_CONNECT

    // DHTLIB_ERROR_ACK_L

    // DHTLIB_ERROR_ACK_H

    int8_t read11(uint8_t pin);

    int8_t read(uint8_t pin);

 

    inline int8_t read21(uint8_t pin) { return read(pin); };

    inline int8_t read22(uint8_t pin) { return read(pin); };

    inline int8_t read33(uint8_t pin) { return read(pin); };

    inline int8_t read44(uint8_t pin) { return read(pin); };

 

    double humidity;

    double temperature;

 

private:

    uint8_t bits[5];  // buffer to receive data

    int8_t _readSensor(uint8_t pin, uint8_t wakeupDelay, uint8_t leadingZeroBits);

};

#endif

//

// END OF FILE

//

 

(1).PT550 亮度传感器

#define PIN_A 1

#define PIN_D 2

 

void setup()

{

  Serial.begin(9600);

}

 

void loop()

{

  int val;

  val=analogRead(PIN_A);

  //Serial.print("a:");

  Serial.print(val,DEC);

  Serial.println();

  //Serial.print(",d:");

  //val=digitalRead(PIN_D);

  //Serial.println(val+"\n");

  delay(500);

}

 

(2).DHT11 温湿度传感器

//   FILE:  dht_test.pde

// PURPOSE: DHT library test sketch for Arduino

//

 

#include <dht.h>

 

dht DHT;

 

#define DHT11_PIN 4//put the sensor in the digital pin 4 

 

void setup()

{

  Serial.begin(9600);

  Serial.println("DHT TEST PROGRAM ");

  Serial.print("LIBRARY VERSION: ");

  Serial.println(DHT_LIB_VERSION);

  Serial.println();

  Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)");

}

 

void loop()

{

 

  // READ DATA

  Serial.print("DHT11, \t");

  int chk = DHT.read11(DHT11_PIN);

  switch (chk)

  {

    case 0:  Serial.print("OK,\t"); break;

    case -1: Serial.print("Checksum error,\t"); break;

    case -2: Serial.print("Time out error,\t"); break;

    default: Serial.print("Unknown error,\t"); break;

  }

  // DISPLAT DATA

  Serial.print(DHT.humidity, 1);

  Serial.print(",\t");

  Serial.println(DHT.temperature, 1);

 

  delay(1000);

}

//

// END OF FILE

//

 

2.Java串口通信依赖

 

Java和DHT11温湿度检测器串口通信

package com.kingtake.common.rxtx.util;

 

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.nio.charset.Charset;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Enumeration;

import java.util.TooManyListenersException;

 

import gnu.io.CommPortIdentifier;

import gnu.io.PortInUseException;

import gnu.io.SerialPort;

import gnu.io.SerialPortEvent;

import gnu.io.SerialPortEventListener;

import gnu.io.UnsupportedCommOperationException;

 

public class DHTSerialPortListener implements Runnable, SerialPortEventListener {

      private String appName = "串口通讯";

      private int timeout = 2000;// open 端口时的等待时间

      private int threadTime = 0;

 

      private CommPortIdentifier commPort;

      private SerialPort serialPort;

      private InputStream inputStream;

      private OutputStream outputStream;

 

      @SuppressWarnings("restriction")

      public void listPort()

      {

            CommPortIdentifier cpid;// 当前串口对象

            Enumeration en = CommPortIdentifier.getPortIdentifiers();

            System.out.print("列出所有端口:");

            while (en.hasMoreElements())

            {

                  cpid = (CommPortIdentifier) en.nextElement();

 

                  // 检测端口类型是否为串口

                  if (cpid.getPortType() == CommPortIdentifier.PORT_SERIAL)

                  {

                       System.out.println(cpid.getName() + ", " + cpid.getCurrentOwner());

                  }

            }

      }

 

      /**

       *   * @方法名称 :openPort   * @功能描述 :选择一个端口,比如:COM1 并实例 SerialPort   * @返回值类型 :void

       *   * @param portName

       */

      private void openPort(String portName)

      {

            // TODO TCF 打开指定串口

            this.commPort = null;

            CommPortIdentifier cpid;

            Enumeration en = CommPortIdentifier.getPortIdentifiers();

 

            while (en.hasMoreElements())

            {

                  cpid = (CommPortIdentifier) en.nextElement();

                  if (cpid.getPortType() == CommPortIdentifier.PORT_SERIAL && cpid.getName().equals(portName))

                  {

                       this.commPort = cpid;

                       break;

                  }

            }

 

            /* 实例 SerialPort */

            if (commPort == null)

            {

                  System.out.println(String.format("无法找到名字为'%1$s'的串口!", portName));

            }

            else

            {

                  try

                  {

                       // 应用程序名【随意命名】,等待的毫秒数

                       serialPort = (SerialPort) commPort.open(appName, timeout);

                  }

                  catch (PortInUseException e)

                  {

                       // 端口已经被占用

                       throw new RuntimeException(String.format("端口'%1$s'正在使用中!", commPort.getName()));

                  }

            }

      }

     

      /**

        * @方法名称 :checkPort

        * @功能描述 :检查端口是否正确连接

        * @返回值类型 :void

      */

      private void checkPort()

      {

          if(commPort == null)

          {

                throw new RuntimeException("没有选择端口,请使用 " +"selectPort(String portName) 方法选择端口");

          }

       

 

            if (serialPort == null)

            {

                  throw new RuntimeException("SerialPort 对象无效!");

            }

      }

     

      /**

        * @方法名称 :write

        * @功能描述 :向端口发送数据,请在调用此方法前 先选择端口,并确定SerialPort正常打开!

        * @返回值类型 :void

        *    @param message

        * @throws IOException

      */

      public void write(String message) throws InterruptedException

      {

            checkPort();

            try

            {

                  outputStream = new BufferedOutputStream(serialPort.getOutputStream());

                  outputStream.write(message.getBytes());

                  outputStream.close();

            }

            catch(Exception e)

            {

                  throw new RuntimeException("向端口发送信息时出错:"+e.getMessage());

            }

      }

     

      /**

        * @方法名称 :startRead

        * @功能描述 :开始监听从端口中接收的数据

        * @返回值类型 :void

        *    @param time  监听程序时间,单位为秒,0 则是一直监听

      */

      public void startRead(int time)

      {

          checkPort();

          try

          {

             inputStream = new BufferedInputStream(serialPort.getInputStream());

          }

          catch(IOException e)

          {

             throw new RuntimeException("获取端口的InputStream出错:"+e.getMessage());

          }

       

          try

        {

             serialPort.addEventListener(this);

            

             // 设置可监听

             serialPort.notifyOnDataAvailable(true);

       

           serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

          }

        catch(TooManyListenersException e)

        {

             //端口监听者过多;  

           throw new RuntimeException(e.getMessage());

          }

        catch (UnsupportedCommOperationException e)

        {

             //"端口操作命令不支持";  

           e.printStackTrace();

        }

       

        /* 关闭监听 */

          if(time>0)

          {

              this.threadTime = time*1000;

              Thread t = new Thread(this);

              t.start();

          } 

      }       

     

      /**

        * @方法名称 :close

      * @功能描述 :关闭 SerialPort

      * @返回值类型 :void

      */

      public void close()

      {

          serialPort.close();

          serialPort = null;

          commPort = null;

      }

 

      @Override

      public void serialEvent(SerialPortEvent arg0)

      {

            switch (arg0.getEventType())

            {

            case SerialPortEvent.BI:/* Break interrupt,通讯中断 */

            case SerialPortEvent.OE:/* Overrun error,溢位错误 */

            case SerialPortEvent.FE:/* Framing error,传帧错误 */

            case SerialPortEvent.PE:/* Parity error,校验错误 */

            case SerialPortEvent.CD:/* Carrier detect,载波检测 */

            case SerialPortEvent.CTS:/* Clear to send,清除发送 */

            case SerialPortEvent.DSR:/* Data set ready,数据设备就绪 */

            case SerialPortEvent.RI:/* Ring indicator,响铃指示 */

            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:/* Output buffer is empty,输出缓冲区清空 */

                  break;

            case SerialPortEvent.DATA_AVAILABLE:/* Data available at the serial port,端口有可用数据。读到缓冲数组,输出到终端 */

                  byte[] readBuffer = new byte[1024];

                  String readStr = "";

                  String s2 = "";

                  try

                  {

                       while (inputStream.available() > 0)

                       {

                             inputStream.read(readBuffer);

                             readStr += new String(readBuffer,"UTF-8").trim();

                       }

                      

                       //System.out.println("接收到端口返回数据(长度为" + readStr.length() + "):" + readStr);

                     

                       if(readStr.length()>=4)

                       {

                             System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"温度:"+new String(readStr.getBytes(),"UTF-8"));

                       }

                  }

                  catch (IOException e)

                  {

                       throw new RuntimeException(e.getMessage());

                  }

            }

      }

 

      @Override

      public void run()

      {

            try

            {

                  Thread.sleep(threadTime);

                  serialPort.close();

                  System.out.println(String.format("端口'%1$s'监听关闭了!", commPort.getName()));

            }

            catch(Exception e)

            {

                  e.printStackTrace();

            }

      }

     

      /**

        * 测试

        * */

      public static void main(String[] args) throws Exception

      {

            DHTSerialPortListener sp = new DHTSerialPortListener();

           

            //列出所有端口

            sp.listPort();

           

            //打开相应端口

            sp.openPort("COM3");

           

            //设置为一直监听

            sp.startRead(0);

           

            //首次连接后需暂停5秒再继续执行否则数据会有问题

            Thread.sleep(5000);

      }

}

 

Java和PT550亮度检测器串口通信:

package com.kingtake.common.rxtx.util;

 

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.nio.charset.Charset;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Enumeration;

import java.util.TooManyListenersException;

 

import gnu.io.CommPortIdentifier;

import gnu.io.PortInUseException;

import gnu.io.SerialPort;

import gnu.io.SerialPortEvent;

import gnu.io.SerialPortEventListener;

import gnu.io.UnsupportedCommOperationException;

 

public class PTSerialPortListener implements Runnable, SerialPortEventListener {

      private String appName = "串口通讯";

      private int timeout = 2000;// open 端口时的等待时间

      private int threadTime = 0;

 

      private CommPortIdentifier commPort;

      private SerialPort serialPort;

      private InputStream inputStream;

      private OutputStream outputStream;

 

      @SuppressWarnings("restriction")

      public void listPort()

      {

            CommPortIdentifier cpid;// 当前串口对象

            Enumeration en = CommPortIdentifier.getPortIdentifiers();

            System.out.print("列出所有端口:");

            while (en.hasMoreElements())

            {

                  cpid = (CommPortIdentifier) en.nextElement();

 

                  // 检测端口类型是否为串口

                  if (cpid.getPortType() == CommPortIdentifier.PORT_SERIAL)

                  {

                       System.out.println(cpid.getName() + ", " + cpid.getCurrentOwner());

                  }

            }

      }

 

      /**

       *   * @方法名称 :openPort   * @功能描述 :选择一个端口,比如:COM1 并实例 SerialPort   * @返回值类型 :void

       *   * @param portName

       */

      private void openPort(String portName)

      {

            // TODO TCF 打开指定串口

            this.commPort = null;

            CommPortIdentifier cpid;

            Enumeration en = CommPortIdentifier.getPortIdentifiers();

 

            while (en.hasMoreElements())

            {

                  cpid = (CommPortIdentifier) en.nextElement();

                  if (cpid.getPortType() == CommPortIdentifier.PORT_SERIAL && cpid.getName().equals(portName))

                  {

                       this.commPort = cpid;

                        break;

                  }

            }

 

            /* 实例 SerialPort */

            if (commPort == null)

            {

                  System.out.println(String.format("无法找到名字为'%1$s'的串口!", portName));

            }

            else

            {

                  try

                  {

                       // 应用程序名【随意命名】,等待的毫秒数

                       serialPort = (SerialPort) commPort.open(appName, timeout);

                  }

                  catch (PortInUseException e)

                  {

                       // 端口已经被占用

                       throw new RuntimeException(String.format("端口'%1$s'正在使用中!", commPort.getName()));

                  }

            }

      }

     

      /**

        * @方法名称 :checkPort

        * @功能描述 :检查端口是否正确连接

        * @返回值类型 :void

      */

      private void checkPort()

      {

          if(commPort == null)

          {

                throw new RuntimeException("没有选择端口,请使用 " +"selectPort(String portName) 方法选择端口");

          }

       

 

            if (serialPort == null)

            {

                  throw new RuntimeException("SerialPort 对象无效!");

            }

      }

     

      /**

        * @方法名称 :write

        * @功能描述 :向端口发送数据,请在调用此方法前 先选择端口,并确定SerialPort正常打开!

        * @返回值类型 :void

        *    @param message

        * @throws IOException

      */

      public void write(String message) throws InterruptedException

      {

            checkPort();

            try

            {

                  outputStream = new BufferedOutputStream(serialPort.getOutputStream());

                  outputStream.write(message.getBytes());

                  outputStream.close();

            }

            catch(Exception e)

            {

                  throw new RuntimeException("向端口发送信息时出错:"+e.getMessage());

            }

      }

     

      /**

        * @方法名称 :startRead

        * @功能描述 :开始监听从端口中接收的数据

        * @返回值类型 :void

        *    @param time  监听程序时间,单位为秒,0 则是一直监听

      */

      public void startRead(int time)

      {

          checkPort();

          try

          {

             inputStream = new BufferedInputStream(serialPort.getInputStream());

          }

          catch(IOException e)

          {

             throw new RuntimeException("获取端口的InputStream出错:"+e.getMessage());

          }

       

          try

        {

             serialPort.addEventListener(this);

            

             // 设置可监听

             serialPort.notifyOnDataAvailable(true);

       

           serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

          }

        catch(TooManyListenersException e)

        {

             //端口监听者过多;  

           throw new RuntimeException(e.getMessage());

          }

        catch (UnsupportedCommOperationException e)

        {

             //"端口操作命令不支持";  

           e.printStackTrace();

        }

       

        /* 关闭监听 */

          if(time>0)

          {

              this.threadTime = time*1000;

              Thread t = new Thread(this);

              t.start();

          } 

      }       

     

      /**

        * @方法名称 :close

      * @功能描述 :关闭 SerialPort

      * @返回值类型 :void

      */

      public void close()

      {

          serialPort.close();

          serialPort = null;

          commPort = null;

      }

 

      @Override

      public void serialEvent(SerialPortEvent arg0)

      {

            switch (arg0.getEventType())

            {

            case SerialPortEvent.BI:/* Break interrupt,通讯中断 */

            case SerialPortEvent.OE:/* Overrun error,溢位错误 */

            case SerialPortEvent.FE:/* Framing error,传帧错误 */

            case SerialPortEvent.PE:/* Parity error,校验错误 */

            case SerialPortEvent.CD:/* Carrier detect,载波检测 */

            case SerialPortEvent.CTS:/* Clear to send,清除发送 */

            case SerialPortEvent.DSR:/* Data set ready,数据设备就绪 */

            case SerialPortEvent.RI:/* Ring indicator,响铃指示 */

            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:/* Output buffer is empty,输出缓冲区清空 */

                  break;

            case SerialPortEvent.DATA_AVAILABLE:/* Data available at the serial port,端口有可用数据。读到缓冲数组,输出到终端 */

                  byte[] readBuffer = new byte[1024];

                  String readStr = "";

                  String s2 = "";

                  try

                  {

                       while (inputStream.available() > 0)

                       {

                             inputStream.read(readBuffer);

                             readStr += new String(readBuffer,"UTF-8").trim();

                       }

                      

                       //System.out.println("接收到端口返回数据(长度为" + readStr.length() + "):" + readStr);

                     

                       if(readStr.length()>=3)

                       {

                             System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"亮度:"+new String(readStr.getBytes(),"UTF-8"));

                       }

                  }

                  catch (IOException e)

                  {

                       throw new RuntimeException(e.getMessage());

                  }

            }

      }

 

      @Override

      public void run()

      {

            try

            {

                  Thread.sleep(threadTime);

                  serialPort.close();

                  System.out.println(String.format("端口'%1$s'监听关闭了!", commPort.getName()));

            }

            catch(Exception e)

            {

                  e.printStackTrace();

            }

      }

     

      /**

        * 测试

        * */

      public static void main(String[] args) throws Exception

      {

            PTSerialPortListener sp = new PTSerialPortListener();

           

            //列出所有端口

            sp.listPort();

           

            //打开相应端口

            sp.openPort("COM3");

           

            //设置为一直监听

            sp.startRead(0);

           

            //首次连接后需暂停1秒再继续执行否则数据会有问题

            Thread.sleep(1000);

      }

}

 

3.Java对接百度云平台的人脸活体检测

package com.kingtake.gacp.common.util;

 

import org.springframework.boot.context.properties.ConfigurationProperties;

 

import com.baidu.aip.face.AipFace;

 

@ConfigurationProperties(prefix="baidu")

public class AipFaceUtil {

 

     //TODO TCF 百度云配置项

     //appId

     private static String appId="16304725";

    

     //apiKey

     private static String apiKey="I6BPAytoqc7kw5LdWqca3pRN";

    

     //secretKey

     private static String secretKey="frtmb1IhapyYONzN6ecOBqz2VdNaFx8F";

    

     //TODO TCF 核心控制器AipFace,单例

     private static AipFace client;

    

     public static AipFace getInstance()

     {

           if(client==null)

           {

                client=new AipFace(appId, apiKey, secretKey);

               

                // 可选:设置网络连接参数

             client.setConnectionTimeoutInMillis(2000);

             client.setSocketTimeoutInMillis(60000);

           }

          

           return client;

     }

}

 

//TODO TCF 校验身份证号唯一、人证合一

     @RequestMapping("/checkPeopleCard.do")

     @ResponseBody

     public Map checkPeopleCard(HttpServletRequest request) throws JSONException

     {

           Map<String,Object> map=new HashMap<String,Object>();

          

           //TODO TCF 身份证号

           String idCardNumber=request.getParameter("idCardNumber");

          

           //TODO TCF 人脸识别照片BASE64

           String photoPicPath=request.getParameter("photoPicPath");

          

           //TODO TCF 身份证照片BASE64

           String userPhoto=request.getParameter("userPhoto");

          

           //TODO TCF 编辑的用户id

           String accountId=request.getParameter("accountId");

          

           //TODO TCF 校验身份证号唯一

           Map<String,Object> findMap=new HashMap<String,Object>();

           findMap.put("fieldName","idCardNumber");

           findMap.put("fieldValue",idCardNumber);

          

           if(StringUtil.isNotEmpty(accountId))

           {

                findMap.put("accountId",accountId);

           }

          

           Integer count=sysAccountService.checkFieldValueExists(findMap);

           if(count!=null && count.intValue()>0)

           {

                map.put("success",false);

                map.put("message","身份证号已存在");

           }

           else

           {

                //TODO TCF 校验是否人证合一

                AipFace client=AipFaceUtil.getInstance();

               

                if(client!=null)

                {

                      ArrayList<MatchRequest> matchList=new ArrayList<MatchRequest>();

                      if(StringUtils.isNotEmpty(photoPicPath) && StringUtil.isNotEmpty(userPhoto)

                        && photoPicPath.length()>=22 && userPhoto.length()>=22)

                      {

                      photoPicPath=photoPicPath.substring(22);

                            userPhoto=userPhoto.substring(22);

                           

                            MatchRequest request1=new MatchRequest(photoPicPath,"BASE64");

                            MatchRequest request2=new MatchRequest(userPhoto,"BASE64");

                           

                            matchList.add(request1);//人脸识别采集照片BASE64

                            matchList.add(request2);//身份证照片BASE64

 

                          JSONObject jsonObject=client.match(matchList);

                          if(jsonObject!=null)

                          {

                              try

                              {

                                    JSONObject result=jsonObject.getJSONObject("result");

                                    if(result!=null)

                                    {

                                          double score=result.getDouble("score");

                                          if(score>=60)

                                          {

                                                map.put("success",true);

                                          }

                                          else

                                          {

                                                map.put("success",false);

                                                map.put("message","人脸识别和身份证照片不是同一用户");

                                          }

                                    }

                              }

                              catch(Exception e)

                              {

                                    map.put("success",false);

                                    map.put("message","人脸识别和身份证照片不是同一用户");

                              }

                          }

                      }

                      else

                      {

                            map.put("success",false);

                            map.put("message","照片采集失败");

                      }

                }

           }

          

           return map;

     }

    

     //TODO TCF 校验抓拍照片是否和当前用户已存照片匹配

     @RequestMapping("/checkFirstPhoto.do")

     @ResponseBody

     public Map checkFirstPhoto(HttpServletRequest request) throws JSONException

     {

           Map<String,Object> map=new HashMap<String,Object>();

          

           //TODO TCF 用户账户ID

           String accountId=request.getParameter("accountId");

          

           //TODO TCF 用户ID

           String userId=request.getParameter("userId");

          

           //TODO TCF 抓拍图片BASE64

           String cameraPhotoPath=request.getParameter("cameraPhotoPath");

          

           SysAccount sysAccount=new SysAccount();

           if(StringUtil.isNotEmpty(accountId))

           {

           sysAccount=sysAccountService.selectByPrimaryKey(accountId);

           }

          

           if(StringUtil.isNotEmpty(userId))

           {

           sysAccount=sysAccountService.selectByUserId(userId);

           }

          

           //TODO TCF 当前用户已保存的人脸照片BASE64

           String photoPicPath=sysAccount.getPhotoPicPath();

           if(StringUtil.isNotEmpty(photoPicPath) && photoPicPath.length()>=22)

           {

                photoPicPath=photoPicPath.substring(22);

               

                //TODO TCF 编辑用户信息,比对照片

                if(StringUtil.isNotEmpty(cameraPhotoPath) && cameraPhotoPath.length()>=22)

                {

                cameraPhotoPath=cameraPhotoPath.substring(22);

                     

                      ArrayList<MatchRequest> requests=new ArrayList<MatchRequest>();

                      MatchRequest request1=new MatchRequest(cameraPhotoPath,"BASE64");

                      MatchRequest request2=new MatchRequest(photoPicPath,"BASE64");

                      requests.add(request1);

                      requests.add(request2);

               

                    AipFace client=AipFaceUtil.getInstance();

                    if(client!=null)

                    {

                        JSONObject jsonObject=client.match(requests);

                        if(jsonObject!=null)

                        {

                              try

                              {

                                    JSONObject result=jsonObject.getJSONObject("result");

                                    if(result!=null)

                                    {

                                          double score=result.getDouble("score");

                                          if(score>=80)

                                          {

                                                map.put("success",true);

                                          }

                                          else

                                          {

                                                map.put("success",false);

                                                map.put("message","非法操作【不是当前用户本人】");

                                          }

                                    }

                              }

                              catch(Exception e)

                              {

                                    map.put("success",false);

                                    map.put("message","非法操作【照片采集失败,请阅读下方提示后重试】");

                              }

                        }

                    }

                }

           }

           else

           {

                //TODO TCF 新增用户信息

                map.put("success",true);

           }

          

           return map;

     }

    

     //TODO TCF 根据用户id比对人脸库图片和本次抓拍图片

     @RequestMapping("/checkFacePhoto.do")

     @ResponseBody

     public Map checkFasePhoto(HttpServletRequest request)

     {

           Map<String,Object> map=new HashMap<String,Object>();

          

           //TODO TCF 当前用户id

           String userId=request.getParameter("userId");

    

         //TODO TCF 本次抓拍图片BASE64

           String cameraPhotoPath=request.getParameter("cameraPhotoPath");

          

           if(StringUtil.isNotEmpty(userId))

           {

                SysAccount sysAccount=sysAccountService.selectByUserId(userId);

               

                if(sysAccount!=null)

                {

                      if(StringUtil.isNotEmpty(cameraPhotoPath) && cameraPhotoPath.length()>=22)

                      {

                      cameraPhotoPath=cameraPhotoPath.substring(22);

                      }

                     

                      String photoPicPath=sysAccount.getPhotoPicPath();

                      if(StringUtil.isNotEmpty(photoPicPath) && photoPicPath.length()>=22)

                      {

                      photoPicPath=photoPicPath.substring(22);

                           

                            ArrayList<MatchRequest> requests=new ArrayList<MatchRequest>();

                     

                            MatchRequest request1=new MatchRequest(photoPicPath,"BASE64");

                            MatchRequest request2=new MatchRequest(cameraPhotoPath,"BASE64");

                            requests.add(request1);

                            requests.add(request2);

                           

                            AipFace client=AipFaceUtil.getInstance();

                            if(client!=null)

                            {

                                  JSONObject jsonObject=client.match(requests);

                                  if(jsonObject!=null)

                                  {

                                        try

                                        {

                                              JSONObject result=jsonObject.getJSONObject("result");

                                              if(result!=null)

                                              {

                                                   double score=result.getDouble("score");

                                                   if(score>=80)

                                                   {

                                                         map.put("success",true);

                                                   }

                                                   else

                                                   {

                                                         map.put("success",false);

                                                         map.put("message","人脸识别校验失败");

                                                   }

                                              }

                                        }

                                        catch(Exception e)

                                        {

                                              map.put("success",false);

                                              map.put("message","人脸识别校验失败");

                                        }

                                  }

                            }

                      }

                      else

                      {

                            map.put("success",false);

                            map.put("message","人脸识别校验失败");

                      }

                }

           }

          

           return map;

     }

    

     //TODO TCF 根据用户id校验身份证号是否和刷的身份证证件号码匹配

     @RequestMapping("/checkIdCardNumber.do")

     @ResponseBody

     public Map checkIdCardNumber(HttpServletRequest request)

     {

           Map<String,Object> map=new HashMap<String,Object>();

          

           //TODO TCF 当前用户id

           String userId=request.getParameter("userId");

          

           //TODO TCF 刷的身份证号码

           String idCardNumber=request.getParameter("idCardNumber");

          

           if(StringUtil.isNotEmpty(userId))

           {

                SysAccount sysAccount=sysAccountService.selectByUserId(userId);

               

                if(sysAccount!=null)

                {

                      //TODO TCF 用户登记时录入的身份证号

                      String cardNumber=sysAccount.getIdCardNumber();

                     

                      if(StringUtil.isNotEmpty(cardNumber) && StringUtil.isNotEmpty(idCardNumber))

                      {

                      if(cardNumber.trim().equals(idCardNumber.trim()))

                            {

                                  map.put("success",true);

                            }

                            else

                            {

                                  map.put("success",false);

                                  map.put("message","【身份证和当前用户本人不匹配】校验失败");

                            }

                      }

                      else

                      {

                            map.put("success",false);

                            map.put("message","【身份证和当前用户本人不匹配】校验失败");

                      }

                }

           }

          

           return map;

     }

    

//TODO TCF 根据用户id查询用户账户信息,用于指纹校验

     @RequestMapping("/selectByUserId.do")

     @ResponseBody

     public SysAccount selectByUserId(HttpServletRequest request)

     {

           //TODO TCF 当前用户id

           String userId=request.getParameter("userId");

          

           return sysAccountService.selectByUserId(userId);

}

 

 

4.对接秒滴云平台的发送短信接口调用代码

package com.kingtake.common.miaodiyun;

 

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.HttpURLConnection;

import java.net.URL;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.text.SimpleDateFormat;

import java.util.Date;

 

import org.json.JSONException;

import org.json.JSONObject;

/**

 *

 * @Title:GetMessageCode

 * @author TCF

 * @Description:发送验证码

 */

public class GetMessageCode {

     private static final String QUERY_PATH="https://api.miaodiyun.com/20150822/industrySMS/sendSMS";

     private static final String ACCOUNT_SID="a9c07995abc648c98edb12d5f15bd651";

     private static final String AUTH_TOKEN="94da4ab341c94ebd9f0c213677510e0b";

    

     //根据相应的手机号发送验证码

     public static String getCode(String phone) throws JSONException{

           String rod=smsCode();

           String timestamp=getTimestamp();

           String sig=getMD5(ACCOUNT_SID,AUTH_TOKEN,timestamp);

           String tamp="【军区物资业务平台】您的验证码为”+rod+”,请于2分钟内正确输入,如非本人操作,请忽略此短信。";

           OutputStreamWriter out=null;

           BufferedReader br=null;

           StringBuilder result=new StringBuilder();

           try {

                URL url=new URL(QUERY_PATH);

                HttpURLConnection connection=(HttpURLConnection) url.openConnection();

                connection.setRequestMethod("POST");

                connection.setDoInput(true);//设置是否允许数据写入

                connection.setDoOutput(true);//设置是否允许参数数据输出

                connection.setConnectTimeout(5000);//设置链接响应时间

                connection.setReadTimeout(10000);//设置参数读取时间

                connection.setRequestProperty("Content-type","application/x-www-form-urlencoded");            

                //提交请求

                out=new OutputStreamWriter(connection.getOutputStream(),"UTF-8");

                String args=getQueryArgs(ACCOUNT_SID, tamp, phone, timestamp, sig, "JSON");

                out.write(args);

                out.flush();

                //读取返回参数

               

                br=new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));

                String temp="";

                while((temp=br.readLine())!=null){

                      result.append(temp);

                }

           } catch (Exception e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

           }

           JSONObject json=new JSONObject(result.toString());

           String respCode=json.getString("respCode");

           String defaultRespCode="00000";

           if(defaultRespCode.equals(respCode)){

                 return "256585";

           }else{

                return "256585";                

           }

     }

     //定义一个请求参数拼接方法

     public static String getQueryArgs(String accountSid,String smsContent,String to,String timestamp,String sig,String respDataType){

           return "accountSid="+accountSid+"&smsContent="+smsContent+"&to="+to+"&timestamp="+timestamp+"&sig="+sig+"&respDataType="+respDataType;

     }

     //获取时间戳

     public static String getTimestamp(){

           return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

     }

     //sing签名

     public static String getMD5(String sid,String token,String timestamp){

          

           StringBuilder result=new StringBuilder();

           String source=sid+token+timestamp;

           //获取某个类的实例

                      try {                           

                         MessageDigest digest=MessageDigest.getInstance("MD5");

                         //要进行加密的东西

                         byte[] bytes=digest.digest(source.getBytes());

                         for(byte b:bytes){

                               String hex=Integer.toHexString(b&0xff);

                               if(hex.length()==1){

                                     result.append("0"+hex);

                               }else{

                                     result.append(hex);

                               }

                         }

                      } catch (NoSuchAlgorithmException e) {

                            // TODO Auto-generated catch block

                            e.printStackTrace();

                      }

                     

          

           return result.toString();

     }

     //创建验证码

     public static String smsCode(){

           String random=(int)((Math.random()*9+1)*100000)+"";        

           return random;

     }

}

 

//TODO TCF 二级安全校验:通过用户ID给用户注册时登记的手机号发短信验证码

     @RequestMapping("/sendMessageByUserId.do")

     @ResponseBody

     public Map sendMessageByUserId(HttpServletRequest request)

     {

           Map<String,Object> map=new HashMap<String,Object>();

          

           //TODO TCF 用户id

           String userId=request.getParameter("userId");

          

           if(StringUtil.isNotEmpty(userId))

           {

                SysAccount sysAccount=sysAccountService.selectByUserId(userId);

               

                if(sysAccount!=null)

                {

                      String phoneNumber=sysAccount.getMobilephone();

                     

                      if(StringUtil.isNotEmpty(phoneNumber) && phoneNumber.length()==11)

                      {

                            try

                            {

                                  String code = GetMessageCode.getCode(phoneNumber);

 

                                  map.put("success", true);

                                  map.put("message", "发送成功");

                                  map.put("code", code);

                            }

                            catch (Exception e)

                            {

                                  e.printStackTrace();

                                  map.put("success", false);

                                  map.put("message", "发送失败");

                            }

                      }

                }

           }

          

           return map;

     }

 

 

发布了100 篇原创文章 · 获赞 10 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_30056341/article/details/91488492
今日推荐