SocketCAN in dotnet core - linux

I am writing software for the device on Linux, and which should work with the CAN interface. Ideally, I would like to work with the interface without connecting third-party libraries from c ++. Is it possible?

I solved this problem using native function. Here example to bind socket, can read and write message with native functions write( or aio_write) and read. CanPublisher in UDSim as example
const int Siocgifindex = 0x8933;
private const int PfCan = 29;
private const int SockRaw = 3;
private const int CanRaw = 1;
private const int CanMtu = 16;
[DllImport("libc", SetLastError = true)]
private static extern int socket(int domain, int type, int protocol);
[DllImport("libc", SetLastError = true)]
private static extern int ioctl(int fd, int request, ref Ifreq mtu);
[DllImport("libc", SetLastError = true)]
private static extern int bind(int fd, ref SockaddrCan addr, int addrlen);
[StructLayout(LayoutKind.Sequential)]
struct SockaddrCan
{
public ushort can_family;
public int can_ifindex;
public uint rx_id;
public uint tx_id;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct Ifreq
{
public Ifreq(string ifr_name)
{
this.ifr_name = ifr_name;
this.ifr_ifindex = 0; // ifru_ivalue
this.ifru_mtu = 0;
}
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string ifr_name;
public int ifr_ifindex;
public uint ifru_mtu;
}
var addr = new SockaddrCan();
var s = socket(PfCan, SockRaw, CanRaw);
var ifr = new Ifreq("vcan0");
var ret = ioctl(s, Siocgifindex, ref ifr);
addr.can_ifindex = ifr.ifr_ifindex;
addr.can_family = PfCan;
ret = bind(s, ref addr, Marshal.SizeOf(addr));

I have written a .NET managed wrapper library for SocketCAN called SocketCAN# (SocketCANSharp): https://github.com/derek-will/SocketCANSharp
SocketCAN# enables utilizing Raw CAN, ISO-TP, Broadcast Manager, and J1939 sockets in a .NET application on Linux.
Some sample code:
IEnumerable<CanNetworkInterface> collection = CanNetworkInterface.GetAllInterfaces(true);
var iface = collection.FirstOrDefault(i => i.Name.Equals("vcan0"));
using (var rawCanSocket = new RawCanSocket())
{
rawCanSocket.Bind(iface);
int bytesWritten = rawCanSocket.Write(
new CanFrame(0x123, new byte[] { 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef }));
}
Underneath the library uses P/Invoke to call the native libc functions and marshal the various types back and fourth between the managed and unmanaged code.

You need to look at the SocketCAN library that is part of Linux.
You can also use candump and cansend to help you develop and also look at the candump.c and cansend.c source files for inspiration.
I see there is a dotnet tag, if you want to use CAN in dotnet I suggest you write a small C library to handle the CAN stuff. Then marshal that to dotnet, once you have access in dotnet you can wrap things in classes and create whatever abstractions you need.

Related

How to detect in which Excel-workbook was clicked ?

Using Excel-2010, Visual-Studio-2013 Professional,
I am trying to find out programatically, in which Excel-Workbook a mouse-click occurrs (or keyboard-shortcut occurs would also be acceptable)? There are several ideas I persuaded, but all of them show the same issue: The Excel-AddIn used does get executed for all open Excel-Workbooks and messes up the needed information in a sense that it does give me the wrong origin of the mouse-click (or keyboard-shortcut click). It does not tell me the desired origin-window but tells me that the click occurred from a window that is not active by all means! I really don't know why the below code-snippets return arbitrary workbook-origins (but never the one I needed, which is the one window I click inside!)...
What is the best way to tell from which window a mouse-click (or keyboard-shortcut) occurrs having several Excel-Workbooks open working with the same Excel-AddIn code ???
Here is what I tried so far:
A) As seen here, a global keyboard-hook was not the solution.
B) GetActiveWindow()
const int nChars = 256;
IntPtr handle1 = GetActiveWindow();
StringBuilder Buff1 = new StringBuilder(nChars);
if (GetWindowText(handle1, Buff1, nChars) > 0) {
MessageBox.Show(Buff1.ToString());
}
C) GetForegroundWindow()
const int nChars = 256;
IntPtr handle2 = GetForegroundWindow();
StringBuilder Buff2 = new StringBuilder(nChars);
if (GetWindowText(handle2, Buff2, nChars) > 0) {
MessageBox.Show(Buff2.ToString());
}
D) ApplicationIsActivated()
public static bool ApplicationIsActivated()
{
var activatedHandle = GetForegroundWindow();
if (activatedHandle == IntPtr.Zero) {
return false; // No window is currently activated
}
var procId = Process.GetCurrentProcess().Id;
int activeProcId;
GetWindowThreadProcessId(activatedHandle, out activeProcId);
MessageBox.Show(activeProcId.ToString());
MessageBox.Show(procId.ToString());
return activeProcId == procId;
}
Needed imports for the above code-snippets:
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll")]
static extern IntPtr GetActiveWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
[DllImport("user32.dll")]
static extern IntPtr SetFocus(IntPtr hWnd);
[DllImport("user32.dll")]
static extern IntPtr GetFocus();
Any idea appreciated!

