Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved PS/2 decoder, added stacked mouse decoder #104

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions decoders/ps2/__init__.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2016 Daniel Schulte <[email protected]>
## Copyright (C) 2023 Marshal Horn <[email protected]>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
Expand All @@ -18,9 +19,11 @@
##

'''
This protocol decoder can decode PS/2 device -> host communication.
This protocol decoder can decode PS/2 device -> host communication \
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just noticed - are you sure you need the trailing \ ? see e.g. the uart PD

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah. I don't actually want to force a line break there, but I also don't want to exceed the standard column width (80 characters)

and host -> device communication.

Host -> device communication is currently not supported.
To interpret the data, please stack the appropriate keyboard or mouse \
decoder
'''

from .pd import Decoder
178 changes: 118 additions & 60 deletions decoders/ps2/pd.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2016 Daniel Schulte <[email protected]>
## Copyright (C) 2023 Marshal Horn <[email protected]>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
Expand All @@ -18,22 +19,33 @@
##

import sigrokdecode as srd
from collections import namedtuple

class Ann:
BIT, START, STOP, PARITY_OK, PARITY_ERR, DATA, WORD = range(7)
BIT, START, WORD, PARITY_OK, PARITY_ERR, STOP, ACK, NACK, HREQ, HSTART, HWORD, HPARITY_OK, HPARITY_ERR, HSTOP = range(14)

class Bit:
def __init__(self, val, ss, es):
self.val = val
self.ss = ss
self.es = es

class Ps2Packet:
def __init__(self, val, host=False, pok=False, ack=False):
self.val = val #byte value
self.host = host #Host transmissions
self.pok = pok #Parity ok
self.ack = ack #Acknowlege ok for host transmission.

Bit = namedtuple('Bit', 'val ss es')

class Decoder(srd.Decoder):
api_version = 3
id = 'ps2'
name = 'PS/2'
longname = 'PS/2'
desc = 'PS/2 keyboard/mouse interface.'
desc = 'PS/2 packet interface used by PC keyboards and mice'
license = 'gplv2+'
inputs = ['logic']
outputs = []
outputs = ['ps2']
tags = ['PC']
channels = (
{'id': 'clk', 'name': 'Clock', 'desc': 'Clock line'},
Expand All @@ -42,85 +54,131 @@ class Decoder(srd.Decoder):
annotations = (
('bit', 'Bit'),
('start-bit', 'Start bit'),
('stop-bit', 'Stop bit'),
('word', 'Word'),
('parity-ok', 'Parity OK bit'),
('parity-err', 'Parity error bit'),
('data-bit', 'Data bit'),
('stop-bit', 'Stop bit'),
('ack', 'Acknowledge'),
('nack', 'Not Acknowledge'),
('req', 'Host request to send'),
('start-bit', 'Start bit'),
('word', 'Word'),
('parity-ok', 'Parity OK bit'),
('parity-err', 'Parity error bit'),
('stop-bit', 'Stop bit'),
)
annotation_rows = (
('bits', 'Bits', (0,)),
('fields', 'Fields', (1, 2, 3, 4, 5, 6)),
('fields', 'Device', (1,2,3,4,5,6,7,)),
('host', 'Host', (8,9,10,11,12,13)),
)

def __init__(self):
self.reset()
self.min_clk_hz = 9e3 #Minimum clock rate for PS/2 is 10kHz, but I want to be lenient

def reset(self):
self.bits = []
self.bitcount = 0

def start(self):
self.out_ann = self.register(srd.OUTPUT_ANN)

def putb(self, bit, ann_idx):
b = self.bits[bit]
self.put(b.ss, b.es, self.out_ann, [ann_idx, [str(b.val)]])
self.out_py = self.register(srd.OUTPUT_PYTHON)

def metadata(self,key,value):
if key == srd.SRD_CONF_SAMPLERATE:
self.samplerate = value

def get_bits(self, n, edge:'r'):
_, dat = self.wait([{0:edge},{1:'l'}]) #No timeout for start bit
if not self.matched[1]:
return #No start bit
self.bits.append(Bit(dat, self.samplenum, self.samplenum+self.max_period))
if not self.matched[0]:
self.wait({0:'f'}) #Wait for clock edge from device
for i in range(1,n):
_, dat = self.wait([{0:edge},{'skip':self.max_period}])
if not self.matched[0]:
break #Timed out
self.bits.append(Bit(dat, self.samplenum, self.samplenum+self.max_period))
#Fix the ending period
self.bits[i-1].es = self.samplenum
if len(self.bits) == n:
self.wait([{0:'r'},{'skip':self.max_period}])
self.bits[-1].es = self.samplenum
self.bitcount = len(self.bits)

def putx(self, bit, ann):
self.put(self.bits[bit].ss, self.bits[bit].es, self.out_ann, ann)

def handle_bits(self, datapin):
# Ignore non start condition bits (useful during keyboard init).
if self.bitcount == 0 and datapin == 1:
return

# Store individual bits and their start/end samplenumbers.
self.bits.append(Bit(datapin, self.samplenum, self.samplenum))

# Fix up end sample numbers of the bits.
if self.bitcount > 0:
b = self.bits[self.bitcount - 1]
self.bits[self.bitcount - 1] = Bit(b.val, b.ss, self.samplenum)
if self.bitcount == 11:
self.bitwidth = self.bits[1].es - self.bits[2].es
b = self.bits[-1]
self.bits[-1] = Bit(b.val, b.ss, b.es + self.bitwidth)

# Find all 11 bits. Start + 8 data + odd parity + stop.
if self.bitcount < 11:
self.bitcount += 1
return

# Extract data word.
word = 0
for i in range(8):
word |= (self.bits[i + 1].val << i)
def handle_bits(self, host=False):
packet = None
if self.bitcount > 8:
# Annotate individual bits
for b in self.bits:
self.put(b.ss, b.es, self.out_ann, [Ann.BIT, [str(b.val)]])
# Annotate start bit
self.putx(0, [Ann.HSTART if host else Ann.START, ['Start bit', 'Start', 'S']])
# Annotate the data word
word = 0
for i in range(8):
word |= (self.bits[i + 1].val << i)
self.put(self.bits[1].ss, self.bits[8].es, self.out_ann,
[Ann.HWORD if host else Ann.WORD,
['Data: %02x' % word, 'D: %02x' % word, '%02x' % word]])
packet = Ps2Packet(val = word, host = host)

# Calculate parity.
parity_ok = (bin(word).count('1') + self.bits[9].val) % 2 == 1

# Emit annotations.
for i in range(11):
self.putb(i, Ann.BIT)
self.putx(0, [Ann.START, ['Start bit', 'Start', 'S']])
self.put(self.bits[1].ss, self.bits[8].es, self.out_ann, [Ann.WORD,
['Data: %02x' % word, 'D: %02x' % word, '%02x' % word]])
if parity_ok:
self.putx(9, [Ann.PARITY_OK, ['Parity OK', 'Par OK', 'P']])
else:
self.putx(9, [Ann.PARITY_ERR, ['Parity error', 'Par err', 'PE']])
self.putx(10, [Ann.STOP, ['Stop bit', 'Stop', 'St', 'T']])
if self.bitcount > 9:
parity_ok = 0
for bit in self.bits[1:10]:
parity_ok ^= bit.val
if bool(parity_ok):
self.putx(9, [Ann.HPARITY_OK if host else Ann.PARITY_OK, ['Parity OK', 'Par OK', 'P']])
packet.pok = True #Defaults to false in case packet was interrupted
else:
self.putx(9, [Ann.HPARITY_ERR if host else Ann.PARITY_ERR, ['Parity error', 'Par err', 'PE']])

# Annotate stop bit
if self.bitcount > 10:
self.putx(10, [Ann.HSTOP if host else Ann.STOP, ['Stop bit', 'Stop', 'St', 'T']])
# Annotate ACK
if host and self.bitcount > 11:
if self.bits[11].val == 0:
self.putx(11, [Ann.ACK, ['Acknowledge', 'Ack', 'A']])
else:
self.putx(11, [Ann.NACK, ['Not Acknowledge', 'Nack', 'N']])
packet.ack = not bool(self.bits[11].val)

if(packet):
self.put(self.bits[0].ss, self.bits[-1].ss, self.out_py,packet)
self.reset()

self.bits, self.bitcount = [], 0

def decode(self):
if self.samplerate:
self.max_period = int(self.samplerate / self.min_clk_hz)+1
else:
raise SamplerateError("Cannot decode without samplerate")
while True:
# Sample data bits on the falling clock edge (assume the device
# is the transmitter). Expect the data byte transmission to end
# at the rising clock edge. Cope with the absence of host activity.
_, data_pin = self.wait({0: 'f'})
self.handle_bits(data_pin)
if self.bitcount == 1 + 8 + 1 + 1:
_, data_pin = self.wait({0: 'r'})
self.handle_bits(data_pin)
# Falling edge of data indicates start condition
# Clock held for 100us indicates host "request to send"
self.wait([{1: 'f'},{0:'l'}])
ss = self.samplenum
host = self.matched[1]
if host:
# Make sure the clock is held low for at least 100 microseconds before data is pulled down
self.wait([{0:'h'},{'skip': self.max_period},{1:'l'}])
if self.matched[0]:
continue #Probably the trailing edge of a transfer
elif self.matched[2]: #Probably a bus error
self.wait({1:'h'}) #Wait for data to be released
continue
# Host emits bits on rising clk edge
self.get_bits(12, 'r')
if self.bitcount > 0:
self.put(ss,self.bits[0].ss,self.out_ann, [Ann.HREQ,['Host RTS', 'HRTS', 'H']])
else:
# Client emits data on falling edge
self.get_bits(11, 'f')
self.handle_bits(host=host)
25 changes: 25 additions & 0 deletions decoders/ps2_keyboard/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2023 Marshal Horn <[email protected]>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##

'''
This protocol decoder can decode PS/2 keyboard commands.
It should be stacked on the PS/2 packet decoder.
'''

from .pd import Decoder
93 changes: 93 additions & 0 deletions decoders/ps2_keyboard/pd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2023 Marshal Horn <[email protected]>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, see <http://www.gnu.org/licenses/>.
##

import sigrokdecode as srd
from .sc import key_decode

class Ps2Packet:
def __init__(self, val, host=False, pok=False, ack=False):
self.val = val #byte value
self.host = host #Host transmissions
self.pok = pok #Parity ok
self.ack = ack #Acknowlege ok for host transmission.

class Ann:
PRESS,RELEASE,ACK = range(3)

class Decoder(srd.Decoder):
api_version = 3
id = 'ps2_keyboard'
name = 'PS/2 Keyboard'
longname = 'PS/2 Keyboard'
desc = 'PS/2 keyboard interface.'
license = 'gplv2+'
inputs = ['ps2']
outputs = []
tags = ['PC']
binary = (
('Keys', 'Key presses'),
)
annotations = (
('Press', 'Key pressed'),
('Release', 'Key released'),
('Ack', 'Acknowledge'),
)
annotation_rows = (
('keys', 'key presses and releases',(0,1,2)),
)

def __init__(self):
self.reset()

def reset(self):
self.sw = 0 #for switch statement
self.ann = Ann.PRESS #defualt to keypress
self.extended = False

def start(self):
self.out_binary = self.register(srd.OUTPUT_BINARY)
self.out_ann = self.register(srd.OUTPUT_ANN)

def decode(self,startsample,endsample,data):
if data.host:
# Ignore host commands or interrupted keycodes
self.reset()
return
if self.sw < 1:
self.ss = startsample
self.sw = 1
if self.sw < 2:
if data.val == 0xF0: #Break code
self.ann = Ann.RELEASE
return
elif data.val == 0xE0: #Extended character
self.extended = True
return
elif data.val == 0xFA: #Acknowledge code
c = ['Acknowledge','ACK']
self.ann = Ann.ACK
self.sw = 4
if self.sw < 3:
c = key_decode(data.val, self.extended)

self.put(self.ss,endsample,self.out_ann,[self.ann,c])
if self.ann == Ann.PRESS:
self.put(self.ss,endsample,self.out_binary,[0,c[-1].encode('UTF-8')])
self.reset()

Loading