// C library headers #include #include #include // Linux headers #include // Contains file controls like O_RDWR #include // Error integer and strerror() function #include // Contains POSIX terminal control definitions #include // write(), read(), close() #include #include #include #include #include #include #include #include #include //=================================== // for the socket server code int server_socket_fd = 0; struct sockaddr_in addr; //=================================== char read_buf[256]; int serial_port; FILE *log_file; char logFileName[] = "/home/etornick/transmission-control/server-log.txt"; char transmissionTemperatureString[20] = "000"; // This will hold the current transmission temperature read from the elm device int transmissionTemperature = 0; char filename[40]; struct tm *timenow; struct termios tty; // Create new termios structure int result; int checkAndRespondToTemperatureRequest() { char client_message[20]; // Look for a message requesting the transmission temp int client_socket_fd = accept(server_socket_fd, NULL, NULL); if (client_socket_fd == -1) { if (errno == EWOULDBLOCK) { //fprintf(log_file, "socket acceept error - just continue on\n"); //fflush(log_file); ; } else if (errno == EAGAIN || errno == ENONET || errno == EPROTO || errno == ENOPROTOOPT || errno == EOPNOTSUPP || errno == ENETDOWN || errno == ENETUNREACH || errno == EHOSTDOWN || errno == EHOSTUNREACH || errno == ECONNABORTED) { fprintf(log_file, "error accepting connection: Error: %i \n",errno); fflush(log_file); close(client_socket_fd); return (-1); } } else { fprintf(log_file, "Client connected at IP: %s and port: %i\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port)); ssize_t received_message_length = recv(client_socket_fd, client_message, sizeof(client_message), 0); fprintf(log_file, "Msg from client: %s\n", client_message); fflush(log_file); if (send(client_socket_fd, transmissionTemperatureString, strlen(transmissionTemperatureString), 0) < 0) { fprintf(log_file, "Can't send to client so restarting\n"); fflush(log_file); close(client_socket_fd); return (-1); } else { // Send of temperature to client was successful fprintf(log_file, "Sent %s degrees fahrenheit to client\n", transmissionTemperatureString); fflush(log_file); close(client_socket_fd); } } return (0); } int openSocketToGetTemperatureRequests() { if (server_socket_fd != 0){ // This routine has already executed once and we have a server socket to listen to messages. // Because I couldn't figure out how to close a server socket and enable it to be immediately // opened again this was the only solution. This routine will only execute once when the program // is started. return(0); } server_socket_fd = socket(AF_INET, SOCK_STREAM, 0); if (server_socket_fd < 0) { fprintf(log_file, "Couldn't open server socket\n"); fflush(log_file); return -1; } int flags = fcntl(server_socket_fd, F_GETFL); if (flags < 0) { fprintf(log_file, "Couldn't get socket flags\n"); fflush(log_file); return -1; } int result = fcntl(server_socket_fd, F_SETFL, flags | O_NONBLOCK); if (result < 0) { fprintf(log_file, "Couldn't set listen socket parameters\n"); fflush(log_file); return -1; } // This socket option call is to ensure that when there is an error and we close // the server socket if gets fully closed so it can be opened again. int opt = 1; if (setsockopt(server_socket_fd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)) < 0) { fprintf(log_file, "Couldn't set some socket options\n"); fflush(log_file); return -1; } addr.sin_family = AF_INET; addr.sin_port = htons(7777); addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(server_socket_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { fprintf(log_file, "Couldn't bind to the port\n"); fflush(log_file); return -1; } if (listen(server_socket_fd, 100) < 0) { fprintf(log_file, "could not listen\n"); fflush(log_file); return -1; } fprintf(log_file, "Communication socket opened successfully\n"); fflush(log_file); return (0); // success } /* Codes 0 through 31 and 127 (decimal) are unprintable control characters. Code 32 (decimal) is a nonprinting spacing character. Codes 33 through 126 (decimal) are printable graphic characters. */ void printTheBuffer() { fprintf(log_file, "Message Received from ELM: "); for (int i = 0; i < sizeof(read_buf); i++) { if (read_buf[i] == 0) continue; if (read_buf[i] > 31 && read_buf[i] < 127) { fprintf(log_file, "%c", read_buf[i]); fflush(log_file); } else { // replace the character with a '.' read_buf[i] = 46; fprintf(log_file, "%c", read_buf[i]); fflush(log_file); } } fprintf(log_file, "\n"); fflush(log_file); } int sendMessageToElm32Adapter(char *message, char *expectedResponse) { memset(&read_buf, '\0', sizeof(read_buf)); while ((strstr(read_buf, expectedResponse) == 0) || (strstr(read_buf, "STOPPED") != 0) || (strstr(read_buf, "?") != 0)) { // The elm327 device responds to all messages by echoing the command it received. // In addition to this it may tag on the string "STOPPED". // If the "STOPPED" string is in the response then the command failed. // Instead of keep repeating the command return failure so we start all over // from the beginning. The first time this 'while' is encountered the buffer // is nulled out so we will enter the loop. memset(&read_buf, '\0', sizeof(read_buf)); write(serial_port, message, strlen(message)); sleep(5); int num_bytes = read(serial_port, &read_buf, sizeof(read_buf)); if (num_bytes < 0) { fprintf(log_file, "Error reading from the elm device. This happens when unplugged: %s", strerror(errno)); fflush(log_file); return (1); } if ((strstr(read_buf, expectedResponse) == 0) || (strstr(read_buf, "STOPPED") != 0) || (strstr(read_buf, "?") != 0)) { // The command failed to start from the beginning.Trying to repeat the // command after a failure sometimes results in endless errors. printTheBuffer(); // for logging return (1); } printTheBuffer(); // for logging } return (0); } int initializeTheSerialPort() { // Open the serial port. Change device path as needed (currently set to an standard FTDI USB-UART cable type device) //================================================================= // This is where the USB serial port appeared on the mac // serial_port = open("/dev/cu.usbserial-113011198702", O_RDWR); // On linux the USB serial name changes sometimes on startup from // /dev/USB0 to /dev/USB1 etc. // Instead use the name in /dev/serial/by-id //================================================================ serial_port = open("/dev/serial/by-id/usb-ScanTool.net_LLC_OBDLink_SX_113011198702-if00-port0", O_RDWR); fprintf(log_file, "Opening serial port \n"); if (serial_port < 0) { fprintf(log_file, "Could not find the serial port to open\n"); fflush(log_file); return(1); } // Read in existing settings, and handle any error if (tcgetattr(serial_port, &tty) != 0) { fprintf(log_file, "Error %i from tcgetattr: %s\n", errno, strerror(errno)); fflush(log_file); return 1; } tty.c_cflag &= ~PARENB; // Clear parity bit, disabling parity (most common) tty.c_cflag &= ~CSTOPB; // Clear stop field, only one stop bit used in communication (most common) tty.c_cflag &= ~CSIZE; // Clear all bits that set the data size tty.c_cflag |= CS8; // 8 bits per byte (most common) tty.c_cflag &= ~CRTSCTS; // Disable RTS/CTS hardware flow control (most common) tty.c_cflag |= CREAD | CLOCAL; // Turn on READ & ignore ctrl lines (CLOCAL = 1) tty.c_lflag &= ~ICANON; // disable canonical mode tty.c_lflag &= ~ECHO; // Disable echo tty.c_lflag &= ~ECHOE; // Disable erasure tty.c_lflag &= ~ECHONL; // Disable new-line echo tty.c_lflag &= ~ISIG; // Disable interpretation of INTR, QUIT and SUSP tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL); // Disable any special handling of received bytes tty.c_oflag &= ~OPOST; // Prevent special interpretation of output bytes (e.g. newline chars) tty.c_oflag &= ~ONLCR; // Prevent conversion of newline to carriage return/line feed // tty.c_oflag &= ~OXTABS; // Prevent conversion of tabs to spaces (NOT PRESENT ON LINUX) // tty.c_oflag &= ~ONOEOT; // Prevent removal of C-d chars (0x004) in output (NOT PRESENT ON LINUX) tty.c_cc[VTIME] = 10; // Wait for up to 1s (10 deciseconds), returning as soon as any data is received. tty.c_cc[VMIN] = 0; // Set in/out baud rate to be 115200 cfsetispeed(&tty, B115200); cfsetospeed(&tty, B115200); // Save tty settings, also checking for error if (tcsetattr(serial_port, TCSANOW, &tty) != 0) { fprintf(log_file, "Error %i from tcsetattr: %s\n", errno, strerror(errno)); fflush(log_file); return 1; } return (0); // successful initialization of serial port } int initializeTheElm327Adapter() { fprintf(log_file, "Initializing the ELM327 device \n"); fflush(log_file); //================================================================================== // Send the 'atz' command to the adapter. It should respond with 'ELM327' when it // receives the message and has reset itelf. keep trying to reset it until the // response comes back. If nothing comes back after sending atz it is a fatal error // so log it and exit. For debug purposes put the responses received in the logfile. //================================================================================== char resetAdapter[7] = "atz\r"; char resetResponse[] = "ELM327"; if (sendMessageToElm32Adapter(resetAdapter, resetResponse) != 0) { return (1); } //================================================================================== // Send the 'atsp3' command to the adapter. This sets the communication mode to ISO // for the Eurovan. It should respond with 'OK' when it // receives the message. If nothing comes back after sending a set protocol message // it is a fatal error. Log it and exit. For debug purposes put the responses // received in the logfile. //================================================================================== char setProtocol[] = "atsp3\r"; char protocolResponse[] = "OK"; if (sendMessageToElm32Adapter(setProtocol, protocolResponse) != 0) { return (1); } //================================================================================== // Send the 'ath1' command to the adapter. This sets the communication mode to // include headers in the OBD2 response. It should respond with 'OK' when it // receives the message. If nothing comes back after sending ath1 it is a fatal error // so log it and exit. For debug purposes put the responses received in the logfile. //================================================================================== char returnHeaders[] = "ath1\r"; char setHeaderResponse[] = "OK"; if (sendMessageToElm32Adapter(returnHeaders, setHeaderResponse) != 0) { return (1); } //================================================================================== // Send the 'ath1mt1a' command to the adapter. // This causes only messages with a 3rd byte of 1A in them to be returned from the elm adapter. // If the 3rd byte is 1A then it is a transmission temperature message. // Unlike the other commands this one only echoes the command it receives. There is // no "OK" in the return message. //================================================================================== char limitReturnMessages[] = "atmt1a\r"; char limitReturnMessageResponse[] = "atmt1a"; if (sendMessageToElm32Adapter(limitReturnMessages, limitReturnMessageResponse) != 0) { return (1); } return (0); // success } /* int main() { //====================================================================== // Create a time stamped log file for any error messages and general logging // first delete the previous log file. //====================================================================== //time_t now = time(NULL); //timenow = gmtime(&now); //strftime(filename, sizeof(filename), "./terminal-%d-%H-%M-%S", timenow); //log_file = fopen(filename, "w"); remove(logFileName); log_file = fopen(logFileName, "w"); while (true) { if (openSocketToGetTemperatureRequests() != 0) { sleep(5); continue; } if (initializeTheSerialPort() != 0) { sleep(10); close(serial_port); fprintf(log_file, "Closing serial port \n"); fflush(log_file); continue; } if (initializeTheElm327Adapter() != 0) { sleep(10); close(serial_port); fprintf(log_file, "Closing serial port \n"); fflush(log_file); continue; } // Keep getting messages from the Elm327 adapter. If any problems occur start all over again at intializing the serial port // Messages should now be coming from the elm327 adapter. Parse them to get the // transmission temperature. while (true) { // Check that the log file hasn't gotten too large. If it has delete it and open a file with the same name again. // manageLogFileSizeAtRuntime(); memset(&read_buf, '\0', sizeof(read_buf)); int num_bytes_read = read(serial_port, &read_buf, sizeof(read_buf)); if (num_bytes_read > 0) { fprintf(log_file, "Read %i bytes. Received message: %s \n", num_bytes_read, read_buf); fflush(log_file); // Now go thru each byte looking for the sequence // 48 6b 1a 41 05 then convert the next 2 characters in hex convert to decimal, multiply by 9/5 or1.8 then // subract 40 and that is trans temp in farenheit. int i = 0; int bytesLeftToRead = num_bytes_read; while (read_buf[i] != '\0' && bytesLeftToRead >= 22) { if (read_buf[i] == '4' && read_buf[i + 1] == '8' && read_buf[i + 3] == '6' && read_buf[i + 4] == 'B' && read_buf[i + 6] == '1' && read_buf[i + 7] == 'A' && read_buf[i + 9] == '4' && read_buf[i + 10] == '1' && read_buf[i + 12] == '0' && read_buf[i + 13] == '5') { char transmissionTemperatureInHex[] = {' ', ' ', '\n'}; transmissionTemperatureInHex[0] = read_buf[i + 15]; transmissionTemperatureInHex[1] = read_buf[i + 16]; transmissionTemperature = strtol(transmissionTemperatureInHex, NULL, 16); transmissionTemperature = (transmissionTemperature * 1.8) - 40; fprintf(log_file, "Transmission temperature: %d \n", transmissionTemperature); fflush(log_file); // Now save this to the string version of the transmission temperature to pass along // to the gui that requests it via a socket. sprintf(transmissionTemperatureString, "%d", transmissionTemperature); } i++; bytesLeftToRead--; } } else if (num_bytes_read == 0) { // We read no bytes from the Elm Adapter. fprintf(log_file, "No messages received from the Elm Adapter \n"); fflush(log_file); sleep(5); } else if (num_bytes_read < 0) { break; // num_bytes_read was probably -1 or any neg number which is an error so we must start all over again } // Check for a socket request from the User Interface program to get the transmission temperature. if (checkAndRespondToTemperatureRequest() != 0) { break; // start from the beginning } } close(serial_port); fprintf(log_file, "Closing serial port \n"); } fclose(log_file); } */ int main() { //====================================================================== // Create a time stamped log file for any error messages and general logging // first delete the previous log file. //====================================================================== //time_t now = time(NULL); //timenow = gmtime(&now); //strftime(filename, sizeof(filename), "./terminal-%d-%H-%M-%S", timenow); //log_file = fopen(filename, "w"); remove(logFileName); log_file = fopen(logFileName, "w"); while (true) { if (openSocketToGetTemperatureRequests() != 0) { sleep(5); continue; } if (initializeTheSerialPort() != 0) { sleep(10); close(serial_port); fprintf(log_file, "Closing serial port \n"); fflush(log_file); continue; } if (initializeTheElm327Adapter() != 0) { sleep(10); close(serial_port); fprintf(log_file, "Closing serial port \n"); fflush(log_file); continue; } // Keep getting messages from the Elm327 adapter. If any problems occur start all over again at intializing the serial port // Messages should now be coming from the elm327 adapter. Parse them to get the // transmission temperature. while (true) { // Check that the log file hasn't gotten too large. If it has delete it and open a file with the same name again. // manageLogFileSizeAtRuntime(); memset(&read_buf, '\0', sizeof(read_buf)); int num_bytes_read = read(serial_port, &read_buf, sizeof(read_buf)); if (num_bytes_read > 0) { fprintf(log_file, "Read %i bytes. Received message: %s \n", num_bytes_read, read_buf); fflush(log_file); // Now go thru each byte looking for the sequence // 48 6b 1a 41 05 then convert the next 2 characters in hex convert to decimal, multiply by 9/5 or1.8 then // subract 40 and that is trans temp in farenheit. int i = 0; int bytesLeftToRead = num_bytes_read; while (read_buf[i] != '\0' && bytesLeftToRead >= 22) { if (read_buf[i] == '4' && read_buf[i + 1] == '8' && read_buf[i + 3] == '6' && read_buf[i + 4] == 'B' && read_buf[i + 6] == '1' && read_buf[i + 7] == 'A' && read_buf[i + 9] == '4' && read_buf[i + 10] == '1' && read_buf[i + 12] == '0' && read_buf[i + 13] == '5') { char transmissionTemperatureInHex[] = {' ', ' ', '\n'}; transmissionTemperatureInHex[0] = read_buf[i + 15]; transmissionTemperatureInHex[1] = read_buf[i + 16]; transmissionTemperature = strtol(transmissionTemperatureInHex, NULL, 16); transmissionTemperature = (transmissionTemperature * 1.8) - 40; fprintf(log_file, "Transmission temperature: %d \n", transmissionTemperature); fflush(log_file); // Now save this to the string version of the transmission temperature to pass along // to the gui that requests it via a socket. sprintf(transmissionTemperatureString, "%d", transmissionTemperature); } i++; bytesLeftToRead--; } } else if (num_bytes_read == 0) { // We read no bytes from the Elm Adapter. fprintf(log_file, "No messages received from the Elm Adapter \n"); fflush(log_file); sleep(5); } else if (num_bytes_read < 0) { break; // num_bytes_read was probably -1 or any neg number which is an error so we must start all over again } // Check for a socket request from the User Interface program to get the transmission temperature. if (checkAndRespondToTemperatureRequest() != 0) { break; // start from the beginning } } close(serial_port); fprintf(log_file, "Closing serial port \n"); } fclose(log_file); }