使用 Arduino 进行 OSC 通信。
测试时使用的硬件是 NodeMCU-32S 和基于 NodeJS UDP 的 osc.js 进行通信。如果使用 vvvv 发送消息,可以选择是 message 还是 bundle;如果使用 Ventuz 来发送消息,NodeMCU-32S 一定要使用 OSCBundle 来监听;TouchDesigner 还没有测试……
#include <Arduino.h> #include <WiFi.h> #include <WiFiUdp.h> #include <OSCBundle.h> #include <OSCMessage.h> const char MY_SSID[] = "WIFI名称"; const char MY_PASSWORD[] = "WIFI密码"; const unsigned int UDP_PORT = 3333; IPAddress localIP(192, 168, 1, 33); IPAddress gateway(192, 168, 1, 1); IPAddress subnet(255, 255, 255, 0); WiFiUDP udp; /* 初始化 WIFI 和 UDP */ void setupWiFiAndUdp() { if(!WiFi.config(localIP, gateway, subnet)) { Serial.println("STA Failed to configure"); } Serial.print("Connecting to "); Serial.println(MY_SSID); WiFi.begin(MY_SSID, MY_PASSWORD); while(WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected!"); Serial.print("IP Address: "); Serial.println(WiFi.localIP()); udp.begin(UDP_PORT); Serial.print("UDP Remote Ip: "); Serial.print(udp.remoteIP()); Serial.print(", Remote Port: "); Serial.println(udp.remotePort()); } /* 监听 OSCMessage */ void handleMessage(OSCMessage& msg) { // name int len = msg.getDataLength(0); char name[len]; msg.getString(0, name, len); // age int age = msg.getInt(1); // height float height = msg.getFloat(2); Serial.print("OSCMessage name: "); Serial.print(name); Serial.print(", age: "); Serial.print(age); Serial.print(", height: "); Serial.println(height); } /* 初始化 */ void setup() { Serial.begin(115200); delay(3000); setupWiFiAndUdp(); } /* 循环 */ void loop() { OSCMessage msg; unsigned int size = udp.parsePacket(); if(size > 0) { while(size --) { msg.fill(udp.read()); } if(!msg.hasError()) { msg.dispatch("/foo", handleMessage); } } /* * 如果发送的是 Bundle 请用 OSCBundle OSCBundle bundle; unsigned int size = udp.parsePacket(); if(size > 0) { while(size --) { bundle.fill(udp.read()); } if(!bundle.hasError()) { bundle.dispatch("/foo", handleMessage); } } */ }
var osc = require("osc"); // Create an osc.js UDP Port listening on port 57121. var udpPort = new osc.UDPPort({ localAddress: "0.0.0.0", localPort: 4444, metadata: false }); // Listen for incoming OSC messages. udpPort.on("message", (oscMsg, timeTag, info) => { console.log("An OSC message just arrived!", oscMsg); console.log("Remote info is: ", info); }); // Open the socket. udpPort.open(); // When the port is read, send an OSC message to, say, SuperCollider udpPort.on("ready", () => { console.log('READY'); setInterval(doSend, 1000); }); function doSend() { udpPort.send({ address: "/foo", args: [ { type: 's', value: 'futurama' }, { type: 'i', value: 38 }, { type: 'f', value: 176.584 } ] }, "192.168.1.33", 3333); } function doSendPackets() { udpPort.send({ 'timeTag': { native: Date.now() }, 'packets': [ { address: "/foo", args: [ { type: 's', value: 'futurama' }, { type: 'i', value: 38 }, { type: 'f', value: 176.584 } ] } ] }, "192.168.1.33", 3333); }