Пример #1
0
        private byte[] ReceiveData(UInt16?MsgId)
        {
            byte[] data = new byte[1024];//定义数据接收数组
            try
            {
                //var t1 = DateTime.Now;
                socket.Receive(data);//接收数据到data数组
                //var t2 = DateTime.Now;
                //var df = t2 - t1;
                //Console.WriteLine($"收 {df.TotalMilliseconds} ms");

                //Console.WriteLine(data);
            }
            catch (Exception ex)
            {
                this.Connected = false;
                ErrorMessage   = ex.Message;

                try
                {
                    socket.Close();
                }
                catch { }
                return(null);
            }
            var id = ByteUtil.BytesToUInt16(data[0], data[1]);

            if (!MsgId.HasValue || id != MsgId.Value)
            {
                ErrorMessage = "信息标识号不正确!";
                return(null);
            }
            int length = ByteUtil.BytesToInt16(data[4], data[5]);//读取数据长度

            //Console.WriteLine(String.Format("长度={0}", length));


            if (length == 3 && data[7] > 0x80)
            {
                var errorCode = (ModbusErrorEnum)data[8];
                this.ErrorMessage = errorCode.GetDescription();
                return(null);
            }
            Byte[] realData = new byte[length - 2];//定义所要显示的接收的数据的长度
            Array.Copy(data, 8, realData, 0, length - 2);
            return(realData);
        }
