みつきんのメモ

組み込みエンジニアです。Interface誌で「Yocto Projectではじめる 組み込みLinux開発入門」連載中

pyconnmanで遊んでみる。

pyconnmanを使用するとconnmanの機能にpythonからアクセスできるようになる。

クラス

pyconnmanモジュールには次のクラスが定義されている。

クラス 概要
ConnTechnology tecnology
ConnManager connman本体
ConnCanceledException
ConnInterface ネットワークインターフェース
ConnLaunchBrowseException
ConnService サービス
ConnSignalNameNotRecognizedException
ConnSimpleInterface シンプルインターフェース
GenericAgent エージェント
SimpleWifiAgent Wifiエージェント

technologyのリストを取得

最初にtechnologyのリストを取得してみる。

technologyのリストを取得は次のような流れになる。

f:id:mickey_happygolucky:20180411062122p:plain

このようにConnManagerクラスからリストを取得する。

get_technologies()メソッドが返すデータは次のようなペアの配列となっている。

データ 概要
path パス文字列
technology プロパティの辞書

technologyの辞書には次のようなデータが入っている。

キー データ データ型
Name tecnology名称 dbus.String
Type タイプ文字列 dbus.String
Powered 有効/無効 dbus.Boolean
Connected 接続/未接続 dbus.Boolean
Tethering テザリング dbus.Boolean
import pyconnman

# Get manager class object
manager = pyconnman.ConnManager()

# Get list of technologies
technologies = manager.get_technologies()

# Iterate and print data in the list
for (path, technology) in technologies:
    print path
    print '======================='
    for prop in technology.keys():
        print prop + ' : ' + str(technology[prop])
    print '======================='

technologyのプロパティを設定する

プロパティを設定するには、ConnTechnologyクラスのオブジェクトを生成する必要がある。 ConnTechnologyオブジェクトの生成にはpathが必要となるため、 一度ConnManagerオブジェクトからget_technologies()で情報を取得する必要がある。

WiFi technologyのPoweredプロパティをTrueに設定するスクリプトを作成する。

全体の流れは次のようになる。

f:id:mickey_happygolucky:20180411062214p:plain

スクリプトを次に示す。

import pyconnman

# Get manager object
manager = pyconnman.ConnManager()

# Get list of technologies
technologies = manager.get_technologies()

# Get path of Wifi technology
wifi_path = ""
for (path, technology) in technologies:
    if technology['Name'] == 'WiFi':
        wifi_path = path

# Get Technology object from Wifi path
wifi_technology = pyconnman.ConnTechnology(wifi_path)

# Set Powered property to True
if not wifi_technology.get_property(name='Powered'):
    wifi_technology.set_property(name='Powered', value=True)
else:
    print 'Powered already set to True.'

ここまでがtechnology関連の基本操作となる。

任意のtechnologyのpathを取得できるようにしておく

pathを取得するためにいちいちget_technologies()を実行するのも手間なので、 get_technologies()メソッドからtechnologyのリストを取得した時に technology名でpathが引けるように辞書を作成しておくと便利になる。

...(省略)...

# Create the dictionary that contains path and names.
tech_dict = {}
for (path, technology) in technologies:
    tech_dict[technology['Name']] = path

# Get Technology object from Bluetooth path
bt_technology = pyconnman.ConnTechnology(tech_dict['Bluetooth'])

...(省略)..