/// <summary> /// 根据数据类型获取其对应的字节长度,bool型为1个字节 /// </summary> /// <param name="type"></param> /// <returns></returns> public static ushort GetByteSize(PLCDataType type) { switch (type) { case PLCDataType.BYTE: return(1); case PLCDataType.BOOL: return(1); case PLCDataType.DWORD: return(4); case PLCDataType.WORD: return(2); case PLCDataType.INT: return(2); case PLCDataType.DINT: return(4); case PLCDataType.CHAR: return(1); default: return(1); } }
/// <summary> /// 数据类型转换PLC-->WCS /// </summary> /// <param name="type"></param> /// <param name="data"></param> /// <returns></returns> private BllResult <String> TransforAddressDataToWCSData(PLCDataType type, object data) { string str; try { switch (type) { case PLCDataType.BYTE: int i = Convert.ToInt32(data); str = i.ToString(); break; case PLCDataType.BOOL: case PLCDataType.DWORD: case PLCDataType.WORD: case PLCDataType.INT: case PLCDataType.DINT: str = data.ToString(); break; case PLCDataType.CHAR: str = ConverHelper.ASCIIToString((short[])data).Trim().Replace("$03", "").Replace("\u0003", "").Replace("\0", ""); break; default: str = data.ToString(); break; } return(BllResultFactory <string> .Sucess(str, "成功")); } catch (Exception ex) { return(BllResultFactory <string> .Error(null, "PLC到WCS数据转换出现异常,值:" + data + " 目标类型:" + type + " 异常:" + ex.ToString())); } }
internal PLCResponse SetWordValue(string[] strArray, PLCDataType dataType, string strValue) { string strMessageValue = ConvertValueToMessage(strValue, dataType); string strCommand = "@" + strArray[0] + "FA000000000" + "0102" + strArray[1].Substring(4) + strMessageValue; string strFcs = CreateFcsCodeFun(strCommand); string strEndCode = "*" + "\r"; string strMessage = strCommand + strFcs + strEndCode; string strRecieve; HiPerfTimer timeM = new HiPerfTimer(); lock (objLock) { #region 通信 try { serialPort.ReadExisting(); serialPort.Write(strMessage); timeM.Start(); strRecieve = serialPort.ReadExisting(); while (true) { try { strRecieve = strRecieve + serialPort.ReadExisting(); if (strRecieve.IndexOf("\r") > -1) { //strRecieve = strRecieve.Trim(); if (strRecieve.Length != 27) { return(PLCResponse.ERROR); } string strMessageReturn = strRecieve.Substring(0, 23); string strFcsReturn = strRecieve.Substring(23, 2); strFcs = CreateFcsCodeFun(strMessageReturn); if (strFcs != strFcsReturn) { return(PLCResponse.FCSERR); } break; } if (timeM.TimeUp(0.5)) { return(PLCResponse.TIMEOUT); } } catch//(Exception ex) { return(PLCResponse.OTHERS); } System.Threading.Thread.Sleep(1); } } catch { return(PLCResponse.OTHERS); } #endregion } return(PLCResponse.SUCCESS); }
protected override string ConvertValueToMessage(string strValue, PLCDataType dataType) { string strReturn = "00000000"; string strTemp = ""; try { if (dataType == PLCDataType.BIT16) { Int16 iTemp16 = Convert.ToInt16(strValue, 2); strTemp = iTemp16.ToString("X4"); strReturn = strTemp; } if (dataType == PLCDataType.BIT32) { Int32 iTemp32 = Convert.ToInt32(strValue, 2); strTemp = iTemp32.ToString("X8"); strReturn = strTemp.Substring(4, 4) + strTemp.Substring(0, 4); } if (dataType == PLCDataType.BIN16) { Int16 iTemp16 = Convert.ToInt16(strValue, 10); strTemp = iTemp16.ToString("X4"); strReturn = strTemp; } if (dataType == PLCDataType.BIN32) { Int32 iTemp32 = Convert.ToInt32(strValue, 10); strTemp = iTemp32.ToString("X8"); strReturn = strTemp.Substring(4, 4) + strTemp.Substring(0, 4); } if (dataType == PLCDataType.HEX16) { Int16 iTemp16 = Convert.ToInt16(strValue, 16); strTemp = iTemp16.ToString("X4"); strReturn = strTemp; } if (dataType == PLCDataType.HEX32) { Int32 iTemp32 = Convert.ToInt32(strValue, 16); strTemp = iTemp32.ToString("X8"); strReturn = strTemp.Substring(4, 4) + strTemp.Substring(0, 4); } if (dataType == PLCDataType.DOUBLE) { float f = Convert.ToSingle(strValue); byte[] floatValues = BitConverter.GetBytes(f); strTemp = floatValues[3].ToString("X2") + floatValues[2].ToString("X2") + floatValues[1].ToString("X2") + floatValues[0].ToString("X2"); strReturn = strReturn = strTemp.Substring(4, 4) + strTemp.Substring(0, 4); } } catch { } return(strReturn); }
public static PLCResponse SetWord(string strPlcDriver, string strAddress, PLCDataType dataType, string strValue) { try { return(PLCDriverManageClass.dicDrivers[strPlcDriver].SetWord(strAddress, dataType, strValue)); } catch { return(PLCResponse.OTHERS); } }
public override PLCResponse SetWord(string strAddress, PLCDataType dataType, string strValue) { if (bInitOK == false) { return(PLCResponse.INITFAIL); } string[] strArrage; if (DAddressIsOK(strAddress, out strArrage) == false) { return(PLCResponse.ADDWRONG); } return(SetWordValue(strArrage, dataType, strValue)); }
protected virtual string ConvertMesToValue(string strMessage, PLCDataType dataType) { string strReturn = "####"; if (strMessage.Length != 8) { return("Error"); } string strLowWord = strMessage.Substring(2, 1) + strMessage.Substring(3, 1) + strMessage.Substring(0, 1) + strMessage.Substring(1, 1); string strDWord = strMessage.Substring(6, 1) + strMessage.Substring(7, 1) + strMessage.Substring(4, 1) + strMessage.Substring(5, 1) + strLowWord; Int16 iLowWord = Convert.ToInt16(strLowWord, 16); Int32 iDWord = Convert.ToInt32(strDWord, 16); //double dValueResult = Convert.ToDoubde(strDWord,new FOR; if (dataType == PLCDataType.BIT16) { strReturn = Convert.ToString(iLowWord, 2); strReturn = strReturn.PadLeft(16, '0'); } if (dataType == PLCDataType.BIT32) { strReturn = Convert.ToString(iDWord, 2); strReturn = strReturn.PadLeft(32, '0'); } if (dataType == PLCDataType.BIN16) { strReturn = iLowWord.ToString(); } if (dataType == PLCDataType.BIN32) { strReturn = iDWord.ToString(); } if (dataType == PLCDataType.HEX16) { strReturn = strLowWord; } if (dataType == PLCDataType.HEX32) { strReturn = strDWord; } if (dataType == PLCDataType.DOUBLE) { int num = int.Parse(strDWord, System.Globalization.NumberStyles.AllowHexSpecifier); byte[] floatValues = BitConverter.GetBytes(num); float f = BitConverter.ToSingle(floatValues, 0); strReturn = f.ToString(); } return(strReturn); }
/// <summary> /// 数据类型转换WCS-->PLC /// </summary> /// <param name="type"></param> /// <param name="v"></param> /// <returns></returns> private BllResult TansforWCSDataToAddressData(PLCDataType type, string data) { try { object obj = null; switch (type) { case PLCDataType.BYTE: obj = Convert.ToInt32(data); break; case PLCDataType.BOOL: obj = Convert.ToBoolean(data); break; case PLCDataType.DWORD: obj = Convert.ToUInt32(data); break; case PLCDataType.WORD: obj = Convert.ToUInt16(data); break; case PLCDataType.INT: obj = Convert.ToInt16(data); break; case PLCDataType.DINT: obj = Convert.ToInt32(data); break; case PLCDataType.CHAR: obj = ConverHelper.StringToASCII(data); break; default: obj = data; break; } return(BllResultFactory.Sucess(obj, "成功")); } catch (Exception ex) { return(BllResultFactory.Error(null, "WCS到PLC数据转换出现异常,值:" + data + " 目标类型:" + type + " 异常:" + ex.ToString())); } }
/// <summary> /// 数据转换,byte[]到string /// </summary> /// <param name="dataType"></param> /// <param name="buffer"></param> /// <returns></returns> public static BllResult <string> TransferBufferToString(PLCDataType dataType, byte[] buffer) { try { switch (dataType) { case PLCDataType.BYTE: //字节转成int处理 return(BllResultFactory <string> .Sucess(reverseBytesTransform.TransInt32(buffer, 0).ToString(), null)); case PLCDataType.BOOL: return(BllResultFactory <string> .Sucess(reverseBytesTransform.TransBool(buffer, 0).ToString(), null)); case PLCDataType.DWORD: return(BllResultFactory <string> .Sucess(reverseBytesTransform.TransUInt32(buffer, 0).ToString(), null)); case PLCDataType.WORD: return(BllResultFactory <string> .Sucess(reverseBytesTransform.TransUInt16(buffer, 0).ToString(), null)); case PLCDataType.INT: return(BllResultFactory <string> .Sucess(reverseBytesTransform.TransInt16(buffer, 0).ToString(), null)); case PLCDataType.DINT: return(BllResultFactory <string> .Sucess(reverseBytesTransform.TransInt32(buffer, 0).ToString(), null)); case PLCDataType.CHAR: return(BllResultFactory <string> .Sucess(reverseBytesTransform.TransString(buffer, 0, buffer.Length, Encoding.ASCII).Substring(0, 20).Replace("\0", "").Trim(), null)); default: return(BllResultFactory <string> .Error("未识别")); } } catch (Exception ex) { return(BllResultFactory <string> .Error($"转换出错:{ex.Message}")); } }
/// <summary> /// 数据转换,string到byte[] /// </summary> /// <param name="dataType"></param> /// <param name="value"></param> /// <returns></returns> public static BllResult <byte[]> TransferStringToBuffer(PLCDataType dataType, string value) { try { switch (dataType) { case PLCDataType.BYTE: return(BllResultFactory <byte[]> .Sucess(reverseBytesTransform.TransByte(new int[] { Convert.ToInt32(value) }))); case PLCDataType.BOOL: return(BllResultFactory <byte[]> .Sucess(reverseBytesTransform.TransByte(Convert.ToBoolean(value)))); case PLCDataType.DWORD: return(BllResultFactory <byte[]> .Sucess(reverseBytesTransform.TransByte(new UInt32[] { Convert.ToUInt32(value) }))); case PLCDataType.WORD: return(BllResultFactory <byte[]> .Sucess(reverseBytesTransform.TransByte(new UInt16[] { Convert.ToUInt16(value) }))); case PLCDataType.INT: return(BllResultFactory <byte[]> .Sucess(reverseBytesTransform.TransByte(new Int16[] { Convert.ToInt16(value) }))); case PLCDataType.DINT: return(BllResultFactory <byte[]> .Sucess(reverseBytesTransform.TransByte(new int[] { Convert.ToInt32(value) }))); case PLCDataType.CHAR: return(BllResultFactory <byte[]> .Sucess(reverseBytesTransform.TransByte(value.PadRight(20, ' '), Encoding.ASCII))); default: return(BllResultFactory <byte[]> .Error("未识别的数据类型")); } } catch (Exception ex) { return(BllResultFactory <byte[]> .Error("转换出现问题:" + ex.Message)); } }
/// <summary> /// Address type can be Memory or DB address, BUT IT CANNOT BE INPUT OR OUTPUT ADDRESS!! /// It returns false at unexpected situation. /// </summary> /// <param name="aType">Address type of registers that will be written. AddressType is used.</param> /// <param name="dbNo">DB address of registers that will be written. If Address type is Memory, this parameter value is not considered, it can be 0 for the default.</param> /// <param name="byteNo">Starting byte address of registers that will be written.</param> /// <param name="intList">Integer values of registers that will be written. It must be a list of integer in order.</param> /// <param name="dataType">Integer type of registers that will be read. PLCDataType is used. /// <para>Register type in PLC -> Byte => PLCDataType.Byte</para> /// <para>Register type in PLC -> Word, Int(Integer) => PLCDataType.Int</para> /// <para>Register type in PLC -> DInt(DInteger) => PLCDataType.DInt</para></param> /// <param name="isSigned">If the registers that will be written have sign, this parameter should be true.</param> /// <returns></returns> public bool write_integer_values(AddressType aType, int dbNo, int byteNo, List <int> intList, PLCDataType dataType = PLCDataType.DInteger, bool isSigned = true) { bool result = false; List <int> readIntList = new List <int>(); if (aType == AddressType.Input || aType == AddressType.Output) { throw new InvalidOperationException("Address type of registers that will be written cannot be Input or Output address type."); } if (!read_integer_values(aType, dbNo, byteNo, intList.Count, out readIntList, dataType)) { return(result); } int byteNum = dataType == PLCDataType.DInteger ? 4 : dataType == PLCDataType.Integer ? 2 : 1; int tryCounter = 0; int resultValue1 = -1; int resultValue2 = -1; int daveInt = (aType == AddressType.Memory) ? libnodave.daveFlags : libnodave.daveDB; int daveDB = (aType == AddressType.Memory) ? 0 : dbNo; byte[] byteValues = new byte[intList.Count * byteNum]; byte[] byteValuesRead = new byte[intList.Count * byteNum]; try { for (int i = 0; i < intList.Count; i++) { byte[] intToByteArr; if (!convert_byte_values(intList[i], byteNum, isSigned, out intToByteArr)) { return(result); } for (int j = 0; j < byteNum; j++) { byteValues[i * byteNum + j] = intToByteArr[j]; } } } catch (Exception e) { send_error_message(e, "WRITE INTEGER PROBLEM"); return(result); } if (!readIntList.SequenceEqual(intList)) { while (tryCounter < 4) { try { resultValue1 = dc.writeBytes(daveInt, daveDB, byteNo, byteValues.Length, byteValues); resultValue2 = dc.readBytes(daveInt, daveDB, byteNo, byteValues.Length, byteValuesRead); if (byteValues.SequenceEqual(byteValuesRead) && resultValue1 == 0 && resultValue2 == 0) { result = true; return(result); } else { tryCounter += 1; } } catch (Exception e) { send_error_message(e, "WRITE INTEGER PROBLEM"); return(result); } } } else { result = true; } return(result); }
/// <summary> /// Address type can be Memory or DB address, BUT IT CANNOT BE INPUT OR OUTPUT ADDRESS!! /// It returns false at unexpected situation. /// </summary> /// <param name="aType">Address type of registers that will be read. AddressType is used.</param> /// <param name="dbNo">DB address of registers that will be read. If Address type is Memory, this parameter value is not considered, it can be 0 for the default.</param> /// <param name="byteNo">Starting byte address of registers that will be read.</param> /// <param name="length">Number of integers that will be read.</param> /// <param name="resultInts">List that will contain integer values of registers that are read. /// Each element represents each integer that is read in order. /// </param> /// <param name="dataType">Integer type of registers that will be read. PLCDataType is used. /// <para>Register type in PLC -> Byte => PLCDataType.Byte</para> /// <para>Register type in PLC -> Word, Int(Integer) => PLCDataType.Int</para> /// <para>Register type in PLC -> DInt(DInteger) => PLCDataType.DInt</para> /// </param> /// <param name="isSigned"> If the registers that will be read have sign, this parameter should be true.</param> /// <returns></returns> public bool read_integer_values(AddressType aType, int dbNo, int byteNo, int length, out List <int> resultInts, PLCDataType dataType = PLCDataType.DInteger, bool isSigned = true) { bool result = false; int resultValue = -1; resultInts = new List <int>(); int byteNum = dataType == PLCDataType.DInteger ? 4 : dataType == PLCDataType.Integer ? 2 : 1; int byteLength = length * byteNum; byte[] valueRead = new byte[byteLength]; if (aType == AddressType.Input || aType == AddressType.Output) { throw new InvalidOperationException("Address type of registers that will be read cannot be Input or Output address type."); } int daveInt = (aType == AddressType.Memory) ? libnodave.daveFlags : libnodave.daveDB; int daveDB = (aType == AddressType.Memory) ? 0 : dbNo; List <int> IntsRead = new List <int>(); int maxValue = isSigned ? (int)Math.Pow(2, 8 * byteNum - 1) - 1 : (int)Math.Pow(2, 8 * byteNum) - 1; //signed - unsigned int try { resultValue = dc.readBytes(daveInt, daveDB, byteNo, byteLength, valueRead); bool always1Check = always_bit_check(); if (resultValue == 0 && always1Check) { int readValue = 0; for (int i = 0; i < valueRead.Length; i++) { readValue += valueRead[i] * (int)Math.Pow(2, 8 * ((valueRead.Length - i - 1) % byteNum)); if (i % byteNum == byteNum - 1) { int realValue = (isSigned && readValue > maxValue) ? readValue - 2 * (int)Math.Pow(2, 8 * byteNum - 1) : readValue; IntsRead.Add(realValue); readValue = 0; } } result = true; resultInts = IntsRead.ToList(); } } catch (Exception e) { send_error_message(e, "READ INTEGER PROBLEM"); } return(result); }
public void ScanPLC() { if (InovanceManage.m_inovanceAPI[netid].bConnectInovanceOk == false) { return; } while (true) { Action action1 = () => { if (InovanceManage.m_inovanceAPI[netid].bConnectInovanceOk) { ConnIndicatePB.Image = Green; } else { ConnIndicatePB.Image = Grey; } }; ConnIndicatePB.Invoke(action1); for (int i = 0; i < dataGridView.Rows.Count; i++) { //if (!bool.Parse(dataGridView.Rows[i].Cells[4].Value.ToString())) //{ // continue; //} try { string strName = dataGridView.Rows[i].Cells[0].Value.ToString(); ScanItem updatedictionary = InovanceManage.m_inovanceDoc[netid].m_scanDictionary[strName]; ScanItem updatelist = InovanceManage.m_inovanceDoc[netid].m_ScanDataList[i]; SoftElemType elementtype = (SoftElemType)dataGridView.Rows[i].Cells[1].Value; int startaddress = int.Parse(dataGridView.Rows[i].Cells[2].Value.ToString()); PLCDataType datatype = (PLCDataType)dataGridView.Rows[i].Cells[3].Value; string strValue = string.Empty; switch (datatype) { case PLCDataType.BYTE: byte[] tempbyte = new byte[1]; InovanceManage.m_inovanceAPI[netid].ReadH3UElement(netid, elementtype, startaddress, 1, ref tempbyte); strValue = tempbyte[0].ToString(); break; case PLCDataType.INT16: short[] tempshort = new short[1]; InovanceManage.m_inovanceAPI[netid].ReadH3UElement(netid, elementtype, startaddress, 1, ref tempshort); strValue = tempshort[0].ToString(); break; case PLCDataType.INT32: Int32[] templong = new Int32[1]; InovanceManage.m_inovanceAPI[netid].ReadH3UElement(netid, elementtype, startaddress, 2, ref templong); strValue = templong[0].ToString(); break; case PLCDataType.UINT16: ushort[] tempushort = new ushort[1]; InovanceManage.m_inovanceAPI[netid].ReadH3UElement(netid, elementtype, startaddress, 1, ref tempushort); strValue = tempushort[0].ToString(); break; case PLCDataType.UINT32: UInt32[] tempulong = new UInt32[1]; InovanceManage.m_inovanceAPI[netid].ReadH3UElement(netid, elementtype, startaddress, 2, ref tempulong); strValue = tempulong[0].ToString(); break; case PLCDataType.FLOAT: float[] tempfloat = new float[1]; InovanceManage.m_inovanceAPI[netid].ReadH3UElement(netid, elementtype, startaddress, 2, ref tempfloat); strValue = tempfloat[0].ToString(); break; } updatedictionary.strValue = strValue; updatelist.strValue = strValue; Action action = () => { dataGridView.Rows[i].Cells[4].Value = strValue; }; this.Invoke(action); } catch (Exception ex) { Action action = () => { dataGridView.Rows[i].Cells[4].Value = ex.ToString(); }; this.Invoke(action); } Thread.Sleep(10); } } }
private void buttonSet_Click(object sender, EventArgs e) { bool bRet = false; if (dataGridView.SelectedRows.Count <= 0) { MessageBox.Show("请先选中要设定的行"); return; } if (string.IsNullOrEmpty(textBoxName.Text)) { MessageBox.Show("名字为空,请检查!"); return; } if (string.IsNullOrEmpty(cbAddressType.SelectedItem.ToString())) { MessageBox.Show("元件地址为空,请检查!"); return; } if (int.Parse(tbStartAddress.Text) < 0) { MessageBox.Show("元件地址小于零,请检查!"); return; } if (string.IsNullOrEmpty(cbDataType.SelectedItem.ToString())) { MessageBox.Show("元件数据类型为空,请检查!"); return; } switch ((PLCDataType)cbDataType.SelectedItem) { case PLCDataType.BYTE: if (tbSetValue.Text != "0" && tbSetValue.Text != "1") { MessageBox.Show("字节只能赋值为0或1"); return; } break; case PLCDataType.INT16: if (!JudgeNumber.isWhloeNumber(tbSetValue.Text)) { MessageBox.Show("输入数据不是整形"); return; } if (Int64.Parse(tbSetValue.Text) < Int16.MinValue || Int64.Parse(tbSetValue.Text) > Int16.MaxValue) { MessageBox.Show("请输入-32768~32767之间的数字!"); return; } break; case PLCDataType.INT32: if (!JudgeNumber.isWhloeNumber(tbSetValue.Text)) { MessageBox.Show("输入数据不是整形"); return; } if (Int64.Parse(tbSetValue.Text) < Int32.MinValue || Int64.Parse(tbSetValue.Text) > Int32.MaxValue) { MessageBox.Show("请输入-2147483648~2147483647之间的数字!"); return; } break; case PLCDataType.UINT16: if (!JudgeNumber.isPositiveInteger(tbSetValue.Text)) { MessageBox.Show("输入数据不是无符号整形"); return; } if (UInt64.Parse(tbSetValue.Text) < 0 || UInt64.Parse(tbSetValue.Text) > 32767) { MessageBox.Show("请输入0~32767之间的数字!"); return; } break; case PLCDataType.UINT32: if (!JudgeNumber.isPositiveInteger(tbSetValue.Text)) { MessageBox.Show("输入数据不是无符号整形"); return; } if (UInt64.Parse(tbSetValue.Text) < 0 || UInt64.Parse(tbSetValue.Text) > 2147483647) { MessageBox.Show("请输入0~2147483647之间的数字!"); return; } break; case PLCDataType.FLOAT: if (!JudgeNumber.isDecimal(tbSetValue.Text)) { MessageBox.Show("输入数据不是浮点数"); return; } break; } string strName = textBoxName.Text; SoftElemType elementtype = (SoftElemType)cbAddressType.SelectedItem; int startaddress = int.Parse(tbStartAddress.Text); PLCDataType datatype = (PLCDataType)cbDataType.SelectedItem; string strValue = tbSetValue.Text; switch (datatype) { case PLCDataType.BYTE: byte[] tempbyte = new byte[1]; tempbyte[0] = byte.Parse(strValue); bRet = InovanceManage.m_inovanceAPI[netid].WriteH3UElement(netid, elementtype, startaddress, 1, tempbyte); break; case PLCDataType.INT16: Int16[] tempshort = new Int16[1]; tempshort[0] = short.Parse(strValue); bRet = InovanceManage.m_inovanceAPI[netid].WriteH3UElement(netid, elementtype, startaddress, 1, tempshort); break; case PLCDataType.INT32: Int32[] templong = new Int32[1]; templong[0] = Int32.Parse(strValue); bRet = InovanceManage.m_inovanceAPI[netid].WriteH3UElement(netid, elementtype, startaddress, 2, templong); break; case PLCDataType.UINT16: UInt16[] tempushort = new UInt16[1]; tempushort[0] = ushort.Parse(strValue); bRet = InovanceManage.m_inovanceAPI[netid].WriteH3UElement(netid, elementtype, startaddress, 1, tempushort); break; case PLCDataType.UINT32: UInt32[] tempulong = new UInt32[1]; tempulong[0] = UInt32.Parse(strValue); bRet = InovanceManage.m_inovanceAPI[netid].WriteH3UElement(netid, elementtype, startaddress, 2, tempulong); break; case PLCDataType.FLOAT: float[] tempfloat = new float[1]; tempfloat[0] = float.Parse(strValue); bRet = InovanceManage.m_inovanceAPI[netid].WriteH3UElement(netid, elementtype, startaddress, 2, tempfloat); break; } }
public virtual PLCResponse SetWord(string strAddress, PLCDataType dataType, string strValue) { return(PLCResponse.SUCCESS); }
protected virtual string ConvertValueToMessage(string strValue, PLCDataType dataType) { string strReturn = "00000000"; string strTemp = ""; try { if (dataType == PLCDataType.BIT16) { Int16 iTemp16 = Convert.ToInt16(strValue, 2); strTemp = iTemp16.ToString("X4"); strReturn = strTemp.Substring(2, 1) + strTemp.Substring(3, 1) + strTemp.Substring(0, 1) + strTemp.Substring(1, 1); } if (dataType == PLCDataType.BIT32) { Int32 iTemp32 = Convert.ToInt32(strValue, 2); strTemp = iTemp32.ToString("X8"); strReturn = strTemp.Substring(6, 1) + strTemp.Substring(7, 1) + strTemp.Substring(4, 1) + strTemp.Substring(5, 1) + strTemp.Substring(2, 1) + strTemp.Substring(3, 1) + strTemp.Substring(0, 1) + strTemp.Substring(1, 1); } if (dataType == PLCDataType.BIN16) { Int16 iTemp16 = Convert.ToInt16(strValue, 10); strTemp = iTemp16.ToString("X4"); strReturn = strTemp.Substring(2, 1) + strTemp.Substring(3, 1) + strTemp.Substring(0, 1) + strTemp.Substring(1, 1); } if (dataType == PLCDataType.BIN32) { Int32 iTemp32 = Convert.ToInt32(strValue, 10); strTemp = iTemp32.ToString("X8"); strReturn = strTemp.Substring(6, 1) + strTemp.Substring(7, 1) + strTemp.Substring(4, 1) + strTemp.Substring(5, 1) + strTemp.Substring(2, 1) + strTemp.Substring(3, 1) + strTemp.Substring(0, 1) + strTemp.Substring(1, 1); } if (dataType == PLCDataType.HEX16) { Int16 iTemp16 = Convert.ToInt16(strValue, 16); strTemp = iTemp16.ToString("X4"); strReturn = strTemp.Substring(2, 1) + strTemp.Substring(3, 1) + strTemp.Substring(0, 1) + strTemp.Substring(1, 1); } if (dataType == PLCDataType.HEX32) { Int32 iTemp32 = Convert.ToInt32(strValue, 16); strTemp = iTemp32.ToString("X8"); strReturn = strTemp.Substring(6, 1) + strTemp.Substring(7, 1) + strTemp.Substring(4, 1) + strTemp.Substring(5, 1) + strTemp.Substring(2, 1) + strTemp.Substring(3, 1) + strTemp.Substring(0, 1) + strTemp.Substring(1, 1); } if (dataType == PLCDataType.DOUBLE) { float f = Convert.ToSingle(strValue); byte[] floatValues = BitConverter.GetBytes(f); strTemp = floatValues[3].ToString("X2") + floatValues[2].ToString("X2") + floatValues[1].ToString("X2") + floatValues[0].ToString("X2"); strReturn = strTemp.Substring(6, 1) + strTemp.Substring(7, 1) + strTemp.Substring(4, 1) + strTemp.Substring(5, 1) + strTemp.Substring(2, 1) + strTemp.Substring(3, 1) + strTemp.Substring(0, 1) + strTemp.Substring(1, 1); } if (dataType == PLCDataType.STRING) { char[] charArrange = strValue.ToCharArray(); byte byteTemp = 0; foreach (char tempChar in charArrange) { byteTemp = (byte)tempChar; strTemp = strTemp + byteTemp.ToString("X2"); } strReturn = strTemp; } } catch { } return(strReturn); }
internal PLCResponse GetWordValue(string[] strArray, PLCDataType dataType, out string strValue) { strValue = ""; HiPerfTimer timeM = new HiPerfTimer(); string strCommand = "%" + strArray[0] + "#" + strArray[1] + strArray[2] + strArray[3] + strArray[4]; string strFcs = CreateFcsCodeFun(strCommand); string strEndCode = "\r"; string strMessage = strCommand + strFcs + strEndCode; string strRecieve; lock (objLock) { #region 通信 try { serialPort.ReadExisting(); System.Threading.Thread.Sleep(1); serialPort.Write(strMessage); System.Threading.Thread.Sleep(1); timeM.Start(); strRecieve = serialPort.ReadExisting(); while (true) { try { strRecieve = strRecieve + serialPort.ReadExisting(); if (strRecieve.IndexOf("\r") > -1) { //strRecieve = strRecieve.Trim(); if (strRecieve.IndexOf("%") < 0 || strRecieve.IndexOf("$") < 0 || strRecieve.Length != 17) { return(PLCResponse.ERROR); } string strMessageReturn = strRecieve.Substring(0, 14); string strFcsReturn = strRecieve.Substring(14, 2); strFcs = CreateFcsCodeFun(strMessageReturn); if (strFcs != strFcsReturn) { return(PLCResponse.FCSERR); } strValue = strRecieve.Substring(6, 8); strValue = ConvertMesToValue(strValue, dataType); break; } if (timeM.TimeUp(0.5)) { return(PLCResponse.TIMEOUT); } } catch//(Exception ex) { return(PLCResponse.OTHERS); } System.Threading.Thread.Sleep(1); } } catch { return(PLCResponse.OTHERS); } #endregion } return(PLCResponse.SUCCESS); }
internal PLCResponse SetWordValue(string[] strArray, PLCDataType dataType, string strValue) { //strValue = ""; HiPerfTimer timeM = new HiPerfTimer(); strArray[1] = strArray[1].Replace('R', 'W'); string strMessageValue = ConvertValueToMessage(strValue, dataType); string strCommand = ""; if (dataType == PLCDataType.BIN16 || dataType == PLCDataType.HEX16 || dataType == PLCDataType.BIT16 || (dataType == PLCDataType.STRING && strValue.Length <= 2)) { strCommand = "%" + strArray[0] + "#" + strArray[1] + strArray[2] + strArray[3] + strArray[4] + strMessageValue + strMessageValue; } else { strCommand = "%" + strArray[0] + "#" + strArray[1] + strArray[2] + strArray[3] + strArray[4] + strMessageValue; } string strFcs = CreateFcsCodeFun(strCommand); string strEndCode = "\r"; string strMessage = strCommand + strFcs + strEndCode; string strRecieve; lock (objLock) { #region 通信 try { serialPort.ReadExisting(); serialPort.Write(strMessage); timeM.Start(); strRecieve = serialPort.ReadExisting(); while (true) { try { strRecieve = strRecieve + serialPort.ReadExisting(); if (strRecieve.IndexOf("\r") > -1) { //strRecieve = strRecieve.Trim(); if (strRecieve.IndexOf("%") < 0 || strRecieve.IndexOf("$") < 0 || strRecieve.Length != 9) { return(PLCResponse.ERROR); } string strMessageReturn = strRecieve.Substring(0, 6); string strFcsReturn = strRecieve.Substring(6, 2); strFcs = CreateFcsCodeFun(strMessageReturn); if (strFcs != strFcsReturn) { return(PLCResponse.FCSERR); } break; } if (timeM.TimeUp(0.5)) { return(PLCResponse.TIMEOUT); } } catch//(Exception ex) { return(PLCResponse.OTHERS); } System.Threading.Thread.Sleep(1); } } catch { return(PLCResponse.OTHERS); } #endregion } return(PLCResponse.SUCCESS); }