private static void ReadMaximums(RS232 paracom, ValenceBattery paramBattery) { try { paracom.Write(paramBattery.BatteryMaximumRead()); if (paracom.Read(21) == -1) { throw new Exception("Read Maximums Error!"); } if (!paramBattery.BatteryMaximumReturn(paracom.InputStream)) { throw new Exception("Read Maximums Error!"); } Console.WriteLine($"Max Temp (life)): {Convert.ToString(paramBattery.MaxBattLifeTemperature)}"); Console.WriteLine($"Min Temp (life): {Convert.ToString(paramBattery.MinBattLifeTemperature)}"); Console.WriteLine($"Max Cell Voltage: { Convert.ToString(paramBattery.MaximumCellVolt)}"); Console.WriteLine($"Min Cell Voltage: { Convert.ToString(paramBattery.MinimumCellVolt)}"); Console.WriteLine($"Fault Oscillator Count: { Convert.ToString(paramBattery.FaultOscillatorCount.ToString())}"); Console.WriteLine($"Fault Memory Access Count: { Convert.ToString(paramBattery.FaultMemAccessCount.ToString())}"); } catch (Exception ex) { throw ex; } }
/// <summary> /// 포트 접속 해제 /// </summary> private void RS232_Close() { if (RS232.IsOpen) { RS232.Close(); } }
private static void ReadEventLog(RS232 paracom, ValenceBattery paramBattery) { try { paracom.Write(paramBattery.EventLogRead()); if (paracom.Read(30) == -1) { throw new Exception("Read Event Log Error!"); } if (!paramBattery.EventLogReturn(paracom.InputStream)) { throw new Exception("Read Event Log Error!"); } Console.WriteLine($"Max Temp: {Convert.ToString(paramBattery.HTLimit)}"); Console.WriteLine($"Min Temp: {Convert.ToString(paramBattery.LTLimit)}"); Console.WriteLine($"MaxDschrgCurrent: {Convert.ToString(paramBattery.MaxDschrgCurrent)}"); Console.WriteLine($"MaxChrgCurrent: {Convert.ToString(paramBattery.MaxChrgCurrent)}"); Console.WriteLine($"CalibrationCorrection: {Convert.ToString(paramBattery.CalibrationCorrection)}"); Console.WriteLine($"ExceedHighOutput: {Convert.ToString(paramBattery.ExceedHighOutput)}"); Console.WriteLine($"DischargeCutoff: {Convert.ToString(paramBattery.DischargeCutoff)}"); Console.WriteLine($"ChargeCutoff: {Convert.ToString(paramBattery.ChargeCutoff)}"); Console.WriteLine($"CommunicationErrors: {Convert.ToString(paramBattery.CommunicationErrors)}"); Console.WriteLine($"IntraModuleBalanceCount: {Convert.ToString(paramBattery.IntraModuleBalanceCount)}"); Console.WriteLine($"InterModuleBalanceCount: {Convert.ToString(paramBattery.InterModuleBalanceCount)}"); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } }
private void RS232_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { string message = RS232.ReadLine().Substring(5); this.Invoke(new MethodInvoker(delegate() { lblResponse.Text = message; if (message.StartsWith("Sens: ")) { evaluateSensors(message.Substring(6)); } if (message.StartsWith("Filled: ")) { lblFillup.Text = "The Bag Filled Up!"; } if (frmCalibrationWizard != null) { frmCalibrationWizard.processMessage(message); } })); } catch (Exception) { MessageBox.Show("Seri Port Okunamadı", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
private static void ReadRev2Data(RS232 paramcom, ValenceBattery parambattery) { try { ReadMaximums(paramcom, parambattery); ReadCalCycleCount(paramcom, parambattery); ReadStatusByte(paramcom, parambattery); if (parambattery.HardwareRevision == 2) { ReadWattHour(paramcom, parambattery); ReadEventLog(paramcom, parambattery); ReadEventLog2(paramcom, parambattery); if (parambattery.Balancing) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Balance Active"); Console.ForegroundColor = ConsoleColor.White; } else { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("Balance Inactive"); Console.ForegroundColor = ConsoleColor.White; } Console.WriteLine($"Battery Failure? {parambattery.fault_BatteryFailure}"); } else { } } catch (Exception ex) { strErrorMessage = "Communication Error"; } }
public SgmaStg_XR(string comport, bool printmsg = false) { PrintMode = printmsg; Port = new SerialPort() .Act(x => { x.PortName = comport; //x.PortName = "COM7"; x.BaudRate = 38400; x.DataBits = 8; x.Parity = Parity.None; x.StopBits = StopBits.One; x.Handshake = Handshake.RequestToSend; x.ReadTimeout = 500; }); RS = new RS232(this.Port, CommandEndStyle.CR, SendStyle.String, 300); Console.WriteLine(RS.Port.IsOpen.ToString()); }
private static void ReadStatusByte(RS232 paramcom, ValenceBattery parambattery) { try { paramcom.Write(parambattery.BatteryStatusRead()); if (paramcom.Read(9) != -1) { if (!parambattery.BatteryStatusReturn(paramcom.InputStream)) { throw new Exception("Read Battery Status Error"); } Console.WriteLine("Battery Status Flags"); Console.WriteLine($"Under 2.3V: {parambattery.fault_UV2v3}"); Console.WriteLine($"Under 2.5V: {parambattery.fault_UV2v5}"); // Console.WriteLine($"Under 2.3V w/ Chg Curr: ") Console.WriteLine($"Exceed 4V: {parambattery.fault_OV4v0}"); Console.WriteLine($"Exceed 4.5V: {parambattery.fault_OV4v5}"); Console.WriteLine($"Cell Over 60c: {parambattery.fault_OTcell60c}"); Console.WriteLine($"Cell Over 65c: {parambattery.fault_OTcell65c}"); Console.WriteLine($"PCBA Over 80c: {parambattery.fault_OTpcba80c}"); Console.WriteLine($"Cell Over 100c: {parambattery.fault_OTpcba100c}"); Console.WriteLine($"NMI Error: {parambattery.fault_NMIFailure}"); Console.WriteLine($"Battery Failure: {parambattery.fault_WeakCellBank}"); } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } }
private static void ReadBatteryBalanceStatus(RS232 paramcom, ValenceBattery paramBattery) { try { paramcom.Write(paramBattery.BalanceReadSend()); if (paramcom.Read(9) == -1) { throw new Exception("Read SOC Error!"); } if (paramBattery.BalanceReadReturn(paramcom.InputStream)) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Balance: Enabled"); Console.ForegroundColor = ConsoleColor.White; } else { Console.Write("Balance: "); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Disabled"); Console.ForegroundColor = ConsoleColor.White; } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } }
private static void ReadEventLog2(RS232 paracom, ValenceBattery paramBattery) { try { paracom.Write(paramBattery.EventLog2Read()); if (paracom.Read(43) == -1) { throw new Exception("Read Event Log 2 Error"); } if (!paramBattery.EventLog2Return(paracom.InputStream)) { throw new Exception("Read Event Log 2 Error"); } Console.WriteLine($"Fault_UV_S: {paramBattery.Fault_UV_S.ToString()}"); Console.WriteLine($"Fault_OV_S: {paramBattery.Fault_OV_S.ToString()}"); Console.WriteLine($"Fault_OCC_S: {paramBattery.Fault_OCC_S.ToString()}"); Console.WriteLine($"Fault_OCD_S: {paramBattery.Fault_OCD_S.ToString()}"); Console.WriteLine($"Fault_UT_S: {paramBattery.Fault_UT_S.ToString()}"); Console.WriteLine($"Fault_OT_S: {paramBattery.Fault_OT_S.ToString()}"); Console.WriteLine($"Reset Count: {paramBattery.ResetCount.ToString()}"); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } }
// RS-232 Open private void RS232_Open() { /* RS232 통신 */ if (!RS232.IsOpen) { /* 통신 수동 설정 * ConfigXML configXML = new ConfigXML(Application.StartupPath + "\\Config.xml"); * * RS232.PortName = configXML.GetXmlData("USN_PRT_SYSTEM/CommSetting", "PortName"); * RS232.BaudRate = int.Parse(configXML.GetXmlData("USN_PRT_SYSTEM/CommSetting", "BaudRate")); * RS232.DataBits = int.Parse(configXML.GetXmlData("USN_PRT_SYSTEM/CommSetting", "DataBits")); * RS232.Parity = Common.GetParity(configXML.GetXmlData("USN_PRT_SYSTEM/CommSetting", "Parity")); * RS232.StopBits = Common.GetStopBits(configXML.GetXmlData("USN_PRT_SYSTEM/CommSetting", "StopBits")); */ try { RS232.Open(); state.Text = "상태 : 포트 열림"; } catch (Exception e) { MessageBox.Show("msg -> " + e.StackTrace); } } }
private void sendCommandDualParameter(object sender, EventArgs e) { if (sender is ToolStripMenuItem) { ToolStripMenuItem menu = (ToolStripMenuItem)sender; switch (menu.Name) { case "runStepperMotorToolStripMenuItem": frmUserDialog.setDialogBoxParameters("speed: [-248,+248], steps: [0,65535]", true, "#000", "00000"); break; } frmUserDialog.ShowDialog(); if (frmUserDialog.DialogResult == System.Windows.Forms.DialogResult.OK) { string userInput = null; switch (menu.Name) { case "runStepperMotorToolStripMenuItem": userInput = "$00RFJ" + frmUserDialog.getUserInput1() + " " + frmUserDialog.getUserInput2(); break; } if (userInput != null) { userInput = userInput.PadRight(37, '*'); RS232.WriteLine(userInput); } } } }
private static void TestZProtocolProcess() { RS232 rs232 = new RS232("COM4", 115200); rs232.Open(); ZProtocolProcess zProtocolProcess = new ZProtocolProcess(rs232); zProtocolProcess.Start(); Console.WriteLine("Ready..."); //while (true) //{ // Console.ReadLine(); // zProtocolProcess.WriteFrame(1, 2, 0); // zProtocolProcess.AddPackage(0xc0, 0xff, new byte[12]); // zProtocolProcess.Send(); // Console.WriteLine("Send"); //} byte[] bs = new byte[12]; for (int i = 0; i < 12; i++) { bs[i] = (byte)i; } Console.ReadLine(); for (int i = 0; i < 100; i++) { zProtocolProcess.WriteFrame((byte)i, (byte)(i + 1), 0); zProtocolProcess.AddBlock((byte)(i + 100), 0xff, bs); zProtocolProcess.Send(); Console.WriteLine("Send"); Thread.Sleep(15); } }
private static void ReadBatteryTemperature(RS232 paramcom, ValenceBattery paramBattery) { try { paramcom.Write(paramBattery.TempRead()); if (paramcom.Read(21) == -1) { throw new Exception("Read Temperature Error!"); } if (!paramBattery.TempReturn(paramcom.InputStream)) { throw new Exception("Read Temperature Error!"); } strCellTemp[0] = Convert.ToString(paramBattery.TEMP1); strCellTemp[1] = Convert.ToString(paramBattery.TEMP2); strCellTemp[2] = Convert.ToString(paramBattery.TEMP3); strCellTemp[3] = Convert.ToString(paramBattery.TEMP4); //strCellTemp[4] = Convert.ToString(paramBattery.TEMP5); //strCellTemp[5] = Convert.ToString(paramBattery.TEMP6); strPCBATemp = Convert.ToString(paramBattery.TEMPPCB); Console.WriteLine($"C1 Temp: {Convert.ToString(paramBattery.TEMP1)}"); Console.WriteLine($"C2 Temp: {Convert.ToString(paramBattery.TEMP2)}"); Console.WriteLine($"C3 Temp: {Convert.ToString(paramBattery.TEMP3)}"); Console.WriteLine($"C4 Temp: {Convert.ToString(paramBattery.TEMP4)}"); Console.WriteLine($"PCBA Temp: {Convert.ToString(paramBattery.TEMPPCB)}"); } catch (Exception ex) { strErrorMessage = "Communication Error"; WriteError(ex.Message.ToString()); } }
private void HandlePortOpen(SerialPort port) { var conn = new RS232(); conn.PortOpen(port); Connection = conn; Connection.DataReceivedEvent += HandleConnectionDataReceived; }
// 포트 접속 해제 private void RS232_Close() { if (RS232.IsOpen) { RS232.Close(); state.Text = "상태 : 포트 닫힘"; } }
public FrmBusToRS232(string strname, object obj, int devicetype, int maxcount, int type) { InitializeComponent(); this.Type = type; this.MyActiveObj = obj; if (MyActiveObj is RS232) { if (CsConst.myRS232 != null) { foreach (RS232 oTmp in CsConst.myRS232) { if (oTmp.DIndex == (MyActiveObj as RS232).DIndex) { oRS232 = oTmp; break; } } } } this.MaxCount = maxcount; string strDevName = strname.Split('\\')[0].ToString(); strRemark = strname.Split('\\')[1].ToString(); SubNetID = Convert.ToByte(strDevName.Split('-')[0]); DevID = Convert.ToByte(strDevName.Split('-')[1]); this.MyintDeviceType = devicetype; cbType.Items.Clear(); cbType.DropDownStyle = ComboBoxStyle.DropDownList; if (MyintDeviceType == 1041) { cbType.Items.Add(CsConst.mstrINIDefault.IniReadValue("TargetType", "00000", "")); cbType.Items.Add(CsConst.myPublicControlType[14].ControlTypeName); } else { cbType.Items.Add(CsConst.mstrINIDefault.IniReadValue("TargetType", "00000", "")); cbType.Items.Add(CsConst.myPublicControlType[4].ControlTypeName); } cbState.Items.Clear(); cbState.DropDownStyle = ComboBoxStyle.DropDownList; cbState.Items.Add(CsConst.Status[0]); cbState.Items.Add(CsConst.Status[1]); cbType.SelectedIndexChanged += cbType_SelectedIndexChanged; txtNO.TextChanged += txtNO_TextChanged; cbState.SelectedIndexChanged += cbState_SelectedIndexChanged; txtRemark.TextChanged += txtRemark_TextChanged; uc1.UserControlValueChanged += uc1_UserControlValueChanged; uc2.UserControlValueChanged += uc2_UserControlValueChanged; dgvUV.Controls.Add(cbType); dgvUV.Controls.Add(txtRemark); dgvUV.Controls.Add(txtNO); dgvUV.Controls.Add(cbState); dgvUV.Controls.Add(uc1); dgvUV.Controls.Add(uc2); allVisible(false); }
//시리얼 수신 데이터가 있을때 private void RS232_DataReceived(object sender, SerialDataReceivedEventArgs e) { string strMessage = RS232.ReadExisting(); if (strMessage != string.Empty) { MessageRead(strMessage); } }
public void Read() { while (Continue && RS232.IsOpen) { try { RecievedData = RS232.ReadLine(); //DBExchange.AddLine(RecievedData, true); //MainForm.textBox.Invoke(new Action(() => { DBExchange.AddLine(RecievedData, true); })); MainForm.listBox.Invoke(new Action(() => { DBExchange.AddLine(RecievedData, true); DBExchange.LoadTable(); })); } catch (TimeoutException) { } } RS232port.RS232.Close(); }
private void sendCommandSingleParameter(object sender, EventArgs e) { if (sender is ToolStripMenuItem) { ToolStripMenuItem menu = (ToolStripMenuItem)sender; switch (menu.Name) { case "runPeristalticPumpToolStripMenuItem": frmUserDialog.setDialogBoxParameters("Enter speed between [-832,+832]", false, "#000", null); break; case "fillupLargeBagToolStripMenuItem": frmUserDialog.setDialogBoxParameters("Enter weight between [1,3000]g", false, "0000", null); break; case "fillupSmallBagToolStripMenuItem": frmUserDialog.setDialogBoxParameters("Enter weight between [1,3000]g", false, "0000", null); break; } frmUserDialog.ShowDialog(); if (frmUserDialog.DialogResult == System.Windows.Forms.DialogResult.OK) { string userInput = null; switch (menu.Name) { case "runPeristalticPumpToolStripMenuItem": userInput = "$00RFI" + frmUserDialog.getUserInput1(); break; case "fillupLargeBagToolStripMenuItem": userInput = "$00RFK" + frmUserDialog.getUserInput1(); lblFillup.Text = "Waiting for the bag to get filled up"; break; case "fillupSmallBagToolStripMenuItem": userInput = "$00RFL" + frmUserDialog.getUserInput1(); break; } if (userInput != null) { userInput = userInput.PadRight(37, '*'); RS232.WriteLine(userInput); } } } }
/// <summary> /// 포트 접속 /// </summary> private void RS232_Open() { /* RS232 통신 */ if (!RS232.IsOpen) { try { RS232.Encoding = System.Text.Encoding.GetEncoding(1252); RS232.Open(); } catch (Exception e) { MessageBox.Show("msg -> " + e.StackTrace); } } }
public FrmBoundRate(byte subnetid, byte deviceid, Object rs232, bool is485) { this.SubNetID = subnetid; this.DeviceID = deviceid; if (rs232 is MHRCU) { sTmpMhrcu = (MHRCU)rs232; } else if (rs232 is RS232) { sTmpRs232 = (RS232)rs232; } this.is485Port = is485; InitializeComponent(); }
private void prepareUserEnvironment() { try { if (RS232.IsOpen) { RS232.Close(); } RS232.NewLine = "<EOM>"; RS232.BaudRate = 19200; RS232.Open(); } catch (Exception) { MessageBox.Show("Seri Port Açılamadı", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
/// <summary> /// Rozpoczęcie sczytywania stanów zbiorników przez COM /// </summary> public void Init() { _measurementBL = new MeasurementBL(); _measurementBL.Init(); _containerBL = new ContainerBL(); _containerBL.Init(); SystemConfigBL configBL = new SystemConfigBL(); configBL.Init(); configBL.FillRecord(); _rs232 = new RS232(); _rs232.ReadTimeOut = 1000; _rs232.DataReceivedEvent += new RS232.DataReceived(_rs232_DataReceivedEvent); _rs232.CanReadExisting = true; _rs232.Open(configBL.MainRow.ComName, 1200); }
public void ZSModule_InitialComm() { RS232Comm = new SerialPort(); Thread RcvMsgThread = new Thread(new ThreadStart(this.RS232Comm_OnComm)); RS232Comm.PortName = "COM10"; RS232Comm.BaudRate = 115200; RS232Comm.DataBits = 8; //RS232Comm.StopBits = 0; if (RS232.GetSignleton().CreateRS232Interface(ref RS232Comm) != 0) { return; } RcvMsgThread.Start(); }
private static void ReadWattHour(RS232 paramcom, ValenceBattery parambattery) { try { paramcom.Write(parambattery.BatteryWHRead()); if (paramcom.Read(11) != -1) { if (!parambattery.BatteryWHReturn(paramcom.InputStream)) { throw new Exception("Read Watt Hour Error"); } Console.WriteLine($"Watt Hours: {Convert.ToString(parambattery.WattHour)}"); } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } }
private static void ReadBatterySocRefresh(RS232 paramcom, ValenceBattery paramBattery) { try { paramcom.Write(paramBattery.SNSOCReadSend()); if (paramcom.Read(23) == -1) { throw new Exception("Read SOC Error on SNSOCReadSend!"); } if (!paramBattery.SNSOCReadReturn(paramcom.InputStream)) { throw new Exception("Read SOC Error on SNSOCReadReturn!"); } } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } }
/// <summary> /// Initialize this Component /// </summary> public override void Initialize() { base.Initialize(); // Initialize if (Simulate == eSimulate.SimulateDontAsk) { throw new ForceSimulateException("Always Simulate"); } Port = GetParent <RS232>(); if (Port == null) { throw new ForceSimulateException("DPMCtrl needs an RS232 parent"); } if (!Enabled || !Parent.Enabled) { return; } Port.FullyDefined = true; Port.RefreshPort(); if (!Port.IsOpen) { throw new ForceSimulateException("Port is not opened"); } try { Simulate = eSimulate.None; } catch (ForceSimulateException fsex) { throw fsex; } catch (Exception ex) { throw new ForceSimulateException(ex); } }
private void Send_MSG(string MSG) { int count; seqno++; CreateRFMessages m = new CreateRFMessages(); byte[] sendMsg = m.create_framed_packet(System.Convert.ToByte(seqno), 0x04, MSG); count = System.Convert.ToInt32(sendMsg[7]) + 10; // 왜 +10 ??? if (RS232.IsOpen) { lock (RS232) { RS232.Write(sendMsg, 0, count); } } debugRFMsg(count, sendMsg); }
private static void ReadCalCycleCount(RS232 paracom, ValenceBattery paramBattery) { try { paracom.Write(paramBattery.BatteryCycleRead()); if (paracom.Read(11) == -1) { throw new Exception("Read Num Cycle Error!"); } if (!paramBattery.BatteryCycleReturn(paracom.InputStream)) { throw new Exception("Read Num Cycle Error!"); } Console.WriteLine($"NumChargeDischargeCycle: {Convert.ToString(paramBattery.NumChargeDischargeCycle)}"); Console.WriteLine($"NumHardwareCalibration: {Convert.ToString(paramBattery.NumHardwareCalibration)}"); } catch (Exception ex) { throw ex; } }
private static void Openbalancing(RS232 paramcom, ValenceBattery paramBattery) { var errorMsg = "Open balancing Return Error!"; try { paramcom.Write(paramBattery.OpenbalancingRead()); if (paramcom.Read(6) == -1) { throw new Exception(errorMsg); } if (!paramBattery.OpenbalancingReturn(paramcom.InputStream)) { throw new Exception(errorMsg); } } catch (Exception ex) { WriteError(ex.Message.ToString()); throw new Exception("Error during Open balancing check: " + ex.Message); } }
private static void ReadBatteryVersion(RS232 paramcom, ValenceBattery paramBattery) { try { paramcom.Write(paramBattery.BatteryVersionRead()); if (paramcom.Read(51) == -1) { throw new Exception("Read Battery Version Error!"); } if (!paramBattery.BatteryVersionReturn(paramcom.InputStream)) { throw new Exception("Read Battery Version Error!"); } Console.WriteLine($"Version: {paramBattery.Version}"); Console.WriteLine($"Firmware Date: {paramBattery.BuildRevision}"); Console.WriteLine($"Revision: {paramBattery.Revision}"); } catch (Exception ex) { throw new Exception(ex.Message.ToString()); } }
private static byte GetELow(float arg) { if (arg < 0.01f) arg = 0.01f; else if (arg > 1.00f) arg = 1.00f; int temp = ((int)Math.Round(arg * 100)) - 1; temp = temp % 10; if (temp >= 0 && temp <= 9) temp = temp + 48; else if (temp >= 10 && temp <= 15) temp = temp + 55; return (byte)temp; }
public Pirometer(RS232 port) { this.port = port; if (!Directory.Exists(filepath)) Directory.CreateDirectory(filepath); }
public void TestInit() { _rs232 = new RS232(); _rs232.ReadTimeOut = 1000; _rs232.DataReceivedEvent += new RS232.DataReceived(_rs232_DataReceivedEventTest); _rs232.CanReadExisting = true; _rs232.Open("COM1", 1200); _rs232.Start(); }
/// <summary> /// Costruttore /// </summary> /// <param name="port">Nome della porta di comunicazione</param> /// <param name="baudRate">Velocità di comunicazione</param> public Rs232(RS232 port, int baudRate) : base("COM" + ((int)port), baudRate) { }
private void ReceiveStringFSM(RS232 device, byte receivedByte) { switch (state) { // Исходное состояние: ждем '#' или '=' case 1: if (receivedByte == '=') { state = 2; byteCounter = 0; device.receivedTemp[byteCounter] = receivedByte; byteCounter++; } else if (receivedByte == '#') { state = 3; byteCounter = 0; device.receivedMem[byteCounter] = receivedByte; byteCounter++; } break; // Прием строки температуры case 2: { if (byteCounter <= 12) { if (receivedByte == 0) { device.receivedTemp[byteCounter] = 0x30; } else { device.receivedTemp[byteCounter] = receivedByte; } byteCounter++; } else { TemperatureReceived(device, Encoding.ASCII.GetString(device.receivedTemp)); byteCounter = 0; state = 1; } } break; case 3: downloadForm.label1.Text = "Загрузка памяти замеров прибора..."; downloadForm.timerTimeoutByte.Enabled = true; // Если второй байт - 7 то это новый прибор, если 0 - старый, иначе ошибка if (receivedByte == '7') { state = 4; // новый прибор - 32035 байт downloadForm.progressBar1.Maximum = 32037; downloadForm.progressBar1.Value = 2; downloadForm.Show(); device.receivedMem[byteCounter] = receivedByte; byteCounter++; } else { state = 5; // старый прибор - 10035 байт downloadForm.progressBar1.Maximum = 10037; downloadForm.progressBar1.Value = 2; downloadForm.Show(); device.receivedMem[byteCounter] = receivedByte; byteCounter++; } break; case 4: device.receivedMem[byteCounter] = receivedByte; byteCounter++; downloadForm.progressBar1.Value++; downloadForm.timerTimeoutByte.Stop(); downloadForm.timerTimeoutByte.Start(); if (byteCounter >= 32037) { state = 1; if ((CRC_HIGH_FOR_NEW(device) == device.receivedMem[32034]) && (CRC_LOW_FOR_NEW(device) == device.receivedMem[32033])) { downloadForm.timerTimeoutByte.Stop(); downloadForm.label1.Text = "Загрузка завершена!"; } else { downloadForm.timerTimeoutByte.Stop(); downloadForm.label1.Text = "ОШИБКА ДАННЫХ CRC!"; } downloadForm.timer1.Enabled = true; } break; case 5: device.receivedMem[byteCounter] = receivedByte; byteCounter++; downloadForm.progressBar1.Value++; downloadForm.timerTimeoutByte.Stop(); downloadForm.timerTimeoutByte.Start(); if (byteCounter >= 10037) { state = 1; if ((CRC_HIGH_FOR_OLD(device) == device.receivedMem[10034]) && (CRC_LOW_FOR_OLD(device) == device.receivedMem[10033])) { downloadForm.timerTimeoutByte.Stop(); downloadForm.label1.Text = "Загрузка завершена!"; device.pirometer.SaveMemoryToFileOld(";;;" + DateTime.Now.Hour + ':'+ DateTime.Now.Minute + ':'+DateTime.Now.Second, device.pirometer.Port.SystemName); } else { downloadForm.timerTimeoutByte.Stop(); downloadForm.label1.Text = "ОШИБКА ДАННЫХ CRC!"; b = CRC_HIGH_FOR_OLD(device); b = CRC_LOW_FOR_OLD(device); b = device.receivedMem[10030]; b = device.receivedMem[10031]; b = device.receivedMem[10032]; b = device.receivedMem[10033]; b = device.receivedMem[10034]; b = device.receivedMem[10035]; b = device.receivedMem[10036]; } downloadForm.timer1.Enabled = true; } break; case 6: break; case 7: break; case 8: break; case 9: break; default: return; } }
private void RefreshPorts() { // запрещаем действия при изменении галочек у портов doNotExecuteEventCheckItem = true; buttonRefresh.Enabled = false; Cursor oldCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; checkedListBoxPorts.BeginUpdate(); // удаляем неподключенные порты из списка var tempArray = new List<RS232>(); foreach (object port in checkedListBoxPorts.Items) { if (temp.IsPortAvailable(((RS232)port).SystemName) != CommBase.PortStatus.absent) { try { if (((RS232)port).Online) tempArray.Add(port as RS232); } // ReSharper disable EmptyGeneralCatchClause catch { } // ReSharper restore EmptyGeneralCatchClause } } checkedListBoxPorts.Items.Clear(); checkedListBoxPorts.Items.AddRange(tempArray.ToArray()); for (int i = 0; i < checkedListBoxPorts.Items.Count; i++) { checkedListBoxPorts.SetItemChecked(i, true); } for (int i = 0; (i <= 256); i++) { progressBar1.Value = i; if (temp.IsPortAvailable("COM" + i) == CommBase.PortStatus.available) { var port = new RS232 { SystemName = ("COM" + i), VisibleName = ("COM" + i) }; checkedListBoxPorts.Items.Add(port); } } checkedListBoxPorts.EndUpdate(); buttonRefresh.Enabled = true; progressBar1.Value = 0; Cursor.Current = oldCursor; doNotExecuteEventCheckItem = false; }
private void TemperatureReceived(RS232 sender, string received) { float t; float eps; if (string.IsNullOrEmpty(received) || received.Length != 13) { return; } else if (!CheckCRC(received)) { t = 1999f; eps = 1.00f; } else { t = GetTemperatureFromString(received); eps = GetEpsilonFromString(received); } SetIconDataOK(((RS232)sender).SystemName); foreach (Signal signal in signals) { if (signal.Enabled) signal.CheckValueForSignal(t); } ((RS232)sender).pirometer.SaveToFile(t, eps, ((RS232)sender).SystemName); ((RS232)sender).pirometer.points.Add(new XDate(DateTime.Now), t); RefreshGraph(); ((RS232)sender).pirometer.T = t; if (checkedListBoxPorts.SelectedItem == sender) { labelComName.Text = ((RS232)sender).SystemName + ":"; labelEps.Text = "ε = " + eps.ToString("f2"); // отображение температур без десятых if (!received.Substring(8, 4).Contains(".") || (received.Substring(8, 4)[0] == '-' && !char.IsNumber(received.Substring(8, 4), 3))) { if (t == 2000f) { FindMaximum((RS232)sender, t); labelT.Text = ">>>>"; labelMaxT.Text = "max " + ">>>>"; } else if (t == -50f) { FindMinimum((RS232)sender, t); labelT.Text = "<<<<"; labelMinT.Text = "min " + "<<<<"; } else if (t == 1999f) { labelT.Text = "ERROR"; } else { labelT.Text = t.ToString("f0") + "°C"; labelMinT.Text = "min " + FindMinimum((RS232)sender, t).ToString( "f0") + "°C"; labelMaxT.Text = "max " + FindMaximum((RS232)sender, t).ToString( "f0") + "°C"; } } // отображение температур с десятыми else { { if (t == 2000f) { FindMaximum((RS232)sender, t); labelT.Text = ">>>>"; labelMaxT.Text = "max " + ">>>>"; } else if (t == -50f) { FindMinimum((RS232)sender, t); labelT.Text = "<<<<"; labelMinT.Text = "min " + "<<<<"; } else if (t == 1999f) { labelT.Text = "ERROR"; } else { labelT.Text = t.ToString("f1") + "°C"; labelMinT.Text = "min " + FindMinimum((RS232)sender, t). ToString("f1") + "°C"; labelMaxT.Text = "max " + FindMaximum((RS232)sender, t). ToString("f1") + "°C"; } } } } if (((RS232)sender).pirometer.epsMustBeChanged) { if (string.IsNullOrEmpty(received) || received.Length != 13) return; if (eps != ((RS232)sender).pirometer.epsilon) { byte[] transmitBuf = { 35, (byte) received[1], (byte) received[2], (byte) received[3], (byte) received[4], 65, GetEHigh( ((RS232) sender).pirometer.epsilon) , GetELow( ((RS232) sender).pirometer.epsilon) , 0, 13, 10 }; transmitBuf[8] = GetC(transmitBuf, 0, 7); ((RS232)sender).Write(transmitBuf); } else ((RS232)sender).pirometer.epsMustBeChanged = false; } }
private static byte CRC_HIGH_FOR_NEW(RS232 device) { byte CRC = 0; for (int i = 1; i <= 32029; i += 2) { CRC = (byte)(CRC ^ device.receivedMem[i]); } if ((CRC >= 0) && (CRC <= 9)) { CRC += 0x30; } else if ((CRC >= 10) && (CRC <= 15)) { CRC += 0x37; } return CRC; }
private static byte CRC_HIGH_FOR_OLD(RS232 device) { byte CRC = 0; int i = 1; while ( i < 10033 ) { CRC = (byte)(CRC ^ device.receivedMem[i]); i += 2; } if ((CRC >= 0) && (CRC <= 9)) { CRC += 0x30; } else if ((CRC >= 10) && (CRC <= 15)) { CRC += 0x37; } return CRC; }
private static byte CRC_LOW_FOR_OLD(RS232 device) { byte CRC = 0; for (int i = 2; i <= 10030; i += 2) { CRC = (byte)(CRC ^ device.receivedMem[i]); } if ((CRC >= 0) && (CRC <= 9)) { CRC += 0x30; } else if ((CRC >= 10) && (CRC <= 15)) { CRC += 0x37; } return CRC; }
private static float FindMaximum(RS232 port, float t) { if (port.pirometer.Tmax < t) port.pirometer.Tmax = t; return port.pirometer.Tmax; }
private static float FindMinimum(RS232 port, float t) { if (port.pirometer.Tmin > t) port.pirometer.Tmin = t; return port.pirometer.Tmin; }
void ReInit() { if (SerialIOSwitchObj != null) { SerialIOSwitchObj.Close(); } FileObj = new File(InitInfo[2], InitInfo[3]); if (InitInfo[0] != "None") { RS232Obj = new RS232(InitInfo[0], int.Parse(InitInfo[1])); } else { RS232Obj = null; } SerialIOSwitchObj = new SerialIOSwitch(RS232Obj, FileObj); SerialIOSwitchObj.Open(); ZProtocolProcessObj = new ZProtocolProcess(SerialIOSwitchObj); ZProtocolProcessObj.OnReceviceFrame += new ZProtocolProcess.ReceviceData(ZProtocolProcessObj_OnReceviceFrame); ZProtocolProcessObj.OnReceviceBlock += new ZProtocolProcess.ReceviceData(ZProtocolProcessObj_OnReceviceBlock); }