예제 #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="slaveMacId"></param>
        /// <param name="classCode"></param>
        /// <param name="instanceId"></param>
        public void ObjectResetService(int slaveMacId, byte classCode, byte instanceId)
        {
            byte[] request = new byte[]
            {
                (byte)MasterMacId,                  /*Source MAC Id: 0..64 */
                Services.SRVS_RESET,                /*Get Attribute Single*/
                classCode,                          /*Class Code*/
                instanceId,                         /*Instance Id*/
            };

            Adapter.Write(new CanMessage[]
            {
                new CanMessage(DeviceNetAddressing.GetExplicitRequestCanId(slaveMacId), request)
            });

            int  retrty    = 3;
            long timestamp = DateTime.Now.Ticks;
            bool isTimeout = false;

            CanMessage[] rxMsgBuffer = new CanMessage[1];
            do
            {
                do
                {
                    if (Adapter.Attributes.PendingRxMessages > 0)
                    {
                        isTimeout = false;
                        Adapter.Read(rxMsgBuffer, 0, 1);
                        break;
                    }
                    isTimeout = DateTime.Now.Ticks - timestamp > 1000 * 10000;
                } while (!isTimeout);

                if (isTimeout && retrty != 0)
                {
                    timestamp = DateTime.Now.Ticks;
                }
            } while (--retrty != 0 && isTimeout);

            if (isTimeout)
            {
                throw new DeviceNetException("DeviceNet: Response Timeout.");
            }

            byte[] response = rxMsgBuffer[0].Data;

            if (response[1] == 0x94)
            {
                throw new DeviceNetException("DeviceNet:" + DeviceNetException.ErrorMessageToString(response[2], response[3]));
            }

            if ((response[1] & 0x80) != 0x80)
            {
                throw new ApplicationException("DeviceNet:" + "Response Invalid.");
            }
        }
        /// <summary>
        ///
        /// </summary>
        public void AllocateExplicitConnection(int slaveMacId)
        {
            Adapter.Write(new CanMessage[]
            {
                new CanMessage(DeviceNetAddressing.GetUnconnctedExplicitRequestCanId(slaveMacId), new byte[] { 0x00, 0x4B, 0x03, 0x01, 0x01, 0x00 })
            });

            int  retrty    = 3;
            long timestamp = DateTime.Now.Ticks;
            bool isTimeout = false;

            CanMessage[] rxMsgBuffer = new CanMessage[1];
            do
            {
                do
                {
                    if (Adapter.Attributes.PendingRxMessages > 0)
                    {
                        isTimeout = false;
                        Adapter.Read(rxMsgBuffer, 0, 1);
                        break;
                    }
                    isTimeout = DateTime.Now.Ticks - timestamp > 1000 * 10000;
                } while (!isTimeout);

                if (isTimeout && retrty != 0)
                {
                    timestamp = DateTime.Now.Ticks;
                }
            } while (--retrty != 0 && isTimeout);

            CanMessage response = rxMsgBuffer[0];

            if (isTimeout)
            {
                throw new DeviceNetException("DeviceNet: Response Timeout.");
            }

            if (response.Data[1] == 0x94)
            {
                throw new DeviceNetException("DeviceNet:" + DeviceNetException.ErrorMessageToString(response.Data[2], response.Data[3]));
            }

            if ((response.Data[1] & 0x80) != 0x80)
            {
                throw new ApplicationException("DeviceNet:" + "Response Invalid.");
            }
        }
예제 #3
0
        static void Main(string[] args)
        {
            /*Adapter példányosítása*/
            CanAdapterDevice adapter = new CanAdapterDevice();

            /*Kapcsolódás egy létező adapterhez.*/
            adapter.Connect();
            /*Kapcsolódott ezzel a SerialNumber-el rendlekező adapterhez.*/
            Console.WriteLine("Connected to: " + adapter.Attributes.SerialNumber);
            /*Busz lezárás engedélyezése. */
            adapter.Attributes.Termination = true;
            /*Megnyitás az átviteli sebesség paraméterrel.*/
            adapter.Open(CanBaudRateCollection.Speed500kBaud);
            /*Üzenet tömb létrehozása.*/
            var txMsgArray = new CanMessage[]
            {
                new CanMessage(0x01FF, new byte[] { 0x01, 0x02, 0x03, 0x04 })
            };

            /*Üzenet tömb küldése.*/
            adapter.Write(txMsgArray);
            /*Kapcsolat zárása*/
            adapter.Close();
            /*Kapcsolat bontása*/
            adapter.Disconnect();
            Console.Read();
        }
