diff options
Diffstat (limited to 'src/uds')
-rw-r--r-- | src/uds/extras.c | 39 | ||||
-rw-r--r-- | src/uds/extras.h | 73 | ||||
-rw-r--r-- | src/uds/uds.c | 243 | ||||
-rw-r--r-- | src/uds/uds.h | 102 | ||||
-rw-r--r-- | src/uds/uds_types.h | 188 |
5 files changed, 645 insertions, 0 deletions
diff --git a/src/uds/extras.c b/src/uds/extras.c new file mode 100644 index 00000000..2be6bdd8 --- /dev/null +++ b/src/uds/extras.c @@ -0,0 +1,39 @@ +#include <uds/extras.h> +#include <uds/uds.h> + +// TODO everything below here is for future work...not critical for now. + +DiagnosticRequestHandle diagnostic_request_malfunction_indicator_status( + DiagnosticShims* shims, + DiagnosticMilStatusReceived callback) { + // TODO request malfunction indicator light (MIL) status - request mode 1 + // pid 1, parse first bit + DiagnosticRequestHandle handle; + return handle; +} + +DiagnosticRequestHandle diagnostic_request_vin(DiagnosticShims* shims, + DiagnosticVinReceived callback) { + DiagnosticRequestHandle handle; + return handle; +} + +DiagnosticRequestHandle diagnostic_request_dtc(DiagnosticShims* shims, + DiagnosticTroubleCodeType dtc_type, + DiagnosticTroubleCodesReceived callback) { + DiagnosticRequestHandle handle; + return handle; +} + +bool diagnostic_clear_dtc(DiagnosticShims* shims) { + return false; +} + +DiagnosticRequestHandle diagnostic_enumerate_pids(DiagnosticShims* shims, + DiagnosticRequest* request, DiagnosticPidEnumerationReceived callback) { + // before calling the callback, split up the received bytes into 1 or 2 byte + // chunks depending on the mode so the final pid list is actual 1 or 2 byte PIDs + // TODO request supported PIDs - request PID 0 and parse 4 bytes in response + DiagnosticRequestHandle handle; + return handle; +} diff --git a/src/uds/extras.h b/src/uds/extras.h new file mode 100644 index 00000000..c59c7bad --- /dev/null +++ b/src/uds/extras.h @@ -0,0 +1,73 @@ +#ifndef __EXTRAS_H__ +#define __EXTRAS_H__ + +#include <uds/uds_types.h> + +#ifdef __cplusplus +extern "C" { +#endif + +// TODO everything in here is unused for the moment! + +typedef enum { + POWERTRAIN = 0x0, + CHASSIS = 0x1, + BODY = 0x2, + NETWORK = 0x3 +} DiagnosticTroubleCodeGroup; + +typedef struct { + DiagnosticTroubleCodeGroup group; + uint8_t group_num; + uint8_t code; +} DiagnosticTroubleCode; + + +/* Private: TODO unused for now + */ +typedef enum { + DTC_EMISSIONS, + DTC_DRIVE_CYCLE, + DTC_PERMANENT +} DiagnosticTroubleCodeType; + + +// TODO should we enumerate every OBD-II PID? need conversion formulas, too +typedef struct { + uint16_t pid; + uint8_t bytes_returned; + float min_value; + float max_value; +} DiagnosticParameter; + +typedef void (*DiagnosticMilStatusReceived)(bool malfunction_indicator_status); +typedef void (*DiagnosticVinReceived)(uint8_t vin[]); +typedef void (*DiagnosticTroubleCodesReceived)( + DiagnosticMode mode, DiagnosticTroubleCode* codes); +typedef void (*DiagnosticPidEnumerationReceived)( + const DiagnosticResponse* response, uint16_t* pids); + +DiagnosticRequestHandle diagnostic_request_malfunction_indicator_status( + DiagnosticShims* shims, + DiagnosticMilStatusReceived callback); + +DiagnosticRequestHandle diagnostic_request_vin(DiagnosticShims* shims, + DiagnosticVinReceived callback); + +DiagnosticRequestHandle diagnostic_request_dtc(DiagnosticShims* shims, + DiagnosticTroubleCodeType dtc_type, + DiagnosticTroubleCodesReceived callback); + +bool diagnostic_clear_dtc(DiagnosticShims* shims); + +DiagnosticRequestHandle diagnostic_enumerate_pids(DiagnosticShims* shims, + DiagnosticRequest* request, DiagnosticPidEnumerationReceived callback); + +// TODO +float diagnostic_decode_OBD2_pid(DiagnosticResponse* response); + +#ifdef __cplusplus +} +#endif + +#endif // __EXTRAS_H__ diff --git a/src/uds/uds.c b/src/uds/uds.c new file mode 100644 index 00000000..443b05a0 --- /dev/null +++ b/src/uds/uds.c @@ -0,0 +1,243 @@ +#include <uds/uds.h> +#include <bitfield/bitfield.h> +#include <string.h> +#include <limits.h> +#include <stddef.h> +#include <sys/param.h> + +#define ARBITRATION_ID_OFFSET 0x8 +#define MODE_RESPONSE_OFFSET 0x40 +#define NEGATIVE_RESPONSE_MODE 0x7f +#define MAX_DIAGNOSTIC_PAYLOAD_SIZE 6 +#define MODE_BYTE_INDEX 0 +#define PID_BYTE_INDEX 1 +#define NEGATIVE_RESPONSE_MODE_INDEX 1 +#define NEGATIVE_RESPONSE_NRC_INDEX 2 + +#ifndef MAX +#define MAX(x, y) (((x) > (y)) ? (x) : (y)) +#endif + +DiagnosticShims diagnostic_init_shims(LogShim log, + SendCanMessageShim send_can_message, + SetTimerShim set_timer) { + DiagnosticShims shims = { + log: log, + send_can_message: send_can_message, + set_timer: set_timer + }; + return shims; +} + +static void setup_receive_handle(DiagnosticRequestHandle* handle) { + if(handle->request.arbitration_id == OBD2_FUNCTIONAL_BROADCAST_ID) { + uint16_t response_id; + for(response_id = 0; + response_id < OBD2_FUNCTIONAL_RESPONSE_COUNT; ++response_id) { + handle->isotp_receive_handles[response_id] = isotp_receive( + &handle->isotp_shims, OBD2_FUNCTIONAL_RESPONSE_START + response_id, + NULL); + } + handle->isotp_receive_handle_count = OBD2_FUNCTIONAL_RESPONSE_COUNT; + } else { + handle->isotp_receive_handle_count = 1; + handle->isotp_receive_handles[0] = isotp_receive(&handle->isotp_shims, + handle->request.arbitration_id + ARBITRATION_ID_OFFSET, + NULL); + } +} + + +DiagnosticRequestHandle diagnostic_request(DiagnosticShims* shims, + DiagnosticRequest* request, DiagnosticResponseReceived callback) { + DiagnosticRequestHandle handle = { + request: *request, + callback: callback, + success: false, + completed: false + }; + + uint8_t payload[MAX_DIAGNOSTIC_PAYLOAD_SIZE] = {0}; + payload[MODE_BYTE_INDEX] = request->mode; + if(request->pid_length > 0) { + set_bitfield(request->pid, PID_BYTE_INDEX * CHAR_BIT, + request->pid_length * CHAR_BIT, payload, sizeof(payload)); + } + if(request->payload_length > 0) { + memcpy(&payload[PID_BYTE_INDEX + request->pid_length], + request->payload, request->payload_length); + } + + handle.isotp_shims = isotp_init_shims(shims->log, + shims->send_can_message, + shims->set_timer); + + handle.isotp_send_handle = isotp_send(&handle.isotp_shims, + request->arbitration_id, payload, + 1 + request->payload_length + request->pid_length, + NULL); + if(shims->log != NULL) { + shims->log("Sending diagnostic request: arb_id: 0x%02x, mode: 0x%x, pid: 0x%x, payload: 0x%02x%02x%02x%02x%02x%02x%02x, size: %d\r\n", + request->arbitration_id, + request->mode, + request->pid, + request->payload[0], + request->payload[1], + request->payload[2], + request->payload[3], + request->payload[4], + request->payload[5], + request->payload[6], + request->payload_length); + } + + setup_receive_handle(&handle); + + // TODO notes on multi frame: + // TODO what are the timers for exactly? + // + // when sending multi frame, send 1 frame, wait for a response + // if it says send all, send all right away + // if it says flow control, set the time for the next send + // instead of creating a timer with an async callback, add a process_handle + // function that's called repeatedly in the main loop - if it's time to + // send, we do it. so there's a process_handle_send and receive_can_frame + // that are just called continuously from the main loop. it's a waste of a + // few cpu cycles but it may be more natural than callbacks. + // + // what woudl a timer callback look like...it would need to pass the handle + // and that's all. seems like a context void* would be able to capture all + // of the information but arg, memory allocation. look at how it's done in + // the other library again + // + return handle; +} + +DiagnosticRequestHandle diagnostic_request_pid(DiagnosticShims* shims, + DiagnosticPidRequestType pid_request_type, uint16_t arbitration_id, + uint16_t pid, DiagnosticResponseReceived callback) { + DiagnosticRequest request = { + arbitration_id: arbitration_id, + mode: pid_request_type == DIAGNOSTIC_STANDARD_PID ? 0x1 : 0x22, + pid: pid, + pid_length: pid_request_type == DIAGNOSTIC_STANDARD_PID ? 1 : 2 + }; + + return diagnostic_request(shims, &request, callback); +} + +static bool handle_negative_response(IsoTpMessage* message, + DiagnosticResponse* response, DiagnosticShims* shims) { + bool response_was_negative = false; + if(response->mode == NEGATIVE_RESPONSE_MODE) { + response_was_negative = true; + if(message->size > NEGATIVE_RESPONSE_MODE_INDEX) { + response->mode = message->payload[NEGATIVE_RESPONSE_MODE_INDEX]; + } + + if(message->size > NEGATIVE_RESPONSE_NRC_INDEX) { + response->negative_response_code = message->payload[NEGATIVE_RESPONSE_NRC_INDEX]; + } + + response->success = false; + response->completed = true; + } + return response_was_negative; +} + +static bool handle_positive_response(DiagnosticRequestHandle* handle, + IsoTpMessage* message, DiagnosticResponse* response, + DiagnosticShims* shims) { + bool response_was_positive = false; + if(response->mode == handle->request.mode + MODE_RESPONSE_OFFSET) { + response_was_positive = true; + // hide the "response" version of the mode from the user + // if it matched + response->mode = handle->request.mode; + response->has_pid = false; + if(handle->request.pid_length > 0 && message->size > 1) { + response->has_pid = true; + if(handle->request.pid_length == 2) { + response->pid = get_bitfield(message->payload, message->size, + PID_BYTE_INDEX * CHAR_BIT, sizeof(uint16_t) * CHAR_BIT); + } else { + response->pid = message->payload[PID_BYTE_INDEX]; + } + + } + + uint8_t payload_index = 1 + handle->request.pid_length; + response->payload_length = MAX(0, message->size - payload_index); + if(response->payload_length > 0) { + memcpy(response->payload, &message->payload[payload_index], + response->payload_length); + } + + if((handle->request.pid_length == 0 && !response->has_pid) + || response->pid == handle->request.pid) { + response->success = true; + response->completed = true; + } else { + response_was_positive = false; + } + } + return response_was_positive; +} + +DiagnosticResponse diagnostic_receive_can_frame(DiagnosticShims* shims, + DiagnosticRequestHandle* handle, const uint16_t arbitration_id, + const uint8_t data[], const uint8_t size) { + + DiagnosticResponse response = { + arbitration_id: arbitration_id, + success: false, + completed: false + }; + + if(!handle->isotp_send_handle.completed) { + isotp_continue_send(&handle->isotp_shims, + &handle->isotp_send_handle, arbitration_id, data, size); + } else { + uint8_t i; + for(i = 0; i < handle->isotp_receive_handle_count; ++i) { + IsoTpMessage message = isotp_continue_receive(&handle->isotp_shims, + &handle->isotp_receive_handles[i], arbitration_id, data, size); + + // TODO as of now we're completing the handle as soon as one + // broadcast response is received....need to hang on for 100ms + if(message.completed) { + if(message.size > 0) { + response.mode = message.payload[0]; + if(handle_negative_response(&message, &response, shims)) { + shims->log("Received a negative response to mode %d on arb ID 0x%x", + response.mode, response.arbitration_id); + handle->success = true; + handle->completed = true; + } else if(handle_positive_response(handle, &message, &response, + shims)) { + shims->log("Received a positive mode %d response on arb ID 0x%x", + response.mode, response.arbitration_id); + handle->success = true; + handle->completed = true; + } else { + shims->log("Response was for a mode 0x%x request (pid 0x%x), not our mode 0x%x request (pid 0x%x)", + MAX(0, response.mode - MODE_RESPONSE_OFFSET), + response.pid, handle->request.mode, + handle->request.pid); + // TODO just leave handles open until the user decides + // to be done with it - keep a count of valid responses + // received. + } + } else { + shims->log("Received an empty response on arb ID 0x%x", + response.arbitration_id); + } + + if(handle->completed && handle->callback != NULL) { + handle->callback(&response); + } + } + } + } + return response; +} diff --git a/src/uds/uds.h b/src/uds/uds.h new file mode 100644 index 00000000..091d3c9f --- /dev/null +++ b/src/uds/uds.h @@ -0,0 +1,102 @@ +#ifndef __UDS_H__ +#define __UDS_H__ + +#include <uds/uds_types.h> +#include <stdint.h> +#include <stdbool.h> + +#define OBD2_FUNCTIONAL_BROADCAST_ID 0x7df +#define OBD2_FUNCTIONAL_RESPONSE_START 0x7e8 +#define OBD2_FUNCTIONAL_RESPONSE_COUNT 8 + +#ifdef __cplusplus +extern "C" { +#endif + +/* Public: Initialize an DiagnosticShims with the given callback functions. + * + * If any callbacks are not to be used, set them to NULL. For documentation of + * the function type signatures, see higher up in this header file. This struct + * is a handy encapsulation used to pass the shims around to the various + * diagnostic_* functions. + * + * Returns a struct with the fields initailized to the callbacks. + */ +DiagnosticShims diagnostic_init_shims(LogShim log, + SendCanMessageShim send_can_message, + SetTimerShim set_timer); + +/* Public: Initiate a diagnostic request and return a handle, ready to completly + * send the request and process the response via + * diagnostic_receive_can_frame(...). + * + * shims - Low-level shims required to send CAN messages, etc. + * request - + * callback - an optional function to be called when the response is receved + * (use NULL if no callback is required). + * + * Returns a handle to be used with diagnostic_receive_can_frame to complete + * sending the request and receive the response. The 'completed' field in the + * returned DiagnosticRequestHandle will be true when the message is completely + * sent. + */ +DiagnosticRequestHandle diagnostic_request(DiagnosticShims* shims, + DiagnosticRequest* request, DiagnosticResponseReceived callback); + +/* Public: Request a PID from the given arbitration ID, determining the mode + * automatically based on the PID type. + * + * shims - Low-level shims required to send CAN messages, etc. + * pid_request_type - either DIAGNOSTIC_STANDARD_PID (will use mode 0x1 and 1 + * byte PIDs) or DIAGNOSTIC_ENHANCED_PID (will use mode 0x22 and 2 byte + * PIDs) + * arbitration_id - The arbitration ID to send the request to. + * pid - The PID to request from the other node. + * callback - an optional function to be called when the response is receved + * (use NULL if no callback is required). + * + * Returns a handle to be used with diagnostic_receive_can_frame to complete + * sending the request and receive the response. The 'completed' field in the + * returned DiagnosticRequestHandle will be true when the message is completely + * sent. + */ +DiagnosticRequestHandle diagnostic_request_pid(DiagnosticShims* shims, + DiagnosticPidRequestType pid_request_type, uint16_t arbitration_id, + uint16_t pid, DiagnosticResponseReceived callback); + +/* Public: Continue to send and receive a single diagnostic request, based on a + * freshly received CAN message. + * + * shims - Low-level shims required to send CAN messages, etc. + * handle - A DiagnosticRequestHandle previously returned by one of the + * diagnostic_request*(..) functions. + * arbitration_id - The arbitration_id of the received CAN message. + * data - The data of the received CAN message. + * size - The size of the data in the received CAN message. + * + * Returns true if the request was completed and response received, or the + * request was otherwise cancelled. Check the 'success' field of the handle to + * see if it was successful. + */ +DiagnosticResponse diagnostic_receive_can_frame(DiagnosticShims* shims, + DiagnosticRequestHandle* handle, + const uint16_t arbitration_id, const uint8_t data[], + const uint8_t size); + +/* Public: Render a DiagnosticResponse as a string into the given buffer. + * + * TODO implement this + * + * message - the response to convert to a string, for debug logging. + * destination - the target string buffer. + * destination_length - the size of the destination buffer, i.e. the max size + * for the rendered string. + */ +// void diagnostic_response_to_string(const DiagnosticResponse* response, + // char* destination, size_t destination_length); + +#ifdef __cplusplus +} +#endif + +#endif // __UDS_H__ diff --git a/src/uds/uds_types.h b/src/uds/uds_types.h new file mode 100644 index 00000000..f8c7ef08 --- /dev/null +++ b/src/uds/uds_types.h @@ -0,0 +1,188 @@ +#ifndef __UDS_TYPES_H__ +#define __UDS_TYPES_H__ + +#include <isotp/isotp.h> +#include <stdint.h> +#include <stdbool.h> + +#ifdef __cplusplus +extern "C" { +#endif + +// TODO This isn't true for multi frame messages - we may need to dynamically +// allocate this in the future +#define MAX_UDS_PAYLOAD_LENGTH 7 +#define MAX_RESPONDING_ECU_COUNT 8 +#define VIN_LENGTH 17 + +/* Private: The four main types of diagnositc requests that determine how the + * request should be parsed and what type of callback should be used. + * + * TODO this may not be used...yet? + */ +typedef enum { + DIAGNOSTIC_REQUEST_TYPE_PID, + DIAGNOSTIC_REQUEST_TYPE_DTC, + DIAGNOSTIC_REQUEST_TYPE_MIL_STATUS, + DIAGNOSTIC_REQUEST_TYPE_VIN +} DiagnosticRequestType; + +/* Public: A container for a single diagnostic request. + * + * The only required fields are the arbitration_id and mode. + * + * arbitration_id - The arbitration ID to send the request. + * mode - The OBD-II mode for the request. + * pid - (optional) The PID to request, if the mode requires one. + * pid_length - The length of the PID field, either 1 (standard) or 2 bytes + * (extended). + * payload - (optional) The payload for the request, if the request requires + * one. If payload_length is 0 this field is ignored. + * payload_length - The length of the payload, or 0 if no payload is used. + * type - the type of the request (TODO unused) + */ +typedef struct { + uint16_t arbitration_id; + uint8_t mode; + uint16_t pid; + uint8_t pid_length; + uint8_t payload[MAX_UDS_PAYLOAD_LENGTH]; + uint8_t payload_length; + DiagnosticRequestType type; +} DiagnosticRequest; + +/* Public: All possible negative response codes that could be received from a + * requested node. + * + * When a DiagnosticResponse is received and the 'completed' field is true, but + * the 'success' field is false, the 'negative_response_code' field will contain + * one of these values as reported by the requested node. + * + * Thanks to canbushack.com for the list of NRCs. + */ +typedef enum { + NRC_SUCCESS = 0x0, + NRC_SERVICE_NOT_SUPPORTED = 0x11, + NRC_SUB_FUNCTION_NOT_SUPPORTED = 0x12, + NRC_CONDITIONS_NOT_CORRECT = 0x22, + NRC_REQUEST_OUT_OF_RANGE = 0x31, + NRC_SECURITY_ACCESS_DENIED = 0x33, + NRC_INVALID_KEY = 0x35, + NRC_TOO_MANY_ATTEMPS = 0x36, + NRC_TIME_DELAY_NOT_EXPIRED = 0x37, + NRC_RESPONSE_PENDING = 0x78 +} DiagnosticNegativeResponseCode; + +/* Public: A partially or fully completed response to a diagnostic request. + * + * completed - True if the request is complete - some functions return a + * DiagnosticResponse even when it's only partially completed, so be sure + * to check this field. + * success - True if the request was successful. The value if this + * field isn't valid if 'completed' isn't true. If this is 'false', check + * the negative_response_code field for the reason. + * arbitration_id - The arbitration ID the response was received on. + * mode - The OBD-II mode for the original request. + * has_pid - If this is a response to a PID request, this will be true and the + * 'pid' field will be valid. + * pid - If the request was for a PID, this is the PID echo. Only valid if + * 'has_pid' is true. + * negative_response_code - If the request was not successful, 'success' will be + * false and this will be set to a DiagnosticNegativeResponseCode returned + * by the other node. + * payload - An optional payload for the response - NULL if no payload. + * payload_length - The length of the payload or 0 if none. + */ +typedef struct { + bool completed; + bool success; + uint16_t arbitration_id; + uint8_t mode; + bool has_pid; + uint16_t pid; + DiagnosticNegativeResponseCode negative_response_code; + uint8_t payload[MAX_UDS_PAYLOAD_LENGTH]; + uint8_t payload_length; +} DiagnosticResponse; + +/* Public: Friendly names for all OBD-II modes. + */ +typedef enum { + OBD2_MODE_POWERTRAIN_DIAGNOSTIC_REQUEST = 0x1, + OBD2_MODE_POWERTRAIN_FREEZE_FRAME_REQUEST = 0x2, + OBD2_MODE_EMISSIONS_DTC_REQUEST = 0x3, + OBD2_MODE_EMISSIONS_DTC_CLEAR = 0x4, + // 0x5 is for non-CAN only + // OBD2_MODE_OXYGEN_SENSOR_TEST = 0x5, + OBD2_MODE_TEST_RESULTS = 0x6, + OBD2_MODE_DRIVE_CYCLE_DTC_REQUEST = 0x7, + OBD2_MODE_CONTROL = 0x8, + OBD2_MODE_VEHICLE_INFORMATION = 0x9, + OBD2_MODE_PERMANENT_DTC_REQUEST = 0xa, + // this one isn't technically in uds, but both of the enhanced standards + // have their PID requests at 0x22 + OBD2_MODE_ENHANCED_DIAGNOSTIC_REQUEST = 0x22 +} DiagnosticMode; + +/* Public the signature for an optional function to be called when a diagnostic + * request is complete, and a response is received or there is a fatal error. + * + * response - the completed DiagnosticResponse. + */ +typedef void (*DiagnosticResponseReceived)(const DiagnosticResponse* response); + +typedef float (*DiagnosticResponseDecoder)(const DiagnosticResponse* response); + +/* Public: A handle for initiating and continuing a single diagnostic request. + * + * A diagnostic request requires one or more CAN messages to be sent, and one + * or more CAN messages to be received before it is completed. This struct + * encapsulates the local state required to track the request while it is in + * progress. + * + * request - The original DiagnosticRequest that this handle was created for. + * completed - True if the request was completed successfully, or was otherwise + * cancelled. + * success - True if the request send and receive process was successful. The + * value if this field isn't valid if 'completed' isn't true. + */ +typedef struct { + DiagnosticRequest request; + bool success; + bool completed; + + // Private + IsoTpShims isotp_shims; + IsoTpSendHandle isotp_send_handle; + IsoTpReceiveHandle isotp_receive_handles[MAX_RESPONDING_ECU_COUNT]; + uint8_t isotp_receive_handle_count; + DiagnosticResponseReceived callback; + // DiagnosticMilStatusReceived mil_status_callback; + // DiagnosticVinReceived vin_callback; +} DiagnosticRequestHandle; + +/* Public: The two major types of PIDs that determine the OBD-II mode and PID + * field length. + */ +typedef enum { + DIAGNOSTIC_STANDARD_PID, + DIAGNOSTIC_ENHANCED_PID +} DiagnosticPidRequestType; + +/* Public: A container for the 3 shim functions used by the library to interact + * with the wider system. + * + * Use the diagnostic_init_shims(...) function to create an instance of this + * struct. + */ +typedef struct { + LogShim log; + SendCanMessageShim send_can_message; + SetTimerShim set_timer; +} DiagnosticShims; + +#ifdef __cplusplus +} +#endif + +#endif // __UDS_TYPES_H__ |