Пример #2
0
        unsafe public override void Can_Rec_Tick()
        {
            UInt32 res = new UInt32();

            res = VCI_GetReceiveNum(DevType, DevIndex, CanIndex);
            if (res == 0)
            {
                return;
            }
            /////////////////////////////////////
            UInt32 con_maxlen = 100;
            IntPtr pt         = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(VCI_CAN_OBJ)) * (Int32)con_maxlen);

            res = VCI_Receive(DevType, DevIndex, CanIndex, pt, con_maxlen, 5);
            ////////////////////////////////////////////////////////
            String str = "";

            for (UInt32 i = 0; i < res; i++)
            {
                VCI_CAN_OBJ?reviceObj = null;
                try
                {
                    reviceObj = (VCI_CAN_OBJ)Marshal.PtrToStructure((IntPtr)(pt.ToInt64() + i * Marshal.SizeOf(typeof(VCI_CAN_OBJ))), typeof(VCI_CAN_OBJ));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                if (!reviceObj.HasValue)
                {
                    break;
                }
                var obj      = reviceObj.Value;
                var targetID = (byte)(obj.ID >> 3);
                var mask     = (byte)(obj.ID & 0b111);

                Console.Write("rec: 0x{0:x4} ", obj.ID);
                for (var j = 0; j < obj.DataLen; j++)
                {
                    Console.Write("0x{0:x2} ", obj.Data[j]);
                }
                TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                Console.WriteLine("TimeStamp:" + Convert.ToInt64(ts.TotalSeconds).ToString());

                if (targetID != (byte)(ID & (0xFF << 3 | mask)))
                {
                    Console.WriteLine("ID不符,数据丢弃");
                    continue;
                }

                //Console.WriteLine("objlen=" + obj.DataLen);
                str  = "接收到数据: ";
                str += "  设备ID:0x" + Convert.ToString(targetID, 16);
                str += "  ID掩码:0x" + Convert.ToString(mask, 16);
                str += "  帧格式:";
                if (obj.RemoteFlag == 0)
                {
                    str += "数据帧 ";
                }
                else
                {
                    str += "远程帧 ";
                }
                if (obj.ExternFlag == 0)
                {
                    str += "标准帧 ";
                }
                else
                {
                    str += "扩展帧 ";
                }

                //////////////////////////////////////////
                if (obj.RemoteFlag == 0)
                {
                    str += "数据: ";
                    byte   len  = (byte)(Math.Min(obj.DataLen % 50, 8));
                    byte[] data = new byte[len];
                    for (byte j = 0; j < len; j++)
                    {
                        data[j] = obj.Data[j];
                        str    += " " + ByteUtil.ToHex(obj.Data[j]);
                    }
                    //bool is_mask = (data[0] & 0x07) == 0x07;
                    //data[0] = is_mask ? (byte)(data[0] >> 3) : data[0];
                    (String CanAddress, CanFunCodeEnum FunCode) = ParseCanData(data);
                    if (FunCode == CanFunCodeEnum.UPLOAD_COIL || FunCode == CanFunCodeEnum.UPLOAD_REGISTER || FunCode == CanFunCodeEnum.READ_COIL || FunCode == CanFunCodeEnum.READ_REGISTER || FunCode == CanFunCodeEnum.WRITE_SINGLE_COIL || FunCode == CanFunCodeEnum.WRITE_SINGLE_REGISTER)
                    {
                        lock (RecSafeData.Lock)
                        {
                            bool is_pass = true;
                            if (FunCode == CanFunCodeEnum.WRITE_SINGLE_COIL || FunCode == CanFunCodeEnum.WRITE_SINGLE_REGISTER)
                            {
                                is_pass = data[3] == 0xb0 || data[4] == 0xff || data[5] == 0xff;
                            }
                            if (is_pass == false)
                            {
                                ErrorSystem.WriteActError("通讯返回错误!", false);
                            }
                            if (is_pass)
                            {
                                string key_str = ByteUtil.ToHex(targetID) + ByteUtil.ToHex(data[0]) + ByteUtil.ToHex(data[1]) + ByteUtil.ToHex(data[2]) + ByteUtil.ToHex(data[3]);
                                if (!Rec_SafeData.ContainsKey(key_str))
                                {
                                    Rec_SafeData.Add(key_str, true);
                                }
                                else
                                {
                                    Rec_SafeData[key_str] = true;
                                }
                                if (ListenFunList.ContainsKey(key_str))
                                {
                                    var task = Task.Run(() =>
                                    {
                                        ListenFunList[key_str](targetID, data);
                                    });
                                }
                            }
                        }
                    }
                    switch (FunCode)
                    {
                    case CanFunCodeEnum.READ_COIL:
                    {
                        byte   length = 1;
                        String canId  = CanAddress.Split('-')[0];
                        UInt16 addr   = ByteUtil.BytesToUInt16(data[2], data[3]);
                        for (byte k = 0; k < length; k++)
                        {
                            byte   curData = data[k / 8 + 4];
                            String key     = canId + "-" + Convert.ToString(addr + k, 16).PadLeft(4, '0').ToUpper();
                            //var val = ((0x01 << (k % 8)) & curData) == 0x01;
                            var val = data[4] == 0xff;
                            SetBool(key, val);
                        }
                        break;
                    }

                    case CanFunCodeEnum.UPLOAD_COIL:
                    {
                        byte   length = data[4];
                        String canId  = CanAddress.Split('-')[0];
                        UInt16 addr   = ByteUtil.BytesToUInt16(data[2], data[3]);
                        for (byte k = 0; k < length; k++)
                        {
                            byte   curData = data[k / 8 + 5];
                            String key     = canId + "-" + Convert.ToString(addr + k, 16).PadLeft(4, '0').ToUpper();
                            var    val     = ((0x01 << (k % 8)) & curData) == 0x01;
                            SetBool(key, val);
                        }
                        break;
                    }

                    case CanFunCodeEnum.READ_REGISTER:
                    case CanFunCodeEnum.UPLOAD_REGISTER:
                    {
                        var val = ByteUtil.BytesToInt(data[4], data[5], data[6], data[7]);
                        SetInt(CanAddress, val);
                        break;
                    }

                    case CanFunCodeEnum.WRITE_MULTI_COIL:
                    {
                        break;
                    }

                    case CanFunCodeEnum.WRITE_SINGLE_COIL:
                    {
                        break;
                    }

                    case CanFunCodeEnum.WRITE_SINGLE_REGISTER:
                    {
                        break;
                    }
                    }
                }
                //Console.WriteLine(str);
            }
            Marshal.FreeHGlobal(pt);
        }