public bool InsertCacheDataPackets(IList <byte[]> cacheDataPackets) { using (DbConnection conn = new DbConnection()) { using (DbTransaction tran = DbTransaction.Open()) { try { foreach (byte[] bytes in cacheDataPackets) { string str = ValueHelper.Byte2HexStr(bytes, 0, bytes.Length); PacketsToSend packet = new PacketsToSend { DataPacket = str.Trim() }; packet.Save(); } return(true); } catch { return(false); } } } }
/// <summary> /// 发送数据包 /// </summary> private void Send() { log.Info("进入发送函数Send"); try { var file = new ExeConfigurationFileMap { ExeConfigFilename = @".\config\Params.config" }; Configuration config = ConfigurationManager.OpenMappedExeConfiguration( file, ConfigurationUserLevel.None); if (!int.TryParse(config.AppSettings.Settings["byteint"].Value, out byteint)) { byteint = 200; } this.ShowLog("Interval of package is {0}", byteint); // Stopwatch timer = new Stopwatch(); Thread.Sleep(300); // timer.Start(); // portManager.SendSatateBytes(); while (isready) { try { //如果没有可发送数据等20s if (this.packetsToSend.Count == 0) { // log.Info("packetsToSend.Count == 0"); Thread.Sleep(20000); } else { //log.Info("packetsToSend.Count ==" + packetsToSend.Count); byte[] packetBytes; this.packetsToSend.TryDequeue(out packetBytes); if (packetBytes != null) { //log.Info("packetBytes != null"); bool issend = portManager.SendData(packetBytes); //log.Info("离开发送函数SendData"); StringBuilder msg = new StringBuilder(); //msg.Append(ValueHelper.Byte2HexStr(packetBytes, 0, packetBytes.Length)); if (issend) { // this.packetsToSend.TryDequeue(out packetBytes); msg.Insert(0, string.Format("{0},发送成功,数据长度:", DateTime.Now)); msg.Append(packetBytes.Length); msg.Append(",模块号:").Append(BitConverter.ToInt16(packetBytes, 7)); msg.Append("通道号:").Append(packetBytes[9]); msg.Append("总包数:") .Append(packetBytes[10]) .Append("本包号:") .Append(packetBytes[11]); log.Info(msg.ToString()); ShowLog(msg.ToString()); log.DebugFormat(ValueHelper.Byte2HexStr(packetBytes, 0, packetBytes.Length)); // 发送成功等待 封包间隔*2 毫秒 Thread.Sleep(byteint); } else { msg.Insert(0, "发送失败:"); this.packetsToSend.Enqueue(packetBytes); // this.packetsToSend.Enqueue(null); log.Info(msg.ToString()); ShowLog(msg.ToString()); Thread.Sleep(10); } } else { log.Info("packetsToSend.TryPeek失败"); // this.packetsToSend.TryDequeue(out packetBytes); // 获取失败,10毫秒后重新读取 Thread.Sleep(10); } } } catch (Exception ex) { log.Error(ex.Message); ShowLog(ex.Message); } } // } } catch (Exception ex) { log.Error(ex.Message); } }