Twizy-Cfg V1.0 (initial release)

This commit is contained in:
Michael Balzer 2017-06-14 00:35:06 +02:00
commit 7b11d7ce87
11 changed files with 1499 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
assets
*.html

157
LICENSE.md Normal file
View file

@ -0,0 +1,157 @@
### GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates the
terms and conditions of version 3 of the GNU General Public License,
supplemented by the additional permissions listed below.
#### 0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the
GNU General Public License.
"The Library" refers to a covered work governed by this License, other
than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
#### 1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
#### 2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
- a) under this License, provided that you make a good faith effort
to ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
- b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
#### 3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a
header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
- a) Give prominent notice with each copy of the object code that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the object code with a copy of the GNU GPL and this
license document.
#### 4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken
together, effectively do not restrict modification of the portions of
the Library contained in the Combined Work and reverse engineering for
debugging such modifications, if you also do each of the following:
- a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the Combined Work with a copy of the GNU GPL and this
license document.
- c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
- d) Do one of the following:
- 0) Convey the Minimal Corresponding Source under the terms of
this License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
- 1) Use a suitable shared library mechanism for linking with
the Library. A suitable mechanism is one that (a) uses at run
time a copy of the Library already present on the user's
computer system, and (b) will operate properly with a modified
version of the Library that is interface-compatible with the
Linked Version.
- e) Provide Installation Information, but only if you would
otherwise be required to provide such information under section 6
of the GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the Application
with a modified version of the Linked Version. (If you use option
4d0, the Installation Information must accompany the Minimal
Corresponding Source and Corresponding Application Code. If you
use option 4d1, you must provide the Installation Information in
the manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.)
#### 5. Combined Libraries.
You may place library facilities that are a work based on the Library
side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
- a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities, conveyed under the terms of this License.
- b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
#### 6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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 Library
as you received it specifies that a certain numbered version of the
GNU Lesser General Public License "or any later version" applies to
it, you have the option of following the terms and conditions either
of that published version or of any later version published by the
Free Software Foundation. If the Library as you received it does not
specify a version number of the GNU Lesser General Public License, you
may choose any version of the GNU Lesser General Public License ever
published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

97
README.md Normal file
View file

