public bool Send(IMessage message) { if (this.IsOpen) { //TPCANStatus status = PCANBasic.GetStatus(m_handle); //while ((status & TPCANStatus.PCAN_ERROR_XMTFULL) != 0) //{ // if ((status & ~TPCANStatus.PCAN_ERROR_ANYBUSERR) != 0) // { // m_errorStatus = status.ToString(); // return false; // } // status = PCANBasic.GetStatus(m_handle); //} PCANMessage pmsg = (PCANMessage)message; var msg = pmsg.NativeMessage; TPCANStatus result = PCANBasic.Write(m_handle, ref msg); pmsg.NativeMessage = msg; // Save possibly updated message data. if (this.UpdateStatusFromOperation(result) == TPCANStatus.PCAN_ERROR_OK) { return(true); } } return(false); }
private void btClose_Click(object sender, EventArgs e) { switch (cbDevice.SelectedIndex) { case (int)CONNECTON_TYPES.USB: serial.Close(); break; case (int)CONNECTON_TYPES.PEAK: PCANBasic.Uninitialize(m_PcanHandle); m_PcanHandle = 0; break; case (int)CONNECTON_TYPES.VSCP: vscp.Close(); break; default: break; } tReader.Stop(); btOpen.Enabled = true; btClose.Enabled = false; btSend.Enabled = false; }
private void ReadMessages() { TPCANMsg CANMsg; TPCANTimestamp CANTimeStamp; TPCANStatus stsResult; // We read at least one time the queue looking for messages. // If a message is found, we look again trying to find more. // If the queue is empty or an error occurr, we get out from // the dowhile statement. do { // We execute the "Read" function of the PCANBasic // stsResult = PCANBasic.Read(m_PcanHandle, out CANMsg, out CANTimeStamp); // A message was received // We process the message(s) // if (stsResult == TPCANStatus.PCAN_ERROR_OK) { ProcessMessage(CANMsg, CANTimeStamp); } } while ((!Convert.ToBoolean(stsResult & TPCANStatus.PCAN_ERROR_QRCVEMPTY))); }
private void Initialize_Click(object sender, EventArgs e) { TPCANStatus stsResult; PCANBasic.Uninitialize(m_PcanHandle); stsResult = PCANBasic.Initialize(m_PcanHandle, m_Baudrate, m_HwType, Convert.ToUInt32(0x04), Convert.ToUInt16(3)); if (stsResult != TPCANStatus.PCAN_ERROR_OK) { MessageBox.Show(Convert.ToString(stsResult)); } else { MessageBox.Show("Connection Successful!"); boardVoltageTimer = new System.Timers.Timer(350); boardVoltageTimer.Elapsed += boardVoltage_thread; boardVoltageTimer.Enabled = true; statusUpdateTimer = new System.Timers.Timer(100); statusUpdateTimer.Elapsed += statusUpdate_; statusUpdateTimer.Enabled = true; chnlSwitchTimer = new System.Timers.Timer(100); chnlSwitchTimer.Elapsed += chnlSwitchThread; chnlSwitchTimer.Enabled = true; toggleSwitch1.Enabled = false;; porSWITCH.Enabled = false; crntRatingTBar.Enabled = false; Initialize.Enabled = false; } }
private void _read() { // threaded recieve listener AutoResetEvent m_ReceiveEvent = new AutoResetEvent(false); UInt32 iBuffer; TPCANStatus stsResult; iBuffer = Convert.ToUInt32(m_ReceiveEvent.SafeWaitHandle.DangerousGetHandle().ToInt32()); // Sets the handle of the Receive-Event. stsResult = PCANBasic.SetValue((byte)iface, TPCANParameter.PCAN_RECEIVE_EVENT, ref iBuffer, sizeof(UInt32)); if (stsResult != TPCANStatus.PCAN_ERROR_OK) { throw new Exception(GetFormatedError(stsResult)); } while (true) { if (m_ReceiveEvent.WaitOne(50)) { // wait or sleep TPCANMsg m; TPCANTimestamp ts; do { // read all messages from queue, and 'receive' them stsResult = PCANBasic.Read((byte)iface, out m, out ts); if (stsResult == TPCANStatus.PCAN_ERROR_OK) { Receive.Invoke(Frame(m)); TimedReceive.Invoke(Time(ts), Frame(m)); } } while ((!Convert.ToBoolean(stsResult & TPCANStatus.PCAN_ERROR_QRCVEMPTY))); } } }
private void ReceiveThreadHandler() { TPCANMsg msg; TPCANTimestamp timestamp; TPCANStatus result; try { while (m_open) { var status = PCANBasic.GetStatus(m_handle); if ((status & TPCANStatus.PCAN_ERROR_QRCVEMPTY) == 0) // If NOT empty { result = PCANBasic.Read(m_handle, out msg, out timestamp); if (this.UpdateStatusFromOperation(result) == TPCANStatus.PCAN_ERROR_OK) { System.Diagnostics.Debug.WriteLine("CAN In: " + msg.ID.ToString()); this.PutReceivedInQueue(new PCANMessage(msg, timestamp)); } } else { Thread.Sleep(5); } } } finally { m_receiverThread = null; } }
private void ReadRawFrame() { AutoResetEvent can_event = new AutoResetEvent(false); uint numeric_buffer = Convert.ToUInt32(can_event.SafeWaitHandle.DangerousGetHandle().ToInt32()); TPCANStatus status = PCANBasic.SetValue(m_sock, TPCANParameter.PCAN_RECEIVE_EVENT, ref numeric_buffer, sizeof(UInt32)); if (status != TPCANStatus.PCAN_ERROR_OK) { throw new Exception(GetFormatedError(status)); } TPCANMsg raw_frame; while (!m_thread_stop) { if (can_event.WaitOne(50)) { do { if ((status = PCANBasic.Read(m_sock, out raw_frame)) == TPCANStatus.PCAN_ERROR_OK) { m_queue_rx.Add(raw_frame); } } while (!Convert.ToBoolean(status & TPCANStatus.PCAN_ERROR_QRCVEMPTY)); } } }
private TPCANStatus WriteFrame(uint nCAN_ID, byte byLen, bool isRemote, byte[] arrData) { TPCANMsg CANMsg; //TextBox txtbCurrentTextBox; // We create a TPCANMsg message structure // CANMsg = new TPCANMsg(); CANMsg.DATA = new byte[8]; // We configurate the Message. The ID, // Length of the Data, Message Type // and the data // CANMsg.ID = nCAN_ID; // Convert.ToUInt32(txtID.Text, 16); CANMsg.LEN = byLen; // Convert.ToByte(nudLength.Value); CANMsg.MSGTYPE = TPCANMessageType.PCAN_MESSAGE_EXTENDED; // (chbExtended.Checked) ? TPCANMessageType.PCAN_MESSAGE_EXTENDED : TPCANMessageType.PCAN_MESSAGE_STANDARD; // If a remote frame will be sent, the data bytes are not important. // if (isRemote) { CANMsg.MSGTYPE |= TPCANMessageType.PCAN_MESSAGE_RTR; } else { Buffer.BlockCopy(arrData, 0, CANMsg.DATA, 0, byLen); } // The message is sent to the configured hardware // return(PCANBasic.Write(m_PcanHandle, ref CANMsg)); }
/// <summary> /// Configures the PCAN-Trace file for a PCAN-Basic Channel /// </summary> private void ConfigureTraceFile() { UInt32 iBuffer; TPCANStatus stsResult; // Configure the maximum size of a trace file to 5 megabytes // iBuffer = 5; stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_TRACE_SIZE, ref iBuffer, sizeof(UInt32)); if (stsResult != TPCANStatus.PCAN_ERROR_OK) { IncludeTextMessage(GetFormatedError(stsResult)); } // Configure the way how trace files are created: // * Standard name is used // * Existing file is ovewritten, // * Only one file is created. // * Recording stopts when the file size reaches 5 megabytes. // iBuffer = PCANBasic.TRACE_FILE_SINGLE | PCANBasic.TRACE_FILE_OVERWRITE; stsResult = PCANBasic.SetValue(m_PcanHandle, TPCANParameter.PCAN_TRACE_CONFIGURE, ref iBuffer, sizeof(UInt32)); if (stsResult != TPCANStatus.PCAN_ERROR_OK) { IncludeTextMessage(GetFormatedError(stsResult)); } }
public TPCANStatus ReadFrame(TPCANHandle CanHandle) { //CREATE MESSAGE STRUCTURE TPCANMsg CANMsg; TPCANTimestamp CANTimeStamp; TPCANStatus stsResult; //READ RETURN DATA stsResult = PCANBasic.Read(CanHandle, out CANMsg, out CANTimeStamp); //IF READ SUCCESS CHANGE PROPERTY, ELSE IF RETURN ERROR if (stsResult == TPCANStatus.PCAN_ERROR_OK) { this.ReturnData.Time = DateTime.Now.TimeOfDay.ToString(); this.ReturnData.ID = Convert.ToString(CANMsg.ID, 16); this.ReturnData.Length = CANMsg.DATA.Length.ToString(); this.ReturnData.Data = BitConverter.ToString(CANMsg.DATA).Replace("-", " "); if (CANMsg.DATA[0] == 3 || CANMsg.DATA[1] == 127) { stsResult = TPCANStatus.PCAN_ERROR_RESPONSE; } } return(stsResult); }
public TPCANStatus Init() { TPCANStatus result; StringBuilder strMsg; result = PCANBasic.Initialize(mChannel, mBaudrate); if (result != TPCANStatus.PCAN_ERROR_OK) { strMsg = new StringBuilder(256); PCANBasic.GetErrorText(result, 0, strMsg); MessageBox.Show(strMsg.ToString()); } else { MessageBox.Show("PCAN-USB was initialized successfully!"); // Turn the power source oparationa on byte[] data = { 0x01, mDeviceId }; Write("000", data); // data = new byte[8]; data[0] = 0x02; Write("202", data); StartTimers(); } return(result); }
public void Write(string id, byte[] data) { TPCANStatus result; TPCANMsg msg; msg = new TPCANMsg(); msg.ID = Convert.ToUInt32(id, 16); msg.LEN = Convert.ToByte(data.Length); msg.DATA = new byte[8]; msg.MSGTYPE = TPCANMessageType.PCAN_MESSAGE_STANDARD; for (int i = 0; i < msg.LEN; i++) { msg.DATA[i] = data[i]; } PCANBasic.Write(mChannel, ref msg); result = PCANBasic.Write(mChannel, ref msg); if (result != TPCANStatus.PCAN_ERROR_OK) { StringBuilder strMsg = new StringBuilder(256); PCANBasic.GetErrorText(result, 0, strMsg); //Console.WriteLine(strMsg.ToString()); } }
public bool Open([Implicit] ICallContext context) { if (!m_open) { TPCANStatus result = PCANBasic.Initialize(m_handle, ToPCANBaudrate(m_baudrate), TPCANType.PCAN_TYPE_ISA, 0, 0); if (this.UpdateStatusFromOperation(result) == TPCANStatus.PCAN_ERROR_OK) { if (context != null && context.LoggingEnabled) { context.Logger.Log("Open", "Opened successfully"); } m_open = true; if (m_receiverThread == null) { m_receiverThread = new Thread(new ThreadStart(this.ReceiveThreadHandler)); m_receiverThread.Start(); //Core.Main.ServiceManager.Get<> } return(true); } else { if (context != null) { context.Logger.LogError("PCAN", "Open failed"); } } } return(false); }
private void btnSaveSettings_Click(object sender, EventArgs e) { TPCANMsg CANMsg; TPCANStatus stsResult; CANMsg = new TPCANMsg(); CANMsg.DATA = new byte[8]; //get ID from BOX byte MasterUnitId, NewMasterId = 0; try { MasterUnitId = (byte)((Convert.ToUInt16(MasterID.Text))); NewMasterId = (byte)((Convert.ToUInt16(boxNewMasterId.Text))); } catch { MessageBox.Show("Wrong ID. Please fill in value 1-255"); return; } //construct can ID byte[] bytes = { 0x18, 0x00, MasterUnitId, 0x00 }; if (BitConverter.IsLittleEndian) { Array.Reverse(bytes); } uint id = BitConverter.ToUInt32(bytes, 0); // If the system architecture is little-endian (that is, little end first), // reverse the byte array. //////////////////////////////////////////// //create and send settings message //////////////////////////////////////////// //Max avaliable current we read from textbox -boxAvailCurrent CANMsg.ID = id; CANMsg.LEN = 8; CANMsg.MSGTYPE = (TPCANMessageType.PCAN_MESSAGE_EXTENDED); CANMsg.DATA[0] = 0; //CAN adress Hi CANMsg.DATA[1] = 0; //CAN address LO CANMsg.DATA[2] = (byte)boxBaudRate.SelectedIndex; //baudrate CANMsg.DATA[3] = NewMasterId; //ID CANMsg.DATA[4] = 0; CANMsg.DATA[5] = 0; CANMsg.DATA[6] = 0; CANMsg.DATA[7] = 0; stsResult = PCANBasic.Write(m_PcanHandle, ref CANMsg); // The message was successfully sent if (stsResult != TPCANStatus.PCAN_ERROR_OK) { MessageBox.Show(GetFormatedError(stsResult)); } }
/// <summary> /// Disconnect to can bus. /// </summary> public void disconnect()//object sender, EventArgs e) { if (this._canChannel > 0) { PCANBasic.Uninitialize(this._canChannel); } this.isRunning = false; }
private void Form_BasicFunction_FormClosing(object sender, FormClosingEventArgs e) { if (PCAN_COMMON_VAL.pcan_init_flag1 == 0x69 || PCAN_COMMON_VAL.pcan_init_flag2 == 0x69) //初始化成功 { // usbCAN.shutDevice(); PCANBasic.Uninitialize(0x0051); PCANBasic.Uninitialize(0x0052); //MessageBox.Show("通道all设备关闭成功"); } }
public PCAN(Ports device, long baudrate) { iface = device; Bitrate = baudrate; PCANBasic.Initialize((byte)iface, baud); rx = new Thread(_read); rx.IsBackground = true; rx.Start(); }
public void CanReceiveReset(short Ch) { #if PROGRAM_RUNNING TPCANStatus stsResult; stsResult = PCANBasic.Reset(m_PcanHandle[Ch]); #endif return; }
public void CanClose(short Ch) { #if PROGRAM_RUNNING TPCANStatus stsResult; UInt32 iBuffer; try { try { Open[Ch] = false; //-----------------------------[ Open can board ] // Gets the current status of the message filter // if (!GetFilterStatus(Ch, out iBuffer)) { return; } PCANBasic.Reset(m_PcanHandle[Ch]); // The filter will be full opened or complete closed // iBuffer = PCANBasic.PCAN_FILTER_CLOSE; // The filter is configured // stsResult = PCANBasic.SetValue( m_PcanHandle[Ch], TPCANParameter.PCAN_MESSAGE_FILTER, ref iBuffer, sizeof(UInt32)); // If success, an information message is written, if it is not, an error message is shown // if (stsResult == TPCANStatus.PCAN_ERROR_OK) { PCANBasic.Uninitialize(m_PcanHandle[Ch]); return; } } catch (Exception Msg) { //MessageBox.Show(Msg.Message + "\n" + Msg.StackTrace); uMessageBox.Show(title: "경고", promptText: Msg.Message + "\n" + Msg.StackTrace); //MessageBox.Show(GetFormatedError(stsResult)); } } finally { } return; #else return; #endif }
public void Open(Baudrate speed) { TPCANBaudrate bitrate; switch (speed) { case Baudrate.Baudrate5000: bitrate = TPCANBaudrate.PCAN_BAUD_5K; break; case Baudrate.Baudrate10000: bitrate = TPCANBaudrate.PCAN_BAUD_10K; break; case Baudrate.Baudrate20000: bitrate = TPCANBaudrate.PCAN_BAUD_20K; break; case Baudrate.Baudrate50000: bitrate = TPCANBaudrate.PCAN_BAUD_50K; break; case Baudrate.Baudrate100000: bitrate = TPCANBaudrate.PCAN_BAUD_100K; break; case Baudrate.Baudrate125000: bitrate = TPCANBaudrate.PCAN_BAUD_125K; break; case Baudrate.Baudrate250000: bitrate = TPCANBaudrate.PCAN_BAUD_250K; break; case Baudrate.Baudrate500000: bitrate = TPCANBaudrate.PCAN_BAUD_500K; break; case Baudrate.Baudrate800000: bitrate = TPCANBaudrate.PCAN_BAUD_800K; break; case Baudrate.Baudrate1000000: bitrate = TPCANBaudrate.PCAN_BAUD_1M; break; default: throw new Exception("Invalid baudrate."); } var ret = PCANBasic.Initialize(Channel, bitrate); CheckError(ret); }
/// <summary> /// CHECK AVAILABLE DEVICES /// </summary> private void CheckDevice() { uint isChannelValid; UInt32 iDeviceID = 0; dev.Clear(); try { foreach (var Device in m_NonPnPHandles) { stsResult = PCANBasic.GetValue(Device, TPCANParameter.PCAN_CHANNEL_CONDITION, out isChannelValid, sizeof(uint)); if (stsResult == TPCANStatus.PCAN_ERROR_OK) { if (isChannelValid == PCANBasic.PCAN_CHANNEL_AVAILABLE) { stsResult = PCANBasic.GetValue(Device, TPCANParameter.PCAN_DEVICE_ID, out iDeviceID, sizeof(UInt32)); switch (Device) { case 0x41: case 0x42: case 0x43: cbDevice.Items.Add($"PCAN PCI({iDeviceID}h)"); dev.Add(Device, $"PCAN PCI({iDeviceID}h)"); break; case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: cbDevice.Items.Add($"PCAN USB({iDeviceID}h)"); dev.Add(Device, $"PCAN USB({iDeviceID}h)"); break; case 0x801: case 0x802: case 0x803: case 0x804: case 0x805: cbDevice.Items.Add($"PCAN LAN({iDeviceID}h)"); dev.Add(Device, $"PCAN LAN({iDeviceID}h)"); break; } } } } } catch (DllNotFoundException) { tbAlarmLog.Text += "PCANBasic.dll file Not Found."; } }
private void btnRelease_Click(object sender, RoutedEventArgs e) { stsResult = PCANBasic.Uninitialize(m_PcanHandle); //DISCONNECT PCAN DEVICE m_PcanHandle = 0; //RESET PCAN HANDLE btnConnect.IsEnabled = true; cbDevice.IsEnabled = true; cbBaudRate.IsEnabled = true; btnRefresh.IsEnabled = true; tbAlarmLog.Text += "Device was successfully released\n"; }
public void SendFrame(Frame frame) { var msg = new TPCANMsg() { DATA = frame.Data, ID = (uint)frame.Id, LEN = (byte)frame.Data.Length, MSGTYPE = frame.Type == FrameType.Standard ? TPCANMessageType.PCAN_MESSAGE_STANDARD : TPCANMessageType.PCAN_MESSAGE_EXTENDED }; var ret = PCANBasic.Write(Channel, ref msg); CheckError(ret); }
/// <summary> /// Configures the Debug-Log file of PCAN-Basic /// </summary> private void ConfigureLogFile() { UInt32 iBuffer; // Sets the mask to catch all events // iBuffer = PCANBasic.LOG_FUNCTION_ALL; // Configures the log file. // NOTE: The Log capability is to be used with the NONEBUS Handle. Other handle than this will // cause the function fail. // PCANBasic.SetValue(PCANBasic.PCAN_NONEBUS, TPCANParameter.PCAN_LOG_CONFIGURE, ref iBuffer, sizeof(UInt32)); }
public void Flush() { if (m_open) { lock (m_receiveLock) { PCANBasic.Reset(m_handle); foreach (var r in m_receivers) { r.Flush(true); } } } }
/// <summary> /// Function for reading CAN messages on normal CAN devices /// </summary> /// <returns>A TPCANStatus error code</returns> private TPCANStatus ReadMessage() { TPCANMsg CANMsg; TPCANStatus stsResult; // We execute the "Read" function of the PCANBasic stsResult = PCANBasic.Read(m_PcanHandle, out CANMsg); if (stsResult == TPCANStatus.PCAN_ERROR_OK) { postMessage(CANMsg); } return(stsResult); }
/// <summary> /// Sends the PCAN data. /// </summary> /// <param name="msg">The MSG.</param> /// <returns>TPCANStatus.</returns> public TPCANStatus sendPCANData(ref TPCANMsg msg) { TPCANStatus stsResult = TPCANStatus.PCAN_ERROR_BUSOFF; if (this.isRunning) { stsResult = PCANBasic.Write(this._canChannel, ref msg); if (sleepTime > 0) { Thread.Sleep(sleepTime); } } return(stsResult); }
/* * The handle of a PCAN Channel (see TPCANHandle). * Btr0Btr1 The speed for the communication (BTR0BTR1 code). * HwType The type of hardware and operation mode (see TPCANMode). * IOPort The I/O address for the parallel port. * Interrupt Interrupt number of the parallel port */ public void Btn_connectCAN_Click(object sender, EventArgs e) { TPCANStatus stsResult; //CAN/LIN0 m_PcanHandle = Convert.ToByte("51", 16); stsResult = PCANBasic.Initialize( m_PcanHandle, TPCANBaudrate.PCAN_BAUD_250K); //250kbs /*if(appCANbaudrate.SelectedIndex==0){ * stsResult = PCANBasic.Initialize( * m_PcanHandle, * TPCANBaudrate.PCAN_BAUD_250K); * }else { * stsResult = PCANBasic.Initialize( * m_PcanHandle, * TPCANBaudrate.PCAN_BAUD_500K); * * }*/ if (stsResult != TPCANStatus.PCAN_ERROR_OK) { MessageBox.Show(GetFormatedError(stsResult)); } else { // Prepares the PCAN-Basic's PCAN-Trace file // //ConfigureTraceFile(); // Display messages in grid // tmrDisplay.Enabled = true; } tmrRead.Enabled = true; btnSaveSettings.Enabled = true; btnReleseCAN.Enabled = true; Btn_connectCAN.Enabled = false; IncludeTextMessage("CAN connected"); // Sets the connection status of the main-form // //SetConnectionStatus(stsResult == TPCANStatus.PCAN_ERROR_OK); }
public Frame ReceiveFrame(bool blocking = true) { TPCANStatus ret; do { ret = PCANBasic.Read(Channel, out TPCANMsg msg, out TPCANTimestamp time); if (ret == TPCANStatus.PCAN_ERROR_OK) { var frame = new Frame() { Data = msg.DATA, Id = (int)msg.ID, }; if (msg.MSGTYPE == TPCANMessageType.PCAN_MESSAGE_STANDARD) { frame.Type = FrameType.Standard; } else if (msg.MSGTYPE == TPCANMessageType.PCAN_MESSAGE_EXTENDED) { frame.Type = FrameType.Extended; } else if (msg.MSGTYPE == TPCANMessageType.PCAN_MESSAGE_EXTENDED) { frame.Type = FrameType.Error; } else { return(null); } return(frame); } else if (ret == TPCANStatus.PCAN_ERROR_QRCVEMPTY) { if (!blocking) { return(null); } } else { CheckError(ret); } Thread.Sleep(1); } while (blocking && ret == TPCANStatus.PCAN_ERROR_QRCVEMPTY); return(null); }
private string GetFormatedError(TPCANStatus p_error) { StringBuilder sb_error_text; sb_error_text = new StringBuilder(256); if (PCANBasic.GetErrorText(p_error, 0, sb_error_text) != TPCANStatus.PCAN_ERROR_OK) { return($"An error occurred. Error-code's text ({p_error:X}) couldn't be retrieved"); } else { return(sb_error_text.ToString()); } }