using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kvaser.CanLib;
namespace MonitorCanChannel
{
class Program
{
static void Main(string[] args)
{
int handle;
Canlib.canStatus status;
int channelNumber = 0;
Canlib.canInitializeLibrary();
handle = Canlib.canOpenChannel(channelNumber, Canlib.canOPEN_ACCEPT_VIRTUAL);
CheckStatus((Canlib.canStatus)handle, "canOpenChannel");
status = Canlib.canSetBusParams(handle, Canlib.canBITRATE_250K, 0, 0, 0, 0);
CheckStatus(status, "canSetBusParams");
status = Canlib.canBusOn(handle);
CheckStatus(status, "canBusOn");
DumpMessageLoop(handle);
status = Canlib.canBusOff(handle);
CheckStatus(status, "canBusOff");
status = Canlib.canClose(handle);
CheckStatus(status, "canClose");
Console.WriteLine("Channel closed. Press any key to exit");
Console.ReadKey();
}
private static void DumpMessageLoop(int handle)
{
Canlib.canStatus status;
bool finished = false;
byte[] data = new byte[8];
int id;
int dlc;
int flags;
long timestamp;
Console.WriteLine("Channel opened. Press Escape to close. ");
Console.WriteLine("ID DLC DATA Timestamp");
while (!finished)
{
status = Canlib.canReadWait(handle, out id, data, out dlc, out flags, out timestamp, 100);
if (status == Canlib.canStatus.canOK)
{
DumpMessage(id, data, dlc, flags, timestamp);
}
else if (status != Canlib.canStatus.canERR_NOMSG)
{
CheckStatus(status, "canReadWait");
finished = true;
}
if (Console.KeyAvailable)
{
if (Console.ReadKey(true).Key == ConsoleKey.Escape)
{
finished = true;
}
}
}
}
private static void DumpMessage(int id, byte[] data, int dlc, int flags, long timestamp)
{
if ((flags & Canlib.canMSG_ERROR_FRAME) != 0)
{
Console.WriteLine("Error Frame received ****");
}
else
{
Console.WriteLine("{0} {1} {2:x2} {3:x2} {4:x2} {5:x2} {6:x2} {7:x2} {8:x2} {9:x2} {10}",
id, dlc, data[0], data[1], data[2], data[3], data[4],
data[5], data[6], data[7], timestamp);
}
}
private static void CheckStatus(Canlib.canStatus status, string method)
{
if (status < 0)
{
Console.WriteLine(method + " failed: " + status.ToString());
}
}
}
}