@ -0,0 +1,97 @@
# Twizy-Cfg SEVCON configuration shell
This is a minimalistic SEVCON Gen4 configuration shell for Arduino.
It's a port of my SEVCON core functionality from the [OVMS project](https://github.com/openvehicles/Open-Vehicle-Monitoring-System), with a simple command interface on the Arduino serial port.
It currently only supports reading & writing SDO registers and entering/leaving pre-operational mode. Support for the OVMS/Twizy tuning macro commands (i.e. `power`, `speed`, `recup` etc.) has not yet been ported.
So currently you need to know the registers and value scalings for your tuning needs. Read the SEVCON Gen4 manual for some basic description of registers. The full register set is documented in the SEVCON master dictionary, which is ©SEVCON. It's contained in the SEVCON DVT package.
Most registers of interest for normal tuning can be found in the [Twizy SDO list](extras/Twizy-SDO-List.ods).
**Note**: SEVCON write access has been limited by Renault on Twizys (SEVCONs) delivered after June 2016. The write protection applies to all power and driving profile tuning registers, and also to the battery limits. A locked SEVCON will respond to register writes with an error. You can also check the software version (`rs 100a 00`): if it's `0712.0003` or higher, the Twizy is locked.
## Hardware requirements
1. An Arduino (a Nano will do)
2. An MCP 2515 SPI CAN module, i.e. a "CAN-BUS Shield"
3. An OBD2 plug/cable for the MCP module
## Installation
To download, click the DOWNLOADS button in the top right corner, download the ZIP file. Extract the ZIP, open `TwizyCfg/TwizyCfg.ino` from Arduino IDE.
You will also need this library:
- [MCP_CAN_lib by Cory Fowler](https://github.com/coryjfowler/MCP_CAN_lib)
Enter your CAN module configuration in the `TwizyCfg_config.h` tab.
## Usage
Connect to the OBD2 port, switch on the Twizy, start the sketch & open the serial monitor. Set the serial monitor line mode to "new line".
The Arduino will display a help screen, then wait for your commands:
| Function | Command |
| --- | --- |
| Show help | `?` / `help` |
| Enter pre-op mode | `p` |
| Enter op mode | `o` |
| Read numerical register | `r <id> <sub>` |
| Read string register | `rs <id> <sub>` |
| Write register | `w <id> <sub> <val>` |
| Write-only register | `wo <id> <sub> <val>` |
- `<id>` & `<sub>` define the SDO register to access, need to be given as hexadecimal numbers
- `<val>` is the value to write, needs to be given as an unsigned decimal number (negative = two's complement, see below)
**Examples**:
- Get firmware version: `rs 100a 00` (if it's `0712.0003` or higher, the Twizy is locked)
- Set brake recuperation to 30%: `w 2920 04 300`
The shell automatically logs into the SEVCON with access level 4 (highest user level, 5 is reserved for SEVCON engineering), so all user SDOs can be written to. See SEVCON master dictionary for access levels. **Note**: all logins are logged in the SEVCON event logs. See SEVCON manual on how to access the logs.
When writing to a register using `w`, for convenience the old value will be read and shown. For write-only registers use `wo` to skip the read operation.
The shell does not know about the data type of the SDO accessed (that's why you need to use `rs` for string SDOs). It handles all numerical registers as being unsigned long. To convert to/from negative values, build the two's complement value by adding the offset:
| Type | Negative offset | -1 = … |
| --- | --- | --- |
| Integer8 | 256 | 255 |
| Integer16 | 65536 | 65535 |
| Integer32 | 4294967296 | 4294967295 |
Most signed tuning registers are of type Integer16. See [Twizy DCF](extras/Twizy-DCF-0712-0002.ods) for register data and access types and default values.
Error messages are mostly self-explanatory, i.e. "SEVCON OFFLINE" means you haven't switched on the Twizy.
## Author
Twizy-Cfg and the OVMS Twizy adaption has been created and is maintained by Michael Balzer (<dexter@dexters-web.de> / https://dexters-web.de/).
Some of the functions contained in the "utils" module have been written by other [OVMS contributors](https://github.com/openvehicles/Open-Vehicle-Monitoring-System/graphs/contributors).
## Donations
**Donations** to support my efforts and further development are very welcome.
Please send donations via **Paypal** to: `dexter@dexters-web.de`
**Thanks! :-)**
## License
This is free software; you can redistribute it and/or modify it under the terms of the [GNU Lesser General Public License](https://www.gnu.org/licenses/lgpl.html) as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
This software 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110- 1301 USA
**Have fun!**

100
TwizyCfg/CANopen.h Normal file
View file

@ -0,0 +1,100 @@
/**
* ==========================================================================
* Twizy/SEVCON configuration shell
* ==========================================================================
*
* Twizy/SEVCON CANopen SDO client
*
* Based on the OVMS Twizy firmware:
* https://github.com/openvehicles/Open-Vehicle-Monitoring-System
*
* Author: Michael Balzer <dexter@dexters-web.de>
*
* License:
* This is free software under GNU Lesser General Public License (LGPL)
* https://www.gnu.org/licenses/lgpl.html
*
*/
#ifndef _CANopen_h
#define _CANopen_h
// SDO request/response:
// message structure:
// 0 = control byte
// 1+2 = index (little endian)
// 3 = subindex
// 4..7 = data (little endian)
union sdo_buffer {
// raw / segment data:
UINT8 byte[8];
// request / expedited:
struct {
UINT8 control;
UINT index;
UINT8 subindex;
UINT32 data;
};
};
extern sdo_buffer twizy_sdo;
// SDO communication codes:
#define SDO_CommandMask 0b11100000
#define SDO_ExpeditedUnusedMask 0b00001100
#define SDO_Expedited 0b00000010
#define SDO_Abort 0b10000000
#define SDO_Abort_SegMismatch 0x05030000
#define SDO_Abort_Timeout 0x05040000
#define SDO_Abort_OutOfMemory 0x05040005
#define SDO_InitUploadRequest 0b01000000
#define SDO_InitUploadResponse 0b01000000
#define SDO_UploadSegmentRequest 0b01100000
#define SDO_UploadSegmentResponse 0b00000000
#define SDO_InitDownloadRequest 0b00100000
#define SDO_InitDownloadResponse 0b01100000
#define SDO_SegmentToggle 0b00010000
#define SDO_SegmentUnusedMask 0b00001110
#define SDO_SegmentEnd 0b00000001
#define CAN_GeneralError 0x08000000
// I/O level CAN error codes / classes:
#define ERR_NoCANWrite 0x0001
#define ERR_Timeout 0x000a
#define ERR_ComponentOffline 0x000b
#define ERR_ReadSDO 0x0002
#define ERR_ReadSDO_Timeout 0x0003
#define ERR_ReadSDO_SegXfer 0x0004
#define ERR_ReadSDO_SegMismatch 0x0005
#define ERR_WriteSDO 0x0008
#define ERR_WriteSDO_Timeout 0x0009
// App level CAN error codes / classes:
#define ERR_LoginFailed 0x0010
#define ERR_CfgModeFailed 0x0020
#define ERR_Range 0x0030
#define ERR_UnknownHardware 0x0040
#endif // _CANopen_h

441
TwizyCfg/CANopen.ino Normal file
View file

@ -0,0 +1,441 @@
/**
* ==========================================================================
* Twizy/SEVCON configuration shell
* ==========================================================================
*
* Twizy/SEVCON CANopen SDO client
*
* Based on the OVMS Twizy firmware:
* https://github.com/openvehicles/Open-Vehicle-Monitoring-System
*
* Author: Michael Balzer <dexter@dexters-web.de>
*
* License:
* This is free software under GNU Lesser General Public License (LGPL)
* https://www.gnu.org/licenses/lgpl.html
*
*/
#include "CANopen.h"
// SDO TX/RX buffer:
sdo_buffer twizy_sdo;
// CAN RX buffer:
unsigned long rxId;
byte rxLen;
byte rxBuf[8];
// CAN TX utility:
bool sendMsg(INT32U id, INT8U len, INT8U *buf) {
for (int tries=3; tries>0; tries--) {
if (CAN.sendMsgBuf(id, 0, len, buf) != CAN_GETTXBFTIMEOUT) {
// CAN_OK = frame has been sent
// CAN_SENDMSGTIMEOUT = we made it into a send buffer
// → no need to repeat the send:
return true;
}
}
return false;
}
// Check received CAN frames for CANopen reply from node 1 (ID 0x581):
#define SAVEMSG(dst) for(int i = 0; i<rxLen; i++) { dst[i] = rxBuf[i]; }
bool checkReply() {
while (CAN.readMsgBuf(&rxId, &rxLen, rxBuf) == CAN_OK) {
if (rxId == 0x581) {
SAVEMSG(twizy_sdo.byte);
return true;
}
}
return false;
}
// asynchronous SDO request:
void vehicle_twizy_sendsdoreq(void)
{
sendMsg(0x601, 8, twizy_sdo.byte);
// clear status to detect reply:
twizy_sdo.control = 0xff;
}
// synchronous SDO request (50 ms timeout, 3 tries):
UINT vehicle_twizy_sendsdoreq_sync(void)
{
UINT8 control, timeout, tries;
UINT32 data;
control = twizy_sdo.control;
data = twizy_sdo.data;
tries = 3;
do {
// send request:
twizy_sdo.control = control;
twizy_sdo.data = data;
vehicle_twizy_sendsdoreq();
// wait for reply:
timeout = 50;
do {
if (!checkReply()) {
delay(1);
}
} while (twizy_sdo.control == 0xff && --timeout);
if (timeout != 0)
break;
// timeout, abort request:
twizy_sdo.control = SDO_Abort;
twizy_sdo.data = SDO_Abort_Timeout;
vehicle_twizy_sendsdoreq();
if (tries > 1)
delay(10);
} while (--tries);
if (timeout == 0)
return ERR_Timeout;
return 0; // ok, response in twizy_sdo.*
}
// read from SDO:
UINT readsdo(UINT index, UINT8 subindex)
{
UINT8 control;
// request upload:
twizy_sdo.control = SDO_InitUploadRequest;
twizy_sdo.index = index;
twizy_sdo.subindex = subindex;
twizy_sdo.data = 0;
if (vehicle_twizy_sendsdoreq_sync() != 0)
return ERR_ReadSDO_Timeout;
// check response:
if ((twizy_sdo.control & SDO_CommandMask) != SDO_InitUploadResponse) {
// check for CANopen general error:
if (twizy_sdo.data == CAN_GeneralError && index != 0x5310) {
// add SEVCON error code:
control = twizy_sdo.control;
readsdo(0x5310,0x00);
twizy_sdo.control = control;
twizy_sdo.index = index;
twizy_sdo.subindex = subindex;
twizy_sdo.data |= CAN_GeneralError;
}
return ERR_ReadSDO;
}
// if expedited xfer we're done now:
if (twizy_sdo.control & SDO_Expedited)
return 0;
// segmented xfer necessary:
twizy_sdo.control = SDO_Abort;
twizy_sdo.data = SDO_Abort_OutOfMemory;
vehicle_twizy_sendsdoreq();
return ERR_ReadSDO_SegXfer; // caller needs to use readsdo_buf
}
// read from SDO into buffer (supporting segmented xfer):
UINT readsdo_buf(UINT index, UINT8 subindex, byte *dst, byte *maxlen)
{
UINT8 n, toggle, dlen;
// request upload:
twizy_sdo.control = SDO_InitUploadRequest;
twizy_sdo.index = index;
twizy_sdo.subindex = subindex;
twizy_sdo.data = 0;
if (vehicle_twizy_sendsdoreq_sync() != 0)
return ERR_ReadSDO_Timeout;
// check response:
if ((twizy_sdo.control & SDO_CommandMask) != SDO_InitUploadResponse) {
// check for CANopen general error:
if (twizy_sdo.data == CAN_GeneralError && index != 0x5310) {
// add SEVCON error code:
n = twizy_sdo.control;
readsdo(0x5310,0x00);
twizy_sdo.control = n;
twizy_sdo.index = index;
twizy_sdo.subindex = subindex;
twizy_sdo.data |= CAN_GeneralError;
}
return ERR_ReadSDO;
}
// check for expedited xfer:
if (twizy_sdo.control & SDO_Expedited) {
// copy twizy_sdo.data to dst:
dlen = 8 - ((twizy_sdo.control & SDO_ExpeditedUnusedMask) >> 2);
for (n = 4; n < dlen && (*maxlen) > 0; n++, (*maxlen)--)
*dst++ = twizy_sdo.byte[n];
return 0;
}
// segmented xfer necessary:
toggle = 0;
do {
// request segment:
twizy_sdo.control = (SDO_UploadSegmentRequest|toggle);
twizy_sdo.index = 0;
twizy_sdo.subindex = 0;
twizy_sdo.data = 0;
if (vehicle_twizy_sendsdoreq_sync() != 0)
return ERR_ReadSDO_Timeout;
// check response:
if ((twizy_sdo.control & (SDO_CommandMask|SDO_SegmentToggle)) != (SDO_UploadSegmentResponse|toggle)) {
// mismatch:
twizy_sdo.control = SDO_Abort;
twizy_sdo.data = SDO_Abort_SegMismatch;
vehicle_twizy_sendsdoreq();
return ERR_ReadSDO_SegMismatch;
}
// ok, copy response data to dst:
dlen = 8 - ((twizy_sdo.control & SDO_SegmentUnusedMask) >> 1);
for (n = 1; n < dlen && (*maxlen) > 0; n++, (*maxlen)--)
*dst++ = twizy_sdo.byte[n];
// last segment fetched? => success!
if (twizy_sdo.control & SDO_SegmentEnd)
return 0;
// maxlen reached? => abort xfer
if ((*maxlen) == 0) {
twizy_sdo.control = SDO_Abort;
twizy_sdo.data = SDO_Abort_OutOfMemory;
vehicle_twizy_sendsdoreq();
return 0; // consider this as success, we read as much as we could
}
// toggle toggle bit:
toggle = toggle ? 0 : SDO_SegmentToggle;
} while(1);
// not reached
}
// write to SDO without size indication:
UINT writesdo(UINT index, UINT8 subindex, UINT32 data)
{
UINT8 control;
// request download:
twizy_sdo.control = SDO_InitDownloadRequest | SDO_Expedited; // no size needed, server is smart
twizy_sdo.index = index;
twizy_sdo.subindex = subindex;
twizy_sdo.data = data;
if (vehicle_twizy_sendsdoreq_sync() != 0)
return ERR_WriteSDO_Timeout;
// check response:
if ((twizy_sdo.control & SDO_CommandMask) != SDO_InitDownloadResponse) {
// check for CANopen general error:
if (twizy_sdo.data == CAN_GeneralError) {
// add SEVCON error code:
control = twizy_sdo.control;
readsdo(0x5310,0x00);
twizy_sdo.control = control;
twizy_sdo.index = index;
twizy_sdo.subindex = subindex;
twizy_sdo.data |= CAN_GeneralError;
}
return ERR_WriteSDO;
}
// success
return 0;
}
// SEVCON login/logout (access level 4):
UINT login(bool on)
{
UINT err;
// check login level:
if (err = readsdo(0x5000,1))
return ERR_LoginFailed + err;
if (on && twizy_sdo.data != 4) {
// login:
writesdo(0x5000,3,0);
if (err = writesdo(0x5000,2,0x4bdf))
return ERR_LoginFailed + err;
// check new level:
if (err = readsdo(0x5000,1))
return ERR_LoginFailed + err;
if (twizy_sdo.data != 4)
return ERR_LoginFailed;
}
else if (!on && twizy_sdo.data != 0) {
// logout:
writesdo(0x5000,3,0);
if (err = writesdo(0x5000,2,0))
return ERR_LoginFailed + err;
// check new level:
if (err = readsdo(0x5000,1))
return ERR_LoginFailed + err;
if (twizy_sdo.data != 0)
return ERR_LoginFailed;
}
return 0;
}
// SEVCON state change operational/pre-operational:
UINT configmode(bool on)
{
UINT err;
if (!on) {
// request operational state:
if (err = writesdo(0x2800,0,0))
return ERR_CfgModeFailed + err;
// give controller some time:
delay(10);
// check new status:
if (err = readsdo(0x5110,0))
return ERR_CfgModeFailed + err;
if (twizy_sdo.data != 5)
return ERR_CfgModeFailed;
}
else {
// check controller status:
if (err = readsdo(0x5110,0))
return ERR_CfgModeFailed + err;
if (twizy_sdo.data != 127) {
// request preoperational state:
if (err = writesdo(0x2800,0,1))
return ERR_CfgModeFailed + err;
// give controller some time:
delay(10);
// check new status:
if (err = readsdo(0x5110,0))
return ERR_CfgModeFailed + err;
if (twizy_sdo.data != 127) {
// reset preop state request:
if (err = writesdo(0x2800,0,0))
return ERR_CfgModeFailed + err;
return ERR_CfgModeFailed;
}
}
}
return 0;
}
// utility: output SDO to string:
char *vehicle_twizy_fmt_sdo(char *s)
{
s = stp_rom(s, " SDO ");
if ((twizy_sdo.control & 0b11100000) == 0b10000000)
s = stp_rom(s, "ABORT ");
s = stp_x(s, "0x", twizy_sdo.index);
s = stp_sx(s, ".", twizy_sdo.subindex);
if (twizy_sdo.data > 0x0ffff)
s = stp_lx(s, ": 0x", twizy_sdo.data);
else
s = stp_x(s, ": 0x", twizy_sdo.data);
switch (twizy_sdo.data) {
case 0x05040000:
s = stp_rom(s, ": SEVCON OFFLINE ");
break;
case 0x08000004:
s = stp_rom(s, ": NEEDS PRE-OP MODE ");
break;
case 0x08000008:
s = stp_rom(s, ": ACCESS LEVEL TOO LOW ");
break;
case 0x0800000a:
case 0x0800000b:
case 0x0800000c:
s = stp_rom(s, ": INVALID VALUE ");
break;
}
return s;
}
// utility: translate error code to string:
char *vehicle_twizy_fmt_err(char *s, UINT err)
{
UINT8 detail = err & 0x000f;
// output error code:
s = stp_x(s, " ERROR ", err);
switch (err & 0xfff0) {
case ERR_Range:
// User error:
s = stp_i(s, "INVALID PARAM ", detail);
break;
case ERR_CfgModeFailed:
s = stp_rom(s, " NOT IN STOP");
// fall through...
default:
switch (detail) {
case ERR_NoCANWrite:
s = stp_rom(s, " NO CANWRITE");
break;
case ERR_ComponentOffline:
s = stp_rom(s, " SEVCON OFFLINE");
break;
}
s = vehicle_twizy_fmt_sdo(s);
break;
}
return s;
}

326
TwizyCfg/TwizyCfg.ino Normal file
View file

@ -0,0 +1,326 @@
/**
* ==========================================================================
* Twizy/SEVCON configuration shell
* ==========================================================================
*
* Based on the OVMS Twizy firmware:
* https://github.com/openvehicles/Open-Vehicle-Monitoring-System
*
* Author: Michael Balzer <dexter@dexters-web.de>
*
* Libraries used:
* - MCP_CAN: https://github.com/coryjfowler/MCP_CAN_lib
*
* License:
* This is free software under GNU Lesser General Public License (LGPL)
* https://www.gnu.org/licenses/lgpl.html
*
*/
#define TWIZY_CFG_VERSION "V1.0 (2017-06-13)"
#include <mcp_can.h>
#include <mcp_can_dfs.h>
#include "utils.h"
#include "CANopen.h"
#include "TwizyCfg_config.h"
// CAN interface:
MCP_CAN CAN(TWIZY_CAN_CS_PIN);
// Output buffers:
char net_scratchpad[200];
char net_msg_scratchpad[200];
// --------------------------------------------------------------------
// COMMAND DISPATCHER:
//
bool exec(char *cmd)
{
UINT err;
char *s;
char *t;
bool go_op_onexit = true;
char *arguments;
int arg[5] = {-1,-1,-1,-1,-1};
INT8 arg2[4] = {-1,-1,-1,-1};
long data;
char maps[4] = {'D','N','B',0};
UINT8 i;
arguments = net_sms_initargs(cmd);
// convert cmd to upper-case:
for (s=cmd; ((*s!=0)&&(*s!=' ')); s++)
if ((*s > 0x60) && (*s < 0x7b)) *s=*s-0x20;
if (*cmd == '?' || starts_with(cmd, "HELP")) {
Serial.print(F("\n"
"Twizy-Cfg " TWIZY_CFG_VERSION "\n"
"\n"
"Commands:\n"
" ?, help -- output this info\n"
" r <id> <sub> -- read SDO register (numerical)\n"
" rs <id> <sub> -- read SDO register (string)\n"
" w <id> <sub> <val> -- write SDO register (numerical) & show old value\n"
" wo <id> <sub> <val> -- write-only SDO register (numerical)\n"
" p -- preop mode\n"
" o -- op mode\n"
"\n"
"Note: <id> and <sub> are hexadecimal, <val> are decimal\n"
"Examples:\n"
" rs 1008 0 -- read SEVCON firmware name\n"
" w 2920 3 325 -- set neutral recup level to 32.5%\n"
"\n"
));
return false;
}
else {
// common reply intro:
s = stp_ram(net_scratchpad, cmd);
s = stp_rom(s, ": ");
//
// COMMAND DISPATCHER:
// Part 2: online commands (SEVCON access necessary)
// - PRE
// - OP
// - READ[S]
// - WRITE[O]
//
// login:
if (err = login(1)) {
s = vehicle_twizy_fmt_err(s, err);
}
else if (starts_with(cmd, "P")) {
// P: enter config mode
if (err = configmode(1))
s = vehicle_twizy_fmt_err(s, err);
else
s = stp_rom(s, "OK");
go_op_onexit = false;
}
else if (starts_with(cmd, "O")) {
// O: leave config mode
if (err = configmode(0))
s = vehicle_twizy_fmt_err(s, err);
else
s = stp_rom(s, "OK");
go_op_onexit = false;
}
else if (starts_with(cmd, "R")) {
// R index_hex subindex_hex
// RS index_hex subindex_hex
if (arguments = net_sms_nextarg(arguments))
arg[0] = (int)axtoul(arguments);
if (arguments = net_sms_nextarg(arguments))
arg[1] = (int)axtoul(arguments);
if (!arguments) {
s = stp_rom(s, "ERROR: Too few args");
}
else {
if (cmd[1] != 'S') {
// READ:
if (err = readsdo(arg[0], arg[1])) {
s = vehicle_twizy_fmt_err(s, err);
}
else {
s = vehicle_twizy_fmt_sdo(s);
s = stp_ul(s, " = ", twizy_sdo.data);
}
}
else {
// READS: SMS intro 'CFG READS: 0x1234.56=' = 21 chars, 139 remaining
if (err = readsdo_buf(arg[0], arg[1], (byte*)net_msg_scratchpad, (i=139, &i))) {
s = vehicle_twizy_fmt_err(s, err);
}
else {
net_msg_scratchpad[139-i] = 0;
s = stp_x(s, "0x", arg[0]);
s = stp_sx(s, ".", arg[1]);
s = stp_s(s, "=", net_msg_scratchpad);
}
}
}
go_op_onexit = false;
}
else if (starts_with(cmd, "W")) {
// W index_hex subindex_hex data_dec
// WO index_hex subindex_hex data_dec
if (arguments = net_sms_nextarg(arguments))
arg[0] = (int)axtoul(arguments);
if (arguments = net_sms_nextarg(arguments))
arg[1] = (int)axtoul(arguments);
if (arguments = net_sms_nextarg(arguments))
data = atol(arguments);
if (!arguments) {
s = stp_rom(s, "ERROR: Too few args");
}
else {
if (cmd[1] == 'O') {
// WRITEONLY:
// write new value:
if (err = writesdo(arg[0], arg[1], data)) {
s = vehicle_twizy_fmt_err(s, err);
}
else {
s = stp_rom(s, "OK: ");
s = vehicle_twizy_fmt_sdo(s);
}
}
else {
// READ-WRITE:
// read old value:
if (err = readsdo(arg[0], arg[1])) {
s = vehicle_twizy_fmt_err(s, err);
}
else {
// read ok:
s = stp_rom(s, "OLD:");
s = vehicle_twizy_fmt_sdo(s);
s = stp_ul(s, " = ", twizy_sdo.data);
// write new value:
if (err = writesdo(arg[0], arg[1], data))
s = vehicle_twizy_fmt_err(s, err);
else
s = stp_ul(s, " => NEW: ", data);
}
}
}
go_op_onexit = false;
}
else {
// unknown command
s = stp_rom(s, "Unknown command");
}
// go operational?
if (go_op_onexit)
configmode(0);
}
//
// FINISH: send command response
//
Serial.println(net_scratchpad);
return true;
}
// --------------------------------------------------------------------
// MAIN
//
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
void setup() {
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// reserve 200 bytes for the inputString:
inputString.reserve(200);
//
// Init Twizy CAN interface
//
while (CAN.begin(MCP_STDEXT, CAN_500KBPS, TWIZY_CAN_MCP_FREQ) != CAN_OK) {
Serial.println(F("setup: waiting for CAN connection..."));
delay(1000);
}
// Set filters:
CAN.init_Mask(0, 0, 0x07FF0000);
CAN.init_Filt(0, 0, 0x05810000); // CANopen response node 1
CAN.init_Filt(1, 0, 0x00000000);
CAN.init_Mask(1, 0, 0x07FF0000);
CAN.init_Filt(2, 0, 0x00000000);
CAN.init_Filt(3, 0, 0x00000000);
CAN.init_Filt(4, 0, 0x00000000);
CAN.init_Filt(5, 0, 0x00000000);
CAN.setMode(MCP_NORMAL);
// Output info & prompt:
exec((char *) "?");
Serial.print("\n> ");
}
void loop() {
if (stringComplete) {
// execute command:
Serial.println(inputString);
exec((char *) inputString.c_str());
Serial.print("\n> ");
// clear the string:
inputString = "";
stringComplete = false;
}
}
/*
SerialEvent occurs whenever a new data comes in the
hardware serial RX. This routine is run between each
time loop() runs, so using delay inside loop can delay
response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
if (inChar == '\n') {
stringComplete = true;
}
else if (inChar >= 32) {
inputString += inChar;
}
}
}

View file

@ -0,0 +1,16 @@
/**
* ==========================================================================
* Twizy/SEVCON configuration shell
* ==========================================================================
*/
#ifndef _TwizyCfg_config_h
#define _TwizyCfg_config_h
// Set your MCP clock frequency here:
#define TWIZY_CAN_MCP_FREQ MCP_16MHZ
// Set your SPI CS pin number here:
#define TWIZY_CAN_CS_PIN 53
#endif // _TwizyCfg_config_h

42
TwizyCfg/utils.h Normal file
View file

@ -0,0 +1,42 @@
/**
* ==========================================================================
* Twizy/SEVCON configuration shell
* ==========================================================================
*
* Utilities
*
* Based on the OVMS:
* https://github.com/openvehicles/Open-Vehicle-Monitoring-System
*
* License:
* This is free software.
* This is a modified copy of the OVMS general utils, so the OVMS license applies:
* https://github.com/openvehicles/Open-Vehicle-Monitoring-System/blob/master/LICENSE
*
*/
#ifndef _utils_h
#define _utils_h
// Type shortcuts:
typedef unsigned char UINT8;
typedef unsigned int UINT;
typedef unsigned long UINT32;
typedef signed char INT8;
// Useful macros:
#define SQR(n) ((n)*(n))
#define ABS(n) (((n) < 0) ? -(n) : (n))
#define MIN(n,m) ((n) < (m) ? (n) : (m))
#define MAX(n,m) ((n) > (m) ? (n) : (m))
#define LIMIT_MIN(n,lim) ((n) < (lim) ? (lim) : (n))
#define LIMIT_MAX(n,lim) ((n) > (lim) ? (lim) : (n))
#endif // _utils_h

318
TwizyCfg/utils.ino Normal file
View file

@ -0,0 +1,318 @@
/**
* ==========================================================================
* Twizy/SEVCON configuration shell
* ==========================================================================
*
* Utilities
*
* Based on the OVMS:
* https://github.com/openvehicles/Open-Vehicle-Monitoring-System
*
* License:
* This is free software.
* This is a modified copy of the OVMS general utils, so the OVMS license applies:
* https://github.com/openvehicles/Open-Vehicle-Monitoring-System/blob/master/LICENSE
*
*/
#include "utils.h"
// hex string decode:
unsigned long axtoul(char *s)
{
unsigned long val = 0;
unsigned char c;
unsigned int dig = 0;
while (s && *s) {
c = *s | 0x20;
if (c == 'x') {
val = 0; // prefix 0x => reset val
}
else if (c >= '0' && c <= '9') {
dig = c - '0';
val = (val << 4) | dig;
}
else if (c >= 'a' && c <= 'f') {
dig = c - 'a' + 10;
val = (val << 4) | dig;
}
else {
break; // no hex char, stop
}
s++;
}
return val;
}
// string prefix check:
bool starts_with(char *s, const char *pfx)
{
while ((*s == *pfx) && (*pfx != 0))
{
pfx++;
s++;
}
return (*pfx == 0);
}
// string-print string:
char *stp_rom(char *dst, const char *val)
{
while (*dst = *val++) dst++;
return dst;
}
// string-print ram string:
char *stp_ram(char *dst, const char *val)
{
while (*dst = *val++) dst++;
return dst;
}
// string-print ram string with optional prefix:
char *stp_s(char *dst, const char *prefix, char *val)
{
if (prefix)
dst = stp_rom(dst, prefix);
return stp_ram(dst, val);
}
// string-print string with optional prefix:
char *stp_rs(char *dst, const char *prefix, const char *val)
{
if (prefix)
dst = stp_rom(dst, prefix);
return stp_rom(dst, val);
}
// string-print integer with optional string prefix:
char *stp_i(char *dst, const char *prefix, int val)
{
if (prefix)
dst = stp_rom(dst, prefix);
itoa(val, dst, 10);
while (*dst) dst++;
return dst;
}
// string-print long with optional string prefix:
char *stp_l(char *dst, const char *prefix, long val)
{
if (prefix)
dst = stp_rom(dst, prefix);
ltoa(val, dst, 10);
while (*dst) dst++;
return dst;
}
// string-print unsigned long with optional string prefix:
char *stp_ul(char *dst, const char *prefix, unsigned long val)
{
if (prefix)
dst = stp_rom(dst, prefix);
ultoa(val, dst, 10);
while (*dst) dst++;
return dst;
}
// ltox
// (note: fills fixed len chars with '0' padding = sprintf %04x)
void ltox(unsigned long i, char *s, unsigned int len)
{
unsigned char n;
s += len;
*s = '\0';
for (n = len; n != 0; --n)
{
*--s = "0123456789ABCDEF"[i & 0x0F];
i >>= 4;
}
}
// string-print unsigned integer hexadecimal with optional string prefix:
// (note: fills fixed 4 chars with '0' padding = sprintf %04x)
char *stp_x(char *dst, const char *prefix, unsigned int val)
{
if (prefix)
dst = stp_rom(dst, prefix);
ltox(val, dst, 4);
while (*dst) dst++;
return dst;
}
// string-print unsigned long hexadecimal with optional string prefix:
// (note: fills fixed 8 chars with '0' padding = sprintf %08lx)
char *stp_lx(char *dst, const char *prefix, unsigned long val)
{
if (prefix)
dst = stp_rom(dst, prefix);
ltox(val, dst, 8);
while (*dst) dst++;
return dst;
}
// string-print unsigned integer hexadecimal with optional string prefix:
// (note: fills fixed 2 chars with '0' padding = sprintf %02x)
char *stp_sx(char *dst, const char *prefix, unsigned char val)
{
if (prefix)
dst = stp_rom(dst, prefix);
ltox(val, dst, 2);
while (*dst) dst++;
return dst;
}
// string-print unsigned long to fixed size with padding
char *stp_ulp(char *dst, const char *prefix, unsigned long val, int len, char pad)
{
char buf[11];
byte bl;
if (prefix)
dst = stp_rom(dst, prefix);
ultoa(val, buf, 10);
for (bl = strlen(buf); bl < len; bl++)
*dst++ = pad;
dst = stp_ram(dst, buf);
return dst;
}
// string-print fixed precision long as float
char *stp_l2f(char *dst, const char *prefix, long val, int prec)
{
long factor, lval;
char p;
for (factor = 1, p = prec; p > 0; p--)
factor *= 10;
lval = val / factor;
if (prefix)
dst = stp_rom(dst, prefix);
if (lval == 0 && val < 0) // handle "negative zero"
*dst++ = '-';
dst = stp_l(dst, NULL, lval);
*dst++ = '.';
dst = stp_ulp(dst, NULL, ABS(val) % factor, prec, '0');
return dst;
}
// string-print unsigned long as fixed point number with optional string prefix
#define chDecimal '.'
#define chSeparator ','
char *stp_l2f_h(char *dst, const char *prefix, unsigned long val, int cdecimal)
{
char *start, *end;
int cch;
if (prefix)
dst = stp_rom(dst, prefix);
start = dst;
cch = 0;
// decompose the number, writing out the digits backwards
while (val != 0 || cch <= cdecimal)
{
// write out the thousands separator when needed
if (((cch - cdecimal) % 3) == 0 && cch > cdecimal)
*dst++ = chSeparator;
// peel off the next digit
*dst++ = '0' + (val % 10);
val /= 10;
// write out the decimal point when needed
if (++cch == cdecimal)
*dst++ = chDecimal;
}
end = dst - 1;
// reverse the string in place
while (start < end)
{
char chT = *start;
*start++ = *end;
*end-- = chT;
}
// null terminate
*dst = 0;
return dst;
}
// Text command argument tokenizing:
char *net_sms_argend = NULL;
char* net_sms_initargs(char* arguments)
{
char *p;
if (arguments == NULL) return NULL;
net_sms_argend = arguments + strlen(arguments);
if (net_sms_argend == arguments) return NULL;
// Zero-terminate the first argument
for (p = arguments; (*p != ' ') && (*p != 0); p++) {}
if (*p == ' ') *p = 0;
return arguments;
}
char* net_sms_nextarg(char *lastarg)
{
char *p;
if (lastarg == NULL) return NULL;
// find end of previous argument:
for (p = lastarg; (*p != 0); p++) {}
if (p == net_sms_argend) return NULL;
// find start of next argument:
while (*++p == ' ') {}
if (p == net_sms_argend) return NULL;
lastarg = p;
// zero-terminate:
for (; (*p != ' ') && (*p != 0); p++) {}
if (*p == ' ') *p = 0;
return lastarg;
}

Binary file not shown.

BIN
extras/Twizy-SDO-List.ods Normal file

Binary file not shown.