1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

bbc1のサンプルアプリにクライアント間のメッセージング機能を追加してみた

Posted at

前回に引き続き、プログラミングガイドに基づいて機能を実装していきます。

「クライアント間のメッセージング」節から進めていきます。

と、その前に

参考までに、作ったサンプルアプリのイメージ図だけ載せておきます。
このアプリは利用者の履歴を記録し、その履歴を検索することができます。
サンプルアプリの利用イメージ図.001.jpeg

やったこと

大きく以下の3つです。

  • コールバッククラスの定義
    • コールバックメソッドの定義
  • メッセージ送信メソッドの定義
  • メッセージ受信メソッドの定義

実装

コールバッククラスの定義

class MessageProcessor(bbc_app.Callback):
    def __init__(self):
        super(MessageProcessor, self).__init__(self)

    def proc_user_message(self, dat):
        user_message = dat[KeyType.message]
        print("Received user message: %s" % user_message)

ガイドに記載している内容と同様です。

メッセージ送信メソッドの定義

def send_unicast_message(id_who):
    client = connect_to_core_node()
    messeage_to_send = {"message": "registered"}
    client.send_message(messeage_to_send, id_who)

id_whoは送り先のuser_idとなります。バイトコードです。
このメソッドはユーザーの利用を想定しています。

メッセージ受信メソッドの定義

def wait_message():
    client = connect_to_core_node()
    callback_obj = MessageProcessor()
    client.set_callback(callback_obj)
    time.sleep(20)

このメソッドはオーナーの利用を想定しています。ユーザーが履歴登録時にuser_idを指定すると(デフォでオーナーのuser_idを指定しておけば良かったと今気づいた)そのid宛に任意のメッセージを送ることができます。オーナーが待機している20秒間でユーザーは記録をする必要があります。

実行

今回も2つのコンソールを立ち上げる必要があります。
以下の順にコマンドを実行していけば大丈夫です。

ユーザー

$ python usage_ledger.py
type "user" or "owner"> user
user id: 04f8996da763b7a969b1028ee3007569eaf3a635486ddab211d512c85b9df8fb
domain id: 748c0b3fafa02e150928a7d3764a4bb1b16a21cb61a1d3f51ed2021933042baa
# 中略

> # 送り先のid入力を求められますが何も入力せず放置

オーナー

$ python usage_ledger.py
type "user" or "owner"> owner
user id: 4c1029697ee358715d3a14a2add817c4b01651440de808371f78165ac90dc581
domain id: 748c0b3fafa02e150928a7d3764a4bb1b16a21cb61a1d3f51ed2021933042baa

command >wait

waitコマンドを入力したらオーナーのuser_idをコピってください。

ユーザー

> 4c1029697ee358715d3a14a2add817c4b01651440de808371f78165ac90dc581

先ほどコピったidを入力します

オーナー

Received user message: {b'message': b'registered'}

オーナー側にメッセージが届きました。

まとめ

  • プログラミングガイドに沿ってクライアント間のメッセージング機能をサンプルアプリに追加しました。
  • 今回のような単なる送受信ではなく、受け取ったメッセージを起点にしてデバイスを動作させるなどすると活用の幅が広がる気がします。

※サンプルアプリのコードはこちらをご覧ください

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?