예제 #4
0
        public void _0001_MaxWriteSpeed_500kBaud()
        {
            CanMessage cm        = new CanMessage(0x000001, new byte[] { 0x01, 0x02 });
            long       timestamp = DateTime.Now.Ticks;

            do
            {
                _adapterWriter.Write(new CanMessage[] { cm });
            } while ((DateTime.Now.Ticks - timestamp) < 10000 * 10000);
        }
예제 #5
0
        /********************************************************************************/
        public void Write(byte[] data, ref string log)
        {
            CanMessage msg = new CanMessage(TransmittId, data);

            _adapter.Write(new CanMessage[] { msg });
            string templog = Tools.TimestampFormat(DateTime.Now.Ticks) + ";" + "Tx:;" + Tools.MsgFormat(msg);

            Console.WriteLine(templog);
            if (log != null)
            {
                log += templog + "\r\n";
            }
        }
        public void _0009_Loopback_MessageStdA4()
        {
            if (_adapter.IsOpen)
            {
                _adapter.Close();
            }

            if (_adapter.Attributes.State != CanState.SDEV_IDLE)
            {
                _adapter.Services.Reset();
            }

            CanMessage[] buffer = new CanMessage[1];
            _adapter.Attributes.Loopback = true;
            _adapter.Open(_targetBaudrate);
            _adapter.Write(new CanMessage[] { CanMessage.MessageStdA4 });
            do
            {
            } while (_adapter.Attributes.PendingRxMessages != 1);
            _adapter.Read(buffer, 0, 1);
            Assert.IsTrue(buffer.Contains(CanMessage.MessageStdA4));
        }
