Interfacing OBD II with Raspberry Pi in Easy Steps Part-2

This is the continuation of article named "Interfacing OBD II with Raspberry Pi Part-1".I will be using raspberry pi 2 and SIM 808 for GPRS connection to send data to server.We get obd data as described here.And we send data to server through AT commands using SIM 808.
Lets get started, here is sample python code to get started:

import obd
import serial #importing serial module for communicating with SIM 808
import time
DEFAULT_BUFFER_SIZE = 3000
DEFAULT_TIMEOUT = 1
ser = "" #for serial object
commands = SPEED
connection = obd.OBD(baudrate=115200) #making connection to obd module

# Function for Sending AT commands to communicate with SIM 808
def sendCmdWaitForResponse(cmnd, timeOut):
    ser.write(cmnd+'\n')
    time.sleep(DEFAULT_TIMEOUT * timeOut)# Wait for timeOut secs after trasmission of command
    uartRx = ser.readline()
    print(uartRx) #for debugging purpose
    return uartRx

# Function for initialize GPRS module
def initGPRS():
    sendCmdWaitForResponse("AT+CGATT=1",2)
    return 1

# TCP client
def sendtoTCPServer(message):
    sendCmdWaitForResponse("AT+CIPSTART=\"TCP\",\"xxx.xxx.xxx.xxx\",\"xxxx\"",1) #ip and port number of your TCP server
    sendCmdWaitForResponse("AT+CIPSEND",1)
    ser.write(message)
    ser.write("\x1A") # terminate message body (ctrl+z)

def connect_to_gprs():
    while 1:
        try:
            ser = serial.Serial(
            port = '/dev/ttyAMA0',
            baudrate = 9600,
            parity = serial.PARITY_NONE,
            stopbits = serial.STOPBITS_ONE,
            bytesize = serial.EIGHTBITS,
            timeout = 1
            )
            initGPRS() #initializing GPRS
            break
        except:
            time.sleep(5)

def extract_data():
    data = ""
    if obd.commands.has_command(obd.commands[command]):#checking if vehicle support provided command
        response = connection.query(obd.commands[command])
    else:
        pass
    return data

connct_to_gprs() #connecting to GPRS module

while True:
    data = extract_data()
    sendtoTCPServer(data)


Here, we are getting speed data from vehicle and sending to TCP server.You can check out tutorial on how to make TCP server here.You can also get other vehicle data or DTCs(Diagnostic Trouble Codes) as described in tutorial here.Keep following this blog for more articles.

No comments:

Post a Comment