CanadaMes-ui/src/router/index.js | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
CanadaMes-ui/src/views/device/talkvue.vue | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
springboot-vue3/pom.xml | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
springboot-vue3/src/main/java/com/example/springboot/component/PlcHold.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
springboot-vue3/src/main/java/com/example/springboot/component/S7control.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
springboot-vue3/src/main/java/com/example/springboot/component/WebSocketServer.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
springboot-vue3/src/main/java/com/example/springboot/config/AppRunnerConfig.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
springboot-vue3/src/main/java/com/example/springboot/config/WebSocketConfig.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 |
CanadaMes-ui/src/router/index.js
@@ -49,6 +49,11 @@ }, { path: '/device/talk', component: () => import('../views/device/talkvue'), }, { path: '/device/alarm', component: () => import('../views/device/alarm') }, CanadaMes-ui/src/views/device/talkvue.vue
New file @@ -0,0 +1,69 @@ <template> <!-- <button v-on:click="send">测试发送</button> --> <button @click="send()">测试发送</button> </template> <script> let socket; export default { name: "talkvue", data() { return { messagepack: { data: { taskname:"" } }, queryInfo: { data: "1", pageSize: 10 }, }; }, created() { this.init(); }, methods: { init() { let viewname = "talkvue"; if (typeof (WebSocket) == "undefined") { console.log("您的浏览器不支持WebSocket"); } else { //console.log("您的浏览器支持WebSocket"); let socketUrl = "ws://" + "localhost:8888" + "/springboot-vue3/api/talk/" + viewname; if (socket != null) { socket.close(); socket = null; } // 开启一个websocket服务 socket = new WebSocket(socketUrl); //打开事件 socket.onopen = function () { console.log("websocket已打开"); }; // 浏览器端收消息,获得从服务端发送过来的文本消息 socket.onmessage = function (msg) { console.log("收到数据====" + msg.data) //let data = JSON.parse(msg.data) // 对收到的json数据进行解析, 类似这样的: {"users": [{"username": "zhang"},{ "username": "admin"}]} }; //关闭事件 socket.onclose = function () { console.log("websocket已关闭"); }; //发生了错误事件 socket.onerror = function () { console.log("websocket发生了错误"); } } }, send() { this.messagepack.data = {taskname:"前端到后台"} ; socket?.send(JSON.stringify(this.messagepack)); // 将组装好的json发送给服务端,由服务端进行转发 } } } </script> springboot-vue3/pom.xml
File was deleted springboot-vue3/src/main/java/com/example/springboot/component/PlcHold.java
New file @@ -0,0 +1,36 @@ package com.example.springboot.component; import java.util.List; import javax.websocket.Session; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; public class PlcHold extends Thread { @Override public void run() { while (this != null) { try { Thread.sleep(15000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } List<Boolean> bitlist = S7control.getinstance().ReadBits("DB2.0.0", 100); List<Short> paramlist = S7control.getinstance().ReadWord("DB100.6", 1); //查询数据库 //推送到前端 JSONObject jsonObject = new JSONObject(); jsonObject.append("params", new short[] { 0, 1, 2, 3, 4, 5, }); WebSocketServer sendwServer = WebSocketServer.sessionMap.get("talkvue"); if (sendwServer != null) { sendwServer.sendMessage(jsonObject.toString()); } } } } springboot-vue3/src/main/java/com/example/springboot/component/S7control.java
New file @@ -0,0 +1,219 @@ package com.example.springboot.component; import java.util.ArrayList; import java.util.List; import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType; import com.github.xingshuangs.iot.protocol.s7.service.MultiAddressWrite; import com.github.xingshuangs.iot.protocol.s7.service.S7PLC; public class S7control { S7PLC s7PLC; // PLC通讯类实例 private EPlcType plcType = EPlcType.S1200; // 西门子PLC类型 private String ip = "127.0.0.1"; // plc ip地址 private int port = 21; // plc 端口号 private static volatile S7control instance = null; private S7control() { if (s7PLC == null) s7PLC = new S7PLC(plcType, ip, port); } // 单例模式 获取类的唯一实例 public static S7control getinstance() { if (instance == null) { synchronized (S7control.class) { if (instance == null) instance = new S7control(); } } return instance; } /** * 关闭西门子s7通讯连接 */ public void CloseS7client() { if (s7PLC == null) s7PLC.close(); } /** * 按指定的地址 写入一个word * * @param address 地址 * @param data word的值 */ public void WriteWord(String address, short data) { if (!s7PLC.checkConnected()) return; s7PLC.writeInt16(address, data); } /** * 从某地址连续 写入多个word * * @param address 地址 * @param datas word的值 */ public void WriteWord(String address, List<Short> datas) { if (!s7PLC.checkConnected()) return; // s7PLC.write(address, data); List<String> addresslist = GetAddressList(address, datas.size(), 16); MultiAddressWrite addressWrite = new MultiAddressWrite(); for (int i = 0; i < datas.size(); i++) { addressWrite.addInt16(addresslist.get(i), datas.get(i)); } s7PLC.writeMultiData(addressWrite); } /** * 按指定的地址 写入多个word * * @param address 地址 * @param datas word的值 */ public void WriteWord(List<String> address, List<Short> datas) { if (!s7PLC.checkConnected()) return; // s7PLC.write(address, data); MultiAddressWrite addressWrite = new MultiAddressWrite(); for (int i = 0; i < address.size(); i++) { addressWrite.addInt16(address.get(i), datas.get(i)); } s7PLC.writeMultiData(addressWrite); } /** * 按指定的地址 写入一个Bit * * @param address 地址 * @param data Bit的值 */ public void WriteBit(String address, Boolean data) { if (!s7PLC.checkConnected()) return; s7PLC.writeBoolean(address, data); } /** * 按指定的地址 写入多个bit * * @param address 地址 * @param datas bit的值 */ public void WriteBit(List<String> address, List<Boolean> datas) { if (!s7PLC.checkConnected()) return; // s7PLC.write(address, data); MultiAddressWrite addressWrite = new MultiAddressWrite(); for (int i = 0; i < address.size(); i++) { addressWrite.addBoolean(address.get(i), datas.get(i)); } s7PLC.writeMultiData(addressWrite); } /** * 从某地址连续 写入多个bit * * @param address 地址 * @param datas word的值 */ public void WriteBit(String address, List<Boolean> datas) { if (!s7PLC.checkConnected()) return; // s7PLC.write(address, data); List<String> addresslist = GetAddressList(address, datas.size(), 1); MultiAddressWrite addressWrite = new MultiAddressWrite(); for (int i = 0; i < datas.size(); i++) { addressWrite.addBoolean(addresslist.get(i), datas.get(i)); } s7PLC.writeMultiData(addressWrite); } /** * 按指定的地址 读取word结果集 * * @param address 地址 * @return 结果 */ public List<Short> ReadWord(List<String> address) { if (!s7PLC.checkConnected()) return null; return s7PLC.readInt16(address); } /** * 按指定的地址 读取word结果集 * * @param address 地址 * @param count 连续读多少个word * @return 结果 */ public List<Short> ReadWord(String address, int count) { if (!s7PLC.checkConnected()) return null; List<String> addresslist = GetAddressList(address, count, 16); return s7PLC.readInt16(addresslist); } /** * 按指定的地址 按bit位 0 flase 1 true 读取结果 * * @param addresslist 地址集 * @return Boolean结果 */ public List<Boolean> ReadBits(List<String> addresslist) { if (!s7PLC.checkConnected()) return null; return s7PLC.readBoolean(addresslist); } /** * 从指定的地址开始 连续按bit位读取 * * @param address 地址 * @param count 长度 * @return Boolean结果 */ public List<Boolean> ReadBits(String address, int count) { if (!s7PLC.checkConnected()) return null; List<String> addresslist = GetAddressList(address, count, 1); return s7PLC.readBoolean(addresslist); } private List<String> GetAddressList(String address, int count, int addedbit) { List<String> addresslist = new ArrayList<>(); String[] stringdatas = address.split("."); if (stringdatas.length < 2 || !address.startsWith("DB")) return null; int dbwindex = 0; int bitindex = 0; if (stringdatas.length == 2) { dbwindex = Integer.parseInt(stringdatas[1]); } else if (stringdatas.length == 3) { bitindex = Integer.parseInt(stringdatas[2]); } else return null; for (int i = 0; i < count; i++) { int bitcurrent = bitindex + addedbit; if (bitcurrent > 7) { dbwindex += bitcurrent / 8; bitindex = 0; } else bitindex = bitcurrent; addresslist.add(stringdatas[0] + "." + dbwindex + "." + bitindex); } return addresslist; } } springboot-vue3/src/main/java/com/example/springboot/component/WebSocketServer.java
New file @@ -0,0 +1,118 @@ package com.example.springboot.component; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import org.springframework.stereotype.Component; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; @ServerEndpoint(value = "/api/talk/{username}") @Component public class WebSocketServer { private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class); /** * 记录当前在线连接数 */ public static final Map<String, WebSocketServer> sessionMap = new ConcurrentHashMap<>(); private String username; private Session session; /** * 连接建立成功调用的方法 */ @OnOpen public void onOpen(Session session, @PathParam("username") String username) { this.username=username; this.session=session; sessionMap.put(username, this); log.info("有新用户加入,username={}, 当前在线人数为:{}", username, sessionMap.size()); // JSONObject result = new JSONObject(); // JSONArray array = new JSONArray(); // result.set("users", array); // for (Object key : sessionMap.keySet()) { // JSONObject jsonObject = new JSONObject(); // jsonObject.set("username", key); // array.add(jsonObject); // } //sendAllMessage(JSONUtil.toJsonStr(result)); // 后台发送消息给所有的客户端 } /** * 连接关闭调用的方法 */ @OnClose public void onClose(Session session, @PathParam("username") String username) { sessionMap.remove(username); log.info("有一连接关闭,移除username={}的用户session, 当前在线人数为:{}", username, sessionMap.size()); } /** * 收到客户端消息后调用的方法 * 后台收到客户端发送过来的消息 * onMessage 是一个消息的中转站 * 接受 浏览器端 socket.send 发送过来的 json数据 * @param message 客户端发送过来的消息 */ @OnMessage public void onMessage(String message, Session session, @PathParam("username") String username) { log.info("服务端收到用户username={}的消息:{}", username, message); JSONObject obj = JSONUtil.parseObj(message); String text = obj.getStr("data"); JSONObject jsonObject = new JSONObject(); jsonObject.set("message", "ngng"); this.sendMessage(jsonObject.toString()); //JSONUtil.toJsonStr(jsonObject) } @OnError public void onError(Session session, Throwable error) { log.error("发生错误"); error.printStackTrace(); } /** * 服务端发送消息给客户端 */ public void sendMessage(String message) { try { log.info("服务端给客户端[{}]发送消息{}", this.session.getId(), message); this.session.getBasicRemote().sendText(message); } catch (Exception e) { log.error("服务端发送消息给客户端失败", e); } } /** * 服务端发送消息给所有客户端 */ public void sendAllMessage(String message) { try { for (WebSocketServer webSocketServer : sessionMap.values()) { log.info("服务端给客户端[{}]发送消息{}", this.session.getId(), message); webSocketServer.sendMessage(message); } } catch (Exception e) { log.error("服务端发送消息给客户端失败", e); } } } springboot-vue3/src/main/java/com/example/springboot/config/AppRunnerConfig.java
New file @@ -0,0 +1,21 @@ package com.example.springboot.config; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import com.example.springboot.component.PlcHold; @Component @Order(1) public class AppRunnerConfig implements ApplicationRunner{ @Override public void run(ApplicationArguments args) throws Exception { // TODO Auto-generated method stub // System.out.println("启动完成"); new PlcHold().start(); } } springboot-vue3/src/main/java/com/example/springboot/config/WebSocketConfig.java
New file @@ -0,0 +1,16 @@ package com.example.springboot.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }