summaryrefslogtreecommitdiffstats
path: root/CAN-binder/can_samples/init_can.sh
blob: a7900343f3dd1dcba37362a95f6145cf6518bf40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/bin/sh

CAN_DEVICE=can0
CAN_BITRATE=500000

echo "Check if CAN module loaded:"
lsmod | grep can > /dev/null
if [ "$?" -ne "0" ]; then
	echo -e "\tCAN module is not loaded, loading it..."
	sudo modprobe can
	if [ "$?" -ne "0" ]; then
		echo -e "\tFAILED to load CAN module !"
		exit 1
	fi
	echo -e "\tCAN module loaded."
fi

echo "Setup connection:"
sudo ip link set $CAN_DEVICE type can bitrate $CAN_BITRATE
if [ "$?" -ne 0 ]; then
	echo -e "\tFAILED to configure $CAN_DEVICE interface !"
	exit 2
fi

sudo ip link set up $CAN_DEVICE
if [ "$?" -ne 0 ]; then
	echo -e "\tFAILED to enable $CAN_DEVICE interface !"
	exit 3
fi

echo "Ready to use $CAN_DEVICE !"
device_name is the kernel network device name of the CAN interface. /// /// @return Upon successful completion, shall return a non-negative integer, the socket file descriptor. Otherwise, a value of -1 shall be returned and errno set to indicate the error. int socketcan_raw_t::open(std::string device_name) { close(); struct ifreq ifr; socket_ = socketcan_t::open(PF_CAN, SOCK_RAW, CAN_RAW); // Attempts to open a socket to CAN bus ::strcpy(ifr.ifr_name, device_name.c_str()); AFB_DEBUG("ifr_name is : %s", ifr.ifr_name); if(::ioctl(socket_, SIOCGIFINDEX, &ifr) < 0) { AFB_ERROR("ioctl failed. Error was : %s", strerror(errno)); close(); } else { tx_address_.can_family = AF_CAN; tx_address_.can_ifindex = ifr.ifr_ifindex; if(bind((struct sockaddr *)&tx_address_, sizeof(tx_address_)) < 0) { AFB_ERROR("Bind failed. %s", strerror(errno)); close(); } } return socket_; } std::shared_ptr<message_t> socketcan_raw_t::read_message() { std::shared_ptr<can_message_t> cm = std::make_shared<can_message_t>(); struct canfd_frame frame; const struct sockaddr_can& addr = get_tx_address(); socklen_t addrlen = sizeof(addr); struct ifreq ifr; ssize_t nbytes = ::recvfrom(socket(), &frame, sizeof(frame), 0, (struct sockaddr*)&addr, &addrlen); ifr.ifr_ifindex = addr.can_ifindex; ioctl(socket(), SIOCGIFNAME, &ifr); //AFB_DEBUG("Data available: %i bytes read", (int)nbytes); AFB_DEBUG("read: Found on bus %s:\n id: %X, length: %X, data %02X%02X%02X%02X%02X%02X%02X%02X", ifr.ifr_name, frame.can_id, frame.len, frame.data[0], frame.data[1], frame.data[2], frame.data[3], frame.data[4], frame.data[5], frame.data[6], frame.data[7]); struct timeval tv; ioctl(socket(), SIOCGSTAMP, &tv); uint64_t timestamp = 1000000 * tv.tv_sec + tv.tv_usec; cm = ::can_message_t::convert_from_frame(frame , nbytes, timestamp); return cm; } int socketcan_raw_t::write_message(message_t& m) { AFB_WARNING("Not implemented"); return -1; } }