Open8

obnizのWebSocket API調査

n0bisuken0bisuke

Touch Designer

まずは入門はこれがよさそうだった

https://www.youtube.com/watch?v=1gxN1-dUfyw&list=PLH6Y6o7cLK9hj0KpPr-5iWVUZcrioBMY8&index=1

たしかによかった。ゆるい感じも素敵。

その上でこちら。obnizと連携触る記事

https://qiita.com/yskmjp/items/6f3a7986824b3d715f8d

n0bisuken0bisuke
const obnizId = '1234-5678'; // ここに実際のobniz IDを入力してください
let host = 'wss://obniz.io';

function connect() {
  const socket = new WebSocket(`${host}/obniz/${obnizId}/ws/1`);

  socket.addEventListener('open', () => {
    console.log('WebSocket接続が開かれました');
  });

  socket.addEventListener('message', (event) => {
    const arr = JSON.parse(event.data);
    for (const obj of arr) {
      if (obj.ws?.redirect) {
        host = obj.ws.redirect;
        console.log(`新しいホストにリダイレクトします: ${host}`);
        socket.close();
        connect();
        return;
      }
      if (obj.ws?.ready) {
        console.log('obnizの準備ができました。メッセージを送信します。');
        socket.send(JSON.stringify([
          { display: { clear: true } },
          { display: { text: "Works fine." } }
        ]));
      }
    }
  });

  socket.addEventListener('close', () => {
    console.log('WebSocket接続が閉じられました');
  });

  socket.addEventListener('error', (error) => {
    console.error('WebSocketエラー:', error);
  });
}

connect();

こんな感じでNode.jsからやってみるとうまく動いた。そしてリダイレクトURLも

wss://18ws.obniz.com

n0bisuken0bisuke
(2022/08/20 追記)
最新でリダイレクト先を確認したところ8ws.obniz.ioでした。
今後も変更される可能性があるので、うまく接続できない場合は本来のWebsocket APIである「wss://obniz.io/obniz/{obniz_id}/ws/1」を「Network Address」に設定してください。
上記画面のように「redirect」として最新のリダイレクト先が表示されますので、そのアドレスを「Network Address」に書き換えて再接続してみてください。

松下さんの記事をみるとこう書いてるのでここのアドレスが今回だとwss://18ws.obniz.comに変わるらしい

n0bisuken0bisuke

全然繋がらなんなーと思ったらポート変えたらいけた。。

他の人の記事だと80のままだったんだけどwssだからそうだよね

  • 80 これだとエラー

  • 443 これで疎通

n0bisuken0bisuke

できた。

https://x.com/n0bisuke/status/1834902285056688353

中のPythonコード。PythonあんまりわからなんのでClaudeに書いてもらった・

import json

def safe_send(message):
    websocket_dat = op('/project1/websocket1')
    if websocket_dat is None:
        print("Error: WebSocket DAT not found")
        return False
    
    try:
        if hasattr(websocket_dat, 'sendText'):
            websocket_dat.sendText(json.dumps(message))
        else:
            websocket_dat.par.Receivedmessages = json.dumps(message)
        print(f"Message sent: {message}")
        return True
    except Exception as e:
        print(f"Error sending message: {e}")
        return False

def onConnect(dat):
    print('WebSocket connection opened')
    safe_send([{"display": {"clear": True}}])

def onDisconnect(dat):
    print('WebSocket connection closed')

def onReceiveText(dat, rowIndex, message):
    print(f'Received message: {message}')
    try:
        data = json.loads(message)
        for obj in data:
            if 'ws' in obj and 'ready' in obj['ws']:
                print('obniz is ready. Sending display message.')
                safe_send([
                    {"display": {"clear": True}},
                    {"display": {"text": "TouchDesigner Works!"}}
                ])
    except json.JSONDecodeError:
        print(f"JSON parsing error: {message}")
    except Exception as e:
        print(f'Error in onReceiveText: {e}')

def onMonitorMessage(dat, message):
    print(f"Monitor: {message}")

# Test function (can be called from Textport)
def test_send():
    return safe_send([{"display": {"clear": True}}, {"display": {"text": "Test from TD"}}])