diff options
author | Romain Forlot <romain.forlot@iot.bzh> | 2017-04-11 12:55:23 +0200 |
---|---|---|
committer | Romain Forlot <romain.forlot@iot.bzh> | 2017-04-11 12:55:23 +0200 |
commit | 9e444ade872bc436cf12bc12d03c3a5d51ac0b9e (patch) | |
tree | d828311d50f1c02a91c8254b1e8e3a18843fe8be /low-can-binding/can | |
parent | 8eaebc2cdfcab4b2f7cd5381241bb0e8bc39701c (diff) |
Handle project new architecture using new CMakeFile
Change-Id: I672a9b49d9d5a3953ba6dccaafbbd738839f64a6
Signed-off-by: Romain Forlot <romain.forlot@iot.bzh>
# Conflicts:
# low-can-binding/libs/bitfield-c
# low-can-binding/libs/isotp-c
# low-can-binding/libs/openxc-message-format
Diffstat (limited to 'low-can-binding/can')
-rw-r--r-- | low-can-binding/can/can-bus-dev.cpp | 255 | ||||
-rw-r--r-- | low-can-binding/can/can-bus-dev.hpp | 65 | ||||
-rw-r--r-- | low-can-binding/can/can-bus.cpp | 398 | ||||
-rw-r--r-- | low-can-binding/can/can-bus.hpp | 94 | ||||
-rw-r--r-- | low-can-binding/can/can-command.hpp | 55 | ||||
-rw-r--r-- | low-can-binding/can/can-decoder.cpp | 233 | ||||
-rw-r--r-- | low-can-binding/can/can-decoder.hpp | 49 | ||||
-rw-r--r-- | low-can-binding/can/can-message-definition.cpp | 55 | ||||
-rw-r--r-- | low-can-binding/can/can-message-definition.hpp | 57 | ||||
-rw-r--r-- | low-can-binding/can/can-message-set.cpp | 37 | ||||
-rw-r--r-- | low-can-binding/can/can-message-set.hpp | 47 | ||||
-rw-r--r-- | low-can-binding/can/can-message.cpp | 264 | ||||
-rw-r--r-- | low-can-binding/can/can-message.hpp | 75 | ||||
-rw-r--r-- | low-can-binding/can/can-signals.cpp | 186 | ||||
-rw-r--r-- | low-can-binding/can/can-signals.hpp | 158 |
15 files changed, 2028 insertions, 0 deletions
diff --git a/low-can-binding/can/can-bus-dev.cpp b/low-can-binding/can/can-bus-dev.cpp new file mode 100644 index 0000000..fb76498 --- /dev/null +++ b/low-can-binding/can/can-bus-dev.cpp @@ -0,0 +1,255 @@ +/* +* Copyright (C) 2015, 2016, 2017 "IoT.bzh" +* Author "Romain Forlot" <romain.forlot@iot.bzh> +* Author "Loïc Collignon" <loic.collignon@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. +*/ + +#include <map> +#include <mutex> +#include <unistd.h> +#include <string.h> +#include <net/if.h> +#include <sys/ioctl.h> +#include <linux/can/raw.h> + +#include "can-bus-dev.hpp" + +#include "can-bus.hpp" +#include "can-message.hpp" +#include "../low-can-binding.hpp" + +/// @brief Class constructor +/// +/// @param[in] dev_name - String representing the device name into the linux /dev tree +/// @param[in] address - integer identifier of the bus, set using init_can_dev from can_bus_t. +can_bus_dev_t::can_bus_dev_t(const std::string& dev_name, int32_t address) + : device_name_{dev_name}, address_{address} +{} + +std::string can_bus_dev_t::get_device_name() const +{ + return device_name_; +} + +uint32_t can_bus_dev_t::get_address() const +{ + return address_; +} + +/// @brief Open the can socket and returning it +/// +/// We try to open CAN socket and apply the following options +/// timestamp received messages and pass the socket to FD mode. +/// +/// @return -1 if something wrong. +int can_bus_dev_t::open() +{ + const int canfd_on = 1; + const int timestamp_on = 1; + struct ifreq ifr; + struct timeval timeout; + + DEBUG(binder_interface, "open: CAN Handler socket : %d", can_socket_.socket()); + if (can_socket_) + return 0; + + can_socket_.open(PF_CAN, SOCK_RAW, CAN_RAW); + if (can_socket_) + { + DEBUG(binder_interface, "open: CAN Handler socket correctly initialized : %d", can_socket_.socket()); + + // Set timeout for read + can_socket_.setopt(SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)); + + // Set timestamp for receveid frame + if (can_socket_.setopt(SOL_SOCKET, SO_TIMESTAMP, ×tamp_on, sizeof(timestamp_on)) < 0) + WARNING(binder_interface, "open: setsockopt SO_TIMESTAMP error: %s", ::strerror(errno)); + DEBUG(binder_interface, "open: Switch CAN Handler socket to use fd mode"); + + // try to switch the socket into CAN_FD mode + if (can_socket_.setopt(SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)) < 0) + { + NOTICE(binder_interface, "open: Can not switch into CAN Extended frame format."); + is_fdmode_on_ = false; + } + else + { + DEBUG(binder_interface, "open: Correctly set up CAN socket to use FD frames."); + is_fdmode_on_ = true; + } + + // Attempts to open a socket to CAN bus + ::strcpy(ifr.ifr_name, device_name_.c_str()); + DEBUG(binder_interface, "open: ifr_name is : %s", ifr.ifr_name); + if(::ioctl(can_socket_.socket(), SIOCGIFINDEX, &ifr) < 0) + { + ERROR(binder_interface, "open: ioctl failed. Error was : %s", strerror(errno)); + } + else + { + txAddress_.can_family = AF_CAN; + txAddress_.can_ifindex = ifr.ifr_ifindex; + + // And bind it to txAddress + DEBUG(binder_interface, "Bind the socket"); + if (can_socket_.bind((struct sockaddr *)&txAddress_, sizeof(txAddress_)) < 0) + ERROR(binder_interface, "Bind failed. %s", strerror(errno)); + else return 0; + } + close(); + } + else ERROR(binder_interface, "open: socket could not be created. Error was : %s", ::strerror(errno)); + return -1; +} + +/// @brief Close the bus. +/// +/// @return interger return value of socket.close() function +int can_bus_dev_t::close() +{ + return can_socket_.close(); +} + +/// @brief Read the can socket and retrieve canfd_frame. +/// +/// Read operation are blocking and we try to read CANFD frame +/// rather than classic CAN frame. CANFD frame are retro compatible. +can_message_t can_bus_dev_t::read() +{ + ssize_t nbytes; + struct canfd_frame cfd; + + // Test that socket is really opened + if (!can_socket_) + { + ERROR(binder_interface, "read: Socket unavailable. Closing thread."); + is_running_ = false; + } + + nbytes = ::read(can_socket_.socket(), &cfd, CANFD_MTU); + + // if we did not fit into CAN sized messages then stop_reading. + if (nbytes != CANFD_MTU && nbytes != CAN_MTU) + { + if (errno == ENETDOWN) + ERROR(binder_interface, "read: %s CAN device down", device_name_.c_str()); + ERROR(binder_interface, "read: Incomplete CAN(FD) frame"); + ::memset(&cfd, 0, sizeof(cfd)); + } + + DEBUG(binder_interface, "read: Found id: %X, length: %X, data %02X%02X%02X%02X%02X%02X%02X%02X", cfd.can_id, cfd.len, + cfd.data[0], cfd.data[1], cfd.data[2], cfd.data[3], cfd.data[4], cfd.data[5], cfd.data[6], cfd.data[7]); + return can_message_t::convert_from_canfd_frame(cfd, nbytes); +} + +/// @brief start reading threads and set flag is_running_ +/// @param[in] can_bus reference can_bus_t. it will be passed to the thread to allow using can_bus_t queue. +void can_bus_dev_t::start_reading(can_bus_t& can_bus) +{ + DEBUG(binder_interface, "Launching reading thread"); + is_running_ = true; + th_reading_ = std::thread(&can_bus_dev_t::can_reader, this, std::ref(can_bus)); + if(!th_reading_.joinable()) + is_running_ = false; +} + +/// @brief stop the reading thread setting flag is_running_ to false and and wait that the thread finish its job. +void can_bus_dev_t::stop_reading() +{ + is_running_ = false; +} + +/// @brief Thread function used to read the can socket. +/// @param[in] can_bus - object to be used to read the can socket +void can_bus_dev_t::can_reader(can_bus_t& can_bus) +{ + while(is_running_) + { + can_message_t msg = read(); + { + std::lock_guard<std::mutex> can_message_lock(can_bus.get_can_message_mutex()); + can_bus.push_new_can_message(msg); + } + can_bus.get_new_can_message_cv().notify_one(); + } +} + +/// @brief Send a can message from a can_message_t object. +/// @param[in] can_msg - the can message object to send +/// +/// @return 0 if message snet, -1 if something wrong. +int can_bus_dev_t::send(can_message_t& can_msg) +{ + ssize_t nbytes; + canfd_frame f; + + f = can_msg.convert_to_canfd_frame(); + + if(can_socket_) + { + nbytes = ::sendto(can_socket_.socket(), &f, sizeof(struct canfd_frame), 0, + (struct sockaddr*)&txAddress_, sizeof(txAddress_)); + if (nbytes == -1) + { + ERROR(binder_interface, "send_can_message: Sending CAN frame failed."); + return -1; + } + return (int)nbytes; + } + else + { + ERROR(binder_interface, "send_can_message: socket not initialized. Attempt to reopen can device socket."); + open(); + } + return 0; +} + +/// @brief Static method used to send diagnostic CAN message +/// that follow isotp SendShimsMessage signature. This method is launched +/// from diagnostic manager's' same name method. It will use the diagnostic +/// manager configured CAN bus device to send the CAN message. +/// +/// @param[in] arbitration_id - CAN arbitration id. +/// @param[in] data - CAN message payload to send +/// @param[in] size - size of the data to send +/// +/// @return True if message sent, false if not. +bool can_bus_dev_t::shims_send(const uint32_t arbitration_id, const uint8_t* data, const uint8_t size) +{ + ssize_t nbytes; + canfd_frame f; + + f.can_id = arbitration_id; + f.len = size; + ::memcpy(f.data, data, size); + + if(can_socket_) + { + nbytes = ::sendto(can_socket_.socket(), &f, sizeof(struct canfd_frame), 0, + (struct sockaddr*)&txAddress_, sizeof(txAddress_)); + if (nbytes == -1) + { + ERROR(binder_interface, "send_can_message: Sending CAN frame failed."); + return false; + } + return true; + } + else + { + ERROR(binder_interface, "send_can_message: socket not initialized. Attempt to reopen can device socket."); + open(); + } + return false; +} diff --git a/low-can-binding/can/can-bus-dev.hpp b/low-can-binding/can/can-bus-dev.hpp new file mode 100644 index 0000000..a612e7d --- /dev/null +++ b/low-can-binding/can/can-bus-dev.hpp @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2015, 2016, 2017 "IoT.bzh" + * Author "Romain Forlot" <romain.forlot@iot.bzh> + * Author "Loïc Collignon" <loic.collignon@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 + +#include <stdint.h> +#include <linux/can.h> +#include <string> +#include <thread> + +#include "../utils/socket.hpp" + +class can_bus_t; +class can_message_t; + +/// @brief Object representing a can device. Handle opening, closing and reading on the +/// socket. This is the low level object to be initialized and use by can_bus_t. +class can_bus_dev_t +{ +private: + std::string device_name_; ///< a string identifier identitfying the linux CAN device. + utils::socket_t can_socket_; + + int32_t address_; ///< an identifier used through binding that refer to that device + + bool is_fdmode_on_; ///< boolean telling if whether or not the can socket use fdmode. + struct sockaddr_can txAddress_; /// < internal member using to bind to the socket + + std::thread th_reading_; ///< Thread handling read the socket can device filling can_message_q_ queue of can_bus_t + bool is_running_ = false; ///< boolean telling whether or not reading is running or not + void can_reader(can_bus_t& can_bus); + +public: + can_bus_dev_t(const std::string& dev_name, int32_t address); + + std::string get_device_name() const; + uint32_t get_address() const; + + int open(); + int close(); + + void start_reading(can_bus_t& can_bus); + + void stop_reading(); + + can_message_t read(); + + int send(can_message_t& can_msg); + bool shims_send(const uint32_t arbitration_id, const uint8_t* data, const uint8_t size); +}; diff --git a/low-can-binding/can/can-bus.cpp b/low-can-binding/can/can-bus.cpp new file mode 100644 index 0000000..33f58fd --- /dev/null +++ b/low-can-binding/can/can-bus.cpp @@ -0,0 +1,398 @@ +/* + * 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. + */ + +#include <map> +#include <cerrno> +#include <vector> +#include <string> +#include <fcntl.h> +#include <unistd.h> +#include <net/if.h> +#include <sys/ioctl.h> +#include <sys/socket.h> +#include <json-c/json.h> +#include <linux/can/raw.h> + +#include "can-bus.hpp" + +#include "can-signals.hpp" +#include "can-decoder.hpp" +#include "../configuration.hpp" +#include "../utils/signals.hpp" +#include "../utils/openxc-utils.hpp" + +extern "C" +{ + #include <afb/afb-binding.h> +} + +/// @brief Class constructor +/// +/// @param[in] conf_file - handle to the json configuration file. +can_bus_t::can_bus_t(int conf_file) + : conf_file_{conf_file} +{ +} + +std::map<std::string, std::shared_ptr<can_bus_dev_t>> can_bus_t::can_devices_; + +/// @brief Will make the decoding operation on a classic CAN message. It will not +/// handle CAN commands nor diagnostic messages that have their own method to get +/// this happens. +/// +/// It will add to the vehicle_message queue the decoded message and tell the event push +/// thread to process it. +/// +/// @param[in] can_message - a single CAN message from the CAN socket read, to be decode. +/// +/// @return How many signals has been decoded. +int can_bus_t::process_can_signals(can_message_t& can_message) +{ + int processed_signals = 0; + std::vector <can_signal_t*> signals; + openxc_DynamicField search_key, decoded_message; + openxc_VehicleMessage vehicle_message; + + // First we have to found which can_signal_t it is + search_key = build_DynamicField((double)can_message.get_id()); + configuration_t::instance().find_can_signals(search_key, signals); + + // Decoding the message ! Don't kill the messenger ! + for(auto& sig : signals) + { + std::lock_guard<std::mutex> subscribed_signals_lock(get_subscribed_signals_mutex()); + std::map<std::string, struct afb_event>& s = get_subscribed_signals(); + + // DEBUG message to make easier debugger STL containers... + //DEBUG(binder_interface, "Operator[] key char: %s, event valid? %d", sig.generic_name, afb_event_is_valid(s[sig.generic_name])); + //DEBUG(binder_interface, "Operator[] key string: %s, event valid? %d", sig.generic_name, afb_event_is_valid(s[std::string(sig.generic_name)])); + //DEBUG(binder_interface, "Nb elt matched char: %d", (int)s.count(sig.generic_name)); + //DEBUG(binder_interface, "Nb elt matched string: %d", (int)s.count(std::string(sig.generic_name)); + if( s.find(sig->get_name()) != s.end() && afb_event_is_valid(s[sig->get_name()])) + { + decoded_message = decoder_t::translateSignal(*sig, can_message, configuration_t::instance().get_can_signals()); + + openxc_SimpleMessage s_message = build_SimpleMessage(sig->get_name(), decoded_message); + vehicle_message = build_VehicleMessage(s_message); + + std::lock_guard<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_); + push_new_vehicle_message(vehicle_message); + processed_signals++; + } + } + + DEBUG(binder_interface, "process_can_signals: %d/%d CAN signals processed.", processed_signals, (int)signals.size()); + return processed_signals; +} + +/// @brief Will make the decoding operation on a diagnostic CAN message.Then it find the subscribed signal +/// corresponding and will add the vehicle_message to the queue of event to pushed before notifying +/// the event push thread to process it. +/// +/// @param[in] manager - the diagnostic manager object that handle diagnostic communication +/// @param[in] can_message - a single CAN message from the CAN socket read, to be decode. +/// +/// @return How many signals has been decoded. +int can_bus_t::process_diagnostic_signals(diagnostic_manager_t& manager, const can_message_t& can_message) +{ + int processed_signals = 0; + + std::lock_guard<std::mutex> subscribed_signals_lock(get_subscribed_signals_mutex()); + std::map<std::string, struct afb_event>& s = get_subscribed_signals(); + + openxc_VehicleMessage vehicle_message = manager.find_and_decode_adr(can_message); + if( (vehicle_message.has_simple_message && vehicle_message.simple_message.has_name) && + (s.find(vehicle_message.simple_message.name) != s.end() && afb_event_is_valid(s[vehicle_message.simple_message.name]))) + { + std::lock_guard<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_); + push_new_vehicle_message(vehicle_message); + processed_signals++; + } + + return processed_signals; +} + +/// @brief thread to decoding raw CAN messages. +/// +/// Depending on the nature of message, if arbitration ID matches ID for a diagnostic response +/// then decoding a diagnostic message else use classic CAN signals decoding functions. +/// +/// It will take from the can_message_q_ queue the next can message to process then it search +/// about signal subscribed if there is a valid afb_event for it. We only decode signal for which a +/// subscription has been made. Can message will be decoded using translateSignal that will pass it to the +/// corresponding decoding function if there is one assigned for that signal. If not, it will be the default +/// noopDecoder function that will operate on it. +/// +/// TODO: make diagnostic messages parsing optionnal. +void can_bus_t::can_decode_message() +{ + can_message_t can_message; + + while(is_decoding_) + { + { + std::unique_lock<std::mutex> can_message_lock(can_message_mutex_); + new_can_message_cv_.wait(can_message_lock); + while(!can_message_q_.empty()) + { + can_message = next_can_message(); + + if(configuration_t::instance().get_diagnostic_manager().is_diagnostic_response(can_message)) + process_diagnostic_signals(configuration_t::instance().get_diagnostic_manager(), can_message); + else + process_can_signals(can_message); + } + } + new_decoded_can_message_.notify_one(); + } +} + +/// @brief thread to push events to suscribers. It will read subscribed_signals map to look +/// which are events that has to be pushed. +void can_bus_t::can_event_push() +{ + openxc_VehicleMessage v_message; + openxc_SimpleMessage s_message; + json_object* jo; + + while(is_pushing_) + { + std::unique_lock<std::mutex> decoded_can_message_lock(decoded_can_message_mutex_); + new_decoded_can_message_.wait(decoded_can_message_lock); + while(!vehicle_message_q_.empty()) + { + v_message = next_vehicle_message(); + + s_message = get_simple_message(v_message); + { + std::lock_guard<std::mutex> subscribed_signals_lock(get_subscribed_signals_mutex()); + std::map<std::string, struct afb_event>& s = get_subscribed_signals(); + if(s.find(std::string(s_message.name)) != s.end() && afb_event_is_valid(s[std::string(s_message.name)])) + { + jo = json_object_new_object(); + jsonify_simple(s_message, jo); + if(afb_event_push(s[std::string(s_message.name)], jo) == 0) + on_no_clients(std::string(s_message.name)); + } + } + } + } +} + +/// @brief Will initialize threads that will decode +/// and push subscribed events. +void can_bus_t::start_threads() +{ + is_decoding_ = true; + th_decoding_ = std::thread(&can_bus_t::can_decode_message, this); + if(!th_decoding_.joinable()) + is_decoding_ = false; + + is_pushing_ = true; + th_pushing_ = std::thread(&can_bus_t::can_event_push, this); + if(!th_pushing_.joinable()) + is_pushing_ = false; +} + +/// @brief Will stop all threads holded by can_bus_t object +/// which are decoding and pushing then will wait that's +/// they'll finish their job. +void can_bus_t::stop_threads() +{ + is_decoding_ = false; + is_pushing_ = false; +} + +/// @brief Will initialize can_bus_dev_t objects after reading +/// the configuration file passed in the constructor. All CAN buses +/// Initialized here will be added to a vector holding them for +/// inventory and later access. +/// +/// That will initialize CAN socket reading too using a new thread. +/// +/// @return 0 if ok, other if not. +int can_bus_t::init_can_dev() +{ + std::vector<std::string> devices_name; + int i = 0; + size_t t; + + devices_name = read_conf(); + + if (! devices_name.empty()) + { + t = devices_name.size(); + + for(const auto& device : devices_name) + { + can_bus_t::can_devices_[device] = std::make_shared<can_bus_dev_t>(device, i); + if (can_bus_t::can_devices_[device]->open() == 0) + { + DEBUG(binder_interface, "Start reading thread"); + NOTICE(binder_interface, "%s device opened and reading", device.c_str()); + can_bus_t::can_devices_[device]->start_reading(*this); + i++; + } + else + { + ERROR(binder_interface, "Can't open device %s", device.c_str()); + return 1; + } + } + + NOTICE(binder_interface, "Initialized %d/%d can bus device(s)", i, (int)t); + return 0; + } + ERROR(binder_interface, "init_can_dev: Error at CAN device initialization. No devices read from configuration file. Did you specify canbus JSON object ?"); + return 1; +} + +/// @brief read the conf_file_ and will parse json objects +/// in it searching for canbus objects devices name. +/// +/// @return Vector of can bus device name string. +std::vector<std::string> can_bus_t::read_conf() +{ + std::vector<std::string> ret; + json_object *jo, *canbus; + int n, i; + const char* taxi; + + FILE *fd = fdopen(conf_file_, "r"); + if (fd) + { + std::string fd_conf_content; + std::fseek(fd, 0, SEEK_END); + fd_conf_content.resize(std::ftell(fd)); + std::rewind(fd); + std::fread(&fd_conf_content[0], 1, fd_conf_content.size(), fd); + std::fclose(fd); + + DEBUG(binder_interface, "Configuration file content : %s", fd_conf_content.c_str()); + jo = json_tokener_parse(fd_conf_content.c_str()); + + if (jo == NULL || !json_object_object_get_ex(jo, "canbus", &canbus)) + { + ERROR(binder_interface, "Can't find canbus node in the configuration file. Please review it."); + ret.clear(); + } + else if (json_object_get_type(canbus) != json_type_array) + { + taxi = json_object_get_string(canbus); + DEBUG(binder_interface, "Can bus found: %s", taxi); + ret.push_back(std::string(taxi)); + } + else + { + n = json_object_array_length(canbus); + for (i = 0 ; i < n ; i++) + ret.push_back(json_object_get_string(json_object_array_get_idx(canbus, i))); + } + return ret; + } + ERROR(binder_interface, "Problem at reading the conf file"); + ret.clear(); + return ret; +} + +/// @brief return new_can_message_cv_ member +/// +/// @return return new_can_message_cv_ member +std::condition_variable& can_bus_t::get_new_can_message_cv() +{ + return new_can_message_cv_; +} + +/// @brief return can_message_mutex_ member +/// +/// @return return can_message_mutex_ member +std::mutex& can_bus_t::get_can_message_mutex() +{ + return can_message_mutex_; +} + +/// @brief Return first can_message_t on the queue +/// +/// @return a can_message_t +can_message_t can_bus_t::next_can_message() +{ + can_message_t can_msg; + + if(!can_message_q_.empty()) + { + can_msg = can_message_q_.front(); + can_message_q_.pop(); + DEBUG(binder_interface, "next_can_message: Here is the next can message : id %X, length %X, data %02X%02X%02X%02X%02X%02X%02X%02X", can_msg.get_id(), can_msg.get_length(), + can_msg.get_data()[0], can_msg.get_data()[1], can_msg.get_data()[2], can_msg.get_data()[3], can_msg.get_data()[4], can_msg.get_data()[5], can_msg.get_data()[6], can_msg.get_data()[7]); + return can_msg; + } + + return can_msg; +} + +/// @brief Push a can_message_t into the queue +/// +/// @param[in] can_msg - the const reference can_message_t object to push into the queue +void can_bus_t::push_new_can_message(const can_message_t& can_msg) +{ + can_message_q_.push(can_msg); +} + +/// @brief Return first openxc_VehicleMessage on the queue +/// +/// @return a openxc_VehicleMessage containing a decoded can message +openxc_VehicleMessage can_bus_t::next_vehicle_message() +{ + openxc_VehicleMessage v_msg; + + if(! vehicle_message_q_.empty()) + { + v_msg = vehicle_message_q_.front(); + vehicle_message_q_.pop(); + DEBUG(binder_interface, "next_vehicle_message: next vehicle message poped"); + return v_msg; + } + + return v_msg; +} + +/// @brief Push a openxc_VehicleMessage into the queue +/// +/// @param[in] v_msg - const reference openxc_VehicleMessage object to push into the queue +void can_bus_t::push_new_vehicle_message(const openxc_VehicleMessage& v_msg) +{ + vehicle_message_q_.push(v_msg); +} + +/// @brief Return a map with the can_bus_dev_t initialized +/// +/// @return map can_bus_dev_m_ map +const std::map<std::string, std::shared_ptr<can_bus_dev_t>>& can_bus_t::get_can_devices() const +{ + return can_bus_t::can_devices_; +} + +/// @brief Return the shared pointer on the can_bus_dev_t initialized +/// with device_name "bus" +/// +/// @param[in] bus - CAN bus device name to retrieve. +/// +/// @return A shared pointer on an object can_bus_dev_t +std::shared_ptr<can_bus_dev_t> can_bus_t::get_can_device(std::string bus) +{ + return can_bus_t::can_devices_[bus]; +} diff --git a/low-can-binding/can/can-bus.hpp b/low-can-binding/can/can-bus.hpp new file mode 100644 index 0000000..eb47476 --- /dev/null +++ b/low-can-binding/can/can-bus.hpp @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2015, 2016, 2017 "IoT.bzh" + * Author "Romain Forlot" <romain.forlot@iot.bzh> + * Author "Loïc Collignon" <loic.collignon@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 + +#include <mutex> +#include <queue> +#include <thread> +#include <linux/can.h> +#include <condition_variable> + +#include "openxc.pb.h" +#include "can-message.hpp" +#include "can-bus-dev.hpp" +#include "../diagnostic/active-diagnostic-request.hpp" + +#include "../low-can-binding.hpp" + +// TODO actual max is 32 but dropped to 24 for memory considerations +#define MAX_ACCEPTANCE_FILTERS 24 +// TODO this takes up a ton of memory +#define MAX_DYNAMIC_MESSAGE_COUNT 12 + +#define CAN_ACTIVE_TIMEOUT_S 30 + +/// @brief Object used to handle decoding and manage event queue to be pushed. +/// +/// This object is also used to initialize can_bus_dev_t object after reading +/// json conf file describing the CAN devices to use. Thus, those object will read +/// on the device the CAN frame and push them into the can_bus_t can_message_q_ queue. +/// +/// That queue will be later used to be decoded and pushed to subscribers. +class can_bus_t +{ +private: + int conf_file_; ///< configuration file handle used to initialize can_bus_dev_t objects. + + void can_decode_message(); + std::thread th_decoding_; ///< thread that'll handle decoding a can frame + bool is_decoding_ = false; ///< boolean member controling thread while loop + + void can_event_push(); + std::thread th_pushing_; ///< thread that'll handle pushing decoded can frame to subscribers + bool is_pushing_ = false; ///< boolean member controling thread while loop + + std::condition_variable new_can_message_cv_; ///< condition_variable use to wait until there is a new CAN message to read + std::mutex can_message_mutex_; ///< mutex protecting the can_message_q_ queue. + std::queue <can_message_t> can_message_q_; ///< queue that'll store can_message_t to decoded + + std::condition_variable new_decoded_can_message_; ///< condition_variable use to wait until there is a new vehicle message to read from the queue vehicle_message_q_ + std::mutex decoded_can_message_mutex_; ///< mutex protecting the vehicle_message_q_ queue. + std::queue <openxc_VehicleMessage> vehicle_message_q_; ///< queue that'll store openxc_VehicleMessage to pushed + + static std::map<std::string, std::shared_ptr<can_bus_dev_t>> can_devices_; ///< Can device map containing all can_bus_dev_t objects initialized during init_can_dev function + +public: + can_bus_t(int conf_file); + can_bus_t(can_bus_t&&); + + int init_can_dev(); + std::vector<std::string> read_conf(); + + void start_threads(); + void stop_threads(); + + int process_can_signals(can_message_t& can_message); + int process_diagnostic_signals(diagnostic_manager_t& manager, const can_message_t& can_message); + + can_message_t next_can_message(); + void push_new_can_message(const can_message_t& can_msg); + std::mutex& get_can_message_mutex(); + std::condition_variable& get_new_can_message_cv(); + + openxc_VehicleMessage next_vehicle_message(); + void push_new_vehicle_message(const openxc_VehicleMessage& v_msg); + + const std::map<std::string, std::shared_ptr<can_bus_dev_t>>& get_can_devices() const; + static std::shared_ptr<can_bus_dev_t> get_can_device(std::string bus); +}; diff --git a/low-can-binding/can/can-command.hpp b/low-can-binding/can/can-command.hpp new file mode 100644 index 0000000..4cf20cb --- /dev/null +++ b/low-can-binding/can/can-command.hpp @@ -0,0 +1,55 @@ +/* + * 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 + +#include "openxc.pb.h" +#include "can-signals.hpp" + +/// +/// @brief The type signature for a function to handle a custom OpenXC command. +/// +/// @param[in] name - the name of the received command. +/// @param[in] value - the value of the received command, in a DynamicField. The actual type +/// may be a number, string or bool. +/// @param[in] event - an optional event from the received command, in a DynamicField. The +/// actual type may be a number, string or bool. +/// @param[in] signals - The list of all signals. +/// @param[in] signalCount - The length of the signals array. +/// +typedef void (*CommandHandler)(const char* name, openxc_DynamicField* value, + openxc_DynamicField* event, can_signal_t* signals, int signalCount); + +/// @struct CanCommand +/// @brief The structure to represent a supported custom OpenXC command. +/// +/// For completely customized CAN commands without a 1-1 mapping between an +/// OpenXC message from the host and a CAN signal, you can define the name of the +/// command and a custom function to handle it in the VI. An example is +/// the "turn_signal_status" command in OpenXC, which has a value of "left" or +/// "right". The vehicle may have separate CAN signals for the left and right +/// turn signals, so you will need to implement a custom command handler to send +/// the correct signals. +/// +/// Command handlers are also useful if you want to trigger multiple CAN messages +/// or signals from a signal OpenXC message. +/// +typedef struct { + const char* generic_name; /*!< generic_name - The name of the command.*/ + CommandHandler handler; /*!< handler - An function to process the received command's data and perform some + * action.*/ +} CanCommand; diff --git a/low-can-binding/can/can-decoder.cpp b/low-can-binding/can/can-decoder.cpp new file mode 100644 index 0000000..8843059 --- /dev/null +++ b/low-can-binding/can/can-decoder.cpp @@ -0,0 +1,233 @@ +/* + * 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. + */ + +#include "can-decoder.hpp" + +#include "canutil/read.h" +#include "../utils/openxc-utils.hpp" + +/// @brief Parse the signal's bitfield from the given data and return the raw +/// value. +/// +/// @param[in] signal - The signal to parse from the data. +/// @param[in] message - can_message_t to parse +/// +/// @return Returns the raw value of the signal parsed as a bitfield from the given byte +/// array. +/// +float decoder_t::parseSignalBitfield(can_signal_t& signal, const can_message_t& message) +{ + return bitfield_parse_float(message.get_data(), CAN_MESSAGE_SIZE, + signal.get_bit_position(), signal.get_bit_size(), signal.get_factor(), + signal.get_offset()); +} + +/// @brief Wrap a raw CAN signal value in a DynamicField without modification. +/// +/// This is an implementation of the SignalDecoder type signature, and can be +/// used directly in the can_signal_t.decoder field. +/// +/// @param[in] signal - The details of the signal that contains the state mapping. +/// @param[in] signals - The list of all signals +/// @param[in] value - The numerical value that will be wrapped in a DynamicField. +/// @param[out] send - An output argument that will be set to false if the value should +/// not be sent for any reason. +/// +/// @return Returns a DynamicField with the original, unmodified raw CAN signal value as +/// its numeric value. The 'send' argument will not be modified as this decoder +/// always succeeds. +/// +openxc_DynamicField decoder_t::noopDecoder(can_signal_t& signal, + const std::vector<can_signal_t>& signals, float value, bool* send) +{ + openxc_DynamicField decoded_value = build_DynamicField(value); + + return decoded_value; +} +/// @brief Coerces a numerical value to a boolean. +/// +/// This is an implementation of the SignalDecoder type signature, and can be +/// used directly in the can_signal_t.decoder field. +/// +/// @param[in] signal - The details of the signal that contains the state mapping. +/// @param[in] signals - The list of all signals +/// @param[in] value - The numerical value that will be converted to a boolean. +/// @param[out] send - An output argument that will be set to false if the value should +/// not be sent for any reason. +/// +/// @return Returns a DynamicField with a boolean value of false if the raw signal value +/// is 0.0, otherwise true. The 'send' argument will not be modified as this +/// decoder always succeeds. +/// +openxc_DynamicField decoder_t::booleanDecoder(can_signal_t& signal, + const std::vector<can_signal_t>& signals, float value, bool* send) +{ + openxc_DynamicField decoded_value = build_DynamicField(value == 0.0 ? false : true); + + return decoded_value; +} +/// @brief Update the metadata for a signal and the newly received value. +/// +/// This is an implementation of the SignalDecoder type signature, and can be +/// used directly in the can_signal_t.decoder field. +/// +/// This function always flips 'send' to false. +/// +/// @param[in] signal - The details of the signal that contains the state mapping. +/// @param[in] signals - The list of all signals. +/// @param[in] value - The numerical value that will be converted to a boolean. +/// @param[out] send - This output argument will always be set to false, so the caller will +/// know not to publish this value to the pipeline. +/// +/// @return Return value is undefined. +/// +openxc_DynamicField decoder_t::ignoreDecoder(can_signal_t& signal, + const std::vector<can_signal_t>& signals, float value, bool* send) +{ + if(send) + *send = false; + + openxc_DynamicField decoded_value; + + return decoded_value; +} + +/// @brief Find and return the corresponding string state for a CAN signal's +/// raw integer value. +/// +/// This is an implementation of the SignalDecoder type signature, and can be +/// used directly in the can_signal_t.decoder field. +/// +/// @param[in] signal - The details of the signal that contains the state mapping. +/// @param[in] signals - The list of all signals. +/// @param[in] value - The numerical value that should map to a state. +/// @param[out] send - An output argument that will be set to false if the value should +/// not be sent for any reason. +/// +/// @return Returns a DynamicField with a string value if a matching state is found in +/// the signal. If an equivalent isn't found, send is sent to false and the +/// return value is undefined. +/// +openxc_DynamicField decoder_t::stateDecoder(can_signal_t& signal, + const std::vector<can_signal_t>& signals, float value, bool* send) +{ + const std::string signal_state = signal.get_states((uint8_t)value); + openxc_DynamicField decoded_value = build_DynamicField(signal_state); + if(signal_state.size() <= 0) + { + *send = false; + ERROR(binder_interface, "stateDecoder: No state found with index: %d", (int)value); + } + return decoded_value; +} + + +/// @brief Parse a signal from a CAN message, apply any required transforations +/// to get a human readable value and public the result to the pipeline. +/// +/// If the can_signal_t has a non-NULL 'decoder' field, the raw CAN signal value +/// will be passed to the decoder before publishing. +/// +/// @param[in] signal - The details of the signal to decode and forward. +/// @param[in] message - The received CAN message that should contain this signal. +/// @param[in] signals - an array of all active signals. +/// +/// The decoder returns an openxc_DynamicField, which may contain a number, +/// string or boolean. +/// +openxc_DynamicField decoder_t::translateSignal(can_signal_t& signal, can_message_t& message, + const std::vector<can_signal_t>& signals) +{ + float value = decoder_t::parseSignalBitfield(signal, message); + DEBUG(binder_interface, "translateSignal: Decoded message from parseSignalBitfield: %f", value); + + bool send = true; + // Must call the decoders every time, regardless of if we are going to + // decide to send the signal or not. + openxc_DynamicField decoded_value = decoder_t::decodeSignal(signal, + value, signals, &send); + + signal.set_received(true); + signal.set_last_value(value); + return decoded_value; +} + +/// @brief Parse a signal from a CAN message and apply any required +/// transforations to get a human readable value. +/// +/// If the can_signal_t has a non-NULL 'decoder' field, the raw CAN signal value +/// will be passed to the decoder before returning. +/// +/// @param[in] signal - The details of the signal to decode and forward. +/// @param[in] value - The numerical value that will be converted to a boolean. +/// @param[in] signals - an array of all active signals. +/// @param[out] send - An output parameter that will be flipped to false if the value could +/// not be decoded. +/// +/// @return The decoder returns an openxc_DynamicField, which may contain a number, +/// string or boolean. If 'send' is false, the return value is undefined. +/// +openxc_DynamicField decoder_t::decodeSignal( can_signal_t& signal, + float value, const std::vector<can_signal_t>& signals, bool* send) +{ + SignalDecoder decoder = signal.get_decoder() == nullptr ? + noopDecoder : signal.get_decoder(); + openxc_DynamicField decoded_value = decoder(signal, signals, + value, send); + return decoded_value; +} + +/// @brief Decode a transformed, human readable value from an raw CAN signal +/// already parsed from a CAN message. +/// +/// This is the same as decodeSignal but you must parse the bitfield value of the signal from the CAN +/// message yourself. This is useful if you need that raw value for something +/// else. +/// +/// @param[in] signal - The details of the signal to decode and forward. +/// @param[in] message - Raw CAN message to decode +/// @param[in] signals - an array of all active signals. +/// @param[out] send - An output parameter that will be flipped to false if the value could +/// not be decoded. +/// +openxc_DynamicField decoder_t::decodeSignal( can_signal_t& signal, + const can_message_t& message, const std::vector<can_signal_t>& signals, bool* send) +{ + float value = parseSignalBitfield(signal, message); + return decodeSignal(signal, value, signals, send); +} + + +/// +/// @brief Decode the payload of an OBD-II PID. +/// +/// This function matches the type signature for a DiagnosticResponseDecoder, so +/// it can be used as the decoder for a DiagnosticRequest. It returns the decoded +/// value of the PID, using the standard formulas (see +/// http://en.wikipedia.org/wiki/OBD-II_PIDs#Mode_01). +/// +/// @param[in] response - the received DiagnosticResponse (the data is in response.payload, +/// a byte array). This is most often used when the byte order is +/// signiticant, i.e. with many OBD-II PID formulas. +/// @param[in] parsed_payload - the entire payload of the response parsed as an int. +/// +/// @return Float decoded value. +/// +float decoder_t::decode_obd2_response(const DiagnosticResponse* response, float parsed_payload) +{ + return diagnostic_decode_obd2_pid(response); +}
\ No newline at end of file diff --git a/low-can-binding/can/can-decoder.hpp b/low-can-binding/can/can-decoder.hpp new file mode 100644 index 0000000..ebe1de2 --- /dev/null +++ b/low-can-binding/can/can-decoder.hpp @@ -0,0 +1,49 @@ +/* + * 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 + +#include "can-signals.hpp" +#include "can-message.hpp" +#include "openxc.pb.h" + +class decoder_t +{ +public: + static float parseSignalBitfield(can_signal_t& signal, const can_message_t& message); + + static openxc_DynamicField stateDecoder(can_signal_t& signal, const std::vector<can_signal_t>& signals, + float value, bool* send); + static openxc_DynamicField booleanDecoder(can_signal_t& signal, const std::vector<can_signal_t>& signals, + float value, bool* send); + static openxc_DynamicField ignoreDecoder(can_signal_t& signal, const std::vector<can_signal_t>& signals, + float value, bool* send); + static openxc_DynamicField noopDecoder(can_signal_t& signal, const std::vector<can_signal_t>& signals, + float value, bool* send); + + static openxc_DynamicField translateSignal(can_signal_t& signal, can_message_t& message, + const std::vector<can_signal_t>& signals); + + static openxc_DynamicField decodeSignal(can_signal_t& signal, const can_message_t& message, + const std::vector<can_signal_t>& signals, bool* send); + + static openxc_DynamicField decodeSignal(can_signal_t& signal, float value, + const std::vector<can_signal_t>& signals, bool* send); + + static float decode_obd2_response(const DiagnosticResponse* response, float parsed_payload); + +};
\ No newline at end of file diff --git a/low-can-binding/can/can-message-definition.cpp b/low-can-binding/can/can-message-definition.cpp new file mode 100644 index 0000000..206d0b0 --- /dev/null +++ b/low-can-binding/can/can-message-definition.cpp @@ -0,0 +1,55 @@ +/* + * 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. + */ + +#include "can-message-definition.hpp" + +can_message_definition_t::can_message_definition_t(std::uint8_t message_set_id, const std::string bus) + : message_set_id_{message_set_id}, bus_{bus}, last_value_{CAN_MESSAGE_SIZE} +{} + +can_message_definition_t::can_message_definition_t(std::uint8_t message_set_id, + const std::string bus, + uint32_t id, + frequency_clock_t frequency_clock, + bool force_send_changed) + : message_set_id_{message_set_id}, + bus_{bus}, + id_{id}, + frequency_clock_{frequency_clock}, + force_send_changed_{force_send_changed}, + last_value_{CAN_MESSAGE_SIZE} +{} + +can_message_definition_t::can_message_definition_t(std::uint8_t message_set_id, + const std::string bus, + uint32_t id, + can_message_format_t format, + frequency_clock_t frequency_clock, + bool force_send_changed) + : message_set_id_{message_set_id}, + bus_{bus}, + id_{id}, + format_{format}, + frequency_clock_{frequency_clock}, + force_send_changed_{force_send_changed}, + last_value_{CAN_MESSAGE_SIZE} +{} + +uint32_t can_message_definition_t::get_id() const +{ + return id_; +}
\ No newline at end of file diff --git a/low-can-binding/can/can-message-definition.hpp b/low-can-binding/can/can-message-definition.hpp new file mode 100644 index 0000000..98cb2c5 --- /dev/null +++ b/low-can-binding/can/can-message-definition.hpp @@ -0,0 +1,57 @@ +/* + * 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. + */ + +/** + * @class can_message_definition_t + * + * @brief The definition of a CAN message. This includes a lot of metadata, so + * to save memory this struct should not be used for storing incoming and + * outgoing CAN messages. + */ + +#pragma once + +#include <vector> +#include <memory> + +#include "can-bus-dev.hpp" +#include "can-message.hpp" +#include "../utils/timer.hpp" + +class can_message_definition_t +{ +private: + std::uint8_t message_set_id_; + std::string bus_; /*!< bus_ - Address of CAN bus device. */ + uint32_t id_; /*!< id_ - The ID of the message.*/ + can_message_format_t format_; /*!< format_ - the format of the message's ID.*/ + frequency_clock_t frequency_clock_; /*!< clock_ - an optional frequency clock to control the output of this + * message, if sent raw, or simply to mark the max frequency for custom + * handlers to retrieve.*/ + bool force_send_changed_; /*!< force_send_changed_ - If true, regardless of the frequency, it will send CAN + * message if it has changed when using raw passthrough.*/ + std::vector<uint8_t> last_value_; /*!< last_value_ - The last received value of the message. Defaults to undefined. + * This is required for the forceSendChanged functionality, as the stack + * needs to compare an incoming CAN message with the previous frame.*/ + +public: + can_message_definition_t(std::uint8_t message_set_id, const std::string bus); + can_message_definition_t(std::uint8_t message_set_id, const std::string bus, uint32_t id, frequency_clock_t frequency_clock, bool force_send_changed); + can_message_definition_t(std::uint8_t message_set_id, const std::string bus, uint32_t id, can_message_format_t format, frequency_clock_t frequency_clock, bool force_send_changed); + + uint32_t get_id() const; +}; diff --git a/low-can-binding/can/can-message-set.cpp b/low-can-binding/can/can-message-set.cpp new file mode 100644 index 0000000..a9f8cf2 --- /dev/null +++ b/low-can-binding/can/can-message-set.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2015, 2016, 2017 "IoT.bzh" + * Author "Romain Forlot" <romain.forlot@iot.bzh> + * Author "Loïc Collignon" <loic.collignon@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. + */ + +#include "can-message-set.hpp" + +can_message_set_t::can_message_set_t( + uint8_t index, + const std::string& name, + uint8_t can_bus_count, + unsigned short can_message_count, + unsigned short can_signal_count, + unsigned short can_command_count, + unsigned short obd2_signal_count) + : index_{index} + , name_{name} + , can_bus_count_{can_bus_count} + , can_message_count_{can_message_count} + , can_signal_count_{can_signal_count} + , can_command_count_{can_command_count} + , obd2_signal_count_{obd2_signal_count} +{ +} diff --git a/low-can-binding/can/can-message-set.hpp b/low-can-binding/can/can-message-set.hpp new file mode 100644 index 0000000..94e2d8d --- /dev/null +++ b/low-can-binding/can/can-message-set.hpp @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2015, 2016, 2017 "IoT.bzh" + * Author "Romain Forlot" <romain.forlot@iot.bzh> + * Author "Loïc Collignon" <loic.collignon@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 + +#include <cstdint> +#include <string> + +/// @brief A parent wrapper for a particular set of CAN messages and associated +/// CAN buses(e.g. a vehicle or program). +class can_message_set_t +{ +private: + uint8_t index_; /// < A numerical ID for the message set, ideally the index in an array for fast lookup + const std::string name_; /// < The name of the message set. + uint8_t can_bus_count_; /// < The number of CAN buses defined for this message set. + uint16_t can_message_count_; /// < The number of CAN messages (across all buses) defined for this message set. + uint16_t can_signal_count_; /// < The number of CAN signals (across all messages) defined for this message set. + uint16_t can_command_count_; /// < The number of CanCommmands defined for this message set. + uint16_t obd2_signal_count_; /// < The number of obd2 signals defined for this message set. + +public: + can_message_set_t( + uint8_t index, + const std::string& name, + uint8_t can_bus_count, + short unsigned int can_message_count, + short unsigned int can_signal_count, + short unsigned int can_command_count, + short unsigned int obd2_signal_count); + +}; diff --git a/low-can-binding/can/can-message.cpp b/low-can-binding/can/can-message.cpp new file mode 100644 index 0000000..f61de67 --- /dev/null +++ b/low-can-binding/can/can-message.cpp @@ -0,0 +1,264 @@ +/* + * 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. + */ + +#include "can-message.hpp" + +#include <cstring> + +#include "../low-can-binding.hpp" + +/// +/// @brief Class constructor +/// +/// Constructor about can_message_t class. +/// +can_message_t::can_message_t() + : maxdlen_{0}, id_{0}, length_{0}, format_{can_message_format_t::ERROR}, rtr_flag_{false}, flags_{0} +{} + +can_message_t::can_message_t(uint8_t maxdlen, + uint32_t id, + uint8_t length, + can_message_format_t format, + bool rtr_flag, + uint8_t flags, + std::vector<uint8_t> data) + : maxdlen_{maxdlen}, + id_{id}, + length_{length}, + format_{format}, + rtr_flag_{rtr_flag}, + flags_{flags}, + data_{data} +{} + +/// +/// @brief Retrieve id_ member value. +/// +/// @return id_ class member +/// +uint32_t can_message_t::get_id() const +{ + return id_; +} + +/// +/// @brief Retrieve RTR flag member. +/// +/// @return rtr_flags_ class member +/// +bool can_message_t::get_rtr_flag_() const +{ + return rtr_flag_; +} + +/// +/// @brief Retrieve format_ member value. +/// +/// @return format_ class member +/// +can_message_format_t can_message_t::get_format() const +{ + if (format_ != can_message_format_t::STANDARD || format_ != can_message_format_t::EXTENDED) + return can_message_format_t::ERROR; + return format_; +} + +/// +/// @brief Retrieve flags_ member value. +/// +/// @return flags_ class member +/// +uint8_t can_message_t::get_flags() const +{ + return flags_; +} + +/// +/// @brief Retrieve data_ member value. +/// +/// @return pointer to the first element +/// of class member data_ +/// +const uint8_t* can_message_t::get_data() const +{ + return data_.data(); +} + +/// +/// @brief Retrieve length_ member value. +/// +/// @return length_ class member +/// +uint8_t can_message_t::get_length() const +{ + return length_; +} + +/// +/// @brief Control whether the object is correctly initialized +/// to be sent over the CAN bus +/// +/// @return true if object correctly initialized and false if not. +/// +bool can_message_t::is_correct_to_send() +{ + if (id_ != 0 && length_ != 0 && format_ != can_message_format_t::ERROR) + { + int i; + for(i=0;i<CAN_MESSAGE_SIZE;i++) + if(data_[i] != 0) + return true; + } + return false; +} + +/// +/// @brief Set format_ member value. +/// +/// Preferred way to initialize these members by using +/// convert_from_canfd_frame method. +/// +/// @param[in] new_format - class member +/// +void can_message_t::set_format(const can_message_format_t new_format) +{ + if(new_format == can_message_format_t::STANDARD || new_format == can_message_format_t::EXTENDED || new_format == can_message_format_t::ERROR) + format_ = new_format; + else + ERROR(binder_interface, "ERROR: Can set format, wrong format chosen"); +} + +/// +/// @brief Take a canfd_frame struct to initialize class members +/// +/// This is the preferred way to initialize class members. +/// +/// @param[in] frame - canfd_frame to convert coming from a read of CAN socket +/// @param[in] nbytes - bytes read from socket read operation. +/// +/// @return A can_message_t object fully initialized with canfd_frame values. +/// +can_message_t can_message_t::convert_from_canfd_frame(const struct canfd_frame& frame, size_t nbytes) +{ + uint8_t maxdlen, length, flags = (uint8_t)NULL; + uint32_t id; + can_message_format_t format; + bool rtr_flag; + std::vector<uint8_t> data; + + switch(nbytes) + { + case CANFD_MTU: + DEBUG(binder_interface, "set_max_data_length: Got an CAN FD frame"); + maxdlen = CANFD_MAX_DLEN; + break; + case CAN_MTU: + DEBUG(binder_interface, "set_max_data_length: Got a legacy CAN frame"); + maxdlen = CAN_MAX_DLEN; + break; + default: + ERROR(binder_interface, "set_max_data_length: unsupported CAN frame"); + break; + } + + if (frame.can_id & CAN_ERR_FLAG) + format = can_message_format_t::ERROR; + else if (frame.can_id & CAN_EFF_FLAG) + format = can_message_format_t::EXTENDED; + else + format = can_message_format_t::STANDARD; + + switch(format) + { + case can_message_format_t::STANDARD: + id = frame.can_id & CAN_SFF_MASK; + break; + case can_message_format_t::EXTENDED: + id = frame.can_id & CAN_EFF_MASK; + break; + case can_message_format_t::ERROR: + id = frame.can_id & (CAN_ERR_MASK|CAN_ERR_FLAG); + break; + default: + ERROR(binder_interface, "ERROR: Can set id, not a compatible format or format not set prior to set id."); + break; + } + + /* Overwrite length_ if RTR flags is detected. + * standard CAN frames may have RTR enabled. There are no ERR frames with RTR */ + if (frame.can_id & CAN_RTR_FLAG) + { + rtr_flag = true; + if(frame.len && frame.len <= CAN_MAX_DLC) + { + if(rtr_flag) + length = frame.len& 0xF; + else + { + length = (frame.len > maxdlen) ? maxdlen : frame.len; + } + } + } + else + { + length = (frame.len > maxdlen) ? maxdlen : frame.len; + + /* Flags field only present for CAN FD frames*/ + if(maxdlen == CANFD_MAX_DLEN) + flags = frame.flags & 0xF; + + if (data.capacity() < maxdlen) + data.reserve(maxdlen); + int i; + + data.clear(); + /* maxdlen_ is now set at CAN_MAX_DLEN or CANFD_MAX_DLEN, respectively 8 and 64 bytes*/ + for(i=0;i<maxdlen;i++) + { + data.push_back(frame.data[i]); + }; + + DEBUG(binder_interface, "convert_from_canfd_frame: Found id: %X, format: %X, length: %X, data %02X%02X%02X%02X%02X%02X%02X%02X", + id, (uint8_t)format, length, data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]); + } + + return can_message_t(maxdlen, id, length, format, rtr_flag, flags, data); +} + +/// +/// @brief Take all initialized class's members and build an +/// canfd_frame struct that can be use to send a CAN message over +/// the bus. +/// +/// @return canfd_frame struct built from class members. +/// +canfd_frame can_message_t::convert_to_canfd_frame() +{ + canfd_frame frame; + + if(is_correct_to_send()) + { + frame.can_id = get_id(); + frame.len = get_length(); + ::memcpy(frame.data, get_data(), length_); + } + else + ERROR(binder_interface, "can_message_t not correctly initialized to be sent"); + + return frame; +} diff --git a/low-can-binding/can/can-message.hpp b/low-can-binding/can/can-message.hpp new file mode 100644 index 0000000..6fe0317 --- /dev/null +++ b/low-can-binding/can/can-message.hpp @@ -0,0 +1,75 @@ +/* + * 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 + +#include <vector> +#include <string> +#include <cstdint> +#include <linux/can.h> + +#include "../utils/timer.hpp" +#include "can-message-set.hpp" + +#define CAN_MESSAGE_SIZE 8 + +class can_bus_dev_t; + +/** + * @enum can_message_format_t + * @brief The ID format for a CAN message. + */ +enum class can_message_format_t { + STANDARD, /*!< STANDARD - standard 11-bit CAN arbitration ID. */ + EXTENDED, /*!< EXTENDED - an extended frame, with a 29-bit arbitration ID. */ + ERROR, /*!< ERROR - ERROR code used at initialization to signify that it isn't usable'*/ +}; + +/** + * @class can_message_t + * + * @brief A compact representation of a single CAN message, meant to be used in in/out + * buffers. + */ +class can_message_t { +private: + uint8_t maxdlen_; /*!< maxdlen_ - Max data length deduce from number of bytes read from the socket.*/ + uint32_t id_; /*!< id_ - The ID of the message. */ + uint8_t length_; /*!< length_ - the length of the data array (max 8). */ + can_message_format_t format_; /*!< format_ - the format of the message's ID.*/ + bool rtr_flag_; /*!< rtr_flag_ - Telling if the frame has RTR flag positionned. Then frame hasn't data field*/ + uint8_t flags_; /*!< flags_ - flags of a CAN FD frame. Needed if we catch FD frames.*/ + std::vector<uint8_t> data_; /*!< data_ - The message's data field with a size of 8 which is the standard about CAN bus messages.*/ + +public: + can_message_t(); + can_message_t(uint8_t maxdlen, uint32_t id, uint8_t length, can_message_format_t format, bool rtr_flag_, uint8_t flags, std::vector<uint8_t> data); + + uint32_t get_id() const; + bool get_rtr_flag_() const; + can_message_format_t get_format() const; + uint8_t get_flags() const; + const uint8_t* get_data() const; + uint8_t get_length() const; + + void set_format(const can_message_format_t new_format); + + bool is_correct_to_send(); + +static can_message_t convert_from_canfd_frame(const struct canfd_frame& frame, size_t nbytes); + canfd_frame convert_to_canfd_frame(); +}; diff --git a/low-can-binding/can/can-signals.cpp b/low-can-binding/can/can-signals.cpp new file mode 100644 index 0000000..6211fa1 --- /dev/null +++ b/low-can-binding/can/can-signals.cpp @@ -0,0 +1,186 @@ +/* + * 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. + */ + +#include <fnmatch.h> + +#include "can-signals.hpp" + +#include "../configuration.hpp" +#include "../utils/signals.hpp" +#include "can-decoder.hpp" +#include "../diagnostic/diagnostic-message.hpp" + +std::string can_signal_t::prefix_ = "messages"; + +can_signal_t::can_signal_t(std::uint8_t message_set_id, + std::uint8_t message_id, + std::string generic_name, + uint8_t bit_position, + uint8_t bit_size, + float factor, + float offset, + float min_value, + float max_value, + frequency_clock_t frequency, + bool send_same, + bool force_send_changed, + std::map<uint8_t, std::string> states, + bool writable, + SignalDecoder decoder, + SignalEncoder encoder, + bool received) + : message_set_id_{ message_set_id } + , message_id_{ message_id } + , generic_name_{ generic_name } + , bit_position_{ bit_position } + , bit_size_{ bit_size } + , factor_{ factor } + , offset_{ offset } + , min_value_{min_value} + , max_value_{max_value} + , frequency_{frequency} + , send_same_{send_same} + , force_send_changed_{force_send_changed} + , states_{states} + , writable_{writable} + , decoder_{decoder} + , encoder_{encoder} + , received_{received} + , last_value_{.0f} +{} + + +const can_message_definition_t& can_signal_t::get_message() const +{ + return configuration_t::instance().get_can_message_definition(message_set_id_, message_id_); +} + +const std::string& can_signal_t::get_generic_name() const +{ + return generic_name_; +} + +const std::string can_signal_t::get_name() const +{ + return prefix_ + "." + generic_name_; +} + +const std::string& can_signal_t::get_prefix() const +{ + return prefix_; +} + +uint8_t can_signal_t::get_bit_position() const +{ + return bit_position_; +} + +uint8_t can_signal_t::get_bit_size() const +{ + return bit_size_; +} + +float can_signal_t::get_factor() const +{ + return factor_; +} + +float can_signal_t::get_offset() const +{ + return offset_; +} + +float can_signal_t::get_min_value() const +{ + return min_value_; +} + +float can_signal_t::get_max_value() const +{ + return max_value_; +} + +frequency_clock_t& can_signal_t::get_frequency() +{ + return frequency_; +} + +bool can_signal_t::get_send_same() const +{ + return send_same_; +} + +bool can_signal_t::get_force_send_changed() const +{ + return force_send_changed_; +} + +const std::map<uint8_t, std::string>& can_signal_t::get_states() const +{ + return states_; +} + +const std::string can_signal_t::get_states(uint8_t value) +{ + if (value < states_.size()) + return states_[value]; + return std::string(); +} + +size_t can_signal_t::get_state_count() const +{ + return states_.size(); +} + +bool can_signal_t::get_writable() const +{ + return writable_; +} + +SignalDecoder& can_signal_t::get_decoder() +{ + return decoder_; +} + +SignalEncoder& can_signal_t::get_encoder() +{ + return encoder_; +} + +bool can_signal_t::get_received() const +{ + return received_; +} +float can_signal_t::get_last_value() const +{ + return last_value_; +} + +void can_signal_t::set_prefix(std::string val) +{ + prefix_ = val; +} + +void can_signal_t::set_received(bool r) +{ + received_ = r; +} + +void can_signal_t::set_last_value(float val) +{ + last_value_ = val; +} diff --git a/low-can-binding/can/can-signals.hpp b/low-can-binding/can/can-signals.hpp new file mode 100644 index 0000000..34ebeeb --- /dev/null +++ b/low-can-binding/can/can-signals.hpp @@ -0,0 +1,158 @@ +/// +/// 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 + +#include <map> +#include <mutex> +#include <queue> +#include <vector> +#include <string> + +#include "openxc.pb.h" +#include "../utils/timer.hpp" +#include "can-bus.hpp" +#include "can-message.hpp" +#include "can-message-definition.hpp" +#include "../diagnostic/diagnostic-message.hpp" + +extern "C" +{ + #include <afb/afb-binding.h> + #include <afb/afb-event-itf.h> +} + +#define MESSAGE_SET_ID 0 + +class can_signal_t; + +/// +/// @brief The type signature for a CAN signal decoder. +/// +/// A SignalDecoder transforms a raw floating point CAN signal into a number, +/// string or boolean. +/// +/// @param[in] signal - The CAN signal that we are decoding. +/// @param[in] signals - The list of all signals. +/// @param[in] signalCount - The length of the signals array. +/// @param[in] value - The CAN signal parsed from the message as a raw floating point +/// value. +/// @param[out] send - An output parameter. If the decoding failed or the CAN signal should +/// not send for some other reason, this should be flipped to false. +/// +/// @return a decoded value in an openxc_DynamicField struct. +/// +typedef openxc_DynamicField (*SignalDecoder)(can_signal_t& signal, + const std::vector<can_signal_t>& signals, float value, bool* send); + +/// +/// @brief: The type signature for a CAN signal encoder. +/// +/// A SignalEncoder transforms a number, string or boolean into a raw floating +/// point value that fits in the CAN signal. +/// +/// @param[in] signal - The CAN signal to encode. +/// @param[in] value - The dynamic field to encode. +/// @param[out] send - An output parameter. If the encoding failed or the CAN signal should +/// not be encoded for some other reason, this will be flipped to false. +/// +typedef uint64_t (*SignalEncoder)(can_signal_t* signal, + openxc_DynamicField* value, bool* send); + +class can_signal_t +{ +private: + std::uint8_t message_set_id_; + std::uint8_t message_id_; + std::string generic_name_; /*!< generic_name_ - The name of the signal to be output.*/ + static std::string prefix_; /*!< prefix_ - generic_name_ will be prefixed with it. It has to reflect the used protocol. + * which make easier to sort message when the come in.*/ + uint8_t bit_position_; /*!< bitPosition_ - The starting bit of the signal in its CAN message (assuming + * non-inverted bit numbering, i.e. the most significant bit of + * each byte is 0) */ + uint8_t bit_size_; /*!< bitSize_ - The width of the bit field in the CAN message. */ + float factor_; /*!< factor_ - The final value will be multiplied by this factor. Use 1 if you + * don't need a factor. */ + float offset_; /*!< offset_ - The final value will be added to this offset. Use 0 if you + * don't need an offset. */ + float min_value_; /*!< min_value_ - The minimum value for the processed signal.*/ + float max_value_; /*!< max_value_ - The maximum value for the processed signal. */ + frequency_clock_t frequency_; /*!< frequency_ - A frequency_clock_t struct to control the maximum frequency to + * process and send this signal. To process every value, set the + * clock's frequency to 0. */ + bool send_same_; /*!< send_same_ - If true, will re-send even if the value hasn't changed.*/ + bool force_send_changed_; /*!< force_send_changed_ - If true, regardless of the frequency, it will send the + * value if it has changed. */ + std::map<uint8_t, std::string> states_; /*!< states_ - A map of CAN signal state describing the mapping + * between numerical and string values for valid states. */ + bool writable_; /*!< writable - True if the signal is allowed to be written from the USB host + * back to CAN. Defaults to false.*/ + SignalDecoder decoder_; /*!< decoder_ - An optional function to decode a signal from the bus to a human + * readable value. If NULL, the default numerical decoder is used. */ + SignalEncoder encoder_; /*!< encoder_ - An optional function to encode a signal value to be written to + * CAN into a byte array. If NULL, the default numerical encoder + * is used. */ + bool received_; /*!< received_ - True if this signal has ever been received.*/ + float last_value_; /*!< lastValue_ - The last received value of the signal. If 'received' is false, + * this value is undefined. */ + +public: + can_signal_t( + std::uint8_t message_set_id, + std::uint8_t message_id, + std::string generic_name, + uint8_t bit_position, + uint8_t bit_size, + float factor, + float offset, + float min_value, + float max_value, + frequency_clock_t frequency, + bool send_same, + bool force_send_changed, + std::map<uint8_t, std::string> states, + bool writable, + SignalDecoder decoder, + SignalEncoder encoder, + bool received); + + const can_message_definition_t& get_message() const; + const std::string& get_generic_name() const; + const std::string get_name() const; + const std::string& get_prefix() const; + uint8_t get_bit_position() const; + uint8_t get_bit_size() const; + float get_factor() const; + float get_offset() const; + float get_min_value() const; + float get_max_value() const; + frequency_clock_t& get_frequency(); + bool get_send_same() const; + bool get_force_send_changed() const; + const std::map<uint8_t, std::string>& get_states() const; + const std::string get_states(uint8_t value); + size_t get_state_count() const; + bool get_writable() const; + SignalDecoder& get_decoder(); + SignalEncoder& get_encoder(); + bool get_received() const; + float get_last_value() const; + + void set_prefix(std::string val); + void set_received(bool r); + void set_last_value(float val); +};
\ No newline at end of file |