LAPTOP-KB9HII50\70708 2 years ago
parent
commit
7503801221

+ 5 - 0
svr/svr-cloud-care/pom.xml

@ -286,6 +286,11 @@
            <artifactId>tencentcloud-speech-sdk-java</artifactId>
            <version>1.0.12</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.paho</groupId>
            <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
            <version>1.2.5</version>
        </dependency>
    </dependencies>
    <build>

+ 14 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/BaseMqttCallbackRecordDao.java

@ -0,0 +1,14 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.BaseMqttCallbackRecordDO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
 * Created by yeshijie on 2023/1/13.
 */
public interface BaseMqttCallbackRecordDao extends JpaRepository<BaseMqttCallbackRecordDO,String>,
        JpaSpecificationExecutor<BaseMqttCallbackRecordDO> {
}

+ 29 - 2
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/wechat/WechatMenuController.java

@ -12,9 +12,11 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.File;
@ -24,7 +26,7 @@ import java.io.InputStreamReader;
/**
 * Created by chenweida on 2017/8/4.
 */
@Controller
@RestController
@RequestMapping(value = "/wechat/menu", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "微信菜单相关管理")
public class WechatMenuController extends EnvelopRestEndpoint {
@ -34,6 +36,31 @@ public class WechatMenuController extends EnvelopRestEndpoint {
    private WxAccessTokenService wxAccessTokenService;
    @Value("${wechat.id}")
    private String wechatId;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @ApiOperation(value = "微信菜单创建-读数据库")
    @PostMapping(value = "/menu/createByMysql")
    public String createByMysql() {
        try {
            WxAccessTokenDO wxAccessTokenDO = wxAccessTokenService.getWxAccessTokenById(wechatId);
            String sql = "SELECT content from wx_menu_json WHERE id = 'weixin_menu'";
            String params = jdbcTemplate.queryForObject(sql,String.class);
            String url = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + wxAccessTokenDO.getAccessToken();
            // 请求微信接口创建菜单
            String jsonStr = HttpUtil.sendPost(url, params);
            JSONObject result = new JSONObject(jsonStr);
            if (result != null && result.get("errcode").toString().equals("0") && result.getString("errmsg").equals("ok")) {
                return "创建成功!";
            } else {
                return "创建失败!";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "创建失败";
        }
    }
    /**
     * 微信菜单创建

+ 3 - 3
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/PatientDeviceService.java

@ -1863,7 +1863,7 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
        if ("4".equals(devices.get(0).getCategoryCode())){//手表
            Device device = deviceDao.findOne(devices.get(0).getDeviceId());
            if (device!=null){
                if ("X1".equals(device.getModel())){
                if ("X1".equals(device.getModel())||"X3".equals(device.getModel())){
                    url = MessageFormat.format(AqgConfig.X1sos_numbers, deviceSn,seqid);
                }
            }
@ -1973,7 +1973,7 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
            if ("4".equals(devices.get(0).getCategoryCode())){//手表
                Device device = deviceDao.findOne(devices.get(0).getDeviceId());
                if (device!=null){
                    if ("X1".equals(device.getModel())){
                    if ("X1".equals(device.getModel())||"X3".equals(device.getModel())){
                        url = MessageFormat.format(AqgConfig.X1fence_area, deviceSnTmp,fenceNO);
                    }
                }
@ -2208,7 +2208,7 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
            if ("4".equals(devices.get(0).getCategoryCode())){//手表
                Device device = deviceDao.findOne(devices.get(0).getDeviceId());
                if (device!=null){
                    if ("X1".equals(device.getModel())){
                    if ("X1".equals(device.getModel())||"X3".equals(device.getModel())){
                        url = MessageFormat.format(AqgConfig.X1fence_area, deviceSnTmp,1);
                    }
                }

+ 195 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/MQTTKXClientUtil.java

@ -0,0 +1,195 @@
package com.yihu.jw.care.util;
import com.yihu.jw.care.dao.device.BaseMqttCallbackRecordDao;
import com.yihu.jw.entity.care.device.BaseMqttCallbackRecordDO;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.ScheduledExecutorService;
/**
 * 凯旋街道视频
 * Created by yeshijie on 2023/1/12.
 */
@Component
public class MQTTKXClientUtil {
    private static Logger logger = LoggerFactory.getLogger(MQTTKXClientUtil.class);
    public static final String HOST = "tcp://121.40.135.79";
    public static final String deviceId = "18202a08724e5573";
    public static final Integer qos = 1;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BaseMqttCallbackRecordDao mqttCallbackRecordDao;
/*    	1、心跳保活,设置为30s:
    mosquitto_pub -h 121.40.135.79 -t "device/18202a08724e5573/cmd/ipcam_keep_alive" -u admin -P admin -m "30"
            2、订阅:
    mosquitto_sub -h 121.40.135.79 -t "device/18202a08724e5573/response/+"
            3、开启视频推流:
    mosquitto_pub -h 121.40.135.79 -t "device/18202a08724e5573/cmd/ipcam_video_start" -u admin -P admin -m "1"
            6、解析步骤2的payload,获取直播SourceURL:
    如:http://121.40.135.79/live/18202a08724e5573_1673488105807/hls.m3u8
            5、关闭视频推流:
    mosquitto_pub -h 121.40.135.79 -t "device/18202a08724e5573/cmd/ipcam_video_start" -u admin -P admin -m "0"*/
    public static final String ipcam_keep_alive = "device/{deviceId}/cmd/ipcam_keep_alive";
    public static final String TOPIC = "device/{deviceId}/response/+";
    public static final String ipcam_video_start = "device/{deviceId}/cmd/ipcam_video_start";
    private static final String clientid = String.valueOf(System.currentTimeMillis());;
    private MqttClient client;
    private MqttConnectOptions options;
    private String userName = "admin";
    private String passWord = "admin";
    private ScheduledExecutorService scheduler;
    public void start() {
        logger.info("启动监听mqtt-start");
        try {
            // host为主机名,clientid即连接MQTT的客户端ID,一般以唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
            client = new MqttClient(HOST, clientid, new MemoryPersistence());
            // MQTT的连接设置
            options = new MqttConnectOptions();
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            // 设置连接的用户名
            options.setUserName(userName);
            // 设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            options.setAutomaticReconnect(true);//设置自动重连
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            // 设置回调
            client.setCallback(new MqttCallback(){
                @Override
                public void connectionLost(Throwable throwable) {
                    // 连接丢失后,一般在这里面进行重连
                    throwable.printStackTrace();
                    logger.info("连接断开,可以做重连");
                }
                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    // subscribe后得到的消息会执行到这里面
                    BaseMqttCallbackRecordDO mqttCallbackRecordDO = new BaseMqttCallbackRecordDO();
                    if(StringUtils.isNotBlank(topic)){
                        String[] deviceId = topic.split("//");
                        if(deviceId.length>1){
                            mqttCallbackRecordDO.setDeviceId(deviceId[1]);
                        }
                    }
                    mqttCallbackRecordDO.setTopic(topic);
                    mqttCallbackRecordDO.setPayload(new String(message.getPayload()));
                    mqttCallbackRecordDao.save(mqttCallbackRecordDO);
                    logger.info("接收消息主题 : " + topic+","+"接收消息内容 : " + new String(message.getPayload()));
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    logger.info("deliveryComplete---------" + token.isComplete());
                }
            });
            client.connect(options);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("启动监听mqtt-end");
    }
    public MqttClient getClient(){
        return client;
    }
    /**
     * 开启关闭直播
     */
    public void ipcam_video_start(String open,String deviceId) throws Exception{
        String payload = open;//
        MqttMessage message = new MqttMessage(payload.getBytes("UTF-8"));
        // 设置消息的服务质量
        message.setQos(qos);
        message.setRetained(true);
        // 发布消息
        String topic = ipcam_video_start.replace("{deviceId}",deviceId);
        logger.info(topic);
        getClient().publish(topic, message);
    }
    /**
     * 心跳
     */
    public void heart(String deviceId) throws Exception{
        String payload = "30";//
        MqttMessage message = new MqttMessage(payload.getBytes("UTF-8"));
        // 设置消息的服务质量
        message.setQos(qos);
        message.setRetained(true);
        // 发布消息
        String topic = ipcam_keep_alive.replace("{deviceId}",deviceId);
        logger.info(topic);
        getClient().publish(topic, message);
    }
    /**
     * 订阅消息
     */
    public void subscribe(String deviceId) throws Exception{
        int[] Qos  = {qos};
        String topic = TOPIC.replace("{deviceId}",deviceId);
        logger.info(topic);
        String[] topic1 = {topic};
        getClient().subscribe(topic1, Qos);
    }
//    public static void main(String[] args) throws Exception {
//        try {
//            MQTTKXClientUtil mqttkxClientUtil = new MQTTKXClientUtil();
//            mqttkxClientUtil.start();
//            logger.info("启动监听mqtt");
//            // 心跳
//            heart(client,deviceId);
//
//            //订阅消息
//            subscribe(client,deviceId);
//
//            Scanner scanner = new Scanner(System.in);
//            System.out.println("请输入1-3数字");
//            String username = scanner.nextLine();
//            if("1".equals(username)){
//                //开启直播
//                logger.info("开启直播");
//                ipcam_video_start(client,"1",deviceId);
//            }
//            System.out.println("请输入密码");
//            String password = scanner.nextLine();
//            if("2".equals(password)){
//                //关闭直播
//                logger.info("关闭直播");
//                ipcam_video_start(client,"0",deviceId);
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }
}

+ 35 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/PostConstructUtil.java

@ -0,0 +1,35 @@
package com.yihu.jw.care.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
 * 项目启动就执行的类
 * Created by yeshijie on 2022/5/7.
 */
@Component
public class PostConstructUtil {
    private static final Logger logger = LoggerFactory.getLogger(PostConstructUtil.class);
    @Value("${spring.profiles.active}")
    private String profiles;
    @Autowired
    private MQTTKXClientUtil mqttkxClientUtil;
    @PostConstruct
    public void init(){
        logger.info("启动凯旋的设备的mqtt订阅====");
        mqttkxClientUtil.start();
    }
}