예제 #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="address"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        byte[] RequestResponse(byte sMacId, byte dMacId, byte[] request, bool isUnconnected)
        {
            bool rxComplete  = false;
            byte fragCounter = 0;

            byte[] response       = new byte[8];
            int    responseLength = 0;

            string log = string.Empty;

            CanMessage txmsg;

            if (isUnconnected)
            {
                txmsg = new CanMessage(GetMasterUnconnctedExplicitRequestAddress(dMacId), request);
            }
            else
            {
                txmsg = new CanMessage(GetMasterExplicitRequestAddress(dMacId), request);
            }
            Adapter.Write(new CanMessage[] { txmsg });

            do
            {
                var  rxMsgBuffer = new CanMessage[1];
                bool isTimeout   = false;
                long timestamp   = DateTime.Now.Ticks;

                do
                {
                    if (Adapter.Attributes.PendingRxMessages >= 1)
                    {
                        Adapter.Read(rxMsgBuffer, 0, 1);
                        break;
                    }
                    isTimeout = DateTime.Now.Ticks - timestamp > 1000 * 10000;
                } while (!isTimeout);

                if (isTimeout)
                {
                    throw new ApplicationException("Timoeut");
                }

                //Console.WriteLine(string.Format("Frag: 0x{0:X2}", rxMsgBuffer[0].Data[SOURCE_ADDR_POS_IN_FRAME]));

                if ((rxMsgBuffer[0].Data[SOURCE_ADDR_POS_IN_FRAME] & FRAG_BIT_POS_IN_BYTE) == FRAG_BIT_POS_IN_BYTE)
                {
                    //Console.WriteLine(string.Format("Frag Counter: 0x{0:X2}", rxMsgBuffer[0].Data[FRAG_COUNTER_POS_IN_FRAME]));

                    switch ((rxMsgBuffer[0].Data[FRAG_COUNTER_POS_IN_FRAME] & 0xC0) >> 6)
                    {
                    case 0x00: { /*Console.WriteLine("First Fragment");*/ break; }

                    case 0x01: { /*Console.WriteLine("Middle Fragment");*/ break; }

                    case 0x02:
                    {
                        rxComplete = true;
                        /*Console.WriteLine("Last Fragment");*/
                        break;
                    }

                    default:
                    {
                        throw new ApplicationException("Invlaid Response");
                    }
                    }
                    //-------
                    byte[] ack = new byte[]
                    {
                        (byte)(0x80 | sMacId),
                        (byte)((3 << 6) | fragCounter),
                        0x00
                    };
                    txmsg = new CanMessage(GetMasterExplicitRequestAddress(dMacId), ack);
                    Adapter.Write(new CanMessage[] { txmsg });
                    //-------
                    if (responseLength == 0)
                    {//Beszurja a SourceMacId-t az fragmentált üzenet elejére
                        responseLength = 1;
                        Array.Resize(ref response, responseLength);
                        response[0] = rxMsgBuffer[0].Data[0];
                    }

                    Array.Resize(ref response, responseLength + rxMsgBuffer[0].Data.Length - 2);
                    Buffer.BlockCopy(rxMsgBuffer[0].Data, 2, response, responseLength, rxMsgBuffer[0].Data.Length - 2);
                    responseLength += rxMsgBuffer[0].Data.Length - 2;
                    fragCounter++;
                }
                else
                {
                    Buffer.BlockCopy(rxMsgBuffer[0].Data, 0, response, 0, rxMsgBuffer[0].Data.Length);
                    rxComplete = true;
                }
            } while (!rxComplete);
            return(response);
        }
        public void _0001_WriteRead_SingleMessage()
        {
            if (_adapterWriter.IsOpen)
            {
                _adapterWriter.Close();
            }

            if (_adapterReader.IsOpen)
            {
                _adapterReader.Close();
            }

            if (_adapterWriter.Attributes.State != CanState.SDEV_IDLE)
            {
                _adapterWriter.Services.Reset();
            }

            if (_adapterReader.Attributes.State != CanState.SDEV_IDLE)
            {
                _adapterReader.Services.Reset();
            }

            _adapterWriter.Attributes.Termination = true;
            _adapterReader.Attributes.Termination = true;

            _adapterWriter.Open(_targetBaudrate);
            Thread.Sleep(50);
            _adapterReader.Open(_targetBaudrate);

            _adapterWriter.Write(new CanMessage[] { CanMessage.MessageStdC8 });

            CanMessage[] rxFrames = new CanMessage[128];
            int          offset = 0, length = 0;
            long         startTick = DateTime.Now.Ticks;

            do
            {
                length = _adapterReader.Attributes.PendingRxMessages;
                _adapterReader.Read(rxFrames, offset, length);
                offset += length;

                if (DateTime.Now.Ticks - startTick > 1000 * 10000)
                {
                    throw new Exception("Timeout");
                }
            } while (offset == 0);

            Assert.AreEqual(0, _adapterReader.Attributes.RxDrop, "Reader RxDrop nem nulla: " + _adapterReader.Attributes.RxDrop.ToString());
            Assert.AreEqual(1, _adapterReader.Attributes.RxTotal, "");

            Assert.AreEqual(0, _adapterWriter.Attributes.TxDrop, "Writer TxDrop nem nulla: " + _adapterWriter.Attributes.TxDrop.ToString());
            Assert.AreEqual(1, _adapterWriter.Attributes.TxTotal, "Writer TxDrop nem nulla: " + _adapterWriter.Attributes.TxTotal.ToString());

            Assert.AreEqual(0, _adapterWriter.Attributes.TxDrop, "Writer TxDrop nem nulla: " + _adapterWriter.Attributes.TxDrop.ToString());
            Assert.AreEqual(1, _adapterReader.Attributes.RxTotal, "Az adapter FIFO-jába nem jött meg minden:" + _adapterReader.Attributes.RxTotal.ToString());
            Assert.AreEqual(1, offset, "A Host FIFO-jaba nem jött meg minden.");
        }
        void AsyncTest(int msgCount, uint baudrate)
        {
            CanAdapterDevice adapterWriter = new CanAdapterDevice();
            var selectedAdapterWriter      = CanAdapterDevice.GetAdapters()[0]; //{CAN Bus Adpater - MCAN120803 3873366E3133 }

            adapterWriter.ConnectTo(selectedAdapterWriter);

            CanAdapterDevice adapterReader = new CanAdapterDevice();
            var selectedAdapterReader      = CanAdapterDevice.GetAdapters()[1]; //{CAN Bus Adpater - MCAN120803 387536633133 }

            adapterReader.ConnectTo(selectedAdapterReader);

            Stopwatch watch = new Stopwatch();

            if (adapterWriter.Attributes.State != CanState.SDEV_IDLE)
            {
                adapterWriter.Services.Reset();
            }

            if (adapterReader.Attributes.State != CanState.SDEV_IDLE)
            {
                adapterReader.Services.Reset();
            }

            adapterWriter.Attributes.Termination = true;
            adapterReader.Attributes.Termination = true;

            try
            {
                CanMessage[] txFrames = new CanMessage[msgCount];

                Action writer = () =>
                {
                    try
                    {
                        for (int i = 0; i < msgCount; i++)
                        {
                            txFrames[i] = CanMessage.MessageStdC8;
                            byte[] valuebytes = BitConverter.GetBytes((uint)i + 1);
                            Buffer.BlockCopy(valuebytes, 0, txFrames[i].Data, 0, valuebytes.Length);
                        }
                        adapterWriter.Write(txFrames);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                };


                CanMessage[] rxFrames = new CanMessage[msgCount];
                int          offset   = 0;

                watch.Start();
                long           startTick = DateTime.Now.Ticks;
                AutoResetEvent doneEv    = new AutoResetEvent(false);
                Action         reader    = () =>
                {
                    try
                    {
                        do
                        {
                            if (DateTime.Now.Ticks - startTick > 15000 * 10000)
                            {
                                throw new Exception("Timeout");
                            }

                            int length = adapterReader.Attributes.PendingRxMessages;
                            adapterReader.Read(rxFrames, offset, length);
                            //Console.WriteLine("Pending: " + length + "Length: " + offset );
                            offset += length;
                        } while (offset != msgCount);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine("RxTotal:" + adapterReader.Attributes.RxTotal.ToString());
                        Console.WriteLine("RxDrop:" + adapterReader.Attributes.RxDrop.ToString());
                    }
                    doneEv.Set();
                };

                adapterWriter.Open(baudrate);
                adapterReader.Open(baudrate);

                reader.BeginInvoke(null, null);
                Thread.Sleep(50);
                writer.BeginInvoke(null, null);

                doneEv.WaitOne();
                watch.Stop();

                double calcBps1 = ((msgCount * 8E+0) / (watch.ElapsedMilliseconds / 1000E+0));
                double calcBps2 = ((msgCount * 8E+0) / (((DateTime.Now.Ticks - startTick) / 10000E+0) / 1000E+0));

                uint rxTotal = adapterReader.Attributes.RxTotal;
                Console.WriteLine("Reader RxDrop: " + adapterReader.Attributes.RxDrop);
                Console.WriteLine("Writer TxDrop: " + adapterWriter.Attributes.TxDrop);
                Console.WriteLine("Átjött Host FIFO-jába: " + offset);
                Console.WriteLine("Számított Baudrate 1: " + calcBps1.ToString());
                Console.WriteLine("Számított Baudrate 2: " + calcBps2.ToString());
                adapterReader.Close();
                adapterWriter.Close();

                Assert.AreEqual(msgCount, rxTotal, "Az adapter FIFO-jába nem jött meg minden.");
                Assert.AreEqual(msgCount, offset, "A Host FIFO-jaba nem jött meg minden.");
            }
            catch
            {
                throw;
            }
            finally
            {
                adapterWriter.Disconnect();
                adapterReader.Disconnect();
            }
        }
예제 #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();

            Adapter.Write(new CanMessage[] { new CanMessage(0x0000, new byte[0]) });
            Thread.Sleep(2000);

            for (int slaveMacId = 0; slaveMacId < 64; slaveMacId++)
            {
                try
                {
                    if (BackgroundWorker.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }

                    long         timestamp   = DateTime.Now.Ticks;
                    bool         isTimeout   = false;
                    CanMessage[] rxMsgBuffer = new CanMessage[1];

                    Adapter.Write(new CanMessage[] { new CanMessage(DeviceNetAddressing.GetCheckMacId(slaveMacId), new byte[0]) });

                    do
                    {
                        if (Adapter.Attributes.PendingRxMessages >= 1)
                        {
                            Adapter.Read(rxMsgBuffer, 0, 1);
                            break;
                        }
                        isTimeout = DateTime.Now.Ticks - timestamp > 10 * 10000;
                    } while (!isTimeout);
                    CanMessage responseBuffer = rxMsgBuffer[0];

                    BackgroundWorker.ReportProgress((int)((slaveMacId / 63.0) * 100.0), "STATUS: " + slaveMacId.ToString() + ".");

                    if (!isTimeout)
                    {
                        if (DeviceNetAddressing.IsMacIdCheckCanId(responseBuffer.ArbitrationId))
                        {
                            ushort vendorId     = BitConverter.ToUInt16(responseBuffer.Data, 1);
                            uint   serialNumber = BitConverter.ToUInt32(responseBuffer.Data, 2);

                            var unconnected = new UnconnectedSalveDevice(Adapter);
                            var connected   = new ConnectedSalveDevice(Adapter, 0);
                            unconnected.AllocateExplicitConnection(slaveMacId);
                            ushort productCode = 0;
                            try
                            {
                                productCode = BitConverter.ToUInt16(connected.GetAttribute(slaveMacId, 1, 1, 3), 0);
                                Devices.Add(Devices.CreateDevice(slaveMacId, vendorId, productCode, serialNumber));
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                            finally
                            {
                                unconnected.ReleaseExplicitConnection(slaveMacId);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    e.Result = ex;
                }
            }
            watch.Stop();

            if (!BackgroundWorker.CancellationPending)
            {
                BackgroundWorker.ReportProgress(0, "COMPLETE Elapsed:" + (watch.ElapsedMilliseconds / 1000.0).ToString() + "s");
                //e.Result = data;
            }
            else
            {
                BackgroundWorker.ReportProgress(0, "ABORTED Elapsed:" + (watch.ElapsedMilliseconds / 1000.0).ToString() + "s");
            }
        }
예제 #11
0
        static void Main(string[] args)
        {
            /*Adapter példányosítása*/
            CanAdapterDevice adapter = new CanAdapterDevice();

            /*Kapcsolódás egy létező adapterhez.*/
            adapter.Connect();
            /*Busz lezárás engedélyezése. */
            adapter.Attributes.Termination = true;
            /*Loopback moód engedélyezése*/
            adapter.Attributes.Loopback = true;
            /*Megnyitás az átviteli sebesség paraméterrel.*/
            adapter.Open(CanBaudRateCollection.Speed125000Baud);
            /*2 CAN üzenet tartalmazó tömb létrehozása a kimenő üzenetknek.*/
            CanMessage[] txMsgArray = new CanMessage[]
            {
                /*              ArbId     Data                       */
                new CanMessage(0x000001, new byte[] { 0x01, 0x02, 0x03 }),
                new CanMessage(0x000002, new byte[] { 0x04, 0x05, 0x06 }),
            };

            /*Üzenetek küldése*/
            adapter.Write(txMsgArray);

            /*2 elemü üzenet tömb létrehozása a bejövő üzeneteknek.*/
            var rxMsgArray = new CanMessage[2];
            /*Timeout figyeléshez megjegyezzük az beolvasás indításának időpontját.*/
            long timestampTicks = DateTime.Now.Ticks;
            bool isTimeout      = false;

            do
            {
                /*Ha 2db CAN üzenet várakozik a Bufferben, akkor kiolvassuk.*/
                if (adapter.Attributes.PendingRxMessages == 2)
                {
                    /*Bérkezett üzenet beolvasása a tömbe */
                    adapter.Read(rxMsgArray, 0, adapter.Attributes.PendingRxMessages);
                    /*Kilépés a do-while-ból*/
                    break;
                }
                /*Inditás óta eltelt már 5000ms?*/
                isTimeout = (DateTime.Now.Ticks - timestampTicks) > (5000 * 10000);
                /*Timeout-ig ismétli a ciklust...*/
            } while (!isTimeout);

            if (isTimeout)
            {
                Console.WriteLine("Timeout...");
            }
            else
            {
                foreach (CanMessage msg in rxMsgArray)
                {
                    Console.WriteLine("Incoming Msg:" + msg.ToString());
                }

                Console.WriteLine("Complete.");
            }
            /*Kapcsolat zárása*/
            adapter.Close();
            /*Kapcsolat bontása*/
            adapter.Disconnect();
            Console.Read();
        }