// initialize can socket private bool InitSocket(Byte canNo) { IBalObject bal = null; bool succeeded = false; try { // configure and set the channel to be used bal = mDevice.OpenBusAccessLayer(); mCanCh = bal.OpenSocket(canNo, typeof(ICanChannel)) as ICanChannel; mCanSch = bal.OpenSocket(canNo, typeof(ICanScheduler)) as ICanScheduler; mCanCh.Initialize(1024, 128, false); mReader = mCanCh.GetMessageReader(); mReader.Threshold = 1; mRxEvent = new AutoResetEvent(false); mReader.AssignEvent(mRxEvent); mWriter = mCanCh.GetMessageWriter(); mWriter.Threshold = 1; mCanCh.Activate(); mCanCtrl = bal.OpenSocket(canNo, typeof(ICanControl)) as ICanControl; if (BaudRateCBox.SelectedItem.Equals(CanBitrate.Cia125KBit)) { if (ModeSelectCBox.SelectedItem.Equals(CanOperatingModes.Standard)) { mCanCtrl.InitLine(CanOperatingModes.Standard | CanOperatingModes.ErrFrame, CanBitrate.Cia125KBit); mCanCtrl.SetAccFilter(CanFilter.Std, (uint)CanAccCode.All, (uint)CanAccMask.All); } else if (ModeSelectCBox.SelectedItem.Equals(CanOperatingModes.Extended)) { mCanCtrl.InitLine(CanOperatingModes.Extended | CanOperatingModes.ErrFrame, CanBitrate.Cia125KBit); mCanCtrl.SetAccFilter(CanFilter.Ext, (uint)CanAccCode.All, (uint)CanAccMask.All); } mCanCtrl.StartLine(); succeeded = true; } else { MessageBox.Show("Please Select The Baud Rate!", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show(ex.Message, "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error); succeeded = false; } finally { DisposeVciObject(bal); } return(succeeded); }
private void StartChannels() { _channel = (ICanChannel2)_balObject.OpenSocket(0, typeof(ICanChannel2)); _channel.Initialize(3, 3, 0, CanFilterModes.Pass, false); _channel.Activate(); _writer = _channel.GetMessageWriter(); _reader = _channel.GetMessageReader(); _readerThread = new Thread(ReadThread); _readerThread.IsBackground = true; _readerThread.Start(); }
public static bool InitDevice(byte canNo, int canSpeed, int adapterNo) { IBalObject bal = null; System.Collections.IEnumerator deviceEnum = null; int i = -1; try { deviceEnum = deviceList.GetEnumerator(); deviceEnum.MoveNext(); do { i++; if (i == adapterNo) { mDevice = deviceEnum.Current as IVciDevice; } } while (deviceEnum.MoveNext() != false); bal = mDevice.OpenBusAccessLayer(); mCanChn = bal.OpenSocket(canNo, typeof(ICanChannel)) as ICanChannel; mCanChn.Initialize(1024, 128, false); mReader = mCanChn.GetMessageReader(); mReader.Threshold = 1; mRxEvent = new AutoResetEvent(false); mReader.AssignEvent(mRxEvent); mWriter = mCanChn.GetMessageWriter(); mWriter.Threshold = 1; mCanChn.Activate(); int a = bal.Resources.Count - 1; mCanCtl = bal.OpenSocket(canNo, typeof(ICanControl)) as ICanControl; mCanCtl.InitLine(CanOperatingModes.Standard | CanOperatingModes.ErrFrame , CanBitrate.Cia250KBit); mCanCtl.SetAccFilter(CanFilter.Std, (uint)CanAccCode.All, (uint)CanAccMask.All); mCanCtl.StartLine(); return(true); } catch (Exception e) { MessageBox.Show("Error: Initializing socket failed: " + e.Message); return(false); } finally { DisposeVciObject(bal); DisposeVciObject(deviceEnum); IsOpen = true; } }
private void Dispose() { _balObject?.Dispose(); _channel?.Dispose(); _writer?.Dispose(); _reader?.Dispose(); _control?.Dispose(); _readerThread?.Abort(); _balObject = null; _channel = null; _writer = null; _reader = null; _control = null; _readerThread = null; }
//************************************************************************ /// <summary> /// Opens the specified socket, creates a message channel, initializes /// and starts the CAN controller. /// </summary> /// <param name="canNo"> /// Number of the CAN controller to open. /// </param> /// <returns> /// A value indicating if the socket initialization succeeded or failed. /// </returns> //************************************************************************ static bool InitSocket(Byte canNo) { IBalObject bal = null; bool succeeded = false; try { // // Open bus access layer // bal = mDevice.OpenBusAccessLayer(); // // Open a message channel for the CAN controller // mCanChn = bal.OpenSocket(canNo, typeof(ICanChannel)) as ICanChannel; // Initialize the message channel mCanChn.Initialize(1024, 128, false); // Get a message reader object mReader = mCanChn.GetMessageReader(); // Initialize message reader mReader.Threshold = 1; // Create and assign the event that's set if at least one message // was received. mRxEvent = new AutoResetEvent(false); mReader.AssignEvent(mRxEvent); // Get a message wrtier object mWriter = mCanChn.GetMessageWriter(); // Initialize message writer mWriter.Threshold = 1; // Activate the message channel mCanChn.Activate(); // // Open the CAN controller // mCanCtl = bal.OpenSocket(canNo, typeof(ICanControl)) as ICanControl; // Initialize the CAN controller mCanCtl.InitLine(CanOperatingModes.Standard | CanOperatingModes.ErrFrame , CanBitrate.Cia125KBit); // Set the acceptance filter mCanCtl.SetAccFilter(CanFilter.Std, (uint)CanAccCode.All, (uint)CanAccMask.All); // Start the CAN controller mCanCtl.StartLine(); succeeded = true; } catch (Exception) { Console.WriteLine("Error: Initializing socket failed"); } finally { // // Dispose bus access layer // DisposeVciObject(bal); } return(succeeded); }
/// <summary> /// Закрывает CAN порт /// </summary> public override void Close() { String msg; // Закрываем поток на чтение Interlocked.Exchange(ref _FlagMustQuit, 0); lock (_SyncRoot) { this._RxEvent.Set(); } for (int i = 0; i < 1; i++) { if (this._ThreadForInput.IsAlive == true) { // Ждём завершение потока Thread.Sleep(500); } else { // Поток завершён break; } } // Если поток не завершился в течнии 10 секунд, значит дело плохо. // Выводим об этом трассировочную информацию if (this._ThreadForInput.IsAlive == true) { this._ThreadForInput.Abort(); msg = String.Format( "{0}: class CanPort.Close(): Рабочий поток не завершился за 0,5 секунду и находится в состоянии {1}", DateTime.Now.ToString(new System.Globalization.CultureInfo("ru-Ru", false)), this._ThreadForInput.ThreadState.ToString()); Trace.TraceError(msg); } //SetMode(CANPORTSTATUS.IsPassive); _CanController.StopLine(); //_CanChannel.Deactivate(); _RxEvent.Close(); _RxEvent = null; // Освобождаем ресурсы DisposeVciObject(_CanBusLayer); DisposeVciObject(_CanChannel); DisposeVciObject(_CanController); DisposeVciObject(_CanDevice); DisposeVciObject(_Reader); DisposeVciObject(_Writer); _CanBusLayer = null; _CanChannel = null; _CanController = null; _CanDevice = null; _Reader = null; _Writer = null; // Устанавливаем флаг признак "порт закрыт" this._PortStatus = CanPortStatus.IsClosed; // Формирум событие OnPortChangesStatus(CanPortStatus.IsClosed); Trace.TraceInformation("{0}: class CanPort.Close(): Порт закрыт", DateTime.Now.ToString(new System.Globalization.CultureInfo("ru-Ru"))); return; }
/// <summary> /// Opens the specified socket, creates a message channel, initializes /// and starts the CAN controller. /// </summary> /// <param name="canNo"> /// Number of the CAN controller to open. /// </param> /// <returns> /// A value indicating if the socket initialization succeeded or failed. /// </returns> private bool InitSocket(Byte canNo, ref IVciDevice device) { this._CanBusLayer = null; bool succeeded = false; try { // Open bus access layer _CanBusLayer = device.OpenBusAccessLayer(); // Open a message channel for the CAN controller _CanChannel = _CanBusLayer.OpenSocket(canNo, typeof(ICanChannel)) as ICanChannel; // Initialize the message channel // Используем канал единолично (true) _CanChannel.Initialize(1024, 128, true); // Get a message reader object _Reader = _CanChannel.GetMessageReader(); // Initialize message reader _Reader.Threshold = 1; // Create and assign the event that's set if at least one message // was received. _RxEvent = new AutoResetEvent(false); _Reader.AssignEvent(_RxEvent); // Get a message wrtier object _Writer = _CanChannel.GetMessageWriter(); // Initialize message writer _Writer.Threshold = 1; // Activate the message channel _CanChannel.Activate(); // Open the CAN controller _CanController = _CanBusLayer.OpenSocket(canNo, typeof(ICanControl)) as ICanControl; // Инициализируем контроллер с текущими параметрами this.Init(); // !!!! ВНИМАНИЕ применяется фильтр, с данным куском не разобрался // Set the acceptance filter //_CanController.SetAccFilter(CanFilter.Std, // (uint)CanAccCode.All, (uint)CanAccMask.All); // Start the CAN controller _CanController.StartLine(); succeeded = true; } catch { //MessageBox.Show(this, "Error: Initializing socket failed. Description: " + ex.Message, "Ошибка", // MessageBoxButtons.OK, MessageBoxIcon.Error); succeeded = false; // Если не удалось открыть порт удаляем всё объекты DisposeVciObject(_CanChannel); DisposeVciObject(_Reader); DisposeVciObject(_Writer); DisposeVciObject(_CanBusLayer); DisposeVciObject(_CanController); throw; // Возобнавляем исключение } return succeeded; }
static public bool InitSocket(String adapter, uint baudrate) { FinalizeApp(); IBalObject bal = null; bool succeeded = false; IVciDevice device = null; try { device = GetDeviceByString(adapter); // // Open bus access layer // bal = device.OpenBusAccessLayer(); // // Open a message channel for the CAN controller // mCanChn = bal.OpenSocket(0, typeof(ICanChannel)) as ICanChannel; /*// * // Open the scheduler of the CAN controller * // * Log("4"); // не проходит переинициализацию, что-то надо сделать * mCanSched = bal.OpenSocket(0, typeof(ICanScheduler)) as ICanScheduler;*/ // Initialize the message channel mCanChn.Initialize(1024, 128, false); // Get a message reader object mReader = mCanChn.GetMessageReader(); // Initialize message reader mReader.Threshold = 1; // Create and assign the event that's set if at least one message // was received. mRxEvent = new System.Threading.AutoResetEvent(false); mReader.AssignEvent(mRxEvent); // Get a message wrtier object mWriter = mCanChn.GetMessageWriter(); // Initialize message writer mWriter.Threshold = 1; mTxEvent = new System.Threading.AutoResetEvent(false); mWriter.AssignEvent(mTxEvent); // Activate the message channel mCanChn.Activate(); // // Open the CAN controller // mCanCtl = bal.OpenSocket(0, typeof(ICanControl)) as ICanControl; CanBitrate _cb = new CanBitrate(); switch (baudrate) { case BAUDRATE_125: _cb = CanBitrate.Cia125KBit; break; case BAUDRATE_250: _cb = CanBitrate.Cia250KBit; break; default: _cb = CanBitrate.Cia125KBit; break; } // Initialize the CAN controller mCanCtl.InitLine(CanOperatingModes.Standard | CanOperatingModes.Extended | //extended отключить наверняка стоит CanOperatingModes.ErrFrame, _cb); // // print line status // Debug.WriteLine(" LineStatus: " + mCanCtl.LineStatus + "\n|"); // Set the acceptance filter for std identifiers mCanCtl.SetAccFilter(CanFilter.Std, (uint)CanAccCode.All, (uint)CanAccMask.All); // Set the acceptance filter for ext identifiers mCanCtl.SetAccFilter(CanFilter.Ext, (uint)CanAccCode.All, (uint)CanAccMask.All); // Start the CAN controller mCanCtl.StartLine(); succeeded = true; } catch (Exception exc) { Debug.WriteLine("Error: Initializing socket failed : " + exc.Message + "\n|"); succeeded = false; } finally { DisposeVciObject(device); DisposeVciObject(bal); } return(succeeded); }