Browse Source

the new service . manager
Change thread to monitor

add other

hasan 3 years ago
parent
commit
9f28ac1322

+ 2 - 1
README.md

@@ -1,4 +1,5 @@
1
-# IoT_2021 
1
+# IoT_2021
2
+
2 3
 ## nstthh 数量监测
3 4
 
4 5
     NRJavaSerialService usb-9600 

+ 6 - 1
pom.xml

@@ -48,12 +48,17 @@
48 48
             <artifactId>spring-boot-devtools</artifactId>
49 49
             <optional>true</optional>
50 50
         </dependency>
51
-
51
+        <dependency>
52
+            <groupId>mysql</groupId>
53
+            <artifactId>mysql-connector-java</artifactId>
54
+        </dependency>
55
+        <!--
52 56
         <dependency>
53 57
             <groupId>com.h2database</groupId>
54 58
             <artifactId>h2</artifactId>
55 59
             <scope>runtime</scope>
56 60
         </dependency>
61
+        -->
57 62
         <dependency>
58 63
             <groupId>com.neuronrobotics</groupId>
59 64
             <artifactId>nrjavaserial</artifactId>

+ 18 - 2
src/main/java/com/sjls/nstthh/NstthhApplication.java

@@ -2,16 +2,32 @@ package com.sjls.nstthh;
2 2
 
3 3
 
4 4
 import com.sjls.nstthh.service.NRJavaSerialManager;
5
+import gnu.io.NRSerialPort;
6
+import org.slf4j.Logger;
7
+import org.slf4j.LoggerFactory;
5 8
 import org.springframework.boot.SpringApplication;
6 9
 import org.springframework.boot.autoconfigure.SpringBootApplication;
7 10
 
11
+import java.io.IOException;
12
+import java.util.TooManyListenersException;
13
+
8 14
 
9 15
 @SpringBootApplication
