void closeChannelButton_Click(object sender, RoutedEventArgs e) { if (sendHandle >= 0 && readHandle >= 0) { if (isSenderBusOn || isReaderBusOn) { busOffButton_Click(sender, e); } Canlib.canStatus senderStatus = Canlib.canClose(sendHandle); Canlib.canStatus readerStatus = Canlib.canClose(readHandle); CheckStatus("Closing channel " + channelName, senderStatus); sendHandle = -1; readHandle = -1; closeChannelButton.IsEnabled = false; busOnButton.IsEnabled = false; busOffButton.IsEnabled = false; bitrateComboBox.IsEnabled = false; sendMessageButton.IsEnabled = false; clearMessageButton.IsEnabled = false; buildMessageButton.IsEnabled = false; openChannelButton.IsEnabled = true; //channelBox.IsEnabled = true; channelComboBox.IsEnabled = true; } else { MessageBox.Show("Closing Channel " + channelName + " failed. Please try again."); } }
public bool CAN_OpenChannel(int mode) { int _hnd = -1; if (mode == 0) { _hnd = Canlib.canOpenChannel(this._Channel, Canlib.canOPEN_ACCEPT_LARGE_DLC); } else { _hnd = Canlib.canOpenChannel(this._Channel, Canlib.canOPEN_ACCEPT_LARGE_DLC); } if (_hnd >= 0) { this.handle = _hnd; Canlib.canAccept(handle, 0x7DF, Canlib.canFILTER_SET_CODE_STD); Canlib.canAccept(handle, 0x7D0, Canlib.canFILTER_SET_MASK_STD); return(true); } else { return(false); } }
/* This method is invoked when application need to Bus off without user's click (on the 'Bus Off' button). */ void forceAllBusOff() { Canlib.canStatus senderStatus = Canlib.canBusOff(sendHandle); Canlib.canStatus readerStatus = Canlib.canBusOff(readHandle); //CheckStatus("Bus off", status); if (senderStatus == Canlib.canStatus.canOK && readerStatus == Canlib.canStatus.canOK) { isSenderBusOn = false; isReaderBusOn = false; busOffButton.IsEnabled = false; sendMessageButton.IsEnabled = false; clearMessageButton.IsEnabled = false; buildMessageButton.IsEnabled = false; busOnButton.IsEnabled = true; bitrateComboBox.IsEnabled = true; MessageBox.Show("Forced Bus off succeeded. Go Bus on again."); } else { MessageBox.Show("Forced Bus off failed. Restart application again."); this.Close(); } }
//Reads message data from user input and writes a message to the channel private void sendButton_Click(object sender, RoutedEventArgs e) { int id = Convert.ToInt32(idBox.Text); TextBox[] textBoxes = { dataBox0, dataBox1, dataBox2, dataBox3, dataBox4, dataBox5, dataBox6, dataBox7 }; byte[] data = new byte[8]; for (int i = 0; i < 8; i++) { data[i] = textBoxes[i].Text == "" ? (byte)0 : Convert.ToByte(textBoxes[i].Text); } CheckBox[] boxes = { RTRBox, STDBox, EXTBox, WakeUpBox, NERRBox, errorBox, TXACKBox, TXRQBox, delayBox, BRSBox, ESIBox }; int flags = 0; foreach (CheckBox box in boxes) { if (box.IsChecked.Value) { flags += Convert.ToInt32(box.Tag); } } int dlc = Convert.ToInt32(DLCBox.Text); string msg = String.Format("{0} {1} {2:x2} {3:x2} {4:x2} {5:x2} {6:x2} {7:x2} {8:x2} {9:x2} to handle {10}", id, dlc, data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], handle); Canlib.canStatus status = Canlib.canWrite(handle, id, data, dlc, flags); CheckStatus("Writing message " + msg, status); }
//close the can bus after transmission public static void Close() { for (int i = 0; i < CAN_Channel.numOfChan; i++) { switch (CAN_Channel._INTERFACEs[i]) { case CAN_Channel.CAN_INTERFACE.KVASER: Canlib.canBusOff(canHandle[i]); status = Canlib.canClose(canHandle[i]); canHandle[i] = 0; KvaserInit = false; ErrorControl(status: status, location: "canClose: Close()"); break; case CAN_Channel.CAN_INTERFACE.PEAK: PCANBasic.Uninitialize((ushort)canHandle[i]); break; } } CanInit = false; }
// private CAN_Common(){ //#if DEBUG // //Task.Factory.StartNew( // // action: () =>{ // // Thread.Sleep(2000); // // float f = 0; // // Stopwatch sw = Stopwatch.StartNew(); // // Random rand = new Random(); // // FrequencyManager.SendCCComand(1, Globals.Vm_scis[0]); // // while (true){ // // short sin = (short)((Math.Sin(f) * Math.Pow(2, 15))); // // byte[] data = new byte[12]; // // Buffer.BlockCopy(Utils.makePacket("FT", 1, false, true, (Math.Sin(f) * 100).ToString()),0,data,0,8); // // data[5] = (byte)(sin >> 8); // // data[4] = (byte)sin; // // data[6] = 0; // // data[7] = 0; // // innerTranmit(data); // // //SaveToDisk.Write(data); // // while (sw.ElapsedMilliseconds < f *5) ; // // f+=0.01f; // // } // // }); //#endif // } //private CAN_Common(){ // //ActiveCANDriver = Tbl_CanDriver.ActiveCANDriver; // Task.Factory.StartNew( // action: () =>{ // ActiveCANDriver = Static_Utils.ActiveCANDriver; // if (ActiveCANDriver.Equals(Consts.CAN_DRIVER_KVASER)){ // initForKvaser(); // } else if (ActiveCANDriver.Equals(Consts.CAN_DRIVER_GINKGO)){ // initForGinkgo(); // } // initLoop(); // }); // //Active = true; //} #endregion #region METHODS public static void CloseConnection(int NodeId) { if (!Instance.dic_CanChanels.ContainsKey(NodeId)) { return; } byte[] packet = Utils.makePacket(NodeId, "CC", 0, false, false, "0"); for (int i = 0; i < 3; i++) { Canlib.canWrite(Instance.dic_CanChanels[NodeId], 0x37f, packet, packet.Length, 2); Write(packet); Thread.Sleep(50); } Canlib.canWrite( handle: Instance.dic_CanChanels[NodeId], id: 0, msg: new byte[] { 0x80, (byte)NodeId }, dlc: 2, //size of msg flag: 2 //we have defined this as const ); Canlib.canBusOff(Instance.dic_CanChanels[NodeId]); Canlib.canClose(Instance.dic_CanChanels[NodeId]); }
} // End KvaserCanRateReturn // *************************************** // DetectCanInterfaces // Pulls all of the available adapters for the CAN bus // *************************************** public static void DetectCanInterfaces() { // Detect Process for Kvaser CAN devices try { int nrOfChannels; object o = new object(); Canlib.canInitializeLibrary(); //List available channels Canlib.canGetNumberOfChannels(out nrOfChannels); for (int i = 0; i < nrOfChannels; i++) { Canlib.canGetChannelData(i, Canlib.canCHANNELDATA_CHANNEL_NAME, out o); // Display of data in ListView as follows // Network; Type; Mfg; Channel; Status; canHandle BusInterface.AddInterface("CAN;" + o.ToString() + ";" + "Kvaser" + ";" + i, -1); ErrorLog.NewLogEntry("CAN", "Detect CAN: " + o.ToString()); } } catch (Exception) { ErrorLog.NewLogEntry("Adapter", "Kvaser library not found"); } } // End DetectCanInterfaces
public static new string[] GetAdapterNames() { Canlib.canInitializeLibrary(); int nrOfChannels; Canlib.canGetNumberOfChannels(out nrOfChannels); List <string> names = new List <string>(); object channelName = new object(); object channelCapabilities = new object(); for (int i = 0; i < nrOfChannels; i++) { Canlib.canGetChannelData(i, Canlib.canCHANNELDATA_CHANNEL_NAME, out channelName); Canlib.canGetChannelData(i, Canlib.canCHANNELDATA_CHANNEL_CAP, out channelCapabilities); uint capability = (uint)channelCapabilities; if ((capability & Canlib.canCHANNEL_CAP_VIRTUAL) != Canlib.canCHANNEL_CAP_VIRTUAL) { names.Add(channelName.ToString()); logger.Debug(String.Format("Found channel {0}", channelName)); } else { logger.Debug(String.Format("Skipped channel {0}", channelName)); } } return(names.ToArray()); }
public static void CloseAllConnections() { new Thread( () => { lock (LockCanIdsDic) { foreach (var entry in Instance.dic_CanChanels) { byte[] packet = Utils.makePacket(entry.Key, "CC", 0, false, false, "0"); for (int i = 0; i < 3; i++) { Canlib.canWrite(entry.Value, 0x37f, packet, packet.Length, 2); Write(packet); Thread.Sleep(50); } Canlib.canWrite( handle: entry.Value, id: 0, msg: new byte[] { 0x80, (byte)entry.Key }, dlc: 2, //size of msg flag: 2 //we have defined this as const ); Canlib.canBusOff(entry.Value); Canlib.canClose(entry.Value); } } }).Start(); }
public bool CAN_BUS(bool tf) { Canlib.canStatus cs; if (tf) { cs = Canlib.canBusOn(handle); CheckStatus("CAN BUS(" + tf.ToString() + ")", cs); if (cs == Canlib.canStatus.canOK) { this.onBus = true; } else { this.onBus = false; } } else { cs = Canlib.canBusOff(handle); if (cs == Canlib.canStatus.canOK) { this.onBus = false; } } return(this.onBus); }
/* * Initiates the channel */ public void initChannel(int channel, string bitrate) { Canlib.canStatus status; Canlib.canInitializeLibrary(); int hnd = Canlib.canOpenChannel(channel, Canlib.canOPEN_ACCEPT_VIRTUAL); if (hnd >= 0) { chanHandle = hnd; Dictionary <string, int> dicBitRates = new Dictionary <string, int>() { { "125 kb/s", Canlib.canBITRATE_125K }, { "250 kb/s", Canlib.canBITRATE_250K }, { "500 kb/s", Canlib.canBITRATE_500K }, { "1 Mb/s", Canlib.BAUD_1M } }; status = Canlib.canSetBusParams(chanHandle, dicBitRates[bitrate], 0, 0, 0, 0, 0); status = Canlib.canBusOn(chanHandle); if (status == Canlib.canStatus.canOK) { channelOn = true; } } }
internal int FWwrite(byte[] buffer2, int id) { //int id = 888; Canlib.canStatus status; status = Canlib.canWrite(hcan, id, buffer2, 8, Canlib.canMSG_STD); if (status != Canlib.canStatus.canOK) { send2Terminal("mingi error sõnumi saatmisel"); } //Get ACK response byte[] data = new byte[8]; int dlc; int flags; long time; while (id != 889) { Canlib.canReadWait(hcan, out id, data, out dlc, out flags, out time, 100); } if (data[0] == ACK) { return(ACK); } else { return(NACK); } }
//Opens the channel selected in the "Channel" input box void openChannelButton_Click(object sender, RoutedEventArgs e) { //channel = Convert.ToInt32(channelBox.Text); channel = Convert.ToInt32(channelComboBox.SelectedIndex); channelName = ((ComboBoxItem)channelComboBox.SelectedItem).Content.ToString(); //Get a handle for sending sendHandle = Canlib.canOpenChannel(channel, Canlib.canOPEN_REQUIRE_EXTENDED | Canlib.canOPEN_ACCEPT_VIRTUAL); //Get a handle for reading readHandle = Canlib.canOpenChannel(channel, Canlib.canOPEN_REQUIRE_EXTENDED | Canlib.canOPEN_ACCEPT_VIRTUAL); CheckStatus("Opening channel " + channelName, (Canlib.canStatus)sendHandle); if (sendHandle >= 0 && readHandle >= 0) { openChannelButton.IsEnabled = false; //channelBox.IsEnabled = false; channelComboBox.IsEnabled = false; closeChannelButton.IsEnabled = true; busOnButton.IsEnabled = true; bitrateComboBox.IsEnabled = true; } else { MessageBox.Show("Opening Channel " + channelName + " failed. Please try again."); } }
//Goes on bus public void busOn() { Canlib.canStatus status = Canlib.canBusOn(handle); if (status == Canlib.canStatus.canOK) { onBus = true; } }
// The check method takes a canStatus (which is an enumerable) and the method // name as a string argument. If the status is an error code, it will print it. // Most Canlib method return a status, and checking it with a method like this // is a useful practice to avoid code duplication. private static void CheckStatus(Canlib.canStatus status, string method) { if (status < 0) { string errorText; Canlib.canGetErrorText(status, out errorText); Debug.WriteLine(method + " failed: " + errorText); } }
public void deinitCan() { if (hcan >= 0) { Canlib.canBusOff(hcan); Canlib.canClose(hcan); } hcan = -1; }
//Initializes Canlib void initButton_Click(object sender, RoutedEventArgs e) { Canlib.canInitializeLibrary(); statusText.Text = "CAN channel initialized"; initButton.IsEnabled = false; openChannelButton.IsEnabled = true; //channelBox.IsEnabled = true; channelComboBox.IsEnabled = true; }
private bool setCanCardName() { object hwinfo; if (Canlib.canGetChannelData(CANHandle, canlibCLSNET.Canlib.canCHANNELDATA_CARD_TYPE, out hwinfo) != 0) { return(FAIL); } switch ((uint)hwinfo) { case canlibCLSNET.Canlib.canHWTYPE_NONE: CANCardName = "Unknown"; break; case canlibCLSNET.Canlib.canHWTYPE_LAPCAN: CANCardName = "LAPcan"; break; case canlibCLSNET.Canlib.canHWTYPE_USBCAN: CANCardName = "USBcan"; break; case canlibCLSNET.Canlib.canHWTYPE_USBCAN_II: CANCardName = "USBcanII"; break; case canlibCLSNET.Canlib.canHWTYPE_PCCAN: CANCardName = "PCcan"; break; case canlibCLSNET.Canlib.canHWTYPE_PCICAN: CANCardName = "PCIcan"; break; case canlibCLSNET.Canlib.canHWTYPE_PCICAN_II: CANCardName = "PCIcanII"; break; case canlibCLSNET.Canlib.canHWTYPE_SIMULATED: CANCardName = "Simulated"; break; case canlibCLSNET.Canlib.canHWTYPE_VIRTUAL: CANCardName = "Virtual"; break; case canlibCLSNET.Canlib.canHWTYPE_LEAF: CANCardName = " Kvaser Leaf"; break; default: CANCardName = "Unknown"; break; } return(PASS); }
private void OpenChannel(out int hnd, int bitrate) { logger.Debug("hnd = canlibCLSNET.Canlib.canOpenChannel()"); hnd = Canlib.canOpenChannel(ChannelNumber, 0); logger.Debug("canlibCLSNET.Canlib.canSetBusParams(hnd)"); Canlib.canStatus statusSetParam = Canlib.canSetBusParams(hnd, bitrate, 0, 0, 0, 0, 0); logger.Debug("canlibCLSNET.Canlib.canBusOn(hnd)"); Canlib.canStatus statusOn = Canlib.canBusOn(hnd); Canlib.canIoCtl(hnd, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0); }
//Opens the channel selected in the "Channel" input box public void openChannel(int channel) { int hnd = Canlib.canOpenChannel(channel, Canlib.canOPEN_ACCEPT_VIRTUAL); if (hnd >= 0) { handle = hnd; this.channel = channel; } }
private void OpenChannelWithParamsC200(out int hnd, byte btr0, byte btr1) { logger.Debug("hnd = canlibCLSNET.Canlib.canOpenChannel()"); hnd = Canlib.canOpenChannel(ChannelNumber, 0); logger.Debug("canlibCLSNET.Canlib.canSetBusParams(hnd)"); Canlib.canStatus statusSetParam = Canlib.canSetBusParamsC200(hnd, btr0, btr1); logger.Debug("canlibCLSNET.Canlib.canBusOn(hnd)"); Canlib.canStatus statusOn = Canlib.canBusOn(hnd); Canlib.canIoCtl(hnd, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0); }
/// <summary> /// The open method tries to connect to both busses to see if one of them is connected and /// active. The first strategy is to listen for any CAN message. If this fails there is a /// check to see if the application is started after an interrupted flash session. This is /// done by sending a message to set address and length (only for P-bus). /// </summary> /// <returns>OpenResult.OK is returned on success. Otherwise OpenResult.OpenError is /// returned.</returns> override public OpenResult open() { Canlib.canInitializeLibrary(); //Check if bus is connected if (isOpen()) { close(); } Thread.Sleep(200); m_readThread = new Thread(readMessages) { Name = "KvaserCANDevice.m_readThread" }; m_endThread = false; // Take first adapter... string[] adapters = GetAdapterNames(); if (adapters.Length == 0) { return(OpenResult.OpenError); } SetSelectedAdapter(adapters[0]); //Check if P bus is connected logger.Debug("handle1 = canlibCLSNET.Canlib.canOpenChannel()"); handleWrite = Canlib.canOpenChannel(ChannelNumber, 0); logger.Debug("canlibCLSNET.Canlib.canSetBusParams(handleWrite)"); Canlib.canStatus statusSetParamWrite = Canlib.canSetBusParamsC200(handleWrite, 0x40, 0x37); logger.Debug("canlibCLSNET.Canlib.canBusOn(handleWrite)"); Canlib.canStatus statusOnWrite = Canlib.canBusOn(handleWrite); Canlib.canIoCtl(handleWrite, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0); // logger.Debug("handle2 = canlibCLSNET.Canlib.canOpenChannel()"); handleRead = Canlib.canOpenChannel(ChannelNumber, 0); logger.Debug("canlibCLSNET.Canlib.canSetBusParams(handleRead)"); Canlib.canStatus statusSetParamRead = Canlib.canSetBusParamsC200(handleRead, 0x40, 0x37); logger.Debug("canlibCLSNET.Canlib.canBusOn(handleRead)"); Canlib.canStatus statusOnRead = Canlib.canBusOn(handleRead); Canlib.canIoCtl(handleRead, Canlib.canIOCTL_SET_LOCAL_TXECHO, 0); if (handleWrite < 0 || handleRead < 0) { return(OpenResult.OpenError); } logger.Debug("P bus connected"); if (m_readThread.ThreadState == ThreadState.Unstarted) { m_readThread.Start(); } return(OpenResult.OK); }
//Opens the channel selected in the "Channel" input box private void openChannelButton_Click(object sender, RoutedEventArgs e) { channel = Convert.ToInt32(channelBox.Text); int hnd = Canlib.canOpenChannel(channel, Canlib.canOPEN_ACCEPT_VIRTUAL); CheckStatus("Open channel", (Canlib.canStatus)hnd); if (hnd >= 0) { handle = hnd; } }
/// <summary> /// readMessages is the "run" method of this class. It reads all incomming messages /// and publishes them to registered ICANListeners. /// </summary> public void readMessages() { byte[] msg = new byte[8]; int dlc; int flag, id; long time; Canlib.canStatus status; CANMessage canMessage = new CANMessage(); logger.Debug("readMessages started"); while (true) { lock (m_synchObject) { if (m_endThread) { logger.Debug("readMessages thread ended"); return; } } status = Canlib.canReadWait(handleRead, out id, msg, out dlc, out flag, out time, 250); if ((flag & Canlib.canMSG_ERROR_FRAME) == 0) { if (status == Canlib.canStatus.canOK) { canMessage.setID((uint)id); canMessage.setTimeStamp((uint)time); canMessage.setFlags((byte)flag); canMessage.setCanData(msg, (byte)dlc); lock (m_listeners) { //AddToCanTrace("RX: " + canMessage.getID().ToString("X3") + " " + canMessage.getLength().ToString("X1") + " " + canMessage.getData().ToString("X16")); //Console.WriteLine("MSG: " + rxMessage); foreach (ICANListener listener in m_listeners) { listener.handleMessage(canMessage); } //CastInformationEvent(canMessage); // <GS-05042011> re-activated this function } } else if (status == Canlib.canStatus.canERR_NOMSG) { Thread.Sleep(1); } } else { logger.Debug("error frame"); } } }
//Sets the bitrate private void setBitrateButton_Click(object sender, RoutedEventArgs e) { int[] bitrates = new int[4] { Canlib.canBITRATE_125K, Canlib.canBITRATE_250K, Canlib.canBITRATE_500K, Canlib.BAUD_1M }; int bitrate = bitrates[bitrateBox.SelectedIndex]; Canlib.canStatus status = Canlib.canSetBusParams(handle, bitrate, 0, 0, 0, 0, 0); CheckStatus("Setting bitrate to " + ((ComboBoxItem)bitrateBox.SelectedValue).Content, status); }
//Sets the bitrate private void setBitrate_Button_Click(object sender, EventArgs e) { int[] bitrates = new int[4] { Canlib.canBITRATE_125K, Canlib.canBITRATE_250K, Canlib.canBITRATE_500K, Canlib.BAUD_1M }; int bitrate = bitrates[bitrateText.SelectedIndex]; Canlib.canStatus status = Canlib.canSetBusParams(handle, bitrate, 0, 0, 0, 0, 0); CheckStatus("Setting bitrate to " + bitrateText.SelectedValue, status); }
//Goes on bus public void busOn() { Canlib.canStatus status = Canlib.canBusOn(handle); if (status == Canlib.canStatus.canOK) { onBus = true; if (!dumper.IsBusy) { dumper.RunWorkerAsync(); } } }
static void DisplayError(Canlib.canStatus status, String routineName) { String errText = ""; if (status != Canlib.canStatus.canOK) { Canlib.canGetErrorText(status, out errText); Console.WriteLine("{2} failed: {0} = {1}", status, errText, routineName); Environment.Exit(0); } else Console.WriteLine("{0} succeeded", routineName); }
/// <summary> /// CAN获取总线负载率 /// </summary> /// <returns></returns> public int BusLoad() { int busload = 0; Canlib.canBusStatistics sss; if (Canlib.canRequestBusStatistics(canHandler) == Canlib.canStatus.canOK) { Canlib.canGetBusStatistics(canHandler, out sss); busload = (int)sss.busLoad / 100; } return(busload); }
private bool getCanBitRate() { long freq; int tseg1, tseg2, sjw, nosamp, syncmode; if (Canlib.canGetBusParams(CANHandle, out freq, out tseg1, out tseg2, out sjw, out nosamp, out syncmode) != 0) { return(FAIL); } CANBitRate = freq; return(PASS); }
/* * Updates the status bar, prints error message if something goes wrong */ private void CheckStatus(String action, Canlib.canStatus status) { if (status != Canlib.canStatus.canOK) { String errorText = ""; Canlib.canGetErrorText(status, out errorText); statusText.Text = action + " failed: " + errorText; } else { statusText.Text = action + " succeeded"; } }
private void DisplayError(Canlib.canStatus status, String routineName, Boolean exitApp) { String errText = ""; if (status != Canlib.canStatus.canOK) { Canlib.canGetErrorText(status, out errText); errText += ".\nError code = " + status.ToString() + "."; MessageBox.Show(errText, routineName, MessageBoxButtons.OK); // Only exit when signaled if (exitApp) { Environment.Exit(0); } } }
/* ** Check a status code and issue an error message if the code isn't canOK. */ static void ErrorDump(string id, Canlib.canStatus stat, bool quit) { string buf = ""; if (stat != Canlib.canStatus.canOK) { Canlib.canGetErrorText(stat, out buf); Console.WriteLine("{0}: failed, stat={1} ({2})", id, (int)stat, buf); Thread.Sleep(5000); if (quit) Environment.Exit(1); } }