2 ## This file is part of the libsigrokdecode project.
4 ## Copyright (C) 2016 Daniel Schulte <trilader@schroedingers-bit.net>
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ## GNU General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, write to the Free Software
18 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 import sigrokdecode as srd
24 START, STOP, PARITY, WORD = range(4)
26 class Decoder(srd.Decoder):
31 desc = 'PS/2 keyboard/mouse interface.'
36 {'id': 'clk', 'name': 'Clock', 'desc': 'Clock line'},
37 {'id': 'data', 'name': 'Data', 'desc': 'Data line'},
40 ('start-bit', 'Start bit'),
41 ('stop-bit', 'Stop bit'),
42 ('parity-bit', 'Parity bit'),
49 self.prev_clock = None
52 self.clock_was_high = False
55 self.out_ann = self.register(srd.OUTPUT_ANN)
57 def handle_bits(self, datapin):
58 # Ignore non start condition bits (useful during keyboard init).
59 if len(self.bits) == 0 and datapin == 1:
62 # If this is the first bit in a word, save its sample number.
63 if len(self.bits) == 0:
64 self.ss_word = self.samplenum
66 self.bits.append(datapin)
68 # Find all 11 bits. Start + 8 data + odd parity + stop.
69 if len(self.bits) < 11:
75 word |= (self.bits[i + 1] << i)
77 bit_start, bit_stop, bit_parity = self.bits[0], \
78 self.bits[10], self.bits[9]
80 bitstring = ''.join([str(i) for i in self.bits])
81 parity_ok = (bin(word).count('1') + bit_parity) % 2 == 1
83 if bit_start == 0 and bit_stop == 1 and parity_ok:
84 self.put(self.ss_word, self.samplenum, self.out_ann, [Ann.WORD,
85 ['OK: %X (%s)' % (word, bitstring)]])
87 self.put(self.ss_word, self.samplenum, self.out_ann, [Ann.WORD,
88 ['Fail: %X (%s)' % (word, bitstring)]])
90 self.bits, self.ss_word = [], 0
92 def find_clk_edge(self, clock_pin, data_pin):
93 # Ignore sample if the clock pin hasn't changed.
94 if clock_pin == self.prev_clock:
96 self.prev_clock = clock_pin
98 # Sample on falling clock edge.
102 # Found the correct clock edge, now get the bits.
103 self.handle_bits(data_pin)
105 def decode(self, ss, es, data):
106 for (self.samplenum, pins) in data:
107 clock_pin, data_pin = pins[0], pins[1]
109 # Ignore identical samples.
110 if self.prev_pins == pins:
112 self.prev_pins = pins
114 if clock_pin == 0 and not self.clock_was_high:
116 self.clock_was_high = True
118 self.find_clk_edge(clock_pin, data_pin)