10 16
 public class NstthhApplication {
11 17
 
12
-    public static void main(String[] args) {
18
+    private static final Logger logger = LoggerFactory.getLogger(NstthhApplication.class);
19
+
20
+    public static NRSerialPort serialPort = null;
21
+
22
+    public static void main(String[] args) throws TooManyListenersException, IOException, InterruptedException {
13 23
         SpringApplication.run(NstthhApplication.class, args);
14
-        new NRJavaSerialManager().connect();
24
+
25
+        String port = "/dev/tty.usbserial-14130";
26
+        serialPort = new NRSerialPort(port, 9600);
27
+        boolean b = serialPort.connect();
28
+
29
+        new NRJavaSerialManager().operation(NstthhApplication.serialPort);
30
+
15 31
     }
16 32
 
17 33
 }

+ 28 - 3
src/main/java/com/sjls/nstthh/controller/HardwareAdmin.java

@@ -1,12 +1,18 @@
1 1
 package com.sjls.nstthh.controller;
2 2
 
3
+import com.sjls.nstthh.NstthhApplication;
3 4
 import com.sjls.nstthh.mqtt.MsgWriter;
5
+import com.sjls.nstthh.service.CommunicationService;
6
+import com.sjls.nstthh.service.NRJavaSerialManager;
7
+import org.springframework.beans.factory.annotation.Autowired;
4 8
 import org.springframework.stereotype.Controller;
5 9
 import org.springframework.ui.Model;
6 10
 import org.springframework.web.bind.annotation.RequestMapping;
7 11
 import org.springframework.web.bind.annotation.ResponseBody;
8 12
 
9 13
 import javax.annotation.Resource;
14
+import java.io.IOException;
15
+import java.util.TooManyListenersException;
10 16
 
11 17
 /**
12 18
  * smp admin
@@ -15,15 +21,15 @@ import javax.annotation.Resource;
15 21
 @Controller
16 22
 public class HardwareAdmin {
17 23
 
24
+    @Resource
25
+    private MsgWriter msgWriter;
26
+
18 27
     @RequestMapping("")
19 28
     @ResponseBody
20 29
     public String index() {
21 30
         return "Hi Nstthh";
22 31
     }
23 32
 
24
-    @Resource
25
-    private MsgWriter msgWriter;
26
-
27 33
     @RequestMapping(value = "/testmqtt")
28 34
     public void test_mqtt(String msg) {
29 35
         msgWriter.sendToMqtt(msg);
@@ -35,5 +41,24 @@ public class HardwareAdmin {
35 41
         return "nstthh";
36 42
     }
37 43
 
44
+
45
+
46
+    private CommunicationService communicationService;
47
+
48
+    @Autowired
49
+    public void setCommunicationService(CommunicationService communicationService) {
50
+        this.communicationService = communicationService;
51
+    }
52
+
53
+    @RequestMapping("/mtest")
54
+    public void mtest() throws TooManyListenersException, IOException, InterruptedException {
55
+
56
+        communicationService.creatToBeTested(16,35);
57
+
58
+
59
+
60
+
61
+        new NRJavaSerialManager().operationM(NstthhApplication.serialPort);
62
+    }
38 63
 }
39 64
 

+ 32 - 0
src/main/java/com/sjls/nstthh/entity/AngleObject.java

@@ -0,0 +1,32 @@
1
+package com.sjls.nstthh.entity;
2
+
3
+public class AngleObject {
4
+
5
+    private double levelAngle;
6
+    private double verticalAngle;
7
+    private double realHypotenuse;
8
+
9
+    public double getLevelAngle() {
10
+        return levelAngle;
11
+    }
12
+
13
+    public void setLevelAngle(double levelAngle) {
14
+        this.levelAngle = levelAngle;
15
+    }
16
+
17
+    public double getVerticalAngle() {
18
+        return verticalAngle;
19
+    }
20
+
21
+    public void setVerticalAngle(double verticalAngle) {
22
+        this.verticalAngle = verticalAngle;
23
+    }
24
+
25
+    public double getRealHypotenuse() {
26
+        return realHypotenuse;
27
+    }
28
+
29
+    public void setRealHypotenuse(double realHypotenuse) {
30
+        this.realHypotenuse = realHypotenuse;
31
+    }
32
+}

+ 4 - 0
src/main/java/com/sjls/nstthh/entity/Equipment.java

@@ -6,6 +6,7 @@ import javax.persistence.Entity;
6 6
 import javax.persistence.GeneratedValue;
7 7
 import javax.persistence.GenerationType;
8 8
 import javax.persistence.Id;
9
+import java.util.Date;
9 10
 
10 11
 /**
11 12
  * dpj
@@ -29,4 +30,7 @@ public class Equipment {
29 30
 
30 31
     private String emAddress;
31 32
 
33
+    private Date creatTime;
34
+
35
+
32 36
 }

+ 7 - 0
src/main/java/com/sjls/nstthh/entity/ReceiveData.java

@@ -6,6 +6,7 @@ import javax.persistence.Entity;
6 6
 import javax.persistence.GeneratedValue;
7 7
 import javax.persistence.GenerationType;
8 8
 import javax.persistence.Id;
9
+import java.util.Date;
9 10
 
10 11
 @Data
11 12
 @Entity
@@ -20,4 +21,10 @@ public class ReceiveData {
20 21
 
21 22
     private String distance; //00000989
22 23
 
24
+    private Date creatTime;
25
+
26
+    private double levelAngle; //z
27
+    private double verticalAngle; //y
28
+    private double realHypotenuse; //d
29
+
23 30
 }

+ 3 - 1
src/main/java/com/sjls/nstthh/entity/SendData.java

@@ -6,6 +6,7 @@ import javax.persistence.Entity;
6 6
 import javax.persistence.GeneratedValue;
7 7
 import javax.persistence.GenerationType;
8 8
 import javax.persistence.Id;
9
+import java.util.Date;
9 10
 
10 11
 @Data
11 12
 @Entity
@@ -18,4 +19,5 @@ public class SendData {
18 19
 
19 20
     private String sendKey; //12345678;029B029B
20 21
 
21
-}
22
+    private Date creatTime;
23
+ }

+ 15 - 0
src/main/java/com/sjls/nstthh/entity/Test.java

@@ -0,0 +1,15 @@
1
+package com.sjls.nstthh.entity;
2
+
3
+import cn.hutool.core.date.DateTime;
4
+
5
+public class Test {
6
+    public static void main(String[] args) {
7
+        String str222 = "68220185000000E08812345678031101B50102087707EA0000074B00FF79123456786B1B16";
8
+        String strrrrr = "68220185000000E08812345678031101B50102087707EA0000074B00FF79123456786B1B16";
9
+        System.out.println("strrrrr.equals(str222) = " + strrrrr.equals(str222));
10
+
11
+        System.out.println( DateTime.now());
12
+
13
+
14
+    }
15
+}

+ 13 - 20
src/main/java/com/sjls/nstthh/mqtt/MqttSenderConfig.java

@@ -25,35 +25,28 @@ import org.springframework.messaging.MessageHandler;
25 25
 @Slf4j
26 26
 public class MqttSenderConfig {
27 27
 
28
+    /**
29
+     * 订阅的bean名称
30
+     */
31
+    public static final String CHANNEL_NAME_IN = "mqttInboundChannel";
32
+    /**
33
+     * 发布的bean名称
34
+     */
35
+    public static final String CHANNEL_NAME_OUT = "mqttOutboundChannel";
28 36
     private static final Logger LOGGER = LoggerFactory.getLogger(MqttSenderConfig.class);
29
-
30 37
     @Value("${spring.mqtt.username}")
31 38
     private String username;
32
-
33 39
     @Value("${spring.mqtt.password}")
34 40
     private String password;
35
-
36 41
     @Value("${spring.mqtt.url}")
37 42
     private String hostUrl;
38
-
39 43
     @Value("${spring.mqtt.publishclientid}")
40 44
     private String publishclientid;
41
-
42 45
     @Value("${spring.mqtt.subsribeclientid}")
43 46
     private String subsribeclientid;
44
-
45 47
     @Value("${spring.mqtt.default_topic}")
46 48
     private String defaultTopic;
47 49
 
48
-    /**
49
-     * 订阅的bean名称
50
-     */
51
-    public static final String CHANNEL_NAME_IN = "mqttInboundChannel";
52
-    /**
53
-     * 发布的bean名称
54
-     */
55
-    public static final String CHANNEL_NAME_OUT = "mqttOutboundChannel";
56
-
57 50
 //    @Autowired
58 51
 //    private MqttCallbackHandler mqttCallbackHandler;
59 52
 
@@ -120,7 +113,7 @@ public class MqttSenderConfig {
120 113
     public MessageProducer inbound() {
121 114
         // 可以同时消费(订阅)多个Topic
122 115
         MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
123
-                subsribeclientid, mqttClientFactory(), new String[]{defaultTopic});
116
+                subsribeclientid, mqttClientFactory(), defaultTopic);
124 117
         adapter.setCompletionTimeout(5000);
125 118
         adapter.setConverter(new DefaultPahoMessageConverter());
126 119
         adapter.setQos(2);
@@ -145,15 +138,15 @@ public class MqttSenderConfig {
145 138
     public MessageHandler handler() {
146 139
         return new MessageHandler() {
147 140
             @Override
148
-            public void handleMessage(Message<?> message)  {
141
+            public void handleMessage(Message<?> message) {
149 142
                 try {
150 143
                     String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
151 144
                     String qos = message.getHeaders().get("mqtt_receivedQos").toString();
152 145
                     String payload = message.getPayload().toString();
153 146
                     //mqttCallbackHandler.handle(topic,payload);
154
-                    LOGGER.info("主题:"+topic);
155
-                    LOGGER.info("内容:"+payload);
156
-                    LOGGER.info("级别:"+qos);
147
+                    LOGGER.info("主题:" + topic);
148
+                    LOGGER.info("内容:" + payload);
149
+                    LOGGER.info("级别:" + qos);
157 150
                     //message.get
158 151
                 } catch (Exception e) {
159 152
                     LOGGER.error(e.getMessage(), e);

+ 3 - 1
src/main/java/com/sjls/nstthh/mqtt/MsgWriter.java

@@ -10,7 +10,9 @@ import org.springframework.stereotype.Component;
10 10
 public interface MsgWriter {
11 11
 
12 12
     void sendToMqtt(String data);
13
-    void sendToMqtt(String payload,@Header(MqttHeaders.TOPIC) String topic);
13
+
14
+    void sendToMqtt(String payload, @Header(MqttHeaders.TOPIC) String topic);
15
+
14 16
     void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) int qos, String payload);
15 17
 
16 18
 }

+ 31 - 0
src/main/java/com/sjls/nstthh/service/CommConfig.java

@@ -0,0 +1,31 @@
1
+package com.sjls.nstthh.service;
2
+
3
+import org.slf4j.Logger;
4
+import org.slf4j.LoggerFactory;
5
+import org.springframework.beans.factory.annotation.Autowired;
6
+import org.springframework.context.annotation.Configuration;
7
+
8
+import javax.annotation.PostConstruct;
9
+
10
+
11
+@Configuration
12
+public class CommConfig {
13
+
14
+    private static final Logger logger = LoggerFactory.getLogger(CommConfig.class);
15
+
16
+
17
+    private CommunicationService communicationService;
18
+
19
+    @Autowired
20
+    public void setCommunicationService(CommunicationService communicationService) {
21
+        this.communicationService = communicationService;
22
+    }
23
+
24
+
25
+    @PostConstruct
26
+    public void init() {
27
+        //communicationService.addSendStr(35);
28
+    }
29
+
30
+
31
+}

+ 73 - 9
src/main/java/com/sjls/nstthh/service/CommunicationService.java

@@ -1,10 +1,13 @@
1 1
 package com.sjls.nstthh.service;
2 2
 
3 3
 
4
+import cn.hutool.core.date.DateTime;
5
+import cn.hutool.core.util.StrUtil;
4 6
 import com.sjls.nstthh.entity.ReceiveData;
5 7
 import com.sjls.nstthh.entity.SendData;
6 8
 import com.sjls.nstthh.repository.ReceiveDataRepository;
7 9
 import com.sjls.nstthh.repository.SendDataRepository;
10
+import com.sjls.nstthh.util.AlgAlgorithm;
8 11
 import com.sjls.nstthh.util.StrSplicingAssistant;
9 12
 import org.slf4j.Logger;
10 13
 import org.slf4j.LoggerFactory;
@@ -23,14 +26,10 @@ import java.util.List;
23 26
 public class CommunicationService {
24 27
 
25 28
     private static final Logger logger = LoggerFactory.getLogger(CommunicationService.class);
26
-
29
+    static List receiveList = new ArrayList();
27 30
     private SendDataRepository sendDataRepository;
28
-
29 31
     private ReceiveDataRepository receiveDataRepository;
30 32
 
31
-    static List receiveList = new ArrayList();
32
-
33
-
34 33
     @Autowired
35 34
     public void setSendDataRepository(SendDataRepository sendDataRepository) {
36 35
         this.sendDataRepository = sendDataRepository;
@@ -51,16 +50,24 @@ public class CommunicationService {
51 50
         return receiveDataRepository.saveAll(receiveDataList);
52 51
     }
53 52
 
54
-    public synchronized boolean determineRstrPersistence(String str_receive_head, String currentSendStr, String str_receive) {
55
-        //logger.info(" currentSendStr = " + currentSendStr + " str_receive= " + str_receive);
53
+
54
+    /**
55
+     * 验证  打点后的数据 ?是否crc 并组装到list
56
+     * @param str_receive_head
57
+     * @param currentSendStr
58
+     * @param str_receive
59
+     * @return
60
+     */
61
+    public boolean determineRstrPersistence(String str_receive_head, String currentSendStr, String str_receive) {
62
+        //logger.info(" determineRstrPersistence_currentSendStr = " + currentSendStr + " str_receive= " + str_receive);
56 63
         //当前发送的串,截取出角度。
57 64
         String currentSendStr_deviceid = currentSendStr.substring(18, 26);
58 65
         String currentSendStr_zy = currentSendStr.substring(38, 46);
59 66
 
60 67
         //当前接收的串,截取出角度,设备,距离。
61 68
         String deviceid = str_receive.substring(18, 26);//截取设备id
62
-        //String anglez = str_receive.substring(38, 42);//截取角度
63
-        //String angley = str_receive.substring(42, 46);//截取角度
69
+        String anglez = str_receive.substring(38, 42);//截取角度
70
+        String angley = str_receive.substring(42, 46);//截取角度
64 71
         String anglezy = str_receive.substring(38, 46);//角度
65 72
 
66 73
         String distance = str_receive.substring(46, 54);//截取距离
@@ -83,6 +90,7 @@ public class CommunicationService {
83 90
                 receiveData.setReceiveStr(str_receive);
84 91
                 receiveData.setReceiveKey(deviceid + anglezy);
85 92
                 receiveData.setDistance(distance);
93
+                receiveData.setCreatTime(DateTime.now());
86 94
                 //saveReceiveStr(receiveData);
87 95
                 receiveList.add(receiveData);
88 96
                 logger.info(receiveList.size() + ": _receive_str = " + anglezy + " | " + distance);
@@ -92,5 +100,61 @@ public class CommunicationService {
92 100
         return false;
93 101
     }
94 102
 
103
+    /**
104
+     * 创建 待打点 并 2db
105
+     * @param diameter
106
+     * @param high
107
+     */
108
+    public void creatToBeTested(double diameter,double high) {
109
+
110
+        sendDataRepository.deleteAll();
111
+
112
+        String str = AlgAlgorithm.getAveragePosition(diameter,high);
113
+        String[] strArr_z_y = str.split(";");
114
+        List<SendData> list2db = new ArrayList<SendData>();
115
+        for (int i = 0; i < strArr_z_y.length; i++) {
116
+            String[] strArr = strArr_z_y[i].split(",");
117
+            //System.out.println(Long.valueOf(strArr[0]));  System.out.println(Long.valueOf(strArr[1]));
118
+            String str10 = send16strUseCom(Long.valueOf(strArr[0]), Long.valueOf(strArr[1]));
119
+            //System.out.println("sendStr.add(\"" + str10 + "\");");
120
+            SendData SendData = new SendData();
121
+            SendData.setSendStr(str10);
122
+            String deviceid = str10.substring(18, 26);//截取设备id
123
+            String anglezy = str10.substring(38, 46);//角度
124
+            SendData.setSendKey(deviceid + anglezy);
125
+            SendData.setCreatTime(DateTime.now());
126
+            list2db.add(SendData);
127
+        }
128
+
129
+        sendDataRepository.saveAll(list2db);
130
+
131
+    }
132
+
133
+    /**
134
+     * 16进制 str
135
+     * @param z_val
136
+     * @param y_val
137
+     * @return
138
+     */
139
+    public static String send16strUseCom(long z_val, long y_val) {
140
+
141
+        // 第一个{}为 :z,y 角度转为步长 16进制 每隔两位字符串串加空格
142
+        // 第二个{}为 :sendStr_1_tmp串 crc验证后
143
+        String sendStr_0_tmp = "681C0105000000CD96";
144
+        String sendStr_1_tmp = "12345678031101A50102{}0012345678";
145
+        String sendStr_2_tmp = "{}16";
146
+//        String z = StrSplicingAssistant.hex10To16(StrSplicingAssistant.angleTransformationStep(z_val));
147
+//        String y = StrSplicingAssistant.hex10To16(StrSplicingAssistant.angleTransformationStep(y_val));
148
+        String z = StrSplicingAssistant.hex10To16(z_val);
149
+        String y = StrSplicingAssistant.hex10To16(y_val);
150
+        //16进制zy 替换 sendStr_1_tmp{}
151
+        String sendStr_1_v = StrUtil.format(sendStr_1_tmp, z + y);
152
+        //sendStr_1_v比特流CRC验证逆序并高低位置换后加空格格式化 替换 sendStr_2_tmp{}
153
+        String sendStr_2_v = StrUtil.format(sendStr_2_tmp, StrSplicingAssistant.displacementHighLow(StrSplicingAssistant.CRC16Right(sendStr_1_v)));
154
+
155
+        String sendstr_ = sendStr_0_tmp + sendStr_1_v + sendStr_2_v;
156
+        // System.out.print(sendstr_);
157
+        return sendstr_;
158
+    }
95 159
 
96 160
 }

+ 99 - 70
src/main/java/com/sjls/nstthh/service/NRJavaSerialManager.java

@@ -1,6 +1,8 @@
1 1
 package com.sjls.nstthh.service;
2 2
 
3
+import com.sjls.nstthh.entity.AngleObject;
3 4
 import com.sjls.nstthh.entity.SendData;
5
+import com.sjls.nstthh.util.AlgAlgorithm;
4 6
 import com.sjls.nstthh.util.StrSplicingAssistant;
5 7
 import gnu.io.NRSerialPort;
6 8
 import gnu.io.SerialPortEvent;
@@ -13,21 +15,27 @@ import org.springframework.stereotype.Component;
13 15
 import java.io.DataInputStream;
14 16
 import java.io.DataOutputStream;
15 17
 import java.io.IOException;
16
-import java.util.Iterator;
17
-import java.util.List;
18
-import java.util.TooManyListenersException;
18
+import java.util.*;
19 19
 
20 20
 
21 21
 @Component
22 22
 public class NRJavaSerialManager {
23 23
     private static final Logger logger = LoggerFactory.getLogger(NRJavaSerialManager.class);
24 24
 
25
-    private static String str_init = "681C0105000000CD9612345678031101A5010205DC05DC00123456785FA816";
26
-    private static String str_heartbeat = "68140186000000E55A1234567803510112345678B1E216";
27
-    private static String str_receive_head = "68220185000000E088";
25
+    private static final String str_init = "681C0105000000CD9612345678031101A5010205DC05DC00123456785FA816";
26
+    private static final String str_heartbeat = "68140186000000E55A1234567803510112345678B1E216";
27
+    private static final String str_receive_head = "68220185000000E088";
28 28
 
29 29
     private volatile static String currentSendStr = str_init;
30
-    private volatile static String[] str_receive_at_arr = new String[2];
30
+
31
+    public static List<SendData> getSendStr() {
32
+        return sendStr;
33
+    }
34
+
35
+    public static void setSendStr(List<SendData> sendStr) {
36
+        NRJavaSerialManager.sendStr = sendStr;
37
+    }
38
+
31 39
     private volatile static List<SendData> sendStr = null;
32 40
 
33 41
     private volatile static boolean isHeartbeat = false;
@@ -36,45 +44,69 @@ public class NRJavaSerialManager {
36 44
 
37 45
     private static CommunicationService communicationService;
38 46
 
47
+    public final synchronized static boolean wait10Seconds(long m) {
48
+        try {
49
+            Thread.sleep(m);
50
+        } catch (InterruptedException e) {
51
+        }
52
+        return true;
53
+    }
54
+
39 55
     @Autowired
40 56
     public void setCommunicationService(CommunicationService communicationService) {
41
-        this.communicationService = communicationService;
42
-        sendStr = communicationService.getSendStr();
57
+        NRJavaSerialManager.communicationService = communicationService;
43 58
     }
44 59
 
45
-    public void connect() {
46
-        NRSerialPort serialPort = new NRSerialPort("/dev/tty.usbserial-14130", 9600);
47
-        serialPort.connect();
60
+    /**
61
+     * 启动时,打两次。
62
+     *
63
+     * @param serialPort
64
+     * @throws IOException
65
+     * @throws TooManyListenersException
66
+     * @throws InterruptedException
67
+     */
68
+    public void operation(NRSerialPort serialPort) throws IOException, TooManyListenersException, InterruptedException {
69
+        sendStr = communicationService.getSendStr();
48 70
 
71
+        while (sendStr.size() > 0) {
72
+            break;
73
+        }
49 74
         DataInputStream inStream = new DataInputStream(serialPort.getInputStream());
50 75
         DataOutputStream outStream = new DataOutputStream(serialPort.getOutputStream());
51 76
 
52
-        Thread t1 = new Thread(new SerialWriter(outStream));
53
-        t1.start();
77
+        serialPort.addEventListener(new SerialReader(inStream));
78
+        serialPort.notifyOnDataAvailable(true);
54 79
 
55
-        try {
56
-            serialPort.addEventListener(new SerialReader(inStream));
57
-            serialPort.notifyOnDataAvailable(true);
58
-        } catch (TooManyListenersException e1) {
59
-            e1.printStackTrace();
60
-        }
80
+        Thread t1 = new Thread(new SerialWriter(outStream), "t1");
81
+        t1.start();
82
+        t1.join();
83
+        Thread t2 = new Thread(new SerialWriter(outStream), "t2");
84
+        t2.start();
61 85
 
62
-        while (isSerialPortDisconnect) {
63
-            try {
64
-                t1.interrupt();
65
-                //t2.interrupt();
66
-                serialPort.notifyOnDataAvailable(false);
67
-                serialPort.disconnect();
68
-            } catch (Exception e1) {
69
-                e1.printStackTrace();
70
-            }
86
+    }
71 87
 
88
+    /**
89
+     * 定时任务,手动请求,打一次。
90
+     *
91
+     * @param serialPort
92
+     * @throws IOException
93
+     * @throws TooManyListenersException
94
+     * @throws InterruptedException
95
+     */
96
+    public void operationM(NRSerialPort serialPort) throws IOException, TooManyListenersException, InterruptedException {
97
+        while (sendStr.size() > 0) {
98
+            break;
72 99
         }
100
+        DataOutputStream outStream = new DataOutputStream(serialPort.getOutputStream());
101
+        Thread t1 = new Thread(new SerialWriter(outStream), "t1");
102
+        t1.start();
73 103
 
74 104
     }
75 105
 
106
+
76 107
     public static class SerialReader implements SerialPortEventListener {
77
-        private DataInputStream inStream;
108
+        private final DataInputStream inStream;
109
+        private String str_receive_at = "";
78 110
 
79 111
         public SerialReader(DataInputStream inStream) {
80 112
             this.inStream = inStream;
@@ -90,56 +122,51 @@ public class NRJavaSerialManager {
90 122
 
91 123
                 if (str_receive.equals(str_heartbeat)) {
92 124
                     isHeartbeat = true;
93
-                    //logger.info(" SerialReader.isHeartbeat; = " + str_receive);
94 125
                 } else {
95 126
                     if (str_receive.length() == 64) {
96
-                        str_receive_at_arr[0] = str_receive;
127
+                        str_receive_at = str_receive;
97 128
                     }
98 129
                     if (str_receive.length() == 10) {
99
-                        str_receive_at_arr[1] = str_receive;
130
+                        str_receive_at += str_receive;
100 131
                     }
101 132
 
102
-                    if (str_receive_at_arr[0] != null && str_receive_at_arr[1] != null) {
103
-                        String str_receive_at = str_receive_at_arr[0] + str_receive_at_arr[1];
104
-
105
-                        //logger.info(" SerialReader.isHeartbeat; = " + str_receive_at);
106
-
107
-                        if (str_receive_at.contains("EEEEEEEE")) {
108
-                            logger.info("测距失败 eeeeee------" + str_receive_at);
109
-                            isReceive = true;
110
-                        } else {
111
-                            logger.info(isReceive+" ggggggggg eeeeee------");
133
+                    while (str_receive_at.length() == 74) {
134
+                        logger.info("run SerialReader " + str_receive_at);
112 135
 
113
-                            // 判断返回串 正确与否,并组装 list for add。
114
-                            isReceive = communicationService.determineRstrPersistence(str_receive_head, currentSendStr, str_receive_at);
115
-                            if (!isReceive) {
116
-                                logger.info(" ggggggggg eeeeee------");
117
-
118
-                                wait10Seconds(2000);
136
+                        synchronized (this) {
137
+                            if (!str_receive_at.contains("EEEEEEEE")) {
138
+                                // 判断返回串 正确与否,并组装 list for add。
139
+                                isReceive = communicationService.determineRstrPersistence(str_receive_head, currentSendStr, str_receive_at);
140
+                            }else {
119 141
                                 isReceive = true;
120 142
                             }
143
+                            break;
121 144
                         }
122 145
                     }
146
+                    //wait10Seconds(5000);
147
+                    //isReceive = true;
123 148
                 }
124 149
             } catch (IOException e) {
125 150
                 e.printStackTrace();
151
+                return;
126 152
             }
127 153
         }
128 154
     }
129 155
 
130 156
     public static class SerialWriter implements Runnable {
131
-        private DataOutputStream outStream;
132 157
         //初始化设备位置,只一次。
133 158
         boolean onlyOnce = true;
159
+        private final DataOutputStream outStream;
134 160
 
135 161
         public SerialWriter(DataOutputStream outStream) {
136 162
             this.outStream = outStream;
137 163
         }
138 164
 
139 165
         public void run() {
140
-            logger.info(" wait for send point number ......" + sendStr.size());
166
+            logger.info("wait for send point number testing ......" + sendStr.size());
141 167
 
142 168
             while (!Thread.interrupted()) {
169
+                // logger.info("run SerialWriter 11111......" );
143 170
                 try {
144 171
                     if (isHeartbeat && onlyOnce) {
145 172
                         outStream.write(StrSplicingAssistant.hexStrToByteArrs(str_init));
@@ -159,34 +186,36 @@ public class NRJavaSerialManager {
159 186
                             }
160 187
                         } else {
161 188
                             List receiveList_ = CommunicationService.receiveList;
162
-                            //logger.info("success _发送:" + sendStr.size() + "_接收:" + receiveList_.size());
163
-                            //logger.info("success _发送:" + sendStr + "_接收:" + receiveList_);
164
-
165
-                            // 组装的list 一次性save。
189
+                             // 组装的list 一次性save。
166 190
                             List receiveListDB_ = communicationService.saveReceiveData(receiveList_);
167
-                            if (receiveListDB_ != null && receiveListDB_.size() > 0)
191
+                            if (receiveListDB_ != null && receiveListDB_.size() > 0) {
168 192
                                 isSerialPortDisconnect = true;
169
-                            logger.info(isSerialPortDisconnect + "_success _ 接收:" + receiveListDB_);
193
+                                logger.info(isSerialPortDisconnect + "_success _ :");
194
+                                //todo
195
+
196
+                                AngleObject angleObject = new AngleObject();
197
+
198
+
199
+                                Map map = new HashMap<Double,AngleObject>();
200
+
201
+
202
+                                AlgAlgorithm.sxy(map);
203
+
204
+
205
+                                AlgAlgorithm.calculateVolume( AlgAlgorithm.zNums);
206
+
207
+                                 Thread.currentThread().interrupt();
208
+                                break;
209
+                            }
170 210
                         }
171 211
                     }
172
-                    Thread.sleep(10000);
212
+                    Thread.sleep(2000);
173 213
                 } catch (IOException | InterruptedException e) {
174 214
                     e.printStackTrace();
215
+                    return;
175 216
                 }
176 217
             }
177 218
         }
178 219
 
179 220
     }
180
-
181
-    public final synchronized static boolean wait10Seconds(long m) {
182
-        try {
183
-            Thread.sleep(m);
184
-        } catch (InterruptedException e) {
185
-        }
186
-        return true;
187
-    }
188
-
189
-    public static void main(String[] args) {
190
-        new NRJavaSerialManager().connect();
191
-    }
192 221
 }

+ 45 - 0
src/main/java/com/sjls/nstthh/service/SaticScheduleTask.java

@@ -0,0 +1,45 @@
1
+package com.sjls.nstthh.service;
2
+
3
+import com.sjls.nstthh.NstthhApplication;
4
+import org.slf4j.Logger;
5
+import org.slf4j.LoggerFactory;
6
+import org.springframework.beans.factory.annotation.Autowired;
7
+import org.springframework.context.annotation.Configuration;
8
+import org.springframework.scheduling.annotation.EnableScheduling;
9
+import org.springframework.scheduling.annotation.Scheduled;
10
+
11
+import java.io.IOException;
12
+import java.util.TooManyListenersException;
13
+
14
+@Configuration
15
+@EnableScheduling
16
+public class SaticScheduleTask {
17
+
18
+
19
+
20
+    private CommunicationService communicationService;
21
+
22
+    @Autowired
23
+    public void setCommunicationService(CommunicationService communicationService) {
24
+        this.communicationService = communicationService;
25
+    }
26
+
27
+    private static final Logger logger = LoggerFactory.getLogger(SaticScheduleTask.class);
28
+
29
+    //3.添加定时任务
30
+    // 每天的18点、21点都执行一次:0 0 09,18 * * ?
31
+    @Scheduled(cron = "0 0 14,18 * * ?")
32
+    //或直接指定时间间隔,例如:5秒
33
+    //@Scheduled(fixedRate=360000)
34
+    private void configureTasks() throws TooManyListenersException, IOException, InterruptedException {
35
+
36
+        //for (String s : NRSerialPort.getAvailableSerialPorts()) {
37
+        //logger.info(" Availible port: " + s);
38
+        //}
39
+
40
+        // /dev/ttyUSB0     /dev/tty.usbserial-14130
41
+        NRJavaSerialManager.setSendStr(communicationService.getSendStr());
42
+        new NRJavaSerialManager().operation(NstthhApplication.serialPort);
43
+        //System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
44
+    }
45
+}

+ 158 - 20
src/main/java/com/sjls/nstthh/util/AlgAlgorithm.java

@@ -1,23 +1,42 @@
1 1
 package com.sjls.nstthh.util;
2 2
 
3 3
 
4
+import com.sjls.nstthh.entity.AngleObject;
5
+
6
+import java.math.BigDecimal;
7
+import java.util.ArrayList;
8
+import java.util.Collections;
9
+import java.util.List;
10
+import java.util.Map;
11
+
4 12
 public class AlgAlgorithm {
5 13
 
14
+
15
+    //圆筒仓的直径
16
+    static double diameter = 12;
17
+    //AC 是设备到地面的高
18
+    double  high = 35;
19
+
20
+
21
+    static double h1 = 6; //h1 圆锥的高
22
+    static double h2 = 3; // h2 水平地面到圆锥尖的高
23
+    public static List<Double> zNums = new ArrayList<Double>();
6 24
     /**
7
-     * 打点
25
+     * 算法 产生 待检测点。
8 26
      *
9
-     * @param
27
+     * @param high 高
28
+     * @return
10 29
      */
30
+    public static String getAveragePosition(double diameter,double high) {
11 31
 
12
-    public static String getAveragePosition() {
13
-
14
-
32
+        if(diameter==0){
33
+            diameter= diameter;
34
+        }
35
+        if(high==0){
36
+            high= high;
37
+        }
15 38
         StringBuffer sb = new StringBuffer();
16 39
 
17
-        //圆筒仓的直径
18
-        double d = 12;
19
-        //AC 是设备到地面的高
20
-        double AC = 35;
21 40
         double x1 = 0;
22 41
         double y1 = 0;
23 42
         //打出来三角形的底边AB 实际是平面上点的斜边
@@ -31,7 +50,7 @@ public class AlgAlgorithm {
31 50
         double level_step = 0;//水平的步长
32 51
 
33 52
         //根据直径判断半径是整数还是非整数 如果是非整数 则向下取整
34
-        double r = Math.floor(d / 2);  //最大的半径 即一共有多少个圆圈
53
+        double r = Math.floor(diameter / 2);  //最大的半径 即一共有多少个圆圈
35 54
 
36 55
         //一共有多少个圆圈
37 56
         int circleNumber = (int) r;
@@ -55,30 +74,30 @@ public class AlgAlgorithm {
55 74
 
56 75
                 /**
57 76
                  * 以设备为中心,把圆上的点分为上下两半,
58
-                 * 新的圆 是旧的圆向左平移了(d/2-i)+i 个长度 得到的
77
+                 * 新的圆 是旧的圆向左平移了(diameter/2-i)+i 个长度 得到的
59 78
                  * (设备在新的圆的最左边上,设备是坐标系的原点)
60 79
                  * 所以 横坐标加上这个长度  纵坐标不变
61 80
                  */
62 81
 
63 82
                 //纵坐标 无论是处于上半部分还是下半部分 其纵坐标是不变的
64
-                x = x1 + (d / 2 - i) + i;
83
+                x = x1 + (diameter / 2 - i) + i;
65 84
                 y = y1;
66 85
                 //System.out.print("["+x+","+y+"]"+",");
67 86
                 //底面三角形的斜边
68 87
                 AB = Math.sqrt(x * x + y * y);
69 88
                 //垂直三角形的斜边
70
-                BC = Math.sqrt(AB * AB + AC * AC);
89
+                BC = Math.sqrt(AB * AB + high * high);
71 90
                 if (x == 0 && y == 0) {//圆 点
72 91
                     level_angle = 0;
73 92
                     vertical_angle = 0;
74 93
 
75 94
                 } else if (y < 0) {//反向转
76 95
                     level_angle = -Math.toDegrees(Math.acos(Math.abs(y) / AB));
77
-                    vertical_angle = -(90 - Math.toDegrees(Math.acos(AC / BC)));
96
+                    vertical_angle = -(90 - Math.toDegrees(Math.acos(high / BC)));
78 97
 
79 98
                 } else {//正向转
80 99
                     level_angle = Math.toDegrees(Math.acos(y / AB));
81
-                    vertical_angle = 90 - Math.toDegrees(Math.acos(AC / BC));
100
+                    vertical_angle = 90 - Math.toDegrees(Math.acos(high / BC));
82 101
 
83 102
                 }
84 103
                 //转为步长
@@ -90,16 +109,15 @@ public class AlgAlgorithm {
90 109
                 sb.append(Math.round(vertical_step));
91 110
                 sb.append(";");
92 111
                 // sb.append("\n");
93
-
94 112
             }
95 113
         }
96 114
 
97 115
         /**
98
-         * 追加一个圆筒仓中心的点,其坐标是(d/2,0) 水平转动90度 步长为2167
116
+         * 追加一个圆筒仓中心的点,其坐标是(diameter/2,0) 水平转动90度 步长为2167
99 117
          */
100
-        AB = d / 2;//垂直三角形的底边
101
-        BC = Math.sqrt(AB * AB + AC * AC);//垂直三角形的斜边
102
-        vertical_angle = 90 - Math.toDegrees(Math.acos(AC / BC));
118
+        AB = diameter / 2;//垂直三角形的底边
119
+        BC = Math.sqrt(AB * AB + high * high);//垂直三角形的斜边
120
+        vertical_angle = 90 - Math.toDegrees(Math.acos(high / BC));
103 121
         vertical_step = 1500 + vertical_angle / 0.135;
104 122
         sb.append(2167);
105 123
         sb.append(",");
@@ -107,7 +125,127 @@ public class AlgAlgorithm {
107 125
         // sb.append("\n");
108 126
         //System.out.println(Math.round(level_step)+","+Math.round(vertical_step)+"");
109 127
         //System.out.println(sb);
128
+        return sb.toString();
129
+    }
130
+
131
+
132
+    /**
133
+     * 激光测距 给三维
134
+     *
135
+     * @param map
136
+     * @return
137
+     */
138
+
139
+    public static String sxy(Map<Double, AngleObject> map) {
110 140
 
141
+        double d = 30;//圆筒仓的直径
142
+        double AC = 50;//AC是设备到地面的高
143
+        double B1C = 0;//设备和粮面点之间的距离
144
+        double A1B1 = 0;//粮面到设备的水平距离
145
+        double x = 0; //实际点的坐标的x轴
146
+        double y = 0; //实际点的坐标的y轴
147
+        double z = 0; //实际点的坐标的z轴
148
+
149
+        StringBuffer sb = new StringBuffer();
150
+        sb.append("[");
151
+
152
+//        AngleObject angleObject = new AngleObject();
153
+//        angleObject.setLevelAngle(62.0);
154
+//        angleObject.setRealHypotenuse(35.2);
155
+//        map.put(3.0, angleObject);
156
+
157
+        //list集合用于存放 z值
158
+        for (Double verticalAngle : map.keySet()) {
159
+            AngleObject angleObject1 = map.get(verticalAngle);
160
+            //将垂直的角度转化为弧度
161
+            double verticalAngleRadians = Math.toRadians(verticalAngle);
162
+            String verticalAngleS = String.format("%.2f%n", Math.sin(verticalAngleRadians));
163
+            double sinc = new Double(verticalAngleS);
164
+            B1C = angleObject1.getRealHypotenuse();
165
+            A1B1 = B1C * sinc; //即 平面三角形的斜边
166
+
167
+            String sinLevel = String.format("%.2f%n", Math.sin(Math.abs(angleObject1.getLevelAngle())));
168
+            double sinLevelc = new Double(sinLevel);
169
+
170
+            /**
171
+             * 对比实际的A1B1与打到墙上时最大的这个边进行比较 如果A1B1小于这个最大边则可取
172
+             * 如果A1B1大于或等于这个最大的边 则打到了墙上 舍去
173
+             */
174
+            //打到墙上 最大的边
175
+            double maxLength = sinLevelc * d;
176
+            if (A1B1 < maxLength) {
177
+                //实际打在粮面上的点的坐标
178
+                String verticalAngleC = String.format("%.2f%n", Math.cos(verticalAngleRadians));
179
+                double cosc = new Double(verticalAngleC);
180
+                double A1C = B1C * cosc;
181
+                z = AC - A1C;
182
+
183
+                //平面三角形中 已知斜边A1B1和一个角(水平转动的角 angleObject1.getLevelAngle()) 求两直角边
184
+                double LevelAngleRadians = Math.toRadians(Math.abs(angleObject1.getLevelAngle()));
185
+                String LevelAngleS = String.format("%.2f%n", Math.sin(LevelAngleRadians));
186
+                double sinc1 = new Double(LevelAngleS);
187
+                x = sinc1 * A1B1;
188
+
189
+                String LevelAngleC = String.format("%.2f%n", Math.cos(LevelAngleRadians));
190
+                double cosc1 = new Double(LevelAngleC);
191
+                y = cosc1 * A1B1;
192
+
193
+                //发送给三维的坐标 需要向上平移d/2个单位
194
+                if (angleObject1.getLevelAngle() > 0) {
195
+                    //点的坐标就是 (x,y,z)
196
+
197
+                } else if (angleObject1.getLevelAngle() < 0) {
198
+                    //点的坐标就是 (x,-y,z)
199
+                    y = -y;
200
+                }
201
+                y = y + d / 2;
202
+
203
+                sb.append("[" + x + "," + y + "," + z + "],");
204
+
205
+                zNums.add(z);
206
+            }
207
+        }
208
+
209
+        sb = sb.deleteCharAt(sb.length() - 1);
210
+        sb.append("]");
111 211
         return sb.toString();
112 212
     }
213
+
214
+    /**
215
+     * 计算体积
216
+     * @param zList  粮面高集合
217
+     */
218
+    public static void calculateVolume(List<Double> zList) {
219
+
220
+        //z值的集合
221
+
222
+        //17.1  18.3  19.2  18.3    20.1  16.4  19.8  16.7  19.0  18.9
223
+        Double zMin = Collections.min(zList); //z的最小值
224
+
225
+        double sum = 0;
226
+        double zHeigh = 0;//每一个z与最低点的z差值
227
+        for (int i = 0; i < zList.size(); i++) {
228
+            //sum = zList.get(i)+sum;
229
+            zHeigh = zList.get(i) - zMin;
230
+            sum += zHeigh;
231
+
232
+        }
233
+        /** v 是总体积
234
+         * v1 最上面的那一部分
235
+         * v2 是中间的圆柱
236
+         * v3 是 圆锥
237
+         *
238
+         * h1 圆锥的高
239
+         * h2 水平地面到圆锥尖的高
240
+         */
241
+
242
+        double v1 = 3.14 * (diameter / 2) * (diameter / 2) * (sum / zList.size());
243
+        double v2 = 3.14 * (diameter / 2) * (diameter / 2) * (zMin - h2 - h1);
244
+        double v3 = (3.14 * (diameter / 2) * (diameter / 2) * h1) / 3;
245
+        double vv = v1 + v2 + v3;
246
+        BigDecimal bdv = new BigDecimal(vv);
247
+        double v = bdv.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
248
+
249
+    }
250
+
113 251
 }

+ 0 - 23
src/main/java/com/sjls/nstthh/util/SaticScheduleTask.java

@@ -1,23 +0,0 @@
1
-package com.sjls.nstthh.util;
2
-
3
-import com.sjls.nstthh.service.NRJavaSerialManager;
4
-import org.springframework.context.annotation.Configuration;
5
-import org.springframework.scheduling.annotation.EnableScheduling;
6
-
7
-@Configuration
8
-@EnableScheduling
9
-public class SaticScheduleTask {
10
-    //3.添加定时任务
11
-    // 每天的18点、21点都执行一次:0 0 09,18 * * ?
12
-    //@Scheduled(cron = "0 0 09,18 * * ?")
13
-    //或直接指定时间间隔,例如:5秒
14
-    //@Scheduled(fixedRate=5000)
15
-    private void configureTasks() {
16
-        // /dev/ttyUSB0
17
-        String port = "/dev/tty.usbserial-14130";
18
-
19
-        new NRJavaSerialManager().connect();
20
-
21
-        //System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
22
-    }
23
-}

+ 68 - 30
src/main/java/com/sjls/nstthh/util/SnowflakeIdWorker.java

@@ -1,5 +1,6 @@
1 1
 package com.sjls.nstthh.util;
2
- /**
2
+
3
+/**
3 4
  * Twitter_Snowflake<br>
4 5
  * SnowFlake的结构如下(每部分用-分开):<br>
5 6
  * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
@@ -14,52 +15,82 @@ package com.sjls.nstthh.util;
14 15
 public class SnowflakeIdWorker {
15 16
 
16 17
     // ==============================Fields===========================================
17
-    /** 开始时间截 (2015-01-01) */
18
+    /**
19
+     * 开始时间截 (2015-01-01)
20
+     */
18 21
     private final long twepoch = 1420041600000L;
19 22
 
20
-    /** 机器id所占的位数 */
23
+    /**
24
+     * 机器id所占的位数
25
+     */
21 26
     private final long workerIdBits = 5L;
22 27
 
23
-    /** 数据标识id所占的位数 */
28
+    /**
29
+     * 数据标识id所占的位数
30
+     */
24 31
     private final long datacenterIdBits = 5L;
25 32
 
26
-    /** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */
33
+    /**
34
+     * 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数)
35
+     */
27 36
     private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
28 37
 
29
-    /** 支持的最大数据标识id,结果是31 */
38
+    /**
39
+     * 支持的最大数据标识id,结果是31
40
+     */
30 41
     private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
31 42
 
32
-    /** 序列在id中占的位数 */
43
+    /**
44
+     * 序列在id中占的位数
45
+     */
33 46
     private final long sequenceBits = 12L;
34 47
 
35
-    /** 机器ID向左移12位 */
48
+    /**
49
+     * 机器ID向左移12
50
+     */
36 51
     private final long workerIdShift = sequenceBits;
37 52
 
38
-    /** 数据标识id向左移17位(12+5) */
53
+    /**
54
+     * 数据标识id向左移17位(12+5)
55
+     */
39 56
     private final long datacenterIdShift = sequenceBits + workerIdBits;
40 57
 
41
-    /** 时间截向左移22位(5+5+12) */
58
+    /**
59
+     * 时间截向左移22位(5+5+12)
60
+     */
42 61
     private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
43 62
 
44
-    /** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */
63
+    /**
64
+     * 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095)
65
+     */
45 66
     private final long sequenceMask = -1L ^ (-1L << sequenceBits);
46 67
 
47
-    /** 工作机器ID(0~31) */
48
-    private long workerId;
68
+    /**
69
+     * 工作机器ID(0~31)
70
+     */
71
+    private final long workerId;
49 72
 
50
-    /** 数据中心ID(0~31) */
51
-    private long datacenterId;
73
+    /**
74
+     * 数据中心ID(0~31)
75
+     */
76
+    private final long datacenterId;
52 77
 
53
-    /** 毫秒内序列(0~4095) */
78
+    /**
79
+     * 毫秒内序列(0~4095)
80
+     */
54 81
     private long sequence = 0L;
55 82
 
56
-    /** 上次生成ID的时间截 */
83
+    /**
84
+     * 上次生成ID的时间截
85
+     */
57 86
     private long lastTimestamp = -1L;
58 87
 
59 88
     //==============================Constructors=====================================
89
+
60 90
     /**
61 91
      * 构造函数
62
-     * @param workerId 工作ID (0~31)
92
+     *
93
+     * @param workerId     工作ID (0~31)
63 94
      * @param datacenterId 数据中心ID (0~31)
64 95
      */
65 96
     public SnowflakeIdWorker(long workerId, long datacenterId) {
@@ -74,8 +105,23 @@ public class SnowflakeIdWorker {
74 105
     }
75 106
 
76 107
     // ==============================Methods==========================================
108
+
109
+    /**
110
+     * 测试
111
+     */
112
+    public static void main(String[] args) {
113
+        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
114
+
115
+        for (int i = 0; i < 100; i++) {
116
+            long id = idWorker.nextId();
117
+            System.out.println(Long.toBinaryString(id));
118
+            System.out.println(id);
119
+        }
120
+    }
121
+
77 122
     /**
78 123
      * 获得下一个ID (该方法是线程安全的)
124
+     *
79 125
      * @return SnowflakeId
80 126
      */
81 127
     public synchronized long nextId() {
@@ -113,6 +159,7 @@ public class SnowflakeIdWorker {
113 159
 
114 160
     /**
115 161
      * 阻塞到下一个毫秒,直到获得新的时间戳
162
+     *
116 163
      * @param lastTimestamp 上次生成ID的时间截
117 164
      * @return 当前时间戳
118 165
      */
@@ -124,23 +171,14 @@ public class SnowflakeIdWorker {
124 171
         return timestamp;
125 172
     }
126 173
 
174
+    //==============================Test=============================================
175
+
127 176
     /**
128 177
      * 返回以毫秒为单位的当前时间
178
+     *
129 179
      * @return 当前时间(毫秒)
130 180
      */
131 181
     protected long timeGen() {
132 182
         return System.currentTimeMillis();
133 183
     }
134
-
135
-    //==============================Test=============================================
136
-    /** 测试 */
137
-    public static void main(String[] args) {
138
-        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
139
-
140
-        for (int i = 0; i < 100; i++) {
141
-            long id = idWorker.nextId();
142
-            System.out.println(Long.toBinaryString(id));
143
-            System.out.println(id);
144
-        }
145
-    }
146 184
 }

+ 2 - 5
src/main/java/com/sjls/nstthh/util/StrSplicingAssistant.java

@@ -2,9 +2,6 @@ package com.sjls.nstthh.util;
2 2
 
3 3
 public class StrSplicingAssistant {
4 4
 
5
-    private static final String hexString = "0123456789ABCDEF";
6
-
7
-
8 5
     /**
9 6
      * 逆序校验
10 7
      *
@@ -83,6 +80,7 @@ public class StrSplicingAssistant {
83 80
         }
84 81
         return sb.toString().trim().toUpperCase();
85 82
     }
83
+
86 84
     /*显示完美*/
87 85
     public static final String toHex(byte[] data, int off, int length) {
88 86
         // double size, two bytes (hex range) for one byte
@@ -99,6 +97,7 @@ public class StrSplicingAssistant {
99 97
         }
100 98
         return buf.toString().trim().toUpperCase();
101 99
     }
100
+
102 101
     /**
103 102
      * 10进制 转 16进制
104 103
      *
@@ -110,8 +109,6 @@ public class StrSplicingAssistant {
110 109
     }
111 110
 
112 111
 
113
-
114
-
115 112
     /**
116 113
      * 高低位转换 大写
117 114
      * 如“1A2B”转“2B1A”。

+ 6 - 25
src/main/resources/application.yml

@@ -1,43 +1,24 @@
1 1
 server:
2 2
   port: 8080
3
-management:
4
-  endpoint:
5
-    shutdown:
6
-      enabled: true
7
-  endpoints:
8
-    web:
9
-      exposure:
10
-        include: shutdown
11
-# DataSource Config
12 3
 spring:
13 4
   datasource:
14
-    driver-class-name: org.h2.Driver
15
-    url: jdbc:h2:~/nstthh;AUTO_SERVER=TRUE
16
-    username: sa
5
+    driver-class-name: com.mysql.cj.jdbc.Driver
6
+    username: root
17 7
     password: 123456
8
+    ## Edge-dongtian
9
+    url: jdbc:mysql://192.168.40.74:3306/nstthh?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
18 10
   jpa:
19 11
     show-sql: false
20
-    open-in-view: false
12
+    open-in-view : false
21 13
     hibernate:
22 14
       ddl-auto: update
23
-  h2:
24
-    console:
25
-      path: /h2-console
26
-      enabled: true
27 15
   thymeleaf:
28 16
     cache: false
29
-    mode: HTML5
30
-
17
+    mode: HTML
31 18
   mqtt:
32
-    #MQTT-服务端账号
33 19
     username: admin
34
-    #MQTT-服务端密码
35 20
     password: public
36
-    #MQTT-服务端地址
37 21
     url: tcp://192.168.50.169:1883
38
-    #MQTT-发布者clientid
39 22
     publishclientid: client_publish
40
-    #MQTT-接收者clientid
41 23
     subsribeclientid: client_subsribe
42
-    #MQTT-默认主题
43 24
     default_topic: test

+ 94 - 0
src/main/resources/sh/app_boot.sh

@@ -0,0 +1,94 @@
1
+#!/bin/sh
2
+## java env
3
+#export JAVA_HOME=/usr/local/jdk/jdk1.8.0_101
4
+#export JRE_HOME=$JAVA_HOME/jre
5
+
6
+API_NAME=api
7
+JAR_NAME=$API_NAME\.jar
8
+#PID  代表是PID文件
9
+PID=$API_NAME\.pid
10
+
11
+#使用说明,用来提示输入参数
12
+usage() {
13
+    echo "Usage: sh 执行脚本.sh [start|stop|restart|status]"
14
+    exit 1
15
+}
16
+
17
+#检查程序是否在运行
18
+is_exist(){
19
+  pid=`ps -ef|grep $JAR_NAME|grep -v grep|awk '{print $2}' `
20
+  #如果不存在返回1,存在返回0
21
+  if [ -z "${pid}" ]; then
22
+   return 1
23
+  else
24
+    return 0
25
+  fi
26
+}
27
+
28
+#启动方法
29
+start(){
30
+  is_exist
31
+  if [ $? -eq "0" ]; then
32
+    echo ">>> ${JAR_NAME} is already running PID=${pid} <<<"
33
+  else
34
+    nohup $JRE_HOME/bin/java -Xms256m -Xmx512m -jar $JAR_NAME >/dev/null 2>&1 &
35
+    echo $! > $PID
36
+    echo ">>> start $JAR_NAME successed PID=$! <<<"
37
+   fi
38
+  }
39
+
40
+#停止方法
41
+stop(){
42
+  #is_exist
43
+  pidf=$(cat $PID)
44
+  #echo "$pidf"
45
+  echo ">>> api PID = $pidf begin kill $pidf <<<"
46
+  kill $pidf
47
+  rm -rf $PID
48
+  sleep 2
49
+  is_exist
50
+  if [ $? -eq "0" ]; then
51
+    echo ">>> api 2 PID = $pid begin kill -9 $pid  <<<"
52
+    kill -9  $pid
53
+    sleep 2
54
+    echo ">>> $JAR_NAME process stopped <<<"
55
+  else
56
+    echo ">>> ${JAR_NAME} is not running <<<"
57
+  fi
58
+}
59
+
60
+#输出运行状态
61
+status(){
62
+  is_exist
63
+  if [ $? -eq "0" ]; then
64
+    echo ">>> ${JAR_NAME} is running PID is ${pid} <<<"
65
+  else
66
+    echo ">>> ${JAR_NAME} is not running <<<"
67
+  fi
68
+}
69
+
70
+#重启
71
+restart(){
72
+  stop
73
+  start
74
+}
75
+
76
+#根据输入参数,选择执行对应方法,不输入则执行使用说明
77
+case "$1" in
78
+  "start")
79
+    start
80
+    ;;
81
+  "stop")
82
+    stop
83
+    ;;
84
+  "status")
85
+    status
86
+    ;;
87
+  "restart")
88
+    restart
89
+    ;;
90
+  *)
91
+    usage
92
+    ;;
93
+esac
94
+exit 0

+ 1 - 1
src/main/resources/templates/nstthh.html

@@ -5,6 +5,6 @@
5 5
     <title>Title</title>
6 6
 </head>
7 7
 <body>
8
-<div th:text="${message}" ></div>
8
+<div th:text="${message}"></div>
9 9
 </body>
10 10
 </html>

+ 1 - 22
src/test/java/com/sjls/nstthh/RepositoryTest.java

@@ -1,16 +1,12 @@
1 1
 package com.sjls.nstthh;
2 2
 
3 3
 
4
-import com.sjls.nstthh.entity.SendData;
5 4
 import com.sjls.nstthh.repository.SendDataRepository;
6
-import com.sjls.nstthh.util.AlgAlgorithm;
7 5
 import org.junit.runner.RunWith;
8 6
 import org.springframework.beans.factory.annotation.Autowired;
9 7
 import org.springframework.boot.test.context.SpringBootTest;
10 8
 import org.springframework.test.context.junit4.SpringRunner;
11 9
 
12
-import static com.sjls.nstthh.TestNstthh.send16strUseCom;
13
-
14 10
 @SpringBootTest
15 11
 @RunWith(SpringRunner.class)
16 12
 public class RepositoryTest {
@@ -19,25 +15,8 @@ public class RepositoryTest {
19 15
     private SendDataRepository sendDataRepository;
20 16
 
21 17
     //@Test
22
-    public void addSendStr() {
23
-        String str = AlgAlgorithm.getAveragePosition();
24
-        String[] strArr_z_y = str.split(";");
25
-
26
-        for (int i = 0; i < strArr_z_y.length; i++) {
27
-
28
-            String[] strArr = strArr_z_y[i].split(",");
29
-
18
+    public void test() {
30 19
 
31
-            //System.out.println(Long.valueOf(strArr[0]));  System.out.println(Long.valueOf(strArr[1]));
32
-            String str10 = send16strUseCom(Long.valueOf(strArr[0]), Long.valueOf(strArr[1]));
33
-            System.out.println("sendStr.add(\"" + str10 + "\");");
34
-            SendData SendData = new SendData();
35
-            SendData.setSendStr(str10);
36
-            String deviceid = str10.substring(18, 26);//截取设备id
37
-            String anglezy = str10.substring(38, 46);//角度
38
-            SendData.setSendKey(deviceid + anglezy);
39
-            sendDataRepository.save(SendData);
40
-        }
41 20
     }
42 21
 
43 22
 

+ 1 - 1
src/test/java/com/sjls/nstthh/TestNstthh.java

@@ -12,7 +12,7 @@ public class TestNstthh {
12 12
 
13 13
     public static void main(String[] args) throws IOException {
14 14
 
15
-        String str10 = send16strUseCom( 1500, 1500);
15
+        String str10 = send16strUseCom(1500, 1500);
16 16
         System.out.println(str10);
17 17
 
18 18
     }