/// <summary> /// 串口初始化 /// </summary> public void SerialPortInitial() { try { serialPort = new SerialPort(); serialPort.PortName = serialCfg.PortName; //串口号 serialPort.BaudRate = serialCfg.PortBaudRate; //波特率 serialPort.DataBits = serialCfg.PortDataBits; //数据位 serialPort.StopBits = serialCfg.PortStopBits; serialPort.Parity = serialCfg.PortParity; //准备就绪 serialPort.DtrEnable = true; serialPort.RtsEnable = true; serialPort.ReadTimeout = 5000;//设置数据读取超时为5秒 serialPort.Open(); if (serialCfg.ReadCommand.Length > 0)//存在周期读取命令 { cycTask = new Thread(CycSendCommand); cycTask.IsBackground = true; cycTask.Start(); } serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceived); } catch (Exception ex) { _log.WriteLog("串口打开出错", ex); } }
//public HttpClientFactoryHelper(IHttpClientFactory httpClientFactory) //{ // _clientFactory = httpClientFactory; //} /// <summary> /// 获取对象数据。请注意,此方法请求,对方必须直接回json对象,否则会请求失败 /// </summary> /// <typeparam name="T">对象</typeparam> /// <param name="url">请求的url</param> /// <param name="postData">消息内容</param> /// <param name="method">请求方法</param> /// <param name="authorization">授权</param> /// <returns>返回的对象</returns> public async Task <T> GetJsonResult <T>(string url, string postData, HttpMethod method, string authorization = null) { T resp = default(T); try { if (_log != null) { _log.WriteLog($"GetJsonResult请求,url={url}"); } var request = new HttpRequestMessage(method, url); //判断是否需要认证 if (!string.IsNullOrEmpty(authorization)) { request.Headers.Add("Authorization", authorization); } var client = _clientFactory.CreateClient(); HttpResponseMessage response; if (!string.IsNullOrEmpty(postData)) { HttpContent httpContent = new StringContent(postData, Encoding.UTF8); httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); request.Content = httpContent; } response = await client.SendAsync(request); if (response != null && response.IsSuccessStatusCode) { resp = await response.Content.ReadAsAsync <T>(); return(resp); } else { _log.WriteLog("HttpClientFactoryHelper", "GetJsonResult", $"GetJsonResult失败,url={url},error={response.ReasonPhrase}"); return(resp); } } catch (Exception ex) { if (_log != null) { _log.WriteLog($"GetJsonResult请求错误,url={url}", ex); } } finally { //LogHelper.Info($"MyHttpClientHelper结束,url={client.BaseAddress},action={Utils.GetEnumDescription(action)},postData={paramStr} ,jrclientguid={jrclientguid}---------"); } return(resp); }
/// <summary> /// mqtt消息接收处理 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RabbitMQClientHandler_MessageReceivedRaised(object sender, EventArgs e) { MqttMsgArgs mqttMsgArgs = e as MqttMsgArgs; try { MqttDispatchInfo dispatchTaskMqtt = JsonConvert.DeserializeObject <MqttDispatchInfo>(mqttMsgArgs.Content); if (dispatchTaskMqtt != null) { if (dispatchTaskMqtt.client_id.Contains(ClientInfoViewModel.client_id))//派送到本地客户端 { _log.WriteLog($"接收到mqtt派送信息{dispatchTaskMqtt.content_id}"); if (dispatchTaskMqtt.type == 0)//排程信息 { LoadSchedule(dispatchTaskMqtt.content_id); } else//插播试播的节目信息 { LoadProgrammeInfo(dispatchTaskMqtt.content_id); } } } } catch (Exception ex) { _log.WriteLog($"mqtt派送信息处理出错", ex); } rabbitMQClientHandler.RejectQueueMsg(mqttMsgArgs.DeliveryTag, false);//确认消息,否则下次不会再次发送消息过来 }
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { try { e.Handled = true; //把 Handled 属性设为true,表示此异常已处理,程序可以继续运行,不会强制退出 log.WriteLog("捕获App_DispatcherUnhandledException未处理异常", e.Exception); } catch (Exception ex) { log.WriteLog($"程序发生致命错误,将终止{ ex.Message}"); } }
public IActionResult ValidateToken([FromBody] string AuthToken)//验证token结果 { string token = AuthToken; if (token.Contains("Bearer")) { token = token.Replace("Bearer", string.Empty); token = token.Trim(); } _logWrite.WriteLog("Token", "ValidateToken", "请求验证token"); TokenAuthorizeInfo tokenParseResult = _tokenService.ValidateToken(token); return(new JsonResult(tokenParseResult)); }
/// <summary> /// 新增状态 /// </summary> /// <param name="Content"></param> /// <param name="logTypeEnum"></param> /// <param name="IsRecordToFile"></param> public void AddMewStatus(string Content, LogTypeEnum logTypeEnum = LogTypeEnum.Info, bool IsRecordToFile = true) { if (operatesCollection.Count >= 500) { ObservableCollectionHelper.ClearItem <OperateStatus>(operatesCollection); } OperateStatus operateStatus = new OperateStatus(Content, logTypeEnum); ObservableCollectionHelper.InsertItem <OperateStatus>(operatesCollection, operateStatus);//增加记录 if (IsRecordToFile) { _log.WriteLog(Content); } if (logTypeEnum == LogTypeEnum.Error) { GlobalData.ErrMsgObject.SendErrorMessage(Content);//错误消息自动弹窗 } }
/// <summary> /// http Post /// </summary> /// <param name="url">url</param> /// <param name="postData">抛送参数</param> /// <param name="contentType">默认json</param> /// <param name="authorization">token</param> /// <returns></returns> public string HttpPost(string url, string postData, string contentType = "application/json;charset=UTF-8", string authorization = null) { string result = string.Empty; try { HttpWebRequest _reques = (HttpWebRequest)WebRequest.Create(url); _reques.Method = "POST"; _reques.Timeout = 5000; //判断是否需要认证 if (!string.IsNullOrEmpty(authorization)) { _reques.Headers.Add("Authorization", authorization); } //设定ContentType _reques.ContentType = contentType; _reques.ContentLength = 0; if (!string.IsNullOrEmpty(postData)) { byte[] data = Encoding.UTF8.GetBytes(postData); _reques.ContentLength = data.Length; using (Stream reqStream = _reques.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } } HttpWebResponse resp = (HttpWebResponse)_reques.GetResponse(); Stream stream = resp.GetResponseStream(); //获取响应内容 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } } catch (Exception ex) { _log.WriteLog("HttpPost错误", ex); } return(result); }
/// <summary> /// http下载文件 /// </summary> /// <param name="url">文件地址</param> /// <param name="path">下载后的本地目录</param> /// <returns></returns> public bool HttpDownloadFileAsync(string url, string path) { bool res = true; try { // 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); FileInfo fileInfo = new FileInfo(path); if (fileInfo.Exists)//文件存在则删除 { fileInfo.Delete(); } if (!fileInfo.Directory.Exists)//文件目录不存在创建 { fileInfo.Directory.Create(); } //创建本地文件写入流 Stream stream = new FileStream(path, FileMode.Create); byte[] byteArr = new byte[1024]; int size = responseStream.Read(byteArr, 0, (int)byteArr.Length); while (size > 0) { stream.Write(byteArr, 0, size); size = responseStream.Read(byteArr, 0, (int)byteArr.Length); } stream.Close(); responseStream.Close(); _log.WriteLog($"文件{path}下载成功"); } catch (Exception ex) { _log.WriteLog("文件下载失败", ex); res = false; } return(res); }
public bool WriteValue(string Address, short value) { OperateResult res = _deviceDriver.Write(Address, value); if (res.IsSuccess) { return(true); } else { _log.WriteLog($"modbus{_device.Ip}写入地址{Address}值{value}失败"); return(false); } }
/// <summary> /// 设置服务和启动 /// </summary> /// <param name="pLCGroupService"></param> /// <param name="tagService"></param> /// <param name="logWriteObj"></param> public static void SetService(IDatabaseTagGroupService plcGroupService, IDatabaseTagService tagService, ILogWrite logWriteObj) { _plcGroupService = plcGroupService; _tagService = tagService; logWrite = logWriteObj; if (!HslCommunication.Authorization.SetAuthorizationCode("2487cfb8-334f-4b04-bd32-122453cfeb37")) { logWriteObj.WriteLog("访问驱动激活失败"); } LoadTags(); }
/// <summary> /// 查询服务器配置,获取节目列表信息 /// </summary> public void GetMediaFileInfo(int media_id) { string body = string.Empty; string url = ServerCfg.FileServerAddr + $"/file/MediaInfo?id={media_id}"; string res = _httpRequest.HttpGet(url); List <MediaInfo> _mediaInfo = JsonConvert.DeserializeObject <List <MediaInfo> >(res); if (_mediaInfo != null) { if (FileCheck(_mediaInfo[0])) { FilesQueue.Enqueue(_mediaInfo[0].media_address);//将信息中的地址加入下载队列 } else { _log.WriteLog($"文件{_mediaInfo[0].media_address}大小无变化,跳过下载"); } } else { _log.WriteLog($"请求节目信息为空{media_id}"); } }
/// <summary> /// 启动 /// </summary> public void Start() { _device.IsConnected = true; if (tcpListener != null) { tcpListener.Stop(); tcpListener = null; } try { this.tcpListener = new TcpListener(serverAddress, serverPort); tcpListener.Start(); tokenSource = new CancellationTokenSource(); if (this.listenTask == null || this.listenTask.Status != TaskStatus.Running) { this.listenTask = Task.Factory.StartNew(() => ListenForClients(), tokenSource.Token);//TaskCreationOptions.LongRunning, } } catch (Exception ex) { _log.WriteLog("TcpServer启动错误", ex); } }
public PLCScanTask(PLCDevice plcDevice, ILogWrite logWrite) { _log = logWrite; PlcDevice = plcDevice; try { switch (plcDevice.Type) { case PLCType.Simens1200: case PLCType.Simens1500: case PLCType.Simens300: case PLCType.Simens200Smart: plcDriverHelper = new SimensPLCHelper(plcDevice, _log); //指定为西门子PLC连接 break; case PLCType.Omron: plcDriverHelper = new OmronPLCHelper(plcDevice, _log); //指定为欧姆龙PLC连接 break; case PLCType.Fx: plcDriverHelper = new FxPLCHelper(plcDevice, _log); //指定为三菱PLC连接 break; case PLCType.Modbus: plcDriverHelper = new ModbusTcpHelper(plcDevice, _log); //指定为Modbus连接(Robot机械手) break; case PLCType.TcpServer: plcDriverHelper = new TcpServer(plcDevice, _log); //指定为Modbus连接(Robot机械手) break; default: //默认西门子 plcDriverHelper = new SimensPLCHelper(plcDevice, _log); //指定为西门子PLC连接 break; } } catch (Exception ex) { _log.WriteLog(ex.Message); } }
private void Application_Startup(object sender, StartupEventArgs e) { GlobalData.LoadSettings(); //加载参数 IoC.SetupIoC(); //IoC容器启用 log = IoC.Get <ILogWrite>(); var service1 = IoC.Get <IDatabaseTagGroupService>(); var service2 = IoC.Get <IDatabaseTagService>(); PLCManager.SetService(service1, service2, log); log.WriteLog("程序启动"); UserViewService.LoadLoginWindow(); Application.Current.Exit += Current_Exit; //UI线程未捕获异常处理事件 this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException); //Task线程内未捕获异常处理事件 TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; //非UI线程未捕获异常处理事件 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); }
/// <summary> /// 连接对象 /// </summary> /// <returns></returns> public bool Connect() { try { IPAddress ipAddress = IPAddress.Parse(socketCfg.Ip); IPEndPoint remoteEP = new IPEndPoint(ipAddress, socketCfg.Port); // Create a TCP/IP socket. socketClient = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Connect to the remote endpoint. socketClient.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), socketClient); connectDone.WaitOne(3000); return(true); } catch (Exception ex) { _log.WriteLog("AsynTcpClient connect error=" + ex.Message); } return(false); }
/// <summary> /// 节目播放 /// </summary> public override void ProgramPlay() { int disDelay = 0;//播放延时 while (!StopBit) { if (PauseBit) { Thread.Sleep(1000); continue; } if (programRegion.MediaList.Count > 0) { ProgramRegionMedia media = playList[this.PlayIndex]; if (PresentUIElement == null)//未加载组件 { MediaInfo mediaInfo = mediaInfoService.QueryableToEntity(x => x.id == media.media_id); if (mediaInfo != null) { string mediaPath = LocalPath + mediaInfo.serial_number; FileType mediaType = (FileType)Enum.Parse(typeof(FileType), mediaInfo.media_type, true); _logWrite.WriteLog($"加入组件"); switch (mediaType) { case FileType.image: canvasLayout.Dispatcher.Invoke(new Action(() => { PresentUIElement = canvasLayout.AddImageComponent(mediaPath, programRegion, false); })); break; case FileType.pdf: canvasLayout.Dispatcher.Invoke(new Action(() => { PresentUIElement = canvasLayout.AddPdfComponent(mediaPath, programRegion, false); })); break; case FileType.video: canvasLayout.Dispatcher.Invoke(new Action(() => { PresentUIElement = canvasLayout.AddMediaComponent(mediaPath, programRegion, false); })); break; case FileType.html: canvasLayout.Dispatcher.Invoke(new Action(() => { PresentUIElement = canvasLayout.AddWebComponent(mediaPath, programRegion, false); })); break; case FileType.ppt: canvasLayout.Dispatcher.Invoke(new Action(() => { PresentUIElement = canvasLayout.AddPPTComponent(mediaPath, programRegion, false); })); break; default: break; } disDelay = 0; this.PresentPlayObject = mediaInfo;//当前播放的对象 } else { _logWrite.WriteLog($"查找媒体资源失败,media.media_id={media.media_id}"); } } else//播放组件已加载,开始计时播放 { ++media.play_second_count;//计时累计 if (media.play_second > 0 && media.play_second_count >= media.play_second)//时间到达 { media.play_second_count = 0; PlayIndex += 1; LastUIElement = PresentUIElement;//上一个播放组件记忆 this.PresentUIElement.DisposeResource(); this.PresentUIElement = null; //当前播放的组件清除 this.PresentPlayObject = null; //当前播放的对象清除 } if (PlayIndex >= programRegion.MediaList.Count) { PlayIndex = 0;//序号回滚 } } if (PresentUIElement != null && PresentUIElement.Visibility == Visibility.Hidden) { ++disDelay; canvasLayout.Dispatcher.Invoke(new Action(() => { if (disDelay >= 3 || LastUIElement == null) { if (LastUIElement != null && canvasLayout.Children.Contains(LastUIElement)) { LastUIElement.DisposeResource(); //资源释放 canvasLayout.Children.Remove(LastUIElement); //移除上一次加入组件 _logWrite.WriteLog($"播放组件移除"); LastUIElement = null; } PresentUIElement.SetVisible(true); } })); } } Thread.Sleep(1000); } }
public void ConnectToPlc() { string[] ipArray; byte[] values; deviceDriver = new OmronFinsNet(_device.Ip, _device.Port) { ConnectTimeOut = 2000 }; ipArray = _device.Ip.Split('.'); values = System.BitConverter.GetBytes(int.Parse(ipArray[ipArray.Length - 1])); deviceDriver.SA1 = values[0]; // PC网络号,PC的IP地址的最后一个数.假如你的电脑的Ip地址为192.168.0.13,那么这个值就是13 ipArray = _device.Ip.Split('.'); values = System.BitConverter.GetBytes(int.Parse(ipArray[ipArray.Length - 1])); deviceDriver.DA1 = values[0]; // 0x10 PLC网络号,PLC的IP地址的最后一个数.假如你的PLC的Ip地址为192.168.0.10,那么这个值就是10 //omronTcpNet.SA1 = 0x12; // PC网络号,PC的IP地址的最后一个数 //omronTcpNet.DA1 = 0x10; // PLC网络号,PLC的IP地址的最后一个数 deviceDriver.DA2 = 0x00; // PLC单元号,通常为0 deviceDriver.ConnectServer(); deviceDriver.SetPersistentConnection(); // 设置长连接 OperateResult res = deviceDriver.ConnectServer(); if (res.IsSuccess) { _log.WriteLog($"{_device.Name}{_device.Ip}连接成功"); } else { _log.WriteLog($"{_device.Name}{_device.Ip}连接失败"); } _device.IsConnected = res.IsSuccess; }
/// <summary> /// 开始播放任务 /// </summary> public override void ProgramPlay() { DateTime dtNow; ProgramScheduleTime scheduleTime = null; while (!StopBit) { if (schedule == null)//未有排程,持续查询 { LoadSchedule(); if (schedule == null) { Thread.Sleep(5000); continue; } } else if (PauseBit) { Thread.Sleep(1000); continue; } dtNow = DateTime.Now; foreach (var item in schedule.TimeList) { if (!string.IsNullOrEmpty(item.schedule_date))//播放的日期设定不为空,则为优先 { if (dtNow.ToString("yyyy-MM-dd") == item.schedule_date) { scheduleTime = item; break; } } else if (!string.IsNullOrEmpty(item.schedule_week))//星期设定不为空,则为优先 { if (item.schedule_week.Contains(dtNow.DayOfWeek.ToString())) { scheduleTime = item; break; } } } if (scheduleTime == null) //未有复合条件的,加载默认时刻 { scheduleTime = schedule.TimeList.FirstOrDefault(x => x.primary_bit == 1); //默认的排程 } //时刻表未加载,或者时刻表变化,则加载 if (scheduleTime != null) { if (PresentPlayObject == null || (PresentPlayObject as ProgramScheduleTime) != scheduleTime) { RegionManagerDic = new Dictionary <int, ProgramRegionPlayManager>(); try { LoadScheduleDay(scheduleTime); this.PresentPlayObject = scheduleTime; } catch (Exception ex) { _logWrite.WriteLog($"LoadScheduleDay出错", ex); } } } Thread.Sleep(1000); } }
/// <summary> /// 连接 /// </summary> public void Connect() { try { _log.WriteLog("获取RabbitMQ服务器参数:" + mConfig.HostName + ":" + mConfig.Port + " (" + mConfig.UserName + "/" + mConfig.Password + ")"); //连接工厂 mc_ConnectionFactory = new ConnectionFactory(); //连接工厂信息 mc_ConnectionFactory.HostName = mConfig.HostName; // "localhost"; mc_ConnectionFactory.Port = mConfig.Port; // "5672" mc_ConnectionFactory.UserName = mConfig.UserName; // "guest"; mc_ConnectionFactory.Password = mConfig.Password; // "guest"; //mc_ConnectionFactory.VirtualHost = defaultRabbitVirtualHost;// "/" mc_ConnectionFactory.RequestedHeartbeat = 30; //心跳包 mc_ConnectionFactory.AutomaticRecoveryEnabled = true; //自动重连 mc_ConnectionFactory.TopologyRecoveryEnabled = true; //拓扑重连 mc_ConnectionFactory.NetworkRecoveryInterval = TimeSpan.FromSeconds(10); //创建连接 Connection = mc_ConnectionFactory.CreateConnection(); //断开连接时,调用方法自动重连 Connection.ConnectionShutdown += Connection_ConnectionShutdown; //创建发送频道 SendChannel = Connection.CreateModel(); //创建接收频道 ListenChannel = Connection.CreateModel(); //发送频道确认模式,发送了消息后,可以收到回应 SendChannel.ConfirmSelect(); _log.WriteLog("尝试连接至RabbitMQ服务器:" + mConfig.HostName); } catch (RabbitMQ.Client.Exceptions.BrokerUnreachableException e) { _log.WriteLog("尝试连接至RabbitMQ服务器错误:", e); } catch (Exception ex) { _log.WriteLog("尝试连接至RabbitMQ服务器错误:", ex); } }
public void ConnectToPlc() { siemensPLCS = SiemensPLCS.S1200; switch (_device.Type) { case PLCType.Simens1200: siemensPLCS = SiemensPLCS.S1200; break; case PLCType.Simens1500: siemensPLCS = SiemensPLCS.S1500; break; case PLCType.Simens300: siemensPLCS = SiemensPLCS.S300; break; case PLCType.Simens200Smart: siemensPLCS = SiemensPLCS.S200Smart; break; } deviceDriver?.ConnectClose(); deviceDriver?.Dispose(); deviceDriver = new SiemensS7Net(siemensPLCS, _device.Ip) { ConnectTimeOut = 2000 }; //siemensTcpNet.LogNet = LogNet; deviceDriver.SetPersistentConnection(); // 设置长连接 OperateResult res = deviceDriver.ConnectServer(); if (res.IsSuccess) { _log.WriteLog($"{_device.Name}{_device.Ip}连接成功"); } else { _log.WriteLog($"{_device.Name}{_device.Ip}连接失败"); } _device.IsConnected = res.IsSuccess; }
public void ConnectToPlc() { deviceDriver = new MelsecMcAsciiNet(_device.Ip, _device.Port); deviceDriver.ConnectTimeOut = 2000; // 网络连接的超时时间 deviceDriver.NetworkNumber = 0x00; // 网络号 deviceDriver.NetworkStationNumber = 0x00; // 网络站号 deviceDriver.ConnectClose(); deviceDriver.SetPersistentConnection(); OperateResult res = deviceDriver.ConnectServer(); if (res.IsSuccess) { _log.WriteLog($"{_device.Name}{_device.Ip}连接成功"); } else { _log.WriteLog($"{_device.Name}{_device.Ip}连接失败"); } _device.IsConnected = res.IsSuccess; }
/// <summary> /// 周期任务 /// </summary> private void CycReadTagTask() { int count = 0; Thread.Sleep(3000); //延时等待其他任务加载,然后再启动刷新 plcDriverHelper.ConnectToPlc(); //连接放在线程里面,开始连接 while (true) { Console.WriteLine($"周期任务:{PlcDevice.Name}-{PlcDevice.Ip}"); plcDriverHelper.CheckConnect(); if (PlcDevice.IsConnected) { foreach (ITagGroup tagGroup in PlcDevice.TagGroups) { switch (tagGroup.DataType) { case TagDataType.Bool: TagGroup <bool> boolGroup = tagGroup as TagGroup <bool>; foreach (BatchReadSection section in boolGroup.SectionList) { bool[] values; if (plcDriverHelper.BatchReadValue(section.StartAddr, section.ReadLength, out values)) { for (int i = 0; i < section.TagValuePosList.Count; i++) { TagIndexAndPos indexPost = section.TagValuePosList[i]; boolGroup.Tags[indexPost.Index].TagValue = values[indexPost.Pos]; } } } break; case TagDataType.Short: TagGroup <short> shortGroup = tagGroup as TagGroup <short>; foreach (BatchReadSection section in shortGroup.SectionList) { short[] values; if (plcDriverHelper.BatchReadValue(section.StartAddr, section.ReadLength, out values)) { for (int i = 0; i < section.TagValuePosList.Count; i++) { TagIndexAndPos indexPost = section.TagValuePosList[i]; shortGroup.Tags[indexPost.Index].TagValue = values[indexPost.Pos]; } } } break; case TagDataType.Int: TagGroup <int> intGroup = tagGroup as TagGroup <int>; foreach (BatchReadSection section in intGroup.SectionList) { int[] values; if (plcDriverHelper.BatchReadValue(section.StartAddr, section.ReadLength, out values)) { for (int i = 0; i < section.TagValuePosList.Count; i++) { TagIndexAndPos indexPost = section.TagValuePosList[i]; intGroup.Tags[indexPost.Index].TagValue = values[indexPost.Pos]; } } } break; case TagDataType.Float: TagGroup <float> floatGroup = tagGroup as TagGroup <float>; foreach (BatchReadSection section in floatGroup.SectionList) { float[] values; if (plcDriverHelper.BatchReadValue(section.StartAddr, section.ReadLength, out values)) { for (int i = 0; i < section.TagValuePosList.Count; i++) { TagIndexAndPos indexPost = section.TagValuePosList[i]; floatGroup.Tags[indexPost.Index].TagValue = values[indexPost.Pos]; } } } break; case TagDataType.String: TagGroup <string> stringGroup = tagGroup as TagGroup <string>; foreach (BatchReadSection section in stringGroup.SectionList) { string[] values; if (plcDriverHelper.BatchReadValue(section.StartAddr, section.ReadLength, out values)) { for (int i = 0; i < section.TagValuePosList.Count; i++) { TagIndexAndPos indexPost = section.TagValuePosList[i]; stringGroup.Tags[indexPost.Index].TagValue = values[indexPost.Pos]; } } } break; } } if (!string.IsNullOrEmpty(PlcDevice.HeartBit))//写入心跳位 { plcDriverHelper.WriteValue(PlcDevice.HeartBit, true); } } else { if (NetworkHelper.IsNetWorkConnect(PlcDevice.Ip))//plc可以ping通 { Thread.Sleep(1000); ++count; if (count >= 10) { count = 0; _log.WriteLog($"{PlcDevice.Name} {PlcDevice.Ip}重新连接并初始化!"); plcDriverHelper.ConnectToPlc(); } } else { _log.WriteLog($"{PlcDevice.Name} {PlcDevice.Ip}连接断开,等待再次连接!"); Thread.Sleep(5000);//延时等待PLC再次连接 } } Thread.Sleep(PlcDevice.CycleTime); } }