How to get the value of a pointer to an int pointer from c++ in c#

How to get array of values from the intptr. how to get vlues pointed by int_ptr_arr into s1[].... mean to say my s1[] should contain 10,100,15
it works for me if it is char** with Marshal.PtrToStringAnsi(), but i want it for int** because i don't have anything like Marshal.ptrint().... etc..
enter code here
Native code:
extern "C" __declspec(dllexport) int** __stdcall Array_hh()
{
int x=10;
int y=100;
int z=15;
static int* myArray[3] = {&x, &y, &z};
return myArray;
}
wrapper:
[DllImport("Native_DLL.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
public static extern IntPtr Array_hh();
void some_fun
IntPtr int_ptr_arr = Wrapper.Array_hh();
int k = 0;
int[] s1 = new int[4];

Marshaling char * in .NetcompactFramework(Windows CE)

I have the following signature from c++
IDTECHREADER_EXPORTS void ReadTwoBlocks(char *pathConfig,
char *datablock1, char *datablock2, int timeout, bool &ret )
I was able to Marshal this correctly on the Full .NetFrameWork and it works as below
[DllImport("IDTechReader.dll", EntryPoint = "ReadTwoBlocks" )]
private static extern void _ReadTwoBlocks(
[In][MarshalAs(UnmanagedType.LPStr)] string pathConfig,
[Out][MarshalAs(UnmanagedType.LPStr)] StringBuilder datablock1,
[Out] [MarshalAs(UnmanagedType.LPStr)] StringBuilder datablock2,
int TimeOut,
ref bool result);
However using the same Marshaling as above doesn't work on the NetcompactFramework(Windows CE) it gives an error "NotSupported Exception"
How do we correctly Marshal the above C++ method signature so that it will work correctly on the .NET CompactFramework(windows CE)
any ideas are apperciated...thanks.
The marshaler is probably choking on the MarshalAs(UnmanagedType.LPStr). You're either going to have to change the signature to a fixed size byte[] and do the string conversion in managed code using Encoding.ASCII.GetString(), or you could use an IntPtr type and allocate the memory using Marshal.AllocHGlobal/FreeHGlobal and deal with the string conversion in your code.
I think this might work..
private const int MAX_STRING = 256;
[DllImport("IDTechReader.dll", EntryPoint = "ReadTwoBlocks")]
private static extern void _ReadTwoBlocks(
byte[] pathConfig,
[Out] byte[] datablock1,
[Out] byte[] datablock2,
int TimeOut,
ref bool result);
public void ReadTwoBlocks(string pathConfig,
StringBuilder datablock1,
StringBuilder datablock2,
int TimeOut,
ref bool result)
{
var pathConfigBuff = new byte[MAX_STRING];
var datablock1Buff = new byte[MAX_STRING];
var datablock2Buff = new byte[MAX_STRING];
// Convert unicode string to null terminated single byte charater string
Array.Copy(Encoding.ASCII.GetBytes(pathConfig), pathConfigBuff, pathConfig.Length);
// Call your native method
_ReadTwoBlocks(pathConfigBuff, datablock1Buff, datablock2Buff, TimeOut, ref result);
// If success, copy the datablocks to the StringBuffers
if (result)
{
datablock1.Append(Encoding.ASCII.GetString(datablock1Buff, 0, MAX_STRING).Replace('\0', ' ').Trim());
datablock2.Append(Encoding.ASCII.GetString(datablock2Buff, 0, MAX_STRING).Replace('\0', ' ').Trim());
}
}
It would be something like this:
[DllImport("IDTechReader.dll")]
private static extern void ReadTwoBlocks(IntPtr pathConfig,
IntPtr datablock1, IntPtr datablock2, int timeout, ref bool ret);
and when you use it like this:
string pathConfig = "..\program.ini";
IntPtr ptrPathConfig = IntPtr.Zero;
ptrPathConfig = Marshal.StringToHGlobalAnsi(pathConfig);
IntPtr ptrDatablock1 = IntPtr.Zero;
IntPtr ptrDatablock2 = IntPtr.Zero;
int timeout = 300;
bool ret = false;
ReadTwoBlocks(ptrPathConfig, ptrDatablock1, ptrDatablock2, timeout, ref ret);
string db1 = Marshal.PtrToStringAnsi(ptrDatablock1);
string db2 = Marshal.PtrToStringAnsi(ptrDatablock2);

Which is the correct way to register a new net_device?

i'm trying to register a new net_device in linux...i can alloc and register it correctly and ifconfig shows it. The problem arrives when i try to put the interface up:
ifconfig my_dev up
A kernel freeze occurs...the problem is present only on x86 machines and i can't figure out the reason...on a pcc machine all works well. The code is very simple:
static struct net_device *my_dev;
static int veth_dev_init(struct net_device *dev);
static int veth_open(struct net_device *dev);
static int veth_close(struct net_device *dev);
static int veth_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd);
static struct veth_priv
{
...
};
static struct net_device_ops veth_ops =
{
.ndo_init = veth_dev_init,
.ndo_open = veth_open,
.ndo_stop = veth_close,
.ndo_do_ioctl = veth_ioctl
};
static int __init veth_init()
{
my_dev = alloc_netdev(sizeof(struct veth_priv), "my_dev", ether_setup);
if (my_dev == NULL)
return -ENOMEM;
my_dev->netdev_ops = &veth_ops;
register_netdev(my_dev);
return 0;
}
static void __exit veth_exit()
{
unregister_netdev(my_dev);
free_netdev(my_dev);
}
module_init(veth_init);
module_exit(veth_exit);
The first four functions veth_dev_init, veth_open, veth_close and veth_ioctl simply return 0.
Maybe is there a missing field in veth_ops structure?
Thank you all!
Yea, you missed one element in struct net_device_ops
Add .ndo_start_xmit also, And the function must return NETDEV_TX_OK or NETDEV_TX_BUSY.
use as follows
static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev)
{
return NETDEV_TX_OK;
}
And also change the open as
static int veth_open(struct net_device *dev)
{
memcpy(dev->dev_addr, "\0ABCD0", ETH_ALEN);
netif_start_queue(dev);
return 0;
}
Then in veth_ops
static struct net_device_ops veth_ops = {
.ndo_init = veth_dev_init,
.ndo_open = veth_open,
.ndo_stop = veth_close,
.ndo_start_xmit = veth_xmit,
.ndo_do_ioctl = veth_ioctl,
};
Then after inserting the module
give ifconfig my_dev 192.168.10.98 ...

