├── README.md ├── ControllerMain.h ├── TimedAction.h ├── TimedAction.cpp ├── MCP2515RegDefs.h ├── MCPCANbusUDS.h ├── ControllerMain.ino ├── MethService.h ├── MCPCANbusUDS.cpp ├── MethService.cpp └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | # BMW-CANbus-Meth-Controller 2 | Progressive methanol injection controller for BMW E92 and similar cars. The methanol delivery rate is determined by querying the current fuel load from the ECU using the UDS protocol over CANbus (via the OBD port). 3 | -------------------------------------------------------------------------------- /ControllerMain.h: -------------------------------------------------------------------------------- 1 | /********************************************************************/ 2 | /* Controller Core Implementation Header */ 3 | /* ControllerMain.h */ 4 | /* */ 5 | /* Author: Jacob Moroni (jakemoroni@gmail.com) */ 6 | /* */ 7 | /* Description: This file implements the core functionality */ 8 | /* of the CANbus based meth controller. */ 9 | /* */ 10 | /* Revision: Oct 12, 2015 (First) */ 11 | /* */ 12 | /* Copyright (C) 2015 Jacob Moroni. All right reserved. */ 13 | /* */ 14 | /* This library is free software; you can redistribute it and/or */ 15 | /* modify it under the terms of the GNU Lesser General Public */ 16 | /* License as published by the Free Software Foundation; either */ 17 | /* version 2.1 of the License, or (at your option) any later */ 18 | /* version. */ 19 | /* This library is distributed in the hope that it will be */ 20 | /* useful, but WITHOUT ANY WARRANTY; without even the implied */ 21 | /* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR */ 22 | /* PURPOSE. See the GNU Lesser General Public License for more */ 23 | /* details. */ 24 | /* You should have received a copy of the GNU Lesser General */ 25 | /* Public License along with this library; if not, write to the */ 26 | /* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, */ 27 | /* Boston, MA 02110-1301 USA */ 28 | /********************************************************************/ 29 | 30 | #ifndef _CONTROLLERMAIN_H_ 31 | #define _CONTROLLERMAIN_H_ 32 | 33 | /********************************************************************/ 34 | /* DEFINES */ 35 | /********************************************************************/ 36 | 37 | /* Enable debug output. */ 38 | #define CONTROLLER_MAIN_SERIAL_DEBUG 39 | 40 | /* Can controller SPI chip select pin. */ 41 | #define CONTROLLER_MAIN_CAN_CHIP_SEL_PIN 10 42 | 43 | /* Good status output pin. Can be hooked to an LED. */ 44 | /* A better term may have been "armed and ready"... */ 45 | /* This basically ends up being the same as the meth controller's */ 46 | /* failsafe output pin, but inverted. The reason being that */ 47 | /* it's nice to know that the system is powered on and running. */ 48 | /* If the failsafe isn't tripped, we don't know if everything is okay */ 49 | /* or if the unit is just dead. */ 50 | #define CONTROLLER_MAIN_OKAY_OUTPUT_PIN 6 51 | 52 | 53 | #endif /* _CONTROLLERMAIN_H_ */ 54 | -------------------------------------------------------------------------------- /TimedAction.h: -------------------------------------------------------------------------------- 1 | /********************************************************************/ 2 | /* Timed Action Implementation Header */ 3 | /* TimedAction.h */ 4 | /* */ 5 | /* Author: Alexander Brevig */ 6 | /* Contributors: Jacob Moroni (jakemoroni@gmail.com) */ 7 | /* */ 8 | /* Description: This file implements the interface for the */ 9 | /* TimedAction library (C++). */ 10 | /* */ 11 | /* Revision: Oct 15, 2015 (Modified by JMoroni) */ 12 | /* */ 13 | /* This library is free software; you can redistribute it and/or */ 14 | /* modify it under the terms of the GNU Lesser General Public */ 15 | /* License as published by the Free Software Foundation; either */ 16 | /* version 2.1 of the License, or (at your option) any later */ 17 | /* version. */ 18 | /* This library is distributed in the hope that it will be */ 19 | /* useful, but WITHOUT ANY WARRANTY; without even the implied */ 20 | /* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR */ 21 | /* PURPOSE. See the GNU Lesser General Public License for more */ 22 | /* details. */ 23 | /* You should have received a copy of the GNU Lesser General */ 24 | /* Public License along with this library; if not, write to the */ 25 | /* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, */ 26 | /* Boston, MA 02110-1301 USA */ 27 | /********************************************************************/ 28 | 29 | #ifndef _TIMEDACTION_H_ 30 | #define _TIMEDACTION_H_ 31 | 32 | /********************************************************************/ 33 | /* INCLUDES */ 34 | /********************************************************************/ 35 | 36 | /* Standard types. */ 37 | #include 38 | 39 | /********************************************************************/ 40 | /* CLASSES */ 41 | /********************************************************************/ 42 | 43 | class TimedAction 44 | { 45 | public: 46 | /* This constructor initializes a TimedAction. */ 47 | /* This does NOT start the timer. */ 48 | /* IN: intervl - period of which execution of callback should occur (ms) */ 49 | /* IN: function - pointer to a void function which will be executed */ 50 | TimedAction(unsigned long intervl, void (*function)()); 51 | 52 | /* This function starts/resets the timer. */ 53 | void start(); 54 | 55 | /* This function stops the timer. */ 56 | void stop(); 57 | 58 | /* This function checks the timer and executes the callback if the */ 59 | /* period has elapsed. */ 60 | void check(); 61 | 62 | private: 63 | uint8_t active; 64 | unsigned long previous; 65 | unsigned long interval; 66 | void (*execute)(); 67 | }; 68 | 69 | 70 | #endif /* _TIMEDACTION_H_ */ 71 | -------------------------------------------------------------------------------- /TimedAction.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************/ 2 | /* Timed Action Implementation */ 3 | /* TimedAction.cpp */ 4 | /* */ 5 | /* Author: Alexander Brevig */ 6 | /* Contributors: Jacob Moroni (jakemoroni@gmail.com) */ 7 | /* */ 8 | /* Description: This file implements the TimedAction */ 9 | /* library (C++). */ 10 | /* */ 11 | /* Revision: Oct 15, 2015 (Modified by JMoroni) */ 12 | /* */ 13 | /* This library is free software; you can redistribute it and/or */ 14 | /* modify it under the terms of the GNU Lesser General Public */ 15 | /* License as published by the Free Software Foundation; either */ 16 | /* version 2.1 of the License, or (at your option) any later */ 17 | /* version. */ 18 | /* This library is distributed in the hope that it will be */ 19 | /* useful, but WITHOUT ANY WARRANTY; without even the implied */ 20 | /* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR */ 21 | /* PURPOSE. See the GNU Lesser General Public License for more */ 22 | /* details. */ 23 | /* You should have received a copy of the GNU Lesser General */ 24 | /* Public License along with this library; if not, write to the */ 25 | /* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, */ 26 | /* Boston, MA 02110-1301 USA */ 27 | /********************************************************************/ 28 | 29 | /********************************************************************/ 30 | /* INCLUDES */ 31 | /********************************************************************/ 32 | 33 | /* Arduino system. (millis). */ 34 | #include 35 | 36 | /* Private header. */ 37 | #include "TimedAction.h" 38 | 39 | /********************************************************************/ 40 | /* FUNCTION DEFINITIONS */ 41 | /********************************************************************/ 42 | 43 | TimedAction::TimedAction(unsigned long intervl, void (*function)()) 44 | { 45 | active = false; 46 | previous = 0; 47 | interval = intervl; 48 | execute = function; 49 | } 50 | 51 | void TimedAction::start() 52 | { 53 | active = true; 54 | previous = millis(); 55 | } 56 | 57 | void TimedAction::stop() 58 | { 59 | active = false; 60 | } 61 | 62 | void TimedAction::check() 63 | { 64 | unsigned long currTime; 65 | if(active) 66 | { 67 | currTime = millis(); 68 | if((currTime - previous) >= interval) 69 | { 70 | /* Maintain frequency stability by just adding one interval rather */ 71 | /* than using the current time. */ 72 | /* If we use the current time, it's possible for delays in the calling */ 73 | /* of the check function to introduce "slip". */ 74 | previous += interval; 75 | execute(); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /MCP2515RegDefs.h: -------------------------------------------------------------------------------- 1 | /********************************************************************/ 2 | /* MCP2515 Register and Interface Definitions */ 3 | /* MCP2515RegDefs.h */ 4 | /* */ 5 | /* Author: Loovee */ 6 | /* Contributors: Cory J. Fowler */ 7 | /* Jacob Moroni (jakemoroni@gmail.com) */ 8 | /* */ 9 | /* Description: This file implements the register definitions */ 10 | /* for the MCP2515 CANbus controller. */ 11 | /* */ 12 | /* Revision: Oct 12, 2015 */ 13 | /* */ 14 | /* Copyright (C) 2012 Seeed Technology Inc. All right reserved. */ 15 | /* */ 16 | /* This library is free software; you can redistribute it and/or */ 17 | /* modify it under the terms of the GNU Lesser General Public */ 18 | /* License as published by the Free Software Foundation; either */ 19 | /* version 2.1 of the License, or (at your option) any later */ 20 | /* version. */ 21 | /* This library is distributed in the hope that it will be */ 22 | /* useful, but WITHOUT ANY WARRANTY; without even the implied */ 23 | /* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR */ 24 | /* PURPOSE. See the GNU Lesser General Public License for more */ 25 | /* details. */ 26 | /* You should have received a copy of the GNU Lesser General */ 27 | /* Public License along with this library; if not, write to the */ 28 | /* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, */ 29 | /* Boston, MA 02110-1301 USA */ 30 | /********************************************************************/ 31 | 32 | #ifndef _MCP2515REGDEFS_H_ 33 | #define _MCP2515REGDEFS_H_ 34 | 35 | /********************************************************************/ 36 | /* DEFINES */ 37 | /********************************************************************/ 38 | 39 | #define MCP_N_TXBUFFERS (3) 40 | #define MCP_SIDH 0 41 | #define MCP_SIDL 1 42 | #define MCP_EID8 2 43 | #define MCP_EID0 3 44 | #define MCP_TXB_EXIDE_M 0x08 45 | #define MCP_DLC_MASK 0x0F 46 | #define MCP_RTR_MASK 0x40 47 | #define MCP_RXB_RX_STDEXT 0x00 48 | #define MCP_RXB_RX_MASK 0x60 49 | #define MCP_RXB_BUKT_MASK (1 << 2) 50 | #define MCP_TXB_TXREQ_M 0x08 51 | #define MCP_STAT_RXIF_MASK (0x03) 52 | #define MCP_STAT_RX0IF (1 << 0) 53 | #define MCP_STAT_RX1IF (1 << 1) 54 | #define MCP_RXF0SIDH 0x00 55 | #define MCP_RXF1SIDH 0x04 56 | #define MCP_RXF2SIDH 0x08 57 | #define MCP_RXF3SIDH 0x10 58 | #define MCP_RXF4SIDH 0x14 59 | #define MCP_RXF5SIDH 0x18 60 | #define MCP_RXM0SIDH 0x20 61 | #define MCP_RXM1SIDH 0x24 62 | #define MCP_CANSTAT 0x0E 63 | #define MCP_CANCTRL 0x0F 64 | #define MCP_CNF3 0x28 65 | #define MCP_CNF2 0x29 66 | #define MCP_CNF1 0x2A 67 | #define MCP_CANINTE 0x2B 68 | #define MCP_CANINTF 0x2C 69 | #define MCP_TXB0CTRL 0x30 70 | #define MCP_TXB1CTRL 0x40 71 | #define MCP_TXB2CTRL 0x50 72 | #define MCP_RXB0CTRL 0x60 73 | #define MCP_RXB0SIDH 0x61 74 | #define MCP_RXB1CTRL 0x70 75 | #define MCP_RXB1SIDH 0x71 76 | #define MCP_WRITE 0x02 77 | #define MCP_READ 0x03 78 | #define MCP_BITMOD 0x05 79 | #define MCP_READ_STATUS 0xA0 80 | #define MCP_RESET 0xC0 81 | #define MODE_NORMAL 0x00 82 | #define MODE_CONFIG 0x80 83 | #define MODE_MASK 0xE0 84 | #define MCP_RX0IF 0x01 85 | #define MCP_RX1IF 0x02 86 | #define MCP_16MHz_500kBPS_CFG1 (0x00) 87 | #define MCP_16MHz_500kBPS_CFG2 (0xF0) 88 | #define MCP_16MHz_500kBPS_CFG3 (0x86) 89 | #define MCP_16MHz_250kBPS_CFG1 (0x41) 90 | #define MCP_16MHz_250kBPS_CFG2 (0xF1) 91 | #define MCP_16MHz_250kBPS_CFG3 (0x85) 92 | #define MCP_RXBUF_0 (MCP_RXB0SIDH) 93 | #define MCP_RXBUF_1 (MCP_RXB1SIDH) 94 | 95 | 96 | #endif /* _MCP2515REGDEFS_H_ */ 97 | -------------------------------------------------------------------------------- /MCPCANbusUDS.h: -------------------------------------------------------------------------------- 1 | /********************************************************************/ 2 | /* MCP2515 + UDS Protocol Interface Library Header */ 3 | /* MCPCANbusUDS.h */ 4 | /* */ 5 | /* Author: Loovee */ 6 | /* Contributors: Cory J. Fowler */ 7 | /* Jacob Moroni (jakemoroni@gmail.com) */ 8 | /* */ 9 | /* Description: This file implements the interface methods as */ 10 | /* well as the UDS protocol definitions required */ 11 | /* to communicate with a late model (2008+) */ 12 | /* BMW using the MCP2515 CANbus controller. */ 13 | /* */ 14 | /* Revision: Oct 12, 2015 */ 15 | /* */ 16 | /* Copyright (C) 2012 Seeed Technology Inc. All right reserved. */ 17 | /* */ 18 | /* This library is free software; you can redistribute it and/or */ 19 | /* modify it under the terms of the GNU Lesser General Public */ 20 | /* License as published by the Free Software Foundation; either */ 21 | /* version 2.1 of the License, or (at your option) any later */ 22 | /* version. */ 23 | /* This library is distributed in the hope that it will be */ 24 | /* useful, but WITHOUT ANY WARRANTY; without even the implied */ 25 | /* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR */ 26 | /* PURPOSE. See the GNU Lesser General Public License for more */ 27 | /* details. */ 28 | /* You should have received a copy of the GNU Lesser General */ 29 | /* Public License along with this library; if not, write to the */ 30 | /* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, */ 31 | /* Boston, MA 02110-1301 USA */ 32 | /********************************************************************/ 33 | 34 | #ifndef _MCPCANBUSUDS_H_ 35 | #define _MCPCANBUSUDS_H_ 36 | 37 | /********************************************************************/ 38 | /* INCLUDES */ 39 | /********************************************************************/ 40 | 41 | /* Chip register definitions. */ 42 | #include "MCP2515RegDefs.h" 43 | 44 | /* Standard types. */ 45 | #include 46 | 47 | /* Arduino system. */ 48 | #include 49 | 50 | /* SPI Interface. */ 51 | #include 52 | 53 | /********************************************************************/ 54 | /* DEFINES */ 55 | /********************************************************************/ 56 | 57 | /* ---------- BMW UDS (Extended OBD) Definitions. ---------- */ 58 | 59 | /* The ID of which we send requests. (Mailbox) */ 60 | #define UDS_CAN_TRANSMIT_ID 0x6F1 61 | 62 | /* The ID of which responses are sent. (Mailbox) */ 63 | #define UDS_CAN_RECEIVE_ID 0x612 64 | 65 | /* We use an 11 bit ID... */ 66 | #define UDS_CAN_ID_MASK 0x7FF 67 | 68 | /* Fuel load request message. Len SID DID1 DID2 PAD . . */ 69 | #define UDS_CAN_FUEL_LOAD_REQUEST_MSG_PTR (const uint8_t[]){0x12, 0x03, 0x22, 0x45, 0x21, 0, 0, 0} 70 | 71 | /* Fuel load response message. */ 72 | #define UDS_CAN_FUEL_LOAD_RESPONSE_MSG_PTR (const uint8_t[]){0xF1, 0x05, 0x62, 0x45, 0x21, 0, 0, 0} 73 | 74 | /* BMW multipler = 0.10000000149011612. */ 75 | /* Specific gravity of gasoline = 0.73722 kg per liter. */ 76 | /* So, 0.10000000149011612 * (1 / 0.73722). */ 77 | #define UDS_CAN_FUEL_LOAD_KG_TO_L_MULT_SCALAR ((double)0.135645) 78 | 79 | /* Comparison depth for qualifying received UDS messages. */ 80 | #define UDS_CAN_RX_RESP_COMPARE_LENGTH 5 81 | 82 | /* Payload offsets. */ 83 | #define UDS_CAN_RX_RESP_DATA_BYTE_0_IDX 5 84 | #define UDS_CAN_RX_RESP_DATA_BYTE_1_IDX 6 85 | #define UDS_CAN_RX_RESP_DATA_BYTE_2_IDX 7 86 | 87 | /* ---------- Generic MCP CAN Definitions. ---------- */ 88 | 89 | /* Maximum message length under all circumstances. */ 90 | #define MCP_CAN_MAX_MSG_LEN 8 91 | 92 | /* Arduino SPI abstraction. */ 93 | #define spi_readwrite SPI.transfer 94 | #define spi_read() spi_readwrite(0x00) 95 | 96 | /* Arduino chip select abstraction. Active LOW. */ 97 | #define MCP2515_SELECT() digitalWrite(SPICS, LOW) 98 | #define MCP2515_UNSELECT() digitalWrite(SPICS, HIGH) 99 | 100 | /* Timeout value (actually, retry value). This is used for */ 101 | /* instances where we are waiting for transmissions to complete. */ 102 | #define TIMEOUTVALUE 50 103 | 104 | /********************************************************************/ 105 | /* DATATYPES */ 106 | /********************************************************************/ 107 | 108 | /* Supported CANbus speeds. */ 109 | typedef enum 110 | { 111 | MCP_CAN_SPEED_250KBPS, 112 | MCP_CAN_SPEED_500KBPS 113 | } MCP_CAN_Speed_E; 114 | 115 | /* MCP CAN API return values. */ 116 | typedef enum 117 | { 118 | CAN_OK, 119 | CAN_FAILINIT, 120 | CAN_MSGAVAIL, 121 | CAN_NOMSG, 122 | CAN_GETTXBFTIMEOUT 123 | } MCP_CAN_Ret_Val_E; 124 | 125 | /* MCP2515 Interface function return value. */ 126 | typedef enum 127 | { 128 | MCP2515_OK, 129 | MCP2515_FAIL, 130 | MCP2515_ALLTXBUSY 131 | } MCP2515_Ret_Val_E; 132 | 133 | /********************************************************************/ 134 | /* CLASSES */ 135 | /********************************************************************/ 136 | 137 | class MCP_CAN 138 | { 139 | private: 140 | 141 | uint8_t m_nExtFlg; /* Identifier xxxID */ 142 | /* Either extended (the 29 LSB) */ 143 | /* or standard (the 11 LSB) */ 144 | uint32_t m_nID; /* CAN Message ID */ 145 | uint8_t m_nDlc; /* Message Length */ 146 | uint8_t m_nDta[MCP_CAN_MAX_MSG_LEN]; /* Message Data Buffer */ 147 | uint8_t m_nRtr; /* RTR */ 148 | uint8_t SPICS; /* The SPI chip select pin. */ 149 | 150 | private: 151 | 152 | uint8_t mcp2515_readRegister(const uint8_t address); 153 | void mcp2515_readRegisterS(const uint8_t address, uint8_t values[], const uint8_t n); 154 | void mcp2515_setRegister(const uint8_t address, const uint8_t value); 155 | void mcp2515_setRegisterS(const uint8_t address, const uint8_t values[], const uint8_t n); 156 | void mcp2515_modifyRegister(const uint8_t address, const uint8_t mask, const uint8_t data); 157 | uint8_t mcp2515_readStatus(void); 158 | MCP2515_Ret_Val_E mcp2515_setCANCTRL_Mode(const uint8_t newmode); 159 | MCP_CAN_Ret_Val_E mcp2515_init(const MCP_CAN_Speed_E canSpeed); 160 | void mcp2515_write_id( const uint8_t mcp_addr, const uint8_t ext, const uint32_t id ); 161 | void mcp2515_read_id( const uint8_t mcp_addr, uint8_t * ext, uint32_t * id ); 162 | void mcp2515_write_canMsg( const uint8_t buffer_sidh_addr ); 163 | void mcp2515_read_canMsg( const uint8_t buffer_sidh_addr); 164 | MCP2515_Ret_Val_E mcp2515_getNextFreeTXBuf(uint8_t * txbuf_n); 165 | void setMsg(uint32_t id, uint8_t ext, uint8_t len, uint8_t * pData); 166 | MCP_CAN_Ret_Val_E readMsg(); 167 | MCP_CAN_Ret_Val_E sendMsg(); 168 | 169 | public: 170 | 171 | MCP_CAN(uint8_t _CS); 172 | MCP_CAN_Ret_Val_E begin(MCP_CAN_Speed_E speedset); 173 | MCP_CAN_Ret_Val_E init_Mask(uint8_t num, uint8_t ext, uint32_t ulData); 174 | MCP_CAN_Ret_Val_E init_Filt(uint8_t num, uint8_t ext, uint32_t ulData); 175 | MCP_CAN_Ret_Val_E sendMsgBuf(uint32_t id, uint8_t ext, uint8_t len, uint8_t *buf); 176 | MCP_CAN_Ret_Val_E readMsgBuf(uint8_t *len, uint8_t * buf); 177 | MCP_CAN_Ret_Val_E checkReceive(void); 178 | uint32_t getCanId(void); 179 | }; 180 | 181 | 182 | #endif /* _MCPCANBUSUDS_H_ */ 183 | -------------------------------------------------------------------------------- /ControllerMain.ino: -------------------------------------------------------------------------------- 1 | /********************************************************************/ 2 | /* Controller Core Implementation Header */ 3 | /* ControllerMain.ino (cpp) */ 4 | /* */ 5 | /* Author: Jacob Moroni (jakemoroni@gmail.com) */ 6 | /* */ 7 | /* Description: This file implements the core functionality */ 8 | /* of the CANbus based meth controller. */ 9 | /* */ 10 | /* Revision: Oct 12, 2015 (First) */ 11 | /* */ 12 | /* Copyright (C) 2015 Jacob Moroni. All right reserved. */ 13 | /* */ 14 | /* This library is free software; you can redistribute it and/or */ 15 | /* modify it under the terms of the GNU Lesser General Public */ 16 | /* License as published by the Free Software Foundation; either */ 17 | /* version 2.1 of the License, or (at your option) any later */ 18 | /* version. */ 19 | /* This library is distributed in the hope that it will be */ 20 | /* useful, but WITHOUT ANY WARRANTY; without even the implied */ 21 | /* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR */ 22 | /* PURPOSE. See the GNU Lesser General Public License for more */ 23 | /* details. */ 24 | /* You should have received a copy of the GNU Lesser General */ 25 | /* Public License along with this library; if not, write to the */ 26 | /* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, */ 27 | /* Boston, MA 02110-1301 USA */ 28 | /********************************************************************/ 29 | 30 | /********************************************************************/ 31 | /* INCLUDES */ 32 | /********************************************************************/ 33 | 34 | /* Internal header. */ 35 | #include "ControllerMain.h" 36 | 37 | /* Include the MCP2515 API. */ 38 | #include "MCPCANbusUDS.h" 39 | 40 | /* Service headers... */ 41 | #include "MethService.h" 42 | 43 | /********************************************************************/ 44 | /* GLOBAL STATIC VARIABLES */ 45 | /********************************************************************/ 46 | 47 | /* Initialize a CAN library instance. */ 48 | /* Provide chip select on pin 10. */ 49 | MCP_CAN CAN(CONTROLLER_MAIN_CAN_CHIP_SEL_PIN); 50 | 51 | /* Interrupt flag. Single byte; atomic. */ 52 | static volatile unsigned char _intrFlagRecv = 0; 53 | 54 | /********************************************************************/ 55 | /* STATIC FUNCTION PROTOTYPES */ 56 | /********************************************************************/ 57 | 58 | /* These prototypes are necessary to avoid compiler warnings for some reason, */ 59 | /* even though they're defined before they're called... */ 60 | static void _mcp2515ISR(); 61 | static void _canRXMsgDispatch(uint32_t id, uint8_t * buf); 62 | 63 | /********************************************************************/ 64 | /* STATIC FUNCTION DEFINITIONS */ 65 | /********************************************************************/ 66 | 67 | /* Interrupt service routine for the CAN controller's RX interrupt. */ 68 | static void _mcp2515ISR() 69 | { 70 | _intrFlagRecv = 1; 71 | } 72 | 73 | /* This function dispatches received CAN messages to the proper service. */ 74 | static void _canRXMsgDispatch(uint32_t id, uint8_t * buf) 75 | { 76 | if(id == UDS_CAN_RECEIVE_ID) 77 | { 78 | /* Fuel load response. Send to meth service. */ 79 | if(!memcmp(buf, UDS_CAN_FUEL_LOAD_RESPONSE_MSG_PTR, UDS_CAN_RX_RESP_COMPARE_LENGTH)) 80 | { 81 | MethServiceRXFuelLoadMsg(buf); 82 | } 83 | } 84 | } 85 | 86 | /********************************************************************/ 87 | /* GLOBAL FUNCTION DEFINITIONS */ 88 | /********************************************************************/ 89 | 90 | /* Initialization routine for Arduino. */ 91 | void setup() 92 | { 93 | MCP_CAN_Ret_Val_E canInit = CAN_OK; 94 | 95 | /* Initialize UART. Other services might rely on it. */ 96 | Serial.begin(115200); 97 | 98 | /* Initialize system okay output pin to OFF. */ 99 | pinMode(CONTROLLER_MAIN_OKAY_OUTPUT_PIN, OUTPUT); 100 | digitalWrite(CONTROLLER_MAIN_OKAY_OUTPUT_PIN, LOW); 101 | 102 | /* Call the early initialization routine for all controllers. */ 103 | MethServiceInitEarly(); 104 | 105 | /* Register ISR for CAN message RX event. */ 106 | attachInterrupt(0, _mcp2515ISR, FALLING); 107 | 108 | /* 2011 BMW E92 uses a 500Kbps CANbus on the OBD port. */ 109 | if(CAN.begin(MCP_CAN_SPEED_500KBPS) != CAN_OK) canInit = CAN_FAILINIT; 110 | 111 | /* Configure filters and masks. */ 112 | /* Set both masks for the full 11 bit ID. */ 113 | if(CAN.init_Mask(0, 0, UDS_CAN_ID_MASK) != CAN_OK) canInit = CAN_FAILINIT; 114 | if(CAN.init_Mask(1, 0, UDS_CAN_ID_MASK) != CAN_OK) canInit = CAN_FAILINIT; 115 | 116 | /* The first two filters apply to the higher priority RX buffer (buffer 0). */ 117 | /* If that buffer is occupied, it will overflow into the second buffer */ 118 | /* regardless of the second buffer's filters. */ 119 | /* However, the second buffer's filters can allow messages to enter directly in to the second buffer. */ 120 | /* In other words, set both masks full on, and configure only the first two filters. */ 121 | /* This essentially means that all frames will try to enter buf 0 first, then ovf in to buf 1. */ 122 | /* Register to receive transmitted messages so we can detect another scanner on the bus......... */ 123 | if(CAN.init_Filt(0, 0, UDS_CAN_TRANSMIT_ID) != CAN_OK) canInit = CAN_FAILINIT; 124 | if(CAN.init_Filt(1, 0, UDS_CAN_RECEIVE_ID) != CAN_OK) canInit = CAN_FAILINIT; 125 | if(CAN.init_Filt(2, 0, 0) != CAN_OK) canInit = CAN_FAILINIT; 126 | if(CAN.init_Filt(3, 0, 0) != CAN_OK) canInit = CAN_FAILINIT; 127 | if(CAN.init_Filt(4, 0, 0) != CAN_OK) canInit = CAN_FAILINIT; 128 | if(CAN.init_Filt(5, 0, 0) != CAN_OK) canInit = CAN_FAILINIT; 129 | 130 | if(canInit == CAN_OK) 131 | { 132 | /* Call the late initialization routine for all controllers. */ 133 | MethServiceInitLate(); 134 | 135 | #if defined(CONTROLLER_MAIN_SERIAL_DEBUG) 136 | Serial.println("System initialized! Entering main loop..."); 137 | #endif 138 | } 139 | else 140 | { 141 | #if defined(CONTROLLER_MAIN_SERIAL_DEBUG) 142 | Serial.println("MCP2515 initialization failed! Aborting controllers..."); 143 | #endif 144 | /* Send the failure signal to all controllers. */ 145 | MethServiceAbort(); 146 | } 147 | } 148 | 149 | /* Main execution loop. */ 150 | void loop() 151 | { 152 | /* Buffer used to read messages. */ 153 | static uint8_t rxLen = 0; 154 | static uint8_t rxBuf[MCP_CAN_MAX_MSG_LEN] = {0}; 155 | 156 | if(_intrFlagRecv) 157 | { 158 | _intrFlagRecv = 0; 159 | 160 | /* Loop until there are no messages. This ensures that the interrupt will be reset. */ 161 | while(CAN_MSGAVAIL == CAN.checkReceive()) 162 | { 163 | CAN.readMsgBuf(&rxLen, rxBuf); 164 | _canRXMsgDispatch(CAN.getCanId(), rxBuf); 165 | } 166 | } 167 | 168 | /* Execute each service. */ 169 | MethServiceExec(); 170 | 171 | /* Derive the global system status from the controllers' status. */ 172 | /* For now, there's only one controller, so it's easy. */ 173 | /* Decide whether to turn the "okay" LED on or not. */ 174 | switch(MethServiceGetState()) 175 | { 176 | case METH_SERVICE_STATE_FAILURE: 177 | digitalWrite(CONTROLLER_MAIN_OKAY_OUTPUT_PIN, LOW); 178 | #if defined(CONTROLLER_MAIN_SERIAL_DEBUG) 179 | Serial.println("STATE: FAILURE"); 180 | #endif 181 | break; 182 | 183 | case METH_SERVICE_STATE_READY_ARMED: 184 | digitalWrite(CONTROLLER_MAIN_OKAY_OUTPUT_PIN, HIGH); 185 | break; 186 | 187 | case METH_SERVICE_STATE_INJECTING: 188 | digitalWrite(CONTROLLER_MAIN_OKAY_OUTPUT_PIN, HIGH); 189 | break; 190 | 191 | case METH_SERVICE_STATE_DISABLED: 192 | digitalWrite(CONTROLLER_MAIN_OKAY_OUTPUT_PIN, LOW); 193 | #if defined(CONTROLLER_MAIN_SERIAL_DEBUG) 194 | Serial.println("STATE: DISABLED"); 195 | #endif 196 | break; 197 | 198 | case METH_SERVICE_STATE_DISABLED_WARN: 199 | digitalWrite(CONTROLLER_MAIN_OKAY_OUTPUT_PIN, LOW); 200 | #if defined(CONTROLLER_MAIN_SERIAL_DEBUG) 201 | Serial.println("STATE: DISABLED-WARN"); 202 | #endif 203 | break; 204 | 205 | case METH_SERVICE_STATE_LOW_TANK: 206 | digitalWrite(CONTROLLER_MAIN_OKAY_OUTPUT_PIN, LOW); 207 | #if defined(CONTROLLER_MAIN_SERIAL_DEBUG) 208 | Serial.println("STATE: LOW-TANK"); 209 | #endif 210 | break; 211 | 212 | default: 213 | digitalWrite(CONTROLLER_MAIN_OKAY_OUTPUT_PIN, LOW); 214 | #if defined(CONTROLLER_MAIN_SERIAL_DEBUG) 215 | Serial.println("STATE: ERROR - UNKNOWN STATE"); 216 | #endif 217 | break; 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /MethService.h: -------------------------------------------------------------------------------- 1 | /********************************************************************/ 2 | /* Methanol Injection Service Implementation Header */ 3 | /* MethService.h */ 4 | /* */ 5 | /* Author: Jacob Moroni (jakemoroni@gmail.com) */ 6 | /* */ 7 | /* Description: This file implements the methanol injection */ 8 | /* service. This is one of many possible */ 9 | /* services that can be incorporated into the */ 10 | /* main controller. */ 11 | /* */ 12 | /* Revision: Oct 12, 2015 (First) */ 13 | /* */ 14 | /* Copyright (C) 2015 Jacob Moroni. All right reserved. */ 15 | /* */ 16 | /* This library is free software; you can redistribute it and/or */ 17 | /* modify it under the terms of the GNU Lesser General Public */ 18 | /* License as published by the Free Software Foundation; either */ 19 | /* version 2.1 of the License, or (at your option) any later */ 20 | /* version. */ 21 | /* This library is distributed in the hope that it will be */ 22 | /* useful, but WITHOUT ANY WARRANTY; without even the implied */ 23 | /* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR */ 24 | /* PURPOSE. See the GNU Lesser General Public License for more */ 25 | /* details. */ 26 | /* You should have received a copy of the GNU Lesser General */ 27 | /* Public License along with this library; if not, write to the */ 28 | /* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, */ 29 | /* Boston, MA 02110-1301 USA */ 30 | /********************************************************************/ 31 | 32 | #ifndef _METHSERVICE_H_ 33 | #define _METHSERVICE_H_ 34 | 35 | /********************************************************************/ 36 | /* INCLUDES */ 37 | /********************************************************************/ 38 | 39 | /* Use standard types. */ 40 | #include 41 | 42 | /********************************************************************/ 43 | /* DEFINES */ 44 | /********************************************************************/ 45 | 46 | /* Enable debug output. */ 47 | #define METH_SERVICE_SERIAL_DEBUG 48 | 49 | /* The PWM output pin. This drives an N-channel MOSFET which controls */ 50 | /* the solenoid. */ 51 | #define METH_SERVICE_PWM_OUTPUT_PIN 9 52 | 53 | /* The pump control output pin. This drives relay 1 on the relay board. */ 54 | #define METH_SERVICE_PUMP_OUTPUT_PIN 4 55 | 56 | /* The failsafe pin. This drives relay 2 on the relay board. */ 57 | #define METH_SERVICE_FAILSAFE_OUTPUT_PIN 7 58 | 59 | /* The tank sensor input. This pin is pulled high internally and grounded */ 60 | /* to indicate closure of the tank level sensor. */ 61 | #define METH_SERVICE_TANK_LEVEL_INPUT_PIN A2 62 | 63 | /* The disable input pin. This pin is pulled high internally and grounded */ 64 | /* to indicate a user-forced disabling of the meth controller. */ 65 | #define METH_SERVICE_DISABLE_INPUT_PIN A3 66 | 67 | /* The rate of which we request the fuel load from the ECU. 50ms = 20Hz. */ 68 | #define METH_SERVICE_FUEL_LOAD_REQUEST_PERIOD_MS 50 69 | 70 | /* This is how many times we have to have transmitted without receiving */ 71 | /* a response before we declare a failure. */ 72 | #define METH_SERVICE_FUEL_LOAD_SAMPLE_ERROR_LIMIT 2 73 | 74 | /* This is the threshold of when we start spraying (cc/min). */ 75 | /* There should ideally be 0% meth delivery rate at the X value after */ 76 | /* this point to ensure a gradual transition after the pump turns on. */ 77 | #define METH_SERVICE_FUEL_LOAD_UPPER_BOUND ((double)700.0) 78 | /* --- HYSTERESIS --- */ 79 | /* This is the threshold of when we stop spraying (cc/min). */ 80 | #define METH_SERVICE_FUEL_LOAD_LOWER_BOUND ((double)600.0) 81 | 82 | /* This is the percentage of meth to inject with respect to the current fuel delivery rate. */ 83 | /* The fuel delivery rate is in cc/min TOTAL. */ 84 | /* If the rate goes further than the rightmost cell, it uses the last value. */ 85 | /* The first value in the reference array MUST BE ZERO! */ 86 | #define METH_SERVICE_FUEL_DELIVERY_RATE_ARRAY \ 87 | (const double[]){0.0, 240.0, 480.0, 720.0, 960.0, 1200.0, 1440.0, 1680.0, 1920.0, 2160.0, 2400.0, 2640.0} 88 | /* Keep in mind that this is a percentage of cc/min of GASOLINE. Pure methanol has a specific gravity */ 89 | /* of .791 while gasoline's is .737. This means that if we are injecting pure meth, and we want to have */ 90 | /* 15% of the injected fuel mass be methanol, we only need to inject about 14% of the cc/min. */ 91 | /* Normally, this won't matter. We can just think in terms of volume flow rather than mass flow. */ 92 | #define METH_SERVICE_DESIRED_METH_FLOW_FUEL_DELIVERY_PERCENTAGE \ 93 | (const double[]){0.0, 0.0, 0.0, 0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 14.0} 94 | /* EST HORSEPOWER 0 43 85 128 170 208 234 265 302 321 352 387 */ 95 | /* Horsepower estimates are based off of .5 BSFC in low end to .55 BSFC in high end. */ 96 | 97 | /* This is the mapping of desired meth volume flow rate to output PWM duty. */ 98 | /* Ideally, this is linear. We can measure it later... */ 99 | /* This is assuming a 1.0MM (M6.0) Aquamist nozzle. */ 100 | #define METH_SERVICE_DESIRED_METH_FLOW_CC_MIN_ARRAY \ 101 | (const double[]){0.0, 43.2, 86.4, 129.6, 172.8, 216.0, 259.2, 302.4, 345.6, 388.8, 432.0, 480.0} 102 | /* Duty cycle percentage (0-100). */ 103 | #define METH_SERVICE_DESIRED_METH_FLOW_PWM_ARRAY \ 104 | (const double[]){0.0, 9.0, 18.0, 27.0, 36.0, 45.0, 54.0, 63.0, 72.0, 81.0, 90.0, 100.0} 105 | 106 | /* We should add another table to compensate for manifold pressure being subtracted from */ 107 | /* the effective pump pressure, but we won't. Instead, just assume 15 psi everywhere. */ 108 | 109 | /* This is the size of the above tables. */ 110 | #define METH_SERVICE_TABLE_SIZE 12 111 | 112 | /********************************************************************/ 113 | /* DATATYPES */ 114 | /********************************************************************/ 115 | 116 | /* Meth injection service state. */ 117 | typedef enum 118 | { 119 | METH_SERVICE_STATE_FAILURE, /* External failure, sample drops, etc... */ 120 | METH_SERVICE_STATE_READY_ARMED, /* Ready to spray once fuel load is met. */ 121 | METH_SERVICE_STATE_INJECTING, /* Currently spraying. */ 122 | METH_SERVICE_STATE_DISABLED, /* User disabled override. */ 123 | METH_SERVICE_STATE_DISABLED_WARN, /* Disabled, but should be spraying. */ 124 | METH_SERVICE_STATE_LOW_TANK, /* Tank is empty. */ 125 | METH_SERVICE_STATE_ANY /* Invalid state. */ 126 | } MethServiceState_E; 127 | 128 | /* Meth injection service events. */ 129 | typedef enum 130 | { 131 | METH_SERVICE_EVENT_DISABLE_TRUE, /* Disable switch is ON. */ 132 | METH_SERVICE_EVENT_DISABLE_FALSE, /* Disable switch is OFF. */ 133 | METH_SERVICE_EVENT_FUEL_LOAD_ABOVE_UPPER, /* Current fuel load > upper thresh. */ 134 | METH_SERVICE_EVENT_FUEL_LOAD_BELOW_LOWER, /* Current fuel load < lower thresh. */ 135 | METH_SERVICE_EVENT_SAMPLE_TIMEOUT, /* Sent X requests, got no response. */ 136 | METH_SERVICE_EVENT_EXT_FAILURE, /* Another controller failed. */ 137 | METH_SERVICE_EVENT_TANK_EMPTY_TRUE, /* The tank sensor reports empty. */ 138 | METH_SERVICE_EVENT_RESTART, /* Re/Initialize/Start the FSM. */ 139 | METH_SERVICE_EVENT_POWERUP, /* Set FSM to known initial state. */ 140 | METH_SERVICE_EVENT_MSG_RX, /* Fuel load message received. */ 141 | METH_SERVICE_EVENT_ANY /* Invalid event. */ 142 | } MethServiceEvent_E; 143 | 144 | /* FSM state transition structure. */ 145 | typedef struct 146 | { 147 | MethServiceState_E state; 148 | MethServiceEvent_E event; 149 | MethServiceState_E (*func)(void *); 150 | } MethServiceFSMTransition_T; 151 | 152 | /********************************************************************/ 153 | /* GLOBAL FUNCTION PROTOTYPES */ 154 | /********************************************************************/ 155 | 156 | /* This function is the "early" init function. */ 157 | /* These functions get called for each controller */ 158 | /* at the very beginning of boot. */ 159 | void MethServiceInitEarly(void); 160 | 161 | /* After every controller's early init function has been called, */ 162 | /* each controller's "late" function get called. */ 163 | /* This function is the last to be executed before entering the */ 164 | /* "main" loop. */ 165 | /* NOTE: The late function may NEVER get called if the system */ 166 | /* fails to initialize, but the Early init function is guaranteed */ 167 | /* to get called. A system init failure may call abort() rather than init late. */ 168 | void MethServiceInitLate(void); 169 | 170 | /* This controller's "thread". NOTE: This isn't a real thread. */ 171 | /* We use I guess what can be considered cooperative multitasking. */ 172 | /* In other words, don't block in here. */ 173 | void MethServiceExec(void); 174 | 175 | /* Special function for this controller. This is called by */ 176 | /* the main controller when a fuel load message is received. */ 177 | /* We CAN modify the contents of the message buffer if needed. */ 178 | void MethServiceRXFuelLoadMsg(uint8_t * msg); 179 | 180 | /* This is the fail signal handler. */ 181 | /* This gets called when another controller (or some other external */ 182 | /* influence) has caused a global system failure. */ 183 | /* This must stop the controller and leave it in a safe state. */ 184 | void MethServiceAbort(void); 185 | 186 | /* This function returns the state of the controller. */ 187 | MethServiceState_E MethServiceGetState(void); 188 | 189 | 190 | #endif /* _METHSERVICE_H_ */ 191 | -------------------------------------------------------------------------------- /MCPCANbusUDS.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************/ 2 | /* MCP2515 + UDS Protocol Interface Library */ 3 | /* MCPCANbusUDS.cpp */ 4 | /* */ 5 | /* Author: Loovee */ 6 | /* Contributors: Cory J. Fowler */ 7 | /* Jacob Moroni (jakemoroni@gmail.com) */ 8 | /* */ 9 | /* Description: This file implements the interface methods as */ 10 | /* well as the UDS protocol definitions required */ 11 | /* to communicate with a late model (2008+) */ 12 | /* BMW using the MCP2515 CANbus controller. */ 13 | /* */ 14 | /* Revision: Oct 12, 2015 */ 15 | /* */ 16 | /* Copyright (C) 2012 Seeed Technology Inc. All right reserved. */ 17 | /* */ 18 | /* This library is free software; you can redistribute it and/or */ 19 | /* modify it under the terms of the GNU Lesser General Public */ 20 | /* License as published by the Free Software Foundation; either */ 21 | /* version 2.1 of the License, or (at your option) any later */ 22 | /* version. */ 23 | /* This library is distributed in the hope that it will be */ 24 | /* useful, but WITHOUT ANY WARRANTY; without even the implied */ 25 | /* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR */ 26 | /* PURPOSE. See the GNU Lesser General Public License for more */ 27 | /* details. */ 28 | /* You should have received a copy of the GNU Lesser General */ 29 | /* Public License along with this library; if not, write to the */ 30 | /* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, */ 31 | /* Boston, MA 02110-1301 USA */ 32 | /********************************************************************/ 33 | 34 | /********************************************************************/ 35 | /* INCLUDES */ 36 | /********************************************************************/ 37 | 38 | /* Interface header. */ 39 | #include "MCPCANbusUDS.h" 40 | 41 | /********************************************************************/ 42 | /* FUNCTION DEFINITIONS */ 43 | /********************************************************************/ 44 | 45 | uint8_t MCP_CAN::mcp2515_readRegister(const uint8_t address) 46 | { 47 | uint8_t ret; 48 | MCP2515_SELECT(); 49 | spi_readwrite(MCP_READ); 50 | spi_readwrite(address); 51 | ret = spi_read(); 52 | MCP2515_UNSELECT(); 53 | return ret; 54 | } 55 | 56 | void MCP_CAN::mcp2515_readRegisterS(const uint8_t address, uint8_t values[], const uint8_t n) 57 | { 58 | uint8_t i; 59 | MCP2515_SELECT(); 60 | spi_readwrite(MCP_READ); 61 | spi_readwrite(address); 62 | /* Address will auto increment. */ 63 | for (i = 0; i < n; i++) 64 | { 65 | values[i] = spi_read(); 66 | } 67 | MCP2515_UNSELECT(); 68 | } 69 | 70 | void MCP_CAN::mcp2515_setRegister(const uint8_t address, const uint8_t value) 71 | { 72 | MCP2515_SELECT(); 73 | spi_readwrite(MCP_WRITE); 74 | spi_readwrite(address); 75 | spi_readwrite(value); 76 | MCP2515_UNSELECT(); 77 | } 78 | 79 | void MCP_CAN::mcp2515_setRegisterS(const uint8_t address, const uint8_t values[], const uint8_t n) 80 | { 81 | uint8_t i; 82 | MCP2515_SELECT(); 83 | spi_readwrite(MCP_WRITE); 84 | spi_readwrite(address); 85 | for (i = 0; i < n; i++) 86 | { 87 | spi_readwrite(values[i]); 88 | } 89 | MCP2515_UNSELECT(); 90 | } 91 | 92 | void MCP_CAN::mcp2515_modifyRegister(const uint8_t address, const uint8_t mask, const uint8_t data) 93 | { 94 | MCP2515_SELECT(); 95 | spi_readwrite(MCP_BITMOD); 96 | spi_readwrite(address); 97 | spi_readwrite(mask); 98 | spi_readwrite(data); 99 | MCP2515_UNSELECT(); 100 | } 101 | 102 | uint8_t MCP_CAN::mcp2515_readStatus(void) 103 | { 104 | uint8_t i; 105 | MCP2515_SELECT(); 106 | spi_readwrite(MCP_READ_STATUS); 107 | i = spi_read(); 108 | MCP2515_UNSELECT(); 109 | return i; 110 | } 111 | 112 | MCP2515_Ret_Val_E MCP_CAN::mcp2515_setCANCTRL_Mode(const uint8_t newmode) 113 | { 114 | uint16_t i; 115 | mcp2515_modifyRegister(MCP_CANCTRL, MODE_MASK, newmode); 116 | /* We must check the status bits to make sure the configuration took. */ 117 | /* It may take some time (the MCP2515 waits until all pending TX messages are sent */ 118 | /* before applying the mode change). */ 119 | for(i = 0; i < TIMEOUTVALUE; i++) 120 | { 121 | if((mcp2515_readRegister(MCP_CANSTAT) & MODE_MASK) == newmode) 122 | { 123 | /* Success. */ 124 | return MCP2515_OK; 125 | } 126 | } 127 | return MCP2515_FAIL; 128 | } 129 | 130 | MCP_CAN_Ret_Val_E MCP_CAN::mcp2515_init(const MCP_CAN_Speed_E canSpeed) 131 | { 132 | uint8_t i; 133 | 134 | /* Set registers to a known initial state. */ 135 | MCP2515_SELECT(); 136 | spi_readwrite(MCP_RESET); 137 | MCP2515_UNSELECT(); 138 | /* Wait some time for things to settle. */ 139 | delay(10); 140 | 141 | /* Enter configuration mode. */ 142 | if(mcp2515_setCANCTRL_Mode(MODE_CONFIG) != MCP2515_OK) 143 | { 144 | /* Failed to set config mode. */ 145 | return CAN_FAILINIT; 146 | } 147 | 148 | /* Set CAN speed. */ 149 | if(canSpeed == MCP_CAN_SPEED_500KBPS) 150 | { 151 | mcp2515_setRegister(MCP_CNF1, MCP_16MHz_500kBPS_CFG1); 152 | mcp2515_setRegister(MCP_CNF2, MCP_16MHz_500kBPS_CFG2); 153 | mcp2515_setRegister(MCP_CNF3, MCP_16MHz_500kBPS_CFG3); 154 | } 155 | else if(canSpeed == MCP_CAN_SPEED_250KBPS) 156 | { 157 | mcp2515_setRegister(MCP_CNF1, MCP_16MHz_250kBPS_CFG1); 158 | mcp2515_setRegister(MCP_CNF2, MCP_16MHz_250kBPS_CFG2); 159 | mcp2515_setRegister(MCP_CNF3, MCP_16MHz_250kBPS_CFG3); 160 | } 161 | else 162 | { 163 | return CAN_FAILINIT; 164 | } 165 | 166 | /* Initialize buffers. */ 167 | /* Clear and deactivate the three transmit buffers. */ 168 | for (i = 0; i < 14; i++) 169 | { 170 | mcp2515_setRegister(MCP_TXB0CTRL + i, 0); 171 | mcp2515_setRegister(MCP_TXB1CTRL + i, 0); 172 | mcp2515_setRegister(MCP_TXB2CTRL + i, 0); 173 | } 174 | mcp2515_setRegister(MCP_RXB0CTRL, 0); 175 | mcp2515_setRegister(MCP_RXB1CTRL, 0); 176 | 177 | /* Initialize interrupts (both RX buffers). */ 178 | mcp2515_setRegister(MCP_CANINTE, MCP_RX0IF | MCP_RX1IF); 179 | 180 | /* Enable both receive buffers to receive messages with std/ext identifiers */ 181 | /* and enable rollover. */ 182 | /* This means that if there's a match for buffer 1 but it's currently occupied, */ 183 | /* it will overflow in to buffer 2. However, if there's a match for buffer 2 and it's occupied, */ 184 | /* it will drop the message EVEN if buffer 1 is empty. */ 185 | mcp2515_modifyRegister(MCP_RXB0CTRL, 186 | MCP_RXB_RX_MASK | MCP_RXB_BUKT_MASK, 187 | MCP_RXB_RX_STDEXT | MCP_RXB_BUKT_MASK); 188 | mcp2515_modifyRegister(MCP_RXB1CTRL, MCP_RXB_RX_MASK, MCP_RXB_RX_STDEXT); 189 | 190 | /* Set to normal mode. */ 191 | if(mcp2515_setCANCTRL_Mode(MODE_NORMAL) != MCP2515_OK) 192 | { 193 | return CAN_FAILINIT; 194 | } 195 | return CAN_OK; 196 | } 197 | 198 | void MCP_CAN::mcp2515_write_id(const uint8_t mcp_addr, const uint8_t ext, const uint32_t id) 199 | { 200 | uint16_t canid; 201 | uint8_t tbufdata[4]; 202 | canid = (uint16_t)(id & 0x0FFFF); 203 | 204 | if(ext == 1) 205 | { 206 | tbufdata[MCP_EID0] = (uint8_t)(canid & 0xFF); 207 | tbufdata[MCP_EID8] = (uint8_t)(canid >> 8); 208 | canid = (uint16_t)(id >> 16); 209 | tbufdata[MCP_SIDL] = (uint8_t)(canid & 0x03); 210 | tbufdata[MCP_SIDL] += (uint8_t)((canid & 0x1C) << 3); 211 | tbufdata[MCP_SIDL] |= MCP_TXB_EXIDE_M; 212 | tbufdata[MCP_SIDH] = (uint8_t) (canid >> 5 ); 213 | } 214 | else 215 | { 216 | tbufdata[MCP_SIDH] = (uint8_t)(canid >> 3 ); 217 | tbufdata[MCP_SIDL] = (uint8_t)((canid & 0x07 ) << 5); 218 | tbufdata[MCP_EID0] = 0; 219 | tbufdata[MCP_EID8] = 0; 220 | } 221 | mcp2515_setRegisterS(mcp_addr, tbufdata, 4); 222 | } 223 | 224 | void MCP_CAN::mcp2515_read_id(const uint8_t mcp_addr, uint8_t * ext, uint32_t * id) 225 | { 226 | uint8_t tbufdata[4]; 227 | *ext = 0; 228 | *id = 0; 229 | mcp2515_readRegisterS(mcp_addr, tbufdata, 4); 230 | *id = (tbufdata[MCP_SIDH] << 3) + (tbufdata[MCP_SIDL] >> 5); 231 | if((tbufdata[MCP_SIDL] & MCP_TXB_EXIDE_M) == MCP_TXB_EXIDE_M) 232 | { 233 | *id = (*id << 2) + (tbufdata[MCP_SIDL] & 0x03); 234 | *id = (*id << 8) + tbufdata[MCP_EID8]; 235 | *id = (*id << 8) + tbufdata[MCP_EID0]; 236 | *ext = 1; 237 | } 238 | } 239 | 240 | void MCP_CAN::mcp2515_write_canMsg(const uint8_t buffer_sidh_addr) 241 | { 242 | uint8_t mcp_addr; 243 | mcp_addr = buffer_sidh_addr; 244 | mcp2515_setRegisterS(mcp_addr + 5, m_nDta, m_nDlc); 245 | if(m_nRtr == 1) 246 | { 247 | m_nDlc |= MCP_RTR_MASK; 248 | } 249 | mcp2515_setRegister((mcp_addr + 4), m_nDlc); 250 | mcp2515_write_id(mcp_addr, m_nExtFlg, m_nID); 251 | } 252 | 253 | void MCP_CAN::mcp2515_read_canMsg(const uint8_t buffer_sidh_addr) 254 | { 255 | uint8_t mcp_addr, ctrl; 256 | mcp_addr = buffer_sidh_addr; 257 | mcp2515_read_id(mcp_addr, &m_nExtFlg, &m_nID); 258 | ctrl = mcp2515_readRegister(mcp_addr - 1); 259 | m_nDlc = mcp2515_readRegister(mcp_addr + 4); 260 | if((ctrl & 0x08)) 261 | { 262 | m_nRtr = 1; 263 | } 264 | else 265 | { 266 | m_nRtr = 0; 267 | } 268 | m_nDlc &= MCP_DLC_MASK; 269 | mcp2515_readRegisterS(mcp_addr + 5, &(m_nDta[0]), m_nDlc); 270 | } 271 | 272 | MCP2515_Ret_Val_E MCP_CAN::mcp2515_getNextFreeTXBuf(uint8_t * txbuf_n) 273 | { 274 | uint8_t i; 275 | uint8_t ctrlregs[MCP_N_TXBUFFERS] = {MCP_TXB0CTRL, MCP_TXB1CTRL, MCP_TXB2CTRL}; 276 | *txbuf_n = 0x00; 277 | 278 | for (i = 0; i < MCP_N_TXBUFFERS; i++) 279 | { 280 | if((mcp2515_readRegister(ctrlregs[i]) & MCP_TXB_TXREQ_M) == 0) 281 | { 282 | *txbuf_n = ctrlregs[i] + 1; 283 | return MCP2515_OK; 284 | } 285 | } 286 | return MCP2515_ALLTXBUSY; 287 | } 288 | 289 | MCP_CAN::MCP_CAN(uint8_t _CS) 290 | { 291 | SPICS = _CS; 292 | pinMode(SPICS, OUTPUT); 293 | MCP2515_UNSELECT(); 294 | } 295 | 296 | MCP_CAN_Ret_Val_E MCP_CAN::begin(MCP_CAN_Speed_E speedset) 297 | { 298 | SPI.begin(); 299 | return mcp2515_init(speedset); 300 | } 301 | 302 | MCP_CAN_Ret_Val_E MCP_CAN::init_Mask(uint8_t num, uint8_t ext, uint32_t ulData) 303 | { 304 | /* Check for validity of input. */ 305 | if((num == 0) || (num == 1)) 306 | { 307 | /* Good. */ 308 | } 309 | else 310 | { 311 | return CAN_FAILINIT; 312 | } 313 | 314 | if(mcp2515_setCANCTRL_Mode(MODE_CONFIG) != MCP2515_OK) 315 | { 316 | return CAN_FAILINIT; 317 | } 318 | if(num == 0) 319 | { 320 | mcp2515_write_id(MCP_RXM0SIDH, ext, ulData); 321 | } 322 | else 323 | { 324 | mcp2515_write_id(MCP_RXM1SIDH, ext, ulData); 325 | } 326 | if(mcp2515_setCANCTRL_Mode(MODE_NORMAL) != MCP2515_OK) 327 | { 328 | return CAN_FAILINIT; 329 | } 330 | return CAN_OK; 331 | } 332 | 333 | MCP_CAN_Ret_Val_E MCP_CAN::init_Filt(uint8_t num, uint8_t ext, uint32_t ulData) 334 | { 335 | /* Check for validity of input. */ 336 | if((num == 0) || 337 | (num == 1) || 338 | (num == 2) || 339 | (num == 3) || 340 | (num == 4) || 341 | (num == 5)) 342 | { 343 | /* Good. */ 344 | } 345 | else 346 | { 347 | return CAN_FAILINIT; 348 | } 349 | 350 | if(mcp2515_setCANCTRL_Mode(MODE_CONFIG) != MCP2515_OK) 351 | { 352 | return CAN_FAILINIT; 353 | } 354 | switch(num) 355 | { 356 | case 0: 357 | mcp2515_write_id(MCP_RXF0SIDH, ext, ulData); 358 | break; 359 | case 1: 360 | mcp2515_write_id(MCP_RXF1SIDH, ext, ulData); 361 | break; 362 | case 2: 363 | mcp2515_write_id(MCP_RXF2SIDH, ext, ulData); 364 | break; 365 | case 3: 366 | mcp2515_write_id(MCP_RXF3SIDH, ext, ulData); 367 | break; 368 | case 4: 369 | mcp2515_write_id(MCP_RXF4SIDH, ext, ulData); 370 | break; 371 | case 5: 372 | mcp2515_write_id(MCP_RXF5SIDH, ext, ulData); 373 | break; 374 | default: 375 | break; 376 | } 377 | if(mcp2515_setCANCTRL_Mode(MODE_NORMAL) != MCP2515_OK) 378 | { 379 | return CAN_FAILINIT; 380 | } 381 | return CAN_OK; 382 | } 383 | 384 | void MCP_CAN::setMsg(uint32_t id, uint8_t ext, uint8_t len, uint8_t * pData) 385 | { 386 | uint8_t i; 387 | m_nExtFlg = ext; 388 | m_nID = id; 389 | m_nDlc = len; 390 | for(i = 0; i < MCP_CAN_MAX_MSG_LEN; i++) 391 | { 392 | m_nDta[i] = *(pData + i); 393 | } 394 | } 395 | 396 | MCP_CAN_Ret_Val_E MCP_CAN::sendMsg() 397 | { 398 | uint8_t txbuf_n; 399 | uint16_t i = 0; 400 | 401 | /* Wait for a TX buffer. */ 402 | for(i = 0; i < TIMEOUTVALUE; i++) 403 | { 404 | if(mcp2515_getNextFreeTXBuf(&txbuf_n) == MCP2515_OK) 405 | { 406 | /* We have an open TX buffer. Address is loaded to txbuf_n. */ 407 | /* Write msg to HW. */ 408 | mcp2515_write_canMsg(txbuf_n); 409 | /* Trigger send. One byte before the buffer is the buffer's control register. */ 410 | mcp2515_modifyRegister(txbuf_n - 1, MCP_TXB_TXREQ_M, MCP_TXB_TXREQ_M); 411 | return CAN_OK; 412 | } 413 | } 414 | return CAN_GETTXBFTIMEOUT; 415 | } 416 | 417 | MCP_CAN_Ret_Val_E MCP_CAN::sendMsgBuf(uint32_t id, uint8_t ext, uint8_t len, uint8_t *buf) 418 | { 419 | setMsg(id, ext, len, buf); 420 | return sendMsg(); 421 | } 422 | 423 | MCP_CAN_Ret_Val_E MCP_CAN::readMsg() 424 | { 425 | uint8_t stat; 426 | MCP_CAN_Ret_Val_E res; 427 | 428 | stat = mcp2515_readStatus(); 429 | 430 | if(stat & MCP_STAT_RX0IF) 431 | { 432 | mcp2515_read_canMsg(MCP_RXBUF_0); 433 | mcp2515_modifyRegister(MCP_CANINTF, MCP_RX0IF, 0); 434 | res = CAN_OK; 435 | } 436 | else if(stat & MCP_STAT_RX1IF) 437 | { 438 | mcp2515_read_canMsg(MCP_RXBUF_1); 439 | mcp2515_modifyRegister(MCP_CANINTF, MCP_RX1IF, 0); 440 | res = CAN_OK; 441 | } 442 | else 443 | { 444 | res = CAN_NOMSG; 445 | } 446 | return res; 447 | } 448 | 449 | MCP_CAN_Ret_Val_E MCP_CAN::readMsgBuf(uint8_t * len, uint8_t buf[]) 450 | { 451 | MCP_CAN_Ret_Val_E rc; 452 | 453 | rc = readMsg(); 454 | 455 | if (rc == CAN_OK) 456 | { 457 | *len = m_nDlc; 458 | for(int i = 0; i < m_nDlc; i++) 459 | { 460 | buf[i] = m_nDta[i]; 461 | } 462 | } 463 | else 464 | { 465 | *len = 0; 466 | } 467 | return rc; 468 | } 469 | 470 | MCP_CAN_Ret_Val_E MCP_CAN::checkReceive(void) 471 | { 472 | uint8_t res; 473 | res = mcp2515_readStatus(); 474 | if(res & MCP_STAT_RXIF_MASK) 475 | { 476 | return CAN_MSGAVAIL; 477 | } 478 | else 479 | { 480 | return CAN_NOMSG; 481 | } 482 | } 483 | 484 | uint32_t MCP_CAN::getCanId(void) 485 | { 486 | return m_nID; 487 | } 488 | -------------------------------------------------------------------------------- /MethService.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************************/ 2 | /* Methanol Injection Service Implementation */ 3 | /* MethService.cpp */ 4 | /* */ 5 | /* Author: Jacob Moroni (jakemoroni@gmail.com) */ 6 | /* */ 7 | /* Description: This file implements the methanol injection */ 8 | /* service. This is one of many possible */ 9 | /* services that can be incorporated into the */ 10 | /* main controller. */ 11 | /* */ 12 | /* Revision: Oct 12, 2015 (First) */ 13 | /* */ 14 | /* Copyright (C) 2015 Jacob Moroni. All right reserved. */ 15 | /* */ 16 | /* This library is free software; you can redistribute it and/or */ 17 | /* modify it under the terms of the GNU Lesser General Public */ 18 | /* License as published by the Free Software Foundation; either */ 19 | /* version 2.1 of the License, or (at your option) any later */ 20 | /* version. */ 21 | /* This library is distributed in the hope that it will be */ 22 | /* useful, but WITHOUT ANY WARRANTY; without even the implied */ 23 | /* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR */ 24 | /* PURPOSE. See the GNU Lesser General Public License for more */ 25 | /* details. */ 26 | /* You should have received a copy of the GNU Lesser General */ 27 | /* Public License along with this library; if not, write to the */ 28 | /* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, */ 29 | /* Boston, MA 02110-1301 USA */ 30 | /********************************************************************/ 31 | 32 | /********************************************************************/ 33 | /* INCLUDES */ 34 | /********************************************************************/ 35 | 36 | /* Implementation header. */ 37 | #include "MethService.h" 38 | 39 | /* TimedAction library. This handles the deferred tasks. */ 40 | #include "TimedAction.h" 41 | 42 | /* Include the MCP2515 API. We send CAN messages directly from */ 43 | /* this service. */ 44 | #include "MCPCANbusUDS.h" 45 | 46 | /********************************************************************/ 47 | /* EXTERNAL LINKAGES */ 48 | /********************************************************************/ 49 | 50 | /* Link to the main CAN class that's been defined in the ControllerMain */ 51 | /* file. */ 52 | extern MCP_CAN CAN; 53 | 54 | /********************************************************************/ 55 | /* STATIC FUNCTION PROTOTYPES */ 56 | /********************************************************************/ 57 | 58 | /* FSM state transition functions. */ 59 | static MethServiceState_E _fsmNOOP(void * arg); 60 | static MethServiceState_E _fsmReInit(void * arg); 61 | static MethServiceState_E _fsmFailure(void * arg); 62 | static MethServiceState_E _fsmDisable(void * arg); 63 | static MethServiceState_E _fsmEnterInjecting(void * arg); 64 | static MethServiceState_E _fsmLowTank(void * arg); 65 | static MethServiceState_E _fsmReady(void * arg); 66 | static MethServiceState_E _fsmDisabledWarn(void * arg); 67 | static MethServiceState_E _fsmRXMsg(void * arg); 68 | 69 | /* Helper functions. */ 70 | static void _stopInjecting(void); 71 | static void _tripFailSafe(void); 72 | static void _untripFailSafe(void); 73 | static double _unscaledKilogramsPerHrToCCPerMin(uint16_t kgPerHour); 74 | static double _linearInterpolation(double x0, double x1, double y0, double y1, double x); 75 | static void _injectPWMEnable(double dutyCycle); 76 | static void _fuelLoadRequestSend(void); 77 | static void _runMethServiceFSM(MethServiceEvent_E event, void * arg); 78 | 79 | /********************************************************************/ 80 | /* STATIC GLOBAL VARIABLES */ 81 | /********************************************************************/ 82 | 83 | /* This variable keeps track of this service's state. */ 84 | /* Initialization doesn't matter. */ 85 | static MethServiceState_E _state = METH_SERVICE_STATE_FAILURE; 86 | 87 | /* This keeps track of the number of unanswered fuel load requests. */ 88 | /* This is used to transition in to the failure state if we miss */ 89 | /* too many samples. */ 90 | /* Initialization doesn't matter. */ 91 | static uint32_t _fuelLoadReqPendingCount = 0; 92 | 93 | /* This "task" handles sending the requests for the fuel load. */ 94 | static TimedAction _fuelLoadRequestTimer = TimedAction(METH_SERVICE_FUEL_LOAD_REQUEST_PERIOD_MS, 95 | _fuelLoadRequestSend); 96 | 97 | /* Table of FSM state transitions. */ 98 | static MethServiceFSMTransition_T _transitions[] = 99 | { 100 | /* If we are in ANY state and we get the following events... */ 101 | {METH_SERVICE_STATE_ANY, METH_SERVICE_EVENT_SAMPLE_TIMEOUT, _fsmFailure}, 102 | {METH_SERVICE_STATE_ANY, METH_SERVICE_EVENT_EXT_FAILURE, _fsmFailure}, 103 | {METH_SERVICE_STATE_ANY, METH_SERVICE_EVENT_POWERUP, _fsmFailure}, 104 | {METH_SERVICE_STATE_ANY, METH_SERVICE_EVENT_RESTART, _fsmReInit}, 105 | 106 | /* If we are in the FAILURE state... */ 107 | {METH_SERVICE_STATE_FAILURE, METH_SERVICE_EVENT_DISABLE_TRUE, _fsmNOOP}, 108 | {METH_SERVICE_STATE_FAILURE, METH_SERVICE_EVENT_DISABLE_FALSE, _fsmNOOP}, 109 | {METH_SERVICE_STATE_FAILURE, METH_SERVICE_EVENT_FUEL_LOAD_ABOVE_UPPER, _fsmNOOP}, 110 | {METH_SERVICE_STATE_FAILURE, METH_SERVICE_EVENT_FUEL_LOAD_BELOW_LOWER, _fsmNOOP}, 111 | {METH_SERVICE_STATE_FAILURE, METH_SERVICE_EVENT_TANK_EMPTY_TRUE, _fsmNOOP}, 112 | {METH_SERVICE_STATE_FAILURE, METH_SERVICE_EVENT_MSG_RX, _fsmNOOP}, 113 | 114 | /* If we are in the READY_ARMED state... */ 115 | {METH_SERVICE_STATE_READY_ARMED, METH_SERVICE_EVENT_DISABLE_TRUE, _fsmDisable}, 116 | {METH_SERVICE_STATE_READY_ARMED, METH_SERVICE_EVENT_DISABLE_FALSE, _fsmNOOP}, 117 | {METH_SERVICE_STATE_READY_ARMED, METH_SERVICE_EVENT_FUEL_LOAD_ABOVE_UPPER, _fsmEnterInjecting}, 118 | {METH_SERVICE_STATE_READY_ARMED, METH_SERVICE_EVENT_FUEL_LOAD_BELOW_LOWER, _fsmNOOP}, 119 | {METH_SERVICE_STATE_READY_ARMED, METH_SERVICE_EVENT_TANK_EMPTY_TRUE, _fsmLowTank}, 120 | {METH_SERVICE_STATE_READY_ARMED, METH_SERVICE_EVENT_MSG_RX, _fsmNOOP}, 121 | 122 | /* If we are in the INJECTING state... */ 123 | {METH_SERVICE_STATE_INJECTING, METH_SERVICE_EVENT_DISABLE_TRUE, _fsmDisable}, 124 | {METH_SERVICE_STATE_INJECTING, METH_SERVICE_EVENT_DISABLE_FALSE, _fsmNOOP}, 125 | {METH_SERVICE_STATE_INJECTING, METH_SERVICE_EVENT_FUEL_LOAD_ABOVE_UPPER, _fsmNOOP}, 126 | {METH_SERVICE_STATE_INJECTING, METH_SERVICE_EVENT_FUEL_LOAD_BELOW_LOWER, _fsmReady}, 127 | {METH_SERVICE_STATE_INJECTING, METH_SERVICE_EVENT_TANK_EMPTY_TRUE, _fsmLowTank}, 128 | {METH_SERVICE_STATE_INJECTING, METH_SERVICE_EVENT_MSG_RX, _fsmRXMsg}, 129 | 130 | /* If we are in the DISABLED state... */ 131 | {METH_SERVICE_STATE_DISABLED, METH_SERVICE_EVENT_DISABLE_TRUE, _fsmNOOP}, 132 | {METH_SERVICE_STATE_DISABLED, METH_SERVICE_EVENT_DISABLE_FALSE, _fsmReady}, 133 | {METH_SERVICE_STATE_DISABLED, METH_SERVICE_EVENT_FUEL_LOAD_ABOVE_UPPER, _fsmDisabledWarn}, 134 | {METH_SERVICE_STATE_DISABLED, METH_SERVICE_EVENT_FUEL_LOAD_BELOW_LOWER, _fsmNOOP}, 135 | {METH_SERVICE_STATE_DISABLED, METH_SERVICE_EVENT_TANK_EMPTY_TRUE, _fsmNOOP}, 136 | {METH_SERVICE_STATE_DISABLED, METH_SERVICE_EVENT_MSG_RX, _fsmNOOP}, 137 | 138 | /* If we are in the DISABLED_WARN state... */ 139 | {METH_SERVICE_STATE_DISABLED_WARN, METH_SERVICE_EVENT_DISABLE_TRUE, _fsmNOOP}, 140 | {METH_SERVICE_STATE_DISABLED_WARN, METH_SERVICE_EVENT_DISABLE_FALSE, _fsmReady}, 141 | {METH_SERVICE_STATE_DISABLED_WARN, METH_SERVICE_EVENT_FUEL_LOAD_ABOVE_UPPER, _fsmNOOP}, 142 | {METH_SERVICE_STATE_DISABLED_WARN, METH_SERVICE_EVENT_FUEL_LOAD_BELOW_LOWER, _fsmDisable}, 143 | {METH_SERVICE_STATE_DISABLED_WARN, METH_SERVICE_EVENT_TANK_EMPTY_TRUE, _fsmNOOP}, 144 | {METH_SERVICE_STATE_DISABLED_WARN, METH_SERVICE_EVENT_MSG_RX, _fsmNOOP}, 145 | 146 | /* If we are in the LOW_TANK state... */ 147 | {METH_SERVICE_STATE_LOW_TANK, METH_SERVICE_EVENT_DISABLE_TRUE, _fsmDisable}, 148 | {METH_SERVICE_STATE_LOW_TANK, METH_SERVICE_EVENT_DISABLE_FALSE, _fsmNOOP}, 149 | {METH_SERVICE_STATE_LOW_TANK, METH_SERVICE_EVENT_FUEL_LOAD_ABOVE_UPPER, _fsmNOOP}, 150 | {METH_SERVICE_STATE_LOW_TANK, METH_SERVICE_EVENT_FUEL_LOAD_BELOW_LOWER, _fsmNOOP}, 151 | {METH_SERVICE_STATE_LOW_TANK, METH_SERVICE_EVENT_TANK_EMPTY_TRUE, _fsmNOOP}, 152 | {METH_SERVICE_STATE_LOW_TANK, METH_SERVICE_EVENT_MSG_RX, _fsmNOOP}, 153 | 154 | /* This entry must be at the bottom to catch any FSM program errors. */ 155 | /* Every event should be acted upon. */ 156 | {METH_SERVICE_STATE_ANY, METH_SERVICE_EVENT_ANY, _fsmFailure} 157 | }; 158 | #define METH_SERVICE_NUM_FSM_TRANSITIONS (sizeof(_transitions)/sizeof(*_transitions)) 159 | 160 | /********************************************************************/ 161 | /* STATIC FUNCTION DEFINITIONS */ 162 | /********************************************************************/ 163 | 164 | /* This function turns off the meth pump and solenoid. */ 165 | static void _stopInjecting(void) 166 | { 167 | /* Turn off the solenoid. */ 168 | analogWrite(METH_SERVICE_PWM_OUTPUT_PIN, 0); 169 | 170 | /* Turn off pump. */ 171 | digitalWrite(METH_SERVICE_PUMP_OUTPUT_PIN, LOW); 172 | } 173 | 174 | /* This function activates the failsafe relay. */ 175 | static void _tripFailSafe(void) 176 | { 177 | digitalWrite(METH_SERVICE_FAILSAFE_OUTPUT_PIN, HIGH); 178 | } 179 | 180 | /* This function de-activates the failsafe relay. */ 181 | static void _untripFailSafe(void) 182 | { 183 | digitalWrite(METH_SERVICE_FAILSAFE_OUTPUT_PIN, LOW); 184 | } 185 | 186 | /* This function converts the raw kilograms per hour value from the ECU */ 187 | /* to CC/Min. */ 188 | /* It takes in to account the specific gravity of gasoline which is around .730. */ 189 | static double _unscaledKilogramsPerHrToCCPerMin(uint16_t kgPerHour) 190 | { 191 | return ((((double)kgPerHour * UDS_CAN_FUEL_LOAD_KG_TO_L_MULT_SCALAR) * (double)1000.0)) / (double)60.0; 192 | } 193 | 194 | /* This function performs a linear interpolation. */ 195 | static double _linearInterpolation(double x0, double x1, double y0, double y1, double x) 196 | { 197 | if(x1 != x0) 198 | { 199 | double a = (y1 - y0) / (x1 - x0); 200 | double b = -a * x0 + y0; 201 | return (a * x + b); 202 | } 203 | else 204 | { 205 | return y0; 206 | } 207 | } 208 | 209 | /* This function turns on the pump and sets the solenoid for the */ 210 | /* specified PWM duty cycle. */ 211 | static void _injectPWMEnable(double dutyCycle) 212 | { 213 | /* Turn on pump. */ 214 | digitalWrite(METH_SERVICE_PUMP_OUTPUT_PIN, HIGH); 215 | 216 | /* Set PWM output. */ 217 | analogWrite(METH_SERVICE_PWM_OUTPUT_PIN, (uint8_t)(dutyCycle * 0xFF / 100.0)); 218 | } 219 | 220 | /* This function transmits a UDS request for the current fuel load. */ 221 | /* It gets called periodically by the timer task. */ 222 | static void _fuelLoadRequestSend(void) 223 | { 224 | if(_fuelLoadReqPendingCount >= METH_SERVICE_FUEL_LOAD_SAMPLE_ERROR_LIMIT) 225 | { 226 | /* We have sent X requests already and still have not received */ 227 | /* a response. We must shut down all methanol spraying and handle */ 228 | /* the failure. */ 229 | _runMethServiceFSM(METH_SERVICE_EVENT_SAMPLE_TIMEOUT, NULL); 230 | } 231 | else 232 | { 233 | if(CAN.sendMsgBuf(UDS_CAN_TRANSMIT_ID, 234 | 0, 235 | MCP_CAN_MAX_MSG_LEN, 236 | (unsigned char *)UDS_CAN_FUEL_LOAD_REQUEST_MSG_PTR) != CAN_OK) 237 | { 238 | /* There was no room in the transmit FIFO. This should never happen. */ 239 | _runMethServiceFSM(METH_SERVICE_EVENT_SAMPLE_TIMEOUT, NULL); 240 | return; 241 | } 242 | _fuelLoadReqPendingCount++; 243 | } 244 | return; 245 | } 246 | 247 | /* ------- FSM state transition functions. ------- */ 248 | 249 | /* This function does nothing. It is used for events */ 250 | /* that we don't care about when we're in the current state. */ 251 | static MethServiceState_E _fsmNOOP(void * arg) 252 | { 253 | return _state; 254 | } 255 | 256 | /* This function initializes the system. It can */ 257 | /* be called from ANY state and thus must initialize every */ 258 | /* variable. */ 259 | static MethServiceState_E _fsmReInit(void * arg) 260 | { 261 | /* Stop injecting. We don't know which state we are coming from. */ 262 | _stopInjecting(); 263 | /* Reset the failsafe. */ 264 | _untripFailSafe(); 265 | /* Start all of the timers. */ 266 | _fuelLoadRequestTimer.start(); 267 | _fuelLoadReqPendingCount = 0; 268 | return METH_SERVICE_STATE_READY_ARMED; 269 | } 270 | 271 | /* This function is called when one of the failure-inducing events */ 272 | /* occurs. This can be called from ANY state. */ 273 | static MethServiceState_E _fsmFailure(void * arg) 274 | { 275 | /* Stop injecting. We don't know which state we are coming from. */ 276 | _stopInjecting(); 277 | /* Trip the failsafe. */ 278 | _tripFailSafe(); 279 | /* Stop all of the timers. */ 280 | _fuelLoadRequestTimer.stop(); 281 | return METH_SERVICE_STATE_FAILURE; 282 | } 283 | 284 | /* This function gets called when we are to enter the DISABLED state. */ 285 | static MethServiceState_E _fsmDisable(void * arg) 286 | { 287 | /* Stop injecting. We don't know which state we are coming from. */ 288 | _stopInjecting(); 289 | /* Trip the failsafe. */ 290 | _tripFailSafe(); 291 | return METH_SERVICE_STATE_DISABLED; 292 | } 293 | 294 | /* This function is called only from the READY_ARMED state. */ 295 | /* This allows the system to accept injection events. */ 296 | static MethServiceState_E _fsmEnterInjecting(void * arg) 297 | { 298 | return METH_SERVICE_STATE_INJECTING; 299 | } 300 | 301 | /* This function gets called when we are to enter the LOW_TANK state. */ 302 | static MethServiceState_E _fsmLowTank(void * arg) 303 | { 304 | /* Stop injecting. We don't know which state we are coming from. */ 305 | _stopInjecting(); 306 | /* Trip the failsafe. */ 307 | _tripFailSafe(); 308 | return METH_SERVICE_STATE_LOW_TANK; 309 | } 310 | 311 | /* This function gets called when we are to re-enter the READY_ARMED state. */ 312 | static MethServiceState_E _fsmReady(void * arg) 313 | { 314 | /* Stop injecting. We don't know which state we are coming from. */ 315 | _stopInjecting(); 316 | /* Reset the failsafe. */ 317 | _untripFailSafe(); 318 | return METH_SERVICE_STATE_READY_ARMED; 319 | } 320 | 321 | /* This function gets called when we go from the */ 322 | /* DISABLED state to the DISABLED_WARN state. */ 323 | static MethServiceState_E _fsmDisabledWarn(void * arg) 324 | { 325 | return METH_SERVICE_STATE_DISABLED_WARN; 326 | } 327 | 328 | /* This function actually handles the progressive meth spray. */ 329 | static MethServiceState_E _fsmRXMsg(void * arg) 330 | { 331 | uint32_t i; 332 | double desiredMethFlowCC = 0.0; 333 | double desiredMethPWM = 0.0; 334 | /* TODO - Check for NULL ptr. */ 335 | uint8_t * msg = (uint8_t *)arg; 336 | double ccPerMin = 337 | _unscaledKilogramsPerHrToCCPerMin((((uint16_t)msg[UDS_CAN_RX_RESP_DATA_BYTE_0_IDX]) << 8) | 338 | msg[UDS_CAN_RX_RESP_DATA_BYTE_1_IDX]); 339 | 340 | /* First, find the desired meth flow percentage based on the current */ 341 | /* fuel delivery rate. */ 342 | /* Find points it falls between... */ 343 | for(i = 0; i < METH_SERVICE_TABLE_SIZE; i++) 344 | { 345 | if(ccPerMin < METH_SERVICE_FUEL_DELIVERY_RATE_ARRAY[i]) 346 | { 347 | break; 348 | } 349 | } 350 | if(i == METH_SERVICE_TABLE_SIZE) 351 | { 352 | /* It's greater than or equal to the highest X value. */ 353 | /* Don't interpolate; use last value. */ 354 | desiredMethFlowCC = 355 | (METH_SERVICE_DESIRED_METH_FLOW_FUEL_DELIVERY_PERCENTAGE[METH_SERVICE_TABLE_SIZE - 1] * ccPerMin) / 100.0; 356 | } 357 | else 358 | { 359 | desiredMethFlowCC = (_linearInterpolation(METH_SERVICE_FUEL_DELIVERY_RATE_ARRAY[i - 1], 360 | METH_SERVICE_FUEL_DELIVERY_RATE_ARRAY[i], 361 | METH_SERVICE_DESIRED_METH_FLOW_FUEL_DELIVERY_PERCENTAGE[i - 1], 362 | METH_SERVICE_DESIRED_METH_FLOW_FUEL_DELIVERY_PERCENTAGE[i], 363 | ccPerMin) * ccPerMin) / 100.0; 364 | } 365 | 366 | /* Now, find the required PWM output for this desired meth flow CC. */ 367 | /* Find points it falls between. */ 368 | for(i = 0; i < METH_SERVICE_TABLE_SIZE; i++) 369 | { 370 | if(desiredMethFlowCC < METH_SERVICE_DESIRED_METH_FLOW_CC_MIN_ARRAY[i]) 371 | { 372 | break; 373 | } 374 | } 375 | if(i == METH_SERVICE_TABLE_SIZE) 376 | { 377 | /* It's greater than or equal to the highest X value. */ 378 | /* Don't interpolate; use last value. */ 379 | desiredMethPWM = METH_SERVICE_DESIRED_METH_FLOW_PWM_ARRAY[METH_SERVICE_TABLE_SIZE - 1]; 380 | } 381 | else 382 | { 383 | desiredMethPWM = _linearInterpolation(METH_SERVICE_DESIRED_METH_FLOW_CC_MIN_ARRAY[i - 1], 384 | METH_SERVICE_DESIRED_METH_FLOW_CC_MIN_ARRAY[i], 385 | METH_SERVICE_DESIRED_METH_FLOW_PWM_ARRAY[i - 1], 386 | METH_SERVICE_DESIRED_METH_FLOW_PWM_ARRAY[i], 387 | desiredMethFlowCC); 388 | } 389 | 390 | /* Set outputs. */ 391 | _injectPWMEnable(desiredMethPWM); 392 | 393 | /* Debug statements. */ 394 | #if defined(METH_SERVICE_SERIAL_DEBUG) 395 | Serial.print("DUTY: "); 396 | Serial.println(desiredMethPWM, 2); 397 | #endif 398 | 399 | return _state; 400 | } 401 | 402 | /* This function executes the state machine. */ 403 | static void _runMethServiceFSM(MethServiceEvent_E event, void * arg) 404 | { 405 | uint32_t i; 406 | for(i = 0; i < METH_SERVICE_NUM_FSM_TRANSITIONS; i++) 407 | { 408 | if((_state == _transitions[i].state) || (METH_SERVICE_STATE_ANY == _transitions[i].state)) 409 | { 410 | if((event == _transitions[i].event) || (METH_SERVICE_EVENT_ANY == _transitions[i].event)) 411 | { 412 | _state = (_transitions[i].func)(arg); 413 | /* Only one transition can exist per event. */ 414 | break; 415 | } 416 | } 417 | } 418 | } 419 | 420 | /********************************************************************/ 421 | /* GLOBAL FUNCTION DEFINITIONS */ 422 | /********************************************************************/ 423 | 424 | void MethServiceInitEarly(void) 425 | { 426 | /* Configure all pin directions and initial states. */ 427 | /* Initial state should be low anyway... */ 428 | TCCR1B = (TCCR1B & 0xF8) | 0x05; /* Set PWM frequency to ~30 Hz. */ 429 | pinMode(METH_SERVICE_PWM_OUTPUT_PIN, OUTPUT); 430 | analogWrite(METH_SERVICE_PWM_OUTPUT_PIN, 0); 431 | pinMode(METH_SERVICE_PUMP_OUTPUT_PIN, OUTPUT); 432 | digitalWrite(METH_SERVICE_PUMP_OUTPUT_PIN, LOW); 433 | pinMode(METH_SERVICE_FAILSAFE_OUTPUT_PIN, OUTPUT); 434 | digitalWrite(METH_SERVICE_FAILSAFE_OUTPUT_PIN, HIGH); /* Failsafe init ON. */ 435 | pinMode(METH_SERVICE_TANK_LEVEL_INPUT_PIN, INPUT_PULLUP); 436 | pinMode(METH_SERVICE_DISABLE_INPUT_PIN, INPUT_PULLUP); 437 | 438 | /* Wait 20 milliseconds for input pins to settle. */ 439 | /* This prevents a false jump to the DISABLED or LOW_TANK state */ 440 | /* when we check the input pins in the exec loop the first time. */ 441 | delay(20); 442 | 443 | /* Push POWERUP event to FSM. */ 444 | _runMethServiceFSM(METH_SERVICE_EVENT_POWERUP, NULL); 445 | } 446 | 447 | void MethServiceInitLate(void) 448 | { 449 | /* Push RESTART event to FSM. */ 450 | _runMethServiceFSM(METH_SERVICE_EVENT_RESTART, NULL); 451 | } 452 | 453 | void MethServiceExec(void) 454 | { 455 | /* Check the disable input pin. Push event depending on state. */ 456 | /* NOTE: The pin is active LOW. */ 457 | if(digitalRead(METH_SERVICE_DISABLE_INPUT_PIN) == HIGH) 458 | { 459 | _runMethServiceFSM(METH_SERVICE_EVENT_DISABLE_FALSE, NULL); 460 | } 461 | else 462 | { 463 | _runMethServiceFSM(METH_SERVICE_EVENT_DISABLE_TRUE, NULL); 464 | } 465 | 466 | /* Check tank level sensor. */ 467 | if(digitalRead(METH_SERVICE_TANK_LEVEL_INPUT_PIN) == HIGH) 468 | { 469 | /* All good. */ 470 | } 471 | else 472 | { 473 | /* Pin has been grounded. Tank must be empty. */ 474 | /* TODO - Check to see if the sensor is NC or NO. */ 475 | /* This will work if sensor is not connected... */ 476 | _runMethServiceFSM(METH_SERVICE_EVENT_TANK_EMPTY_TRUE, NULL); 477 | } 478 | 479 | /* Tick all timers... */ 480 | _fuelLoadRequestTimer.check(); 481 | } 482 | 483 | void MethServiceRXFuelLoadMsg(uint8_t * msg) 484 | { 485 | double ccPerMin = 486 | _unscaledKilogramsPerHrToCCPerMin((((uint16_t)msg[UDS_CAN_RX_RESP_DATA_BYTE_0_IDX]) << 8) | 487 | msg[UDS_CAN_RX_RESP_DATA_BYTE_1_IDX]); 488 | 489 | /* Qualify the message based on thresholds. */ 490 | /* This may cause a state change, so we do it before pushing the message. */ 491 | if(ccPerMin < METH_SERVICE_FUEL_LOAD_LOWER_BOUND) 492 | { 493 | _runMethServiceFSM(METH_SERVICE_EVENT_FUEL_LOAD_BELOW_LOWER, NULL); 494 | } 495 | if(ccPerMin > METH_SERVICE_FUEL_LOAD_UPPER_BOUND) 496 | { 497 | _runMethServiceFSM(METH_SERVICE_EVENT_FUEL_LOAD_ABOVE_UPPER, NULL); 498 | } 499 | 500 | /* Process received message if the state permits us. */ 501 | _runMethServiceFSM(METH_SERVICE_EVENT_MSG_RX, msg); 502 | 503 | /* Clear pending request counter. */ 504 | _fuelLoadReqPendingCount = 0; 505 | 506 | /* Debug statements. */ 507 | #if defined(METH_SERVICE_SERIAL_DEBUG) 508 | Serial.print("FUEL: "); 509 | Serial.println(ccPerMin, 2); 510 | #endif 511 | } 512 | 513 | void MethServiceAbort(void) 514 | { 515 | /* Process received abort message. */ 516 | /* We must disable the spraying of methanol, stop all request timers, */ 517 | /* and transition to a failure state so that further messages won't re-arm the spray. */ 518 | _runMethServiceFSM(METH_SERVICE_EVENT_EXT_FAILURE, NULL); 519 | } 520 | 521 | MethServiceState_E MethServiceGetState(void) 522 | { 523 | return _state; 524 | } 525 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | (This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.) 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | {description} 474 | Copyright (C) {year} {fullname} 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | {signature of Ty Coon}, 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | 506 | --------------------------------------------------------------------------------