From: norly Date: Tue, 13 Nov 2018 22:38:17 +0000 (+0100) Subject: Import first public commit X-Git-Url: https://git.enpas.org/?a=commitdiff_plain;h=a39ac09e97345289e6471d163dd995eb5f1a4252;p=elmcan.git Import first public commit --- diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3adf3be --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +*~ +*.o + +elmcan-usermode + +*.cmd +*.ko +*.mod.c +modules.order +Module.symvers +.tmp_versions diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/module/Makefile b/module/Makefile new file mode 100644 index 0000000..120df6b --- /dev/null +++ b/module/Makefile @@ -0,0 +1,7 @@ +obj-m += elmcan.o + +all: + make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules + +clean: + make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean diff --git a/module/attach-me.sh b/module/attach-me.sh new file mode 100755 index 0000000..d0c130c --- /dev/null +++ b/module/attach-me.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +sudo ldattach --debug --speed 38400 --eightbits --noparity --onestopbit --iflag -ICRNL,INLCR,-IXOFF 26 $@ diff --git a/module/elmcan.c b/module/elmcan.c new file mode 100644 index 0000000..1e72461 --- /dev/null +++ b/module/elmcan.c @@ -0,0 +1,1062 @@ +/* + * elmcan.c - ELM327 based CAN interface driver + * (tty line discipline) + * + * This file is derived from linux/drivers/net/can/slcan.c + * + * elmcan.c Author : Max Staudt + * slcan.c Author : Oliver Hartkopp + * slip.c Authors : Laurence Culhane + * Fred N. van Kempen + * + * SPDX-License-Identifier: GPL-2.0 + * + */ + +#define pr_fmt(fmt) "[elmcan] " fmt + + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + + +MODULE_ALIAS_LDISC(N_ELMCAN); +MODULE_DESCRIPTION("ELM327 based CAN interface"); +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Max Staudt "); + +/* Line discipline ID number */ +#ifndef N_ELMCAN +#define N_ELMCAN 26 +#endif + +#define ELM327_CAN_CONFIG_SEND_SFF 0x8000 +#define ELM327_CAN_CONFIG_VARIABLE_DLC 0x4000 +#define ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000 +#define ELM327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000 + +#define ELM327_MAGIC_CHAR 'y' +#define ELM327_MAGIC_STRING "y" + + +/* Bits in elm->cmds_todo */ +enum ELM_TODO { + ELM_TODO_CAN_DATA = 0, + ELM_TODO_CANID_11BIT, + ELM_TODO_CANID_29BIT_LOW, + ELM_TODO_CANID_29BIT_HIGH, + ELM_TODO_CAN_CONFIG, + ELM_TODO_RESPONSES, + ELM_TODO_SILENT_MONITOR, + ELM_TODO_INIT +}; + + +struct elmcan { + /* This must be the first member when using alloc_candev() */ + struct can_priv can; + + /* TTY and netdev devices that we're bridging */ + struct tty_struct *tty; + struct net_device *dev; + + int magic; + + /* Per-channel lock */ + spinlock_t lock; + + /* TTY TX helpers */ + struct work_struct tx_work; /* Flushes TTY TX buffer */ + unsigned char txbuf[32]; + unsigned char *txhead; /* Pointer to next TX byte */ + int txleft; /* Bytes left to TX */ + + /* TTY RX helpers */ + unsigned char rxbuf[256]; + int rxfill; + + /* State machine */ + enum { + ELM_NOTINIT = 0, + ELM_GETMAGICCHAR, + ELM_GETPROMPT, + ELM_RECEIVING, + } state; + + int drop_next_line; + + /* The CAN frame and config the ELM327 is sending/using, + * or will send/use after finishing all cmds_todo */ + struct can_frame can_frame; + unsigned short can_config; + unsigned long can_bitrate; + unsigned char can_bitrate_divisor; + int silent_monitoring; + + /* Things we have yet to send */ + char **next_init_cmd; + unsigned long cmds_todo; +}; + + +static DEFINE_SPINLOCK(elmcan_open_lock); + + + + + /************************************************************************ + * ELM327: Transmission * + ************************************************************************/ + +static void elm327_send(struct elmcan *elm, const void *buf, size_t len) +{ + int actual; + + memcpy(elm->txbuf, buf, len); + + /* Order of next two lines is *very* important. + * When we are sending a little amount of data, + * the transfer may be completed inside the ops->write() + * routine, because it's running with interrupts enabled. + * In this case we *never* got WRITE_WAKEUP event, + * if we did not request it before write operation. + * 14 Oct 1994 Dmitry Gorodchanin. + */ + set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags); + actual = elm->tty->ops->write(elm->tty, elm->txbuf, len); + elm->txleft = len - actual; + elm->txhead = elm->txbuf + actual; +} + + +static void elm327_kick_into_cmd_mode(struct elmcan *elm) +{ + if (elm->state != ELM_GETMAGICCHAR && elm->state != ELM_GETPROMPT) { + elm327_send(elm, ELM327_MAGIC_STRING, 1); + + elm->state = ELM_GETMAGICCHAR; + elm->rxfill = 0; + } +} + + +static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame) +{ + if (elm->can_frame.can_id != frame->can_id) { + /* Set the new CAN ID for transmission. */ + if ((frame->can_id & CAN_EFF_FLAG) ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) { + elm->can_config = (frame->can_id & CAN_EFF_FLAG ? 0 : ELM327_CAN_CONFIG_SEND_SFF) + | ELM327_CAN_CONFIG_VARIABLE_DLC + | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF + | elm->can_bitrate_divisor; + + set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo); + } + + if (frame->can_id & CAN_EFF_FLAG) { + clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo); + set_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo); + set_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo); + } else { + set_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo); + clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo); + clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo); + } + } + + elm->can_frame = *frame; + set_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo); + + elm327_kick_into_cmd_mode(elm); +} + + + + /************************************************************************ + * ELM327: Initialization sequence * + ************************************************************************/ + +static char *elm327_init_script[] = { + "AT WS\r", /* v1.0: Warm Start */ + "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */ + "AT M0\r", /* v1.0: Memory Off */ + "AT AL\r", /* v1.0: Allow Long messages */ + "AT BI\r", /* v1.0: Bypass Initialization */ + "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */ + "AT CFC0\r", /* v1.0: CAN Flow Control Off */ + "AT CF 000\r", /* v1.0: Reset CAN ID Filter */ + "AT CM 000\r", /* v1.0: Reset CAN ID Mask */ + "AT E1\r", /* v1.0: Echo On */ + "AT H1\r", /* v1.0: Headers On */ + "AT L0\r", /* v1.0: Linefeeds Off */ + "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */ + "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */ + "AT AT0\r", /* v1.2: Adaptive Timing Off */ + "AT D1\r", /* v1.3: Print DLC On */ + "AT S1\r", /* v1.3: Spaces On */ + "AT TP B\r", /* v1.0: Try Protocol B */ + NULL +}; + + +static void elm327_init(struct elmcan *elm) +{ + elm->state = ELM_NOTINIT; + elm->can_frame.can_id = 0x7df; + elm->rxfill = 0; + elm->drop_next_line = 0; + + /* We can only set the bitrate as a fraction of 500000. + * The bit timing constants in elmcan_bittiming_const will + * limit the user to the right values. + */ + elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate; + elm->can_config = ELM327_CAN_CONFIG_SEND_SFF + | ELM327_CAN_CONFIG_VARIABLE_DLC + | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF + | elm->can_bitrate_divisor; + + /* Configure ELM327 and then start monitoring */ + elm->next_init_cmd = &elm327_init_script[0]; + set_bit(ELM_TODO_INIT, &elm->cmds_todo); + set_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo); + set_bit(ELM_TODO_RESPONSES, &elm->cmds_todo); + set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo); + + elm327_kick_into_cmd_mode(elm); +} + + + + /************************************************************************ + * ELM327: Reception -> netdev glue * + ************************************************************************/ + +static void elm327_feed_frame_to_netdev(struct elmcan *elm, const struct can_frame *frame) +{ + struct can_frame *cf; + struct sk_buff *skb; + + if (!netif_running(elm->dev)) { + return; + } + + skb = alloc_can_skb(elm->dev, &cf); + + if (!skb) + return; + + memcpy(cf, frame, sizeof(struct can_frame)); + + elm->dev->stats.rx_packets++; + elm->dev->stats.rx_bytes += frame->can_dlc; + netif_rx_ni(skb); + + can_led_event(elm->dev, CAN_LED_EVENT_RX); +} + + + + /************************************************************************ + * ELM327: Panic handler * + ************************************************************************/ + +static inline void elm327_panic(struct elmcan *elm) +{ + struct can_frame frame = {0}; + + frame.can_id = CAN_ERR_FLAG | CAN_ERR_RESTARTED; + frame.can_dlc = CAN_ERR_DLC; + elm327_feed_frame_to_netdev(elm, &frame); + + pr_err("ELM327 misbehaved. Re-initializing.\n"); + + elm->can.can_stats.restarts++; + elm327_init(elm); +} + + + + /************************************************************************ + * ELM327: Reception parser * + ************************************************************************/ + +static void elm327_parse_error(struct elmcan *elm, int len) +{ + struct can_frame frame = {0}; + + frame.can_id = CAN_ERR_FLAG; + frame.can_dlc = CAN_ERR_DLC; + + switch(len) { + case 17: + if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) { + pr_err("The ELM327 reported UNABLE TO CONNECT. Please check your setup.\n"); + } + break; + case 11: + if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) { + /* This case will only happen if the last data + * line was complete. + * Otherwise, elm327_parse_frame() will emit the + * error frame instead. + */ + frame.can_id |= CAN_ERR_CRTL; + frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW; + } + break; + case 9: + if (!memcmp(elm->rxbuf, "BUS ERROR", 9)) { + frame.can_id |= CAN_ERR_BUSERROR; + } + if (!memcmp(elm->rxbuf, "CAN ERROR", 9) + || !memcmp(elm->rxbuf, "rxbuf, "BUS BUSY", 8)) { + frame.can_id |= CAN_ERR_PROT; + frame.data[2] = CAN_ERR_PROT_OVERLOAD; + } + if (!memcmp(elm->rxbuf, "FB ERROR", 8)) { + frame.can_id |= CAN_ERR_PROT; + frame.data[2] = CAN_ERR_PROT_TX; + } + break; + case 5: + if (!memcmp(elm->rxbuf, "ERR", 3)) { + pr_err("The ELM327 reported an ERR%c%c. Please power it off and on again.\n", + elm->rxbuf[3], elm->rxbuf[4]); + frame.can_id |= CAN_ERR_CRTL; + } + break; + default: + /* Don't emit an error frame if we're unsure */ + return; + } + + elm327_feed_frame_to_netdev(elm, &frame); +} + + +static int elm327_parse_frame(struct elmcan *elm, int len) +{ + struct can_frame frame = {0}; + int hexlen; + int datastart; + int i; + + /* Find first non-hex and non-space character: + * - In the simplest case, there is none. + * - For RTR frames, 'R' is the first non-hex character. + * - An error message may replace the end of the data line. + */ + for (hexlen = 0; hexlen <= len; hexlen++) { + if (hex_to_bin(elm->rxbuf[hexlen]) < 0 + && elm->rxbuf[hexlen] != ' ') { + break; + } + } + + /* Use spaces in CAN ID to distinguish 29 or 11 bit address length. + * No out-of-bounds access: + * We use the fact that we can always read from elm->rxbuf. */ + if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' ' + && elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' ' + && elm->rxbuf[13] == ' ') { + frame.can_id = CAN_EFF_FLAG; + datastart = 14; + } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') { + frame.can_id = 0; + datastart = 6; + } else { + /* This is not a well-formatted data line. + * Assume it's an error message. */ + return 1; + } + + if (hexlen < datastart) { + /* The line is too short to be a valid frame hex dump. + * Something interrupted the hex dump or it is invalid. */ + return 1; + } + + /* From here on all chars up to buf[hexlen] are hex or spaces, + * at well-defined offsets. */ + + /* Read CAN data length */ + frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0); + + /* Read CAN ID */ + if (frame.can_id & CAN_EFF_FLAG) { + frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28) + | (hex_to_bin(elm->rxbuf[1]) << 24) + | (hex_to_bin(elm->rxbuf[3]) << 20) + | (hex_to_bin(elm->rxbuf[4]) << 16) + | (hex_to_bin(elm->rxbuf[6]) << 12) + | (hex_to_bin(elm->rxbuf[7]) << 8) + | (hex_to_bin(elm->rxbuf[9]) << 4) + | (hex_to_bin(elm->rxbuf[10]) << 0); + } else { + frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8) + | (hex_to_bin(elm->rxbuf[1]) << 4) + | (hex_to_bin(elm->rxbuf[2]) << 0); + } + + /* Check for RTR frame */ + if (elm->rxfill >= hexlen + 3 + && elm->rxbuf[hexlen + 0] == 'R' + && elm->rxbuf[hexlen + 1] == 'T' + && elm->rxbuf[hexlen + 2] == 'R') { + frame.can_id |= CAN_RTR_FLAG; + } + + /* Is the line long enough to hold the advertised payload? */ + if (!(frame.can_id & CAN_RTR_FLAG) && (hexlen < frame.can_dlc * 3 + datastart)) { + /* Incomplete frame. */ + + /* Probably the ELM327's RS232 TX buffer was full. + * Emit an error frame and exit. */ + frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL; + frame.can_dlc = CAN_ERR_DLC; + frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW; + elm327_feed_frame_to_netdev(elm, &frame); + + /* Signal failure to parse. + * The line will be re-parsed as an error line, which will fail. + * However, this will correctly drop the state machine back into + * command mode. + */ + return 2; + } + + /* Parse the data nibbles. */ + for (i = 0; i < frame.can_dlc; i++) { + frame.data[i] = (hex_to_bin(elm->rxbuf[datastart+3*i]) << 4) + | (hex_to_bin(elm->rxbuf[datastart+3*i+1]) << 0); + } + + /* Feed the frame to the network layer. */ + elm327_feed_frame_to_netdev(elm, &frame); + + return 0; +} + + +static void elm327_parse_line(struct elmcan *elm, int len) +{ + /* Skip empty lines */ + if (!len) { + return; + } + + /* Skip echo lines */ + if (elm->drop_next_line) { + elm->drop_next_line = 0; + return; + } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') { + return; + } + + /* Regular parsing */ + switch(elm->state) { + case ELM_RECEIVING: + if (elm327_parse_frame(elm, len)) { + /* Parse an error line. */ + elm327_parse_error(elm, len); + + /* After the error line, we expect a prompt. */ + elm->state = ELM_GETPROMPT; + } + break; + default: + break; + } +} + + +static void elm327_handle_prompt(struct elmcan *elm) +{ + if (elm->cmds_todo) { + struct can_frame *frame = &elm->can_frame; + char txbuf[20]; + + if (test_bit(ELM_TODO_INIT, &elm->cmds_todo)) { + elm327_send(elm, *elm->next_init_cmd, strlen(*elm->next_init_cmd)); + elm->next_init_cmd++; + if (!(*elm->next_init_cmd)) { + clear_bit(ELM_TODO_INIT, &elm->cmds_todo); + pr_info("%s: Initialization finished.\n", elm->dev->name); + } + + /* Some chips are unreliable and need extra time after + * init commands, as seen with a clone. + * So let's do a dummy get-cmd-prompt dance. */ + elm->state = ELM_NOTINIT; + elm327_kick_into_cmd_mode(elm); + } else if (test_and_clear_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo)) { + snprintf(txbuf, sizeof(txbuf), "ATCSM%i\r", !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY))); + } else if (test_and_clear_bit(ELM_TODO_RESPONSES, &elm->cmds_todo)) { + snprintf(txbuf, sizeof(txbuf), "ATR%i\r", !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)); + } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo)) { + snprintf(txbuf, sizeof(txbuf), "ATPB%04X\r", elm->can_config); + } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) { + snprintf(txbuf, sizeof(txbuf), "ATCP%02X\r", (frame->can_id & CAN_EFF_MASK) >> 24); + } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo)) { + snprintf(txbuf, sizeof(txbuf), "ATSH%06X\r", frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1)); + } else if (test_and_clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo)) { + snprintf(txbuf, sizeof(txbuf), "ATSH%03X\r", frame->can_id & CAN_SFF_MASK); + } else if (test_and_clear_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo)) { + if (frame->can_id & CAN_RTR_FLAG) { + snprintf(txbuf, sizeof(txbuf), "ATRTR\r"); + } else { + int i; + + for (i = 0; i < frame->can_dlc; i++) { + sprintf(&txbuf[2*i], "%02X", frame->data[i]); + } + + sprintf(&txbuf[2*i], "\r"); + } + + elm->drop_next_line = 1; + elm->state = ELM_RECEIVING; + } + + elm327_send(elm, txbuf, strlen(txbuf)); + } else { + /* Enter CAN monitor mode */ + elm327_send(elm, "ATMA\r", 5); + elm->state = ELM_RECEIVING; + } +} + + +static void elm327_drop_bytes(struct elmcan *elm, int i) +{ + memmove(&elm->rxbuf[0], &elm->rxbuf[i], sizeof(elm->rxbuf) - i); + elm->rxfill -= i; +} + + +static void elm327_parse_rxbuf(struct elmcan *elm) +{ + int len; + + switch (elm->state) { + case ELM_NOTINIT: + elm->rxfill = 0; + return; + + case ELM_GETMAGICCHAR: + { + /* Wait for 'y' or '>' */ + int i; + + for (i = 0; i < elm->rxfill; i++) { + if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) { + elm327_send(elm, "\r", 1); + elm->state = ELM_GETPROMPT; + i++; + break; + } else if (elm->rxbuf[i] == '>') { + elm327_send(elm, ELM327_MAGIC_STRING, 1); + i++; + break; + } + } + + elm327_drop_bytes(elm, i); + + return; + } + + case ELM_GETPROMPT: + /* Wait for '>' */ + if (elm->rxbuf[elm->rxfill - 1] == '>') { + elm327_handle_prompt(elm); + } + + elm->rxfill = 0; + return; + + case ELM_RECEIVING: + /* Find delimiting feedback lines. */ + for (len = 0; + (len < elm->rxfill) && (elm->rxbuf[len] != '\r'); + len++) { + /* empty loop */ + } + + if (len == sizeof(elm->rxbuf)) { + /* Line exceeds buffer. It's probably all garbage. + * Did we even connect at the right baud rate? */ + pr_err("RX buffer overflow. Faulty ELM327 connected?\n"); + elm327_panic(elm); + } else if (len == elm->rxfill) { + if (elm->state == ELM_RECEIVING + && elm->rxbuf[elm->rxfill - 1] == '>') { + /* The ELM327's AT ST response timeout ran out, + * so we got a prompt. + * Clear RX buffer and restart listening. */ + elm->rxfill = 0; + + elm327_handle_prompt(elm); + return; + } else { + /* We haven't received a full line yet. Wait for more data. */ + return; + } + } + + /* We have a full line to parse. */ + elm327_parse_line(elm, len); + + /* Remove parsed data from RX buffer. */ + elm327_drop_bytes(elm, len+1); + + /* More data to parse? */ + if (elm->rxfill) { + elm327_parse_rxbuf(elm); + } + } +} + + + + + + /************************************************************************ + * netdev * + ************************************************************************/ + +/* Netdevice DOWN -> UP routine */ +static int elmcan_netdev_open(struct net_device *dev) +{ + struct elmcan *elm = netdev_priv(dev); + int err; + + spin_lock_bh(&elm->lock); + if (elm->tty == NULL) { + spin_unlock_bh(&elm->lock); + return -ENODEV; + } + + /* open_candev() checks for elm->can.bittiming.bitrate != 0 */ + err = open_candev(dev); + if (err) { + spin_unlock_bh(&elm->lock); + return err; + } + + /* Initialize the ELM327 */ + elm327_init(elm); + spin_unlock_bh(&elm->lock); + + can_led_event(dev, CAN_LED_EVENT_OPEN); + elm->can.state = CAN_STATE_ERROR_ACTIVE; + netif_start_queue(dev); + + return 0; +} + +/* Netdevice UP -> DOWN routine */ +static int elmcan_netdev_close(struct net_device *dev) +{ + struct elmcan *elm = netdev_priv(dev); + + spin_lock_bh(&elm->lock); + if (elm->tty) { + /* TTY discipline is running. */ + + /* Interrupt whatever we're doing right now */ + elm327_send(elm, ELM327_MAGIC_STRING, 1); + + /* Clear the wakeup bit, as the netdev will be down and thus + * the wakeup handler won't clear it + */ + clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags); + + spin_unlock_bh(&elm->lock); + + flush_work(&elm->tx_work); + } else { + spin_unlock_bh(&elm->lock); + } + + elm->can.state = CAN_STATE_STOPPED; + netif_stop_queue(dev); + close_candev(dev); + can_led_event(dev, CAN_LED_EVENT_STOP); + + return 0; +} + +/* Send a can_frame to a TTY queue. */ +static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb, struct net_device *dev) +{ + struct elmcan *elm = netdev_priv(dev); + struct can_frame *frame = (struct can_frame *) skb->data; + + if (skb->len != sizeof(struct can_frame)) + goto out; + + if (!netif_running(dev)) { + pr_warn("%s: xmit: iface is down\n", dev->name); + goto out; + } + + /* BHs are already disabled, so no spin_lock_bh(). + * See Documentation/networking/netdevices.txt + */ + spin_lock(&elm->lock); + if (elm->tty == NULL + || elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) { + spin_unlock(&elm->lock); + goto out; + } + + netif_stop_queue(dev); + + elm327_send_frame(elm, frame); + spin_unlock(&elm->lock); + + dev->stats.tx_packets++; + dev->stats.tx_bytes += frame->can_dlc; + + can_led_event(dev, CAN_LED_EVENT_TX); + +out: + kfree_skb(skb); + return NETDEV_TX_OK; +} + +static int elmcan_netdev_change_mtu(struct net_device *dev, int new_mtu) +{ + return -EINVAL; +} + +static const struct net_device_ops elmcan_netdev_ops = { + .ndo_open = elmcan_netdev_open, + .ndo_stop = elmcan_netdev_close, + .ndo_start_xmit = elmcan_netdev_start_xmit, + .ndo_change_mtu = elmcan_netdev_change_mtu, +}; + + + + + + /************************************************************************ + * Line discipline * + ************************************************************************/ + +/* + * Handle the 'receiver data ready' interrupt. + * This function is called by the 'tty_io' module in the kernel when + * a block of ELM327 CAN data has been received, which can now be parsed + * and sent on to some IP layer for further processing. This will not + * be re-entered while running but other ldisc functions may be called + * in parallel + */ +static void elmcan_ldisc_rx(struct tty_struct *tty, + const unsigned char *cp, char *fp, int count) +{ + struct elmcan *elm = (struct elmcan *) tty->disc_data; + + if (!elm) + return; + + /* Read the characters out of the buffer */ + while (count-- && elm->rxfill < sizeof(elm->rxbuf)) { + if (fp && *fp++) { + pr_err("Error in received character stream. Check your wiring."); + + spin_lock_bh(&elm->lock); + elm327_panic(elm); + spin_unlock_bh(&elm->lock); + return; + } + if (*cp != 0) { + elm->rxbuf[elm->rxfill++] = *cp; + } + cp++; + } + + if (count >= 0) { + pr_err("Receive buffer overflowed. Bad chip or wiring?"); + + spin_lock_bh(&elm->lock); + elm327_panic(elm); + spin_unlock_bh(&elm->lock); + return; + } + + spin_lock_bh(&elm->lock); + elm327_parse_rxbuf(elm); + spin_unlock_bh(&elm->lock); +} + +/* Write out remaining transmit buffer. + * Scheduled when TTY is writable. + */ +static void elmcan_ldisc_tx_worker(struct work_struct *work) +{ + struct elmcan *elm = container_of(work, struct elmcan, tx_work); + ssize_t actual; + + spin_lock_bh(&elm->lock); + /* First make sure we're connected. */ + if (!elm->tty || !netif_running(elm->dev)) { + spin_unlock_bh(&elm->lock); + return; + } + + if (elm->txleft <= 0) { + /* Our TTY write buffer is empty: + * We can start transmission of another packet + */ + clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags); + spin_unlock_bh(&elm->lock); + netif_wake_queue(elm->dev); + return; + } + + actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft); + if (actual < 0) { + pr_err("Failed to write to tty for %s.\n", elm->dev->name); + elm327_panic(elm); + } + + elm->txleft -= actual; + elm->txhead += actual; + spin_unlock_bh(&elm->lock); +} + + +/* + * Called by the driver when there's room for more data. + * Schedule the transmit. + */ +static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty) +{ + struct elmcan *elm = tty->disc_data; + + schedule_work(&elm->tx_work); +} + + + +/* Some fake bit timings to allow bitrate setting */ +static const struct can_bittiming_const elmcan_bittiming_const = { + .name = "elmcan", + .tseg1_min = 1, + .tseg1_max = 1, + .tseg2_min = 0, + .tseg2_max = 0, + .sjw_max = 1, + .brp_min = 1, + .brp_max = 500, + .brp_inc = 1, +}; + +/* + * Open the high-level part of the elmcan channel. + * This function is called by the TTY module when the + * elmcan line discipline is called for. + * + * Called in process context serialized from other ldisc calls. + */ +static int elmcan_ldisc_open(struct tty_struct *tty) +{ + struct net_device *dev; + struct elmcan *elm; + int err; + + if (!capable(CAP_NET_ADMIN)) + return -EPERM; + + if (!tty->ops->write) + return -EOPNOTSUPP; + + elm = tty->disc_data; + + /* First make sure we're not already connected. + * Also, protect against simlutaneous open calls. */ + spin_lock_bh(&elmcan_open_lock); + if (elm) { + spin_unlock_bh(&elmcan_open_lock); + return -EEXIST; + } + spin_unlock_bh(&elmcan_open_lock); + + /* OK. Find a free elmcan channel to use. */ + dev = alloc_candev(sizeof(struct elmcan), 0); + if (!dev) + return -ENFILE; + elm = netdev_priv(dev); + + /* Configure TTY interface */ + tty->receive_room = 65536; /* We don't flow control */ + elm->txleft = 0; /* Clear TTY TX buffer */ + spin_lock_init(&elm->lock); + INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker); + + /* Configure CAN metadata */ + elm->can.state = CAN_STATE_STOPPED; + elm->can.clock.freq = 1000000; + elm->can.bittiming_const = &elmcan_bittiming_const; + elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY; + + /* Configure netlink interface */ + elm->dev = dev; + dev->netdev_ops = &elmcan_netdev_ops; + + /* Mark ldisc channel as alive */ + elm->tty = tty; + tty->disc_data = elm; + + devm_can_led_init(elm->dev); + + /* Let 'er rip */ + err = register_candev(elm->dev); + if (err) { + free_candev(elm->dev); + return err; + } + + return 0; +} + +/* + * Close down an elmcan channel. + * This means flushing out any pending queues, and then returning. This + * call is serialized against other ldisc functions. + * + * We also use this method for a hangup event. + */ +static void elmcan_ldisc_close(struct tty_struct *tty) +{ + struct elmcan *elm = (struct elmcan *) tty->disc_data; + + /* First make sure we're connected. */ + if (!elm) + return; + + /* Flush network side */ + unregister_candev(elm->dev); + + /* Mark channel as dead */ + spin_lock_bh(&elm->lock); + tty->disc_data = NULL; + elm->tty = NULL; + spin_unlock_bh(&elm->lock); + + /* Flush TTY side */ + flush_work(&elm->tx_work); + + /* Free our memory */ + free_candev(elm->dev); +} + +static int elmcan_ldisc_hangup(struct tty_struct *tty) +{ + elmcan_ldisc_close(tty); + return 0; +} + +/* Perform I/O control on an active elmcan channel. */ +static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file, + unsigned int cmd, unsigned long arg) +{ + struct elmcan *elm = (struct elmcan *) tty->disc_data; + unsigned int tmp; + + /* First make sure we're connected. */ + if (!elm) + return -EINVAL; + + switch (cmd) { + case SIOCGIFNAME: + tmp = strlen(elm->dev->name) + 1; + if (copy_to_user((void __user *)arg, elm->dev->name, tmp)) + return -EFAULT; + return 0; + + case SIOCSIFHWADDR: + return -EINVAL; + + default: + return tty_mode_ioctl(tty, file, cmd, arg); + } +} + +static struct tty_ldisc_ops elmcan_ldisc = { + .owner = THIS_MODULE, + .magic = TTY_LDISC_MAGIC, + .name = "elmcan", + .receive_buf = elmcan_ldisc_rx, + .write_wakeup = elmcan_ldisc_tx_wakeup, + .open = elmcan_ldisc_open, + .close = elmcan_ldisc_close, + .hangup = elmcan_ldisc_hangup, + .ioctl = elmcan_ldisc_ioctl, +}; + + + + + + /************************************************************************ + * Module init/exit * + ************************************************************************/ + +static int __init elmcan_init(void) +{ + int status; + + pr_info("ELM327 based best-effort CAN interface driver\n"); + pr_info("This device is severely limited as a CAN interface, see documentation.\n"); + + /* Fill in our line protocol discipline, and register it */ + status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc); + if (status) { + pr_err("can't register line discipline\n"); + } + return status; +} + +static void __exit elmcan_exit(void) +{ + /* This will only be called when all channels have been closed by + * userspace - tty_ldisc.c takes care of the module's refcount. + */ + int status; + + status = tty_unregister_ldisc(N_ELMCAN); + if (status) { + pr_err("Can't unregister line discipline (error: %d)\n", status); + } +} + +module_init(elmcan_init); +module_exit(elmcan_exit); diff --git a/readme.rst b/readme.rst new file mode 100644 index 0000000..4911664 --- /dev/null +++ b/readme.rst @@ -0,0 +1,279 @@ +Linux SocketCAN driver for ELM327 +================================== + +Authors +-------- + +Max Staudt + + + +Motivation +----------- + +CAN adapters are expensive, few, and far between. +ELM327 interfaces are cheap and plentiful. + +This driver aims to lower the initial cost for hackers interested in +working with CAN buses. + + + +Introduction +------------- + +This driver is an effort to turn abundant ELM327 based OBD interfaces +into full-fledged (as far as possible) CAN interfaces. + +Since the ELM327 was never meant to be a stand-alone CAN controller, +the driver has to switch between its modes asa quickly as possible in +order to approximate full-duplex operation. + +As such, elmcan is a best-effort driver. However, this is more than +enough to implement simple request-response protocols (such as OBD II), +and to monitor broadcast messages on a bus (such as in a vehicle). + +Most ELM327s come as nondescript serial devices, attached via USB or +Bluetooth. The driver cannot recognize them by itself, and as such it +is up to the user to attach it in form of a TTY line discipline +(similar to PPP, SLIP, slcan, ...). + +This driver is meant for ELM327 versions 1.4b and up, see below for +known limitations in older controllers and clones. + + + +Data sheet +----------- + +The official data sheets can be found at ELM electronics' home page: + + https://www.elmelectronics.com/ + + + +How to check the controller version +------------------------------------ + +Use a terminal program to attach to the controller. + +After issuing the "``AT WS``" command, the controller will respond with +its version:: + + >AT WS + + + ELM327 v1.4b + + > + + + +How to attach the line discipline +---------------------------------- + +Every ELM327 chip is factory programmed to operate at a serial setting +of 38400 baud/s, 8 data bits, no parity, 1 stopbit. + +The line discipline can be attached on a command prompt as follows:: + + sudo ldattach \ + --debug \ + --speed 38400 \ + --eightbits \ + --noparity \ + --onestopbit \ + --iflag -ICRNL,INLCR,-IXOFF \ + 26 \ + /dev/ttyUSB0 + +To change the ELM327's serial settings, please refer to its data +sheet. This needs to be done before attaching the line discipline. + + + +Known limitations of the controller +------------------------------------ + +- All versions + + No automatic full duplex operation is supported. The driver will + switch between input/output mode as quickly as possible. + + The length of outgoing RTR frames cannot be set. In fact, some + clones (tested with one identifying as "``v1.5``") are unable to + send RTR frames at all. + + We don't have a way to get real-time notifications on CAN errors. + While there is a command (``AT CS``) to retrieve some basic stats, + we don't poll it as it would force us to interrupt reception mode. + + +- Versions prior to 1.4b + + These versions do not send CAN ACKs when in monitoring mode (AT MA). + However, they do send ACKs while waiting for a reply immediately + after sending a frame. The driver maximizes this time to make the + controller as useful as possible. + + Starting with version 1.4b, the ELM327 supports the "``AT CSM``" + command, and the "listen-only" CAN option will take effect. + + +- Versions prior to 1.4 + + These chips do not support the "``AT PB``" command, and thus cannot + change bitrate or SFF/EFF mode on-the-fly. This will have to be + programmed by the user before attaching the line discipline. See the + data sheet for details. + + +- Versions prior to 1.3 + + These chips cannot be used at all with elmcan. They do not support + the "``AT D1``", which is necessary to avoid parsing conflicts on + incoming data, as well as distinction of RTR frame lengths. + + Specifically, this allows for easy distinction of SFF and EFF + frames, and to check whether frames are complete. While it is possible + to deduce the type and length from the length of the line the ELM327 + sends us, this method fails when the ELM327's UART output buffer + overruns. It may abort sending in the middle of the line, which will + then be mistaken for something else. + + + +Known limitations of the driver +-------------------------------- + +- No 8/7 timing. + + ELM327 can only set CAN bitrates that are of the form 500000/n, where + n is an integer divisor. + However there is an exception: With a separate flag, it may set the + speed to be 8/7 of the speed indicated by the divisor. + This mode is not currently implemented. + +- No evaluation of command responses. + + The ELM327 will reply with OK when a command is understood, and with ? + when it is not. The driver does not currently check this, and simply + assumes that the chip understands every command. + The driver is built such that functionality degrades gracefully + nevertheless. See the section on known limitations of the controller. + +- No use of hardware CAN ID filtering + + An ELM327's UART sending buffer will easily overflow on heavy CAN bus + load, resulting in the "``BUFFER FULL``" message. Using the hardware + filters available through "``AT CF xxx``" and "``AT CM xxx``" would be + helpful here, however SocketCAN does not currently provide a facility + to make use of such hardware features. + +- No BUS-OFF state and automatic restart + + We currently reset the ELM327 and generate error frames manually. + In the future, we may be able to use ``can_bus_off()`` and its siblings. + + + +Communication example +---------------------- + +This is a short and incomplete introduction on how to talk to an ELM327. + + +The ELM327 has two modes: + +- Command mode +- Reception mode + +In command mode, it expects one command per line, terminated by CR. +By default, the prompt is a "``>``", after which a command can be +entered:: + + >ATE1 + OK + > + +The init script in the driver switches off several configuration options +that are only meaningful in the original OBD scenario the chip is meant +for, and are actually a hindrance for elmcan. + + +When a command is not recognized, such as by an older version of the +ELM327, a question mark is printed as a response instead of OK:: + + >ATUNKNOWN + ? + > + +At present, elmcan does not evaluate this response and silently assumes +that all commands are recognized. It is structured such that it will +degrade gracefully when a command is unknown. See the sections above on +known limitations for details. + + +When a CAN frame is to be sent, the target address is configured, after +which the frame is sent as a command that consists of the data's hex +dump:: + + >ATSH123 + OK + >DEADBEEF12345678 + OK + > + +The above interaction sends the frame "``DE AD BE EF 12 34 56 78``" with +the 11 bit CAN ID ``0x123``. +For this to function, the controller must be configured for 11 bit CAN +ID sending mode (using "``AT PB``", see code or datasheet). + + +Once a frame has been sent and wait-for-reply mode is on (ATR1, +configured on listen-only=off), or when the reply timeout expires and +the driver sets the controller into monitoring mode (``ATMA``), the ELM327 +will send one line for each received CAN frame, consisting of CAN ID, +DLC, and data:: + + 123 8 DEADBEEF12345678 + +For 29 bit CAN frames, the address format is slightly different, which +elmcan uses to tell the two apart:: + + 12 34 56 78 8 DEADBEEF12345678 + +The ELM327 will receive both 11 and 29 bit frames - the current CAN +config (``ATPB``) does not matter. + + +If the ELM327's internal UART sending buffer runs full, it will abort +the monitoring mode, print "BUFFER FULL" and drop back into command +mode. Note that in this case, unlike with other error messages, the +error message may appear on the same line as the last (usually +incomplete) data frame:: + + 12 34 56 78 8 DEADBEEF123 BUFFER FULL + + + +To Do list for future development +---------------------------------- + +- Handle ``write()`` error + +- Rename ``elm327_panic()`` + +- No auto-restart in ``elm327_panic()``? + +- Stop current function when in ``elm327_panic()`` + +- ``if (!elm)``: Race with ``ldisc_close()`` + +- ``elm->dev``: Race in ``ldisc_ioctl()`` + +- DMA capable rx/tx buffers + +- fixup constants, constant for '``>``' + +- flushing of ``tx_work`` is too late in ``ldisc_close()``