Getting list of network devices inside the Linux kernel

I've been looking through net/core/dev.c and other files to try to find out how to get the list of network devices that are currently configured and it's proving to be a little difficult to find.
The end goal is to be able to get network device statistics using dev_get_stats in dev.c, but I need to know the current interfaces so I can grab the net_device struct to pass in. I'm having to do this inside the kernel as I'm writing a module which adds in a new /proc/ entry which relates to some statistics from the current network devices so from what I can gather this must be done inside the kernel.
If someone could point me to how to get the interfaces it would be much appreciated.
This ought to do the trick:
#include <linux/netdevice.h>
struct net_device *dev;
read_lock(&dev_base_lock);
dev = first_net_device(&init_net);
while (dev) {
printk(KERN_INFO "found [%s]\n", dev->name);
dev = next_net_device(dev);
}
read_unlock(&dev_base_lock);
Given a struct net *net identifying the net namespace that you are interested in, you should grab the dev_base_lock and use for_each_netdev():
read_lock(&dev_base_lock);
for_each_netdev(net, dev) {
/* Inspect dev */
}
read_unlock(&dev_base_lock);
(In newer kernels, you can use RCU instead, but that is probably an overcomplication in this case).
To obtain the net namespace to use, you should be registering your proc file with register_pernet_subsys():
static const struct file_operations foostats_seq_fops = {
.owner = THIS_MODULE,
.open = foostats_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = foostats_seq_release,
};
static int foo_proc_init_net(struct net *net)
{
if (!proc_net_fops_create(net, "foostats", S_IRUGO,
&foostats_seq_fops))
return -ENOMEM;
return 0;
}
static void foo_proc_exit_net(struct net *net)
{
proc_net_remove(net, "foostats");
}
static struct pernet_operations foo_proc_ops = {
.init = foo_proc_init_net,
.exit = foo_proc_exit_net,
};
register_pernet_subsys(&foo_proc_ops)
In your foostats_seq_open() function, you take a reference on the net namespace, and drop it in the release function:
static int foostats_seq_open(struct inode *inode, struct file *file)
{
int err;
struct net *net;
err = -ENXIO;
net = get_proc_net(inode);
if (net == NULL)
goto err_net;
err = single_open(file, foostats_seq_show, net);
if (err < 0)
goto err_open;
return 0;
err_open:
put_net(net);
err_net:
return err;
}
static int foostats_seq_release(struct inode *inode, struct file *file)
{
struct net *net = ((struct seq_file *)file->private_data)->private;
put_net(net);
return single_release(inode, file);
}
The foostats_seq_show() function can then obtain the net, walk the devices, gather the statistics and produce the output:
static int sockstat6_seq_show(struct seq_file *seq, void *v)
{
struct net *net = seq->private;
struct net_device *dev;
int foostat, barstat;
read_lock(&dev_base_lock);
for_each_netdev(net, dev) {
/* Inspect dev */
}
read_unlock(&dev_base_lock);
seq_printf(seq, "Foo: %d\n", foostat);
seq_printf(seq, "Bar: %d\n", barstat);
return 0;
}

Resources