aboutsummaryrefslogtreecommitdiffstats
path: root/src/can-utils.cpp
blob: 3aa2ca884c37350ab3ca9f1f526469b2220e48ff (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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
/*
 * Copyright (C) 2015, 2016 "IoT.bzh"
 * Author "Romain Forlot" <romain.forlot@iot.bzh>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *	 http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

/********************************************************************************
*
*		can_bus_dev_t method implementation
*
*********************************************************************************/


can_bus_dev_t::can_bus_dev_t(afb_binding_interface *itf, const std:string &dev_name)
	: device_name_{dev_name}
{
}

int can_bus_dev_t::open()
{
	const int canfd_on = 1;
	struct ifreq ifr;
	struct timeval timeout = {1, 0};

	DEBUG(interface_, "open_can_dev: CAN Handler socket : %d", can_socket_);
	if (can_socket_ >= 0)
		return 0;

	can_socket_ = ::socket(PF_CAN, SOCK_RAW, CAN_RAW);
	if (socket < 0)
	{
		ERROR(interface_, "open_can_dev: socket could not be created");
	}
	else
	{
		/* Set timeout for read */
		::setsockopt(can_socket_, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
		/* try to switch the socket into CAN_FD mode */
		if (::setsockopt(can_socket_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)) < 0)
		{
			NOTICE(interface_, "open_can_dev: Can not switch into CAN Extended frame format.");
			is_fdmode_on_ = false;
		} else {
			is_fdmode_on_ = true;
		}

		/* Attempts to open a socket to CAN bus */
		::strcpy(ifr.ifr_name, device);
		if(ioctl(can_socket_, SIOCGIFINDEX, &ifr) < 0)
			ERROR(interface_, "open_can_dev: ioctl failed");
		else
		{
			txAddress.can_family = AF_CAN;
			txAddress.can_ifindex = ifr.ifr_ifindex;

			/* And bind it to txAddress */
			if (::bind(can_socket_, (struct sockaddr *)&txAddress_, sizeof(txAddress_)) < 0)
			{
				ERROR(interface_, "open_can_dev: bind failed");
			}
			else
			{
				::fcntl(can_socket_, F_SETFL, O_NONBLOCK);
				return 0;
			}
		}
		close();
	}
	return -1;
}

int can_bus_dev_t::close()
{
	::close(can_socket_);
	can_socket_ = -1;
}


canfd_frame can_bus_dev_t::read()
{
	ssize_t nbytes;
	//int maxdlen;
	canfd_frame canfd_frame;

	/* Test that socket is really opened */
	if (can_socket_ < 0)
	{
		ERROR(interface_, "read_can: Socket unavailable. Closing thread.");
		is_running_ = false;
	}

	nbytes = ::read(can_socket_, &canfd_frame, CANFD_MTU);

	switch(nbytes)
	{
		case CANFD_MTU:
			DEBUG(interface_, "read_can: Got an CAN FD frame with length %d", canfd_frame.len);
			//maxdlen = CANFD_MAX_DLEN;
			break;
		case CAN_MTU:
			DEBUG(interface_, "read_can: Got a legacy CAN frame with length %d", canfd_frame.len);
			//maxdlen = CAN_MAX_DLEN;
			break;
		default:
			if (errno == ENETDOWN)
					ERROR(interface_, "read_can: %s interface down", device);
			ERROR(interface_, "read_can: Error reading CAN bus");
			::memset(&canfd_frame, 0, sizeof(canfd_frame));
			break;
	}
	
	return canfd_frame;
}

/**
 * @brief start reading threads and set flag is_running_
 * 
 */
void can_bus_dev_t::start_reading()
{
	th_reading_ = std::thread(can_reader, this);
	is_running_ = true;
}

/*
 * Return is_running_ bool
 */
bool can_bus_dev_t::is_running()
{
	return is_running_;
}

/**
 * @brief: Get a can_message_t from can_message_q and return it
 * then point to the next can_message_t in queue.
 * 
 * @return the next queue element or NULL if queue is empty.
 */
can_message_t can_bus_dev_t::next_can_message()
{
	if(! can_message_q_.empty())
	{
		can_message_t can_msg = can_message_q_.front();
		can_message_q_.pop()
		return &can_msg;
	}
	
	has_can_message_ = false;
}

/**
 * @brief Append a new element to the can message queue and set
 * has_can_message_ boolean to true
 * 
 * @params[const can_message_t& can_msg] the can_message_t to append
 * 
 */
void can_bus_dev_t::push_new_can_message(const can_message_t& can_msg)
{
	can_message_q_.push(can_msg);
}

/**
 * @brief Flag that let you know when can message queue is exhausted
 * 
 * @return[bool] has_can_message_ bool
 */
bool can_bus_dev_t::has_can_message() const
{
	return has_can_message_;
}

/********************************************************************************
*
*		can_bus_t method implementation
*
*********************************************************************************/

can_bus_t::can_bus_t(afb_binding_interface *itf, std::ifstream& conf_file)
	: interface{itf}, conf_file_{conf_file}
{
}

/**
 * @brief start threads relative to the can bus: decoding and pushing
 * as the reading is handled by can_bus_dev_t object
 * 
 */
void can_bus_t::start_threads()
{
	th_decoding_ = std::thread(can_decoder, this);
	th_pushing_ = std::thread(can_event_push, this);
}


/**
 * @brief Initialize as many as can_bus_dev_t objects with their respective reading thread
 * 
 * params[std::ifstream& conf_file] conf_file ifstream to the JSON configuration 
 * file located at the rootdir of the binding
 */
 void init_can_dev()
 {
   std::vector<std::string> devices_name;
   int i, t;
   
   devices_name = read_conf(conf_file_);
   
   t = devices_name.size();
   i=0
   
   for(const auto& device : devices_name)
   {
     can_bus_dev_t(device);
     i++;
   }
   
   NOTICE(interface_, "Initialized %d/%d can bus device(s)", i, t);
 }

/** 
 * @brief Read the conf file and extract device name
 * 
 * @params[std::ifstream& conf_file] conf_file JSON configuration
 * file located at the rootdir of the binding
 * 
 * @return[std:vector<std::string>] return a vector of device name
 */
 std::vector<std::string> read_conf(std::ifstream& conf_file)
 {
  std::vector<std::string> ret;
  std::string fd_conf_content;
	json_object jo, canbus;
  int n, i, ok;
  
	/* Open JSON conf file */
	if (conf_file)
	{
		conf_file.seekg(0, std::ios::end);
		conf_file.resize(conf_file.tellg());
		conf_file.seekg(0, std::ios::beg);
		conf_file.read(&fd_conf_content[0], fd_conf_content.size());
		conf_file.close();

  	jo = json_tokener_parse(&fd_conf_content);
  
    if (jo == NULL || !json_object_object_get_ex(&jo, "canbus", &&canbus))
      ERROR(interface_, "Can't find canbus node in the configuration file. Please review it.");
    else if (json_object_get_type(canbus) != json_type_array)
  		ret.push_back(json_object_get_string(a));
  	else
  	{
  		n = json_object_array_length(a);
  		ok = 0;
  		for (i = 0 ; i < n ; i++)
  			ret.push_back(json_object_get_string(json_object_array_get_idx(a, i)));
    }
    return ret;
	}
  else
  {
    ERROR(interface_, "Problem at reading the conf file");
    return 0;
  }
}

/**
 * @brief Send a can message from a can_message_t object.
 * TODO: specify which can_dev to use as we can use many
 * 
 * params[const can_message_t& can_msg] the can message object to send
 * 
 */
int can_bus_t::send_can_message(const can_message_t &can_msg)
{
	int nbytes;
	canfd_frame *f;

	f = can_msg.convert_to_canfd_frame();

	if(can_socket_ >= 0)
	{
		nbytes = ::sendto(can_socket_, &f, sizeof(struct canfd_frame), 0,
				(struct sockaddr*)&txAddress, sizeof(txAddress));
				
		if (nbytes == -1)
		{
			ERROR(interface_, "send_can_message: Sending CAN frame failed.");
			return -1;
		}
		return nbytes;
	}
	else
	{
		ERROR(interface_, "send_can_message: socket not initialized. Attempt to reopen can device socket.");
		open();
	}
	return 0;
}

/**
 * @brief: Get a VehicleMessage from vehicle_message_q and return it
 * then point to the next VehicleMessage in queue.
 * 
 * @return the next queue element or NULL if queue is empty.
 */
openxc_VehicleMessage* can_bus_t::next_vehicle_message()
{
	if(! vehicle_message_q_.empty())
	{
		openxc_VehicleMessage v_msg = vehicle_message_q_.front();
		vehicle_message_q_.pop();
		return &v_msg;
	}

	has_vehicle_message_ = false;
}

/**
 * @brief Append a new element to the vehicle message queue and set
 * has_vehicle_message_ boolean to true
 * 
 * @params[const openxc_VehicleMessage& v_msg] the openxc_VehicleMessage to append
 * 
 */
void can_bus_t::push_new_vehicle_message(const openxc_VehicleMessage& v_msg)
{
	vehicle_message_q_.push(v_msg);
	has_vehicle_message_ = true;
}

/**
 * @brief Flag that let you know when vehicle message queue is exhausted
 * 
 * @return[bool] has_vehicle_message_ bool
 */
bool can_bus_t::has_vehicle_message() const
{
	return has_vehicle_message_;
}

/********************************************************************************
*
*		CanMessage method implementation
*
*********************************************************************************/

can_message_t::can_message_t(afb_binding_interface *itf)
	: interface_{itf}
{}

uint32_t can_message_t::get_id() const
{
	(id_ != 0) ? return id_ : return 0;
}

int can_message_t::get_format() const
{
	(format_ != CanMessageFormat::SIMPLE || format_ != CanMessageFormat::EXTENDED) return -1 : return format_;
}

uint8_t can_message_t::get_data() const
{
	return data_;
}
uint8_t can_message_t::get_lenght() const
{
	return lenght_;
}

void can_message_t::set_id(uint32_t &new_id)
{
	switch(format):
		case CanMessageFormat::SIMPLE:
			id = new_id & CAN_SFF_MASK;
		case CanMessageFormat::EXTENDED:
			id = new_id & CAN_EFF_MASK;
		default:
			ERROR(interface_, "ERROR: Can set id, not a compatible format or format not set prior to set id.");
}

void can_message_t::set_format(CanMessageFormat &new_format)
{
	if(new_format == CanMessageFormat::SIMPLE || new_format == CanMessageFormat::EXTENDED)
		format = new_format;
	else
		ERROR(interface_, "ERROR: Can set format, wrong format chosen");
}

void can_message_t::set_data(uint8_t &new_data)
{
	::memcpy(data_, new_data, new_data.size());
	lenght_ = new_data(size);
}

/*
 * This is the preferred way to initialize a CanMessage object 
 * from a read canfd_frame message.
 * 
 * params: canfd_frame pointer
 */
void can_message_t::convert_from_canfd_frame(canfd_frame &frame)
{
	lenght_ = (frame.len > CAN_MAX_DLEN) ? CAN_MAX_DLEN : frame.len;
	lenght_ = (frame.len > CANFD_MAX_DLEN) ? CANFD_MAX_DLEN : frame.len;

	switch (frame.can_id): 
		case (frame.can_id & CAN_ERR_FLAG):
			id_ = frame.can_id & (CAN_ERR_MASK|CAN_ERR_FLAG);
			break;
		case (frame.can_id & CAN_EFF_FLAG):
			id_ = frame.can_id & CAN_EFF_MASK;
			format_ = CanMessageFormat::EXTENDED;
			break;
		default:
			format_ = CanMessageFormat::STANDARD;
			id_ = frame.can_id & CAN_SFF_MASK;
			break;

	if (sizeof(frame.data) <= data_.size())
	{
		::memcpy(data_, canfd_frame.data, lenght_);
		return 0;
	} else if (sizeof(frame.data) >= CAN_MAX_DLEN)
		ERROR(interface_, "can_message_t: canfd_frame data too long to be stored into CanMessage object");
}

canfd_frame convert_to_canfd_frame()
{
	canfd_frame frame;

	frame.can_id = get_id();
	frame.len = get_lenght();
	::memcpy(frame.data, get_data(), lenght_);

	return frame;
}