Skip to content

Commit

Permalink
Merge pull request #14 from lvht/no-python-dbus
Browse files Browse the repository at this point in the history
remove dependence for python-dbus
  • Loading branch information
taoso committed Jan 6, 2016
2 parents f2caa82 + 9320cf0 commit 9fab058
Show file tree
Hide file tree
Showing 5 changed files with 187 additions and 145 deletions.
13 changes: 6 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ HIDP协议栈全文可以从蓝牙官网下载到,但是是英文的,啃吧

- 无法支持多设备连接
- 无法很优雅地处理设备断掉连接的情况
- 无法独自完成设备之间的认证和授权(依赖GNOME)工作
- 主程序不支持配置选项
- 不支持systemd集成

Expand All @@ -43,18 +42,18 @@ HIDP协议栈全文可以从蓝牙官网下载到,但是是英文的,啃吧
- 蓝牙硬件
- BlueZ(>=5)
- python(>=2.7)
- [PyGObject](https://live.gnome.org/PyGObject)
- [evdev](https://pypi.python.org/pypi/evdev)
- [dbus-python](https://pypi.python.org/pypi/dbus-python)
- [pydbus]()
- [PyBlueZ](https://pypi.python.org/pypi/PyBluez)
- iOS或者Android设备

系统准备好之后需要对源代码做少许修改。我的电脑的键盘设备节点是`/dev/input/event3`,所以我就将路径硬编码到程序中了。大家需要找到自己的键盘设备节点,然后对btk.py中的第13行做相应更改。

```py
keyboard = kb.Keyboard('/dev/input/event3')
首先,运行脚本:
```bash
sudo python agent.py
```

启动蓝牙之后以root用户运行btk.py脚本就可以了
然后使用手机搜索蓝牙,找到你的主机点击配对。这时agent.py脚本会提示你输入配对码。直接输入并回车即可开启体验之旅

键鼠HID报告描述符
=================
Expand Down
149 changes: 61 additions & 88 deletions agent.py
Original file line number Diff line number Diff line change
@@ -1,67 +1,77 @@
from __future__ import print_function
#from future.builtins import input
import sys
import dbus
import dbus.service
import dbus.mainloop.glib

import evdev as ev
import glob

from btk import HIDProfile, PSM_CTRL, PSM_INTR
import uuid
import bluetooth as bt

try:
from gi.repository import GObject as gobject
except ImportError:
import gobject


BUS_NAME = 'org.bluez'
AGENT_INTERFACE = 'org.bluez.Agent1'
AGENT_PATH = "/test/agent"
from gi.repository import GLib
from pydbus import SystemBus
from dbus import Server

def ask(prompt):
return 1111 # input(prompt)
return 1111

def set_trusted(path):
props = dbus.Interface(bus.get_object("org.bluez", path),
"org.freedesktop.DBus.Properties")
props = bus.get('org.bluez', path)['org.freedesktop.DBus.Properties']
print('trust', path)
props.Set("org.bluez.Device1", "Trusted", True)
props.Set("org.bluez.Device1", "Trusted", GLib.Variant.new_boolean(True))

def dev_connect(path):
dev = dbus.Interface(bus.get_object("org.bluez", path),
"org.bluez.Device1")
dev = bus.get('org.bluez', path)['org.bluez.Device1']
dev.Connect()

class Rejected(dbus.DBusException):
_dbus_error_name = "org.bluez.Error.Rejected"

class Agent(dbus.service.Object):
@dbus.service.method(AGENT_INTERFACE,
in_signature="", out_signature="")
class Agent(Server):
'''
<node>
<interface name='org.bluez.Agent1'>
<method name='Release'></method>
<method name='AuthorizeService'>
<arg type='o' name='device' direction='in'/>
<arg type='s' name='uuid' direction='in'/>
</method>
<method name='RequestPinCode'>
<arg type='o' name='device' direction='in'/>
<arg type='s' name='pin_code' direction='out'/>
</method>
<method name='RequestPasskey'>
<arg type='o' name='device' direction='in'/>
<arg type='u' name='pass_key' direction='out'/>
</method>
<method name='DisplayPasskey'>
<arg type='o' name='device' direction='in'/>
<arg type='u' name='pass_key' direction='in'/>
<arg type='q' name='entered' direction='in'/>
</method>
<method name='DisplayPinCode'>
<arg type='o' name='device' direction='in'/>
<arg type='s' name='pin_code' direction='in'/>
</method>
<method name='RequestConfirmation'>
<arg type='o' name='device' direction='in'/>
<arg type='s' name='pass_key' direction='in'/>
</method>
<method name='RequestAuthorization'>
<arg type='o' name='device' direction='in'/>
</method>
<method name='Cancel'></method>
</interface>
</node>
'''
def Release(self):
print("Release")

@dbus.service.method(AGENT_INTERFACE,
in_signature="os", out_signature="")
def AuthorizeService(self, device, uuid):
print("AuthorizeService (%s, %s)" % (device, uuid))
authorize = ask("Authorize connection (yes/no): ")
if (authorize == "yes"):
return
raise Rejected("Connection rejected by user")

@dbus.service.method(AGENT_INTERFACE,
in_signature="o", out_signature="s")
def RequestPinCode(self, device):
print("RequestPinCode (%s)" % (device))
set_trusted(device)
return ask("Enter PIN Code: ")

@dbus.service.method(AGENT_INTERFACE,
in_signature="o", out_signature="u")
def RequestPasskey(self, device):
print("RequestPasskey (%s)" % (device))
passkey = ""
Expand All @@ -81,81 +91,44 @@ def RequestPasskey(self, device):
passkey = passkey + key

set_trusted(device)
return dbus.UInt32(passkey)
return int(passkey)

@dbus.service.method(AGENT_INTERFACE,
in_signature="ouq", out_signature="")
def DisplayPasskey(self, device, passkey, entered):
print("DisplayPasskey (%s, %06u entered %u)" %
(device, passkey, entered))

@dbus.service.method(AGENT_INTERFACE,
in_signature="os", out_signature="")
def DisplayPinCode(self, device, pincode):
print("DisplayPinCode (%s, %s)" % (device, pincode))

@dbus.service.method(AGENT_INTERFACE,
in_signature="ou", out_signature="")
def RequestConfirmation(self, device, passkey):
print("RequestConfirmation (%s, %06d)" % (device, passkey))
confirm = ask("Confirm passkey ([y]/n): ")
if (confirm != "n"):
set_trusted(device)
return
raise Rejected("Passkey doesn't match")

@dbus.service.method(AGENT_INTERFACE,
in_signature="o", out_signature="")
def RequestAuthorization(self, device):
print("RequestAuthorization (%s)" % (device))
auth = ask("Authorize? ([y]/n): ")
if (auth != "n"):
return
raise Rejected("Pairing rejected")

@dbus.service.method(AGENT_INTERFACE,
in_signature="", out_signature="")
def Cancel(self):
print("Cancel")

if __name__ == '__main__':
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()

props = dbus.Interface(
bus.get_object("org.bluez", '/org/bluez/hci0'),
"org.freedesktop.DBus.Properties"
)
props.Set("org.bluez.Adapter1", "Powered", dbus.Boolean(True))
props.Set("org.bluez.Adapter1", "Discoverable", dbus.Boolean(True))

def open_hci():
props = bus.get('org.bluez', '/org/bluez/hci0')['org.freedesktop.DBus.Properties']
props.Set("org.bluez.Adapter1", "Powered", GLib.Variant.new_boolean(True))
props.Set("org.bluez.Adapter1", "Discoverable", GLib.Variant.new_boolean(True))

def register_agent():
capability = "KeyboardOnly"
path = "/test/agent"
agent = Agent(bus, path)
obj = bus.get_object('org.bluez', "/org/bluez");
manager = dbus.Interface(obj, "org.bluez.AgentManager1")
path = "/net/lvht/btk/agent"
agent = Agent(bus.con, path)
manager = bus.get('org.bluez')['.AgentManager1']
manager.RegisterAgent(path, capability)
manager.RequestDefaultAgent(path)

if __name__ == '__main__':
bus = SystemBus()
open_hci()
register_agent()

print('start hid')
sock = bt.BluetoothSocket(bt.L2CAP)
sock.setblocking(False)
sock.bind(('', PSM_INTR))
sock.listen(1)

obj_path = '/ml/jlyu/HIDProfile'
profile = HIDProfile(bus, obj_path, sock)

opts = {
"PSM": dbus.UInt16(PSM_CTRL),
"ServiceRecord": open('./sdp_record.xml', 'r').read(),
"RequireAuthentication": dbus.Boolean(True),
"RequireAuthorization": dbus.Boolean(True),
}
dbus.Interface(
bus.get_object("org.bluez", "/org/bluez"),
"org.bluez.ProfileManager1"
).RegisterProfile(obj_path, str(uuid.uuid4()), opts)

gobject.MainLoop().run()
import btk
btk.loop()
Loading

0 comments on commit 9fab058

Please sign in to comment.