Skip to content

Instantly share code, notes, and snippets.

@masatoshiitoh
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masatoshiitoh/8b5c14d0ca2a20e3a7a1 to your computer and use it in GitHub Desktop.
Save masatoshiitoh/8b5c14d0ca2a20e3a7a1 to your computer and use it in GitHub Desktop.
m2mqtt(.net 2.0対応fork版)をUnityで使うときの、Unity側呼び出しサンプル
// Please use this with M2mqtt4Unity library.
// about M2mqtt4Unity, see below.
// https://m2mqtt.codeplex.com/SourceControl/network/forks/masatoshiitoh/M2mqtt4Unity
using UnityEngine;
using System.Collections;
using uPLibrary.Networking.M2Mqtt;
using System;
using System.Runtime.InteropServices;
using System.Text;
using uPLibrary.Networking.M2Mqtt.Messages;
public class mqtt : MonoBehaviour {
//http://tdoc.info/blog/2014/11/10/mqtt_csharp.html
private MqttClient4Unity client;
public string brokerHostname = null;
public int brokerPort = 1883;
public string userName = null;
public string password = null;
public string topic = null;
private Queue msgq = new Queue();
string lastMessage = null;
// Use this for initialization
void Start () {
if (brokerHostname != null && userName != null && password != null) {
Connect ();
client.Subscribe(topic);
}
}
// Update is called once per frame
void Update () {
while (client.Count() > 0) {
string s = client.Receive();
msgq.Enqueue(s);
Debug.Log("received :" + s);
}
if (Input.GetMouseButtonDown (0) == true) {
client.Publish(topic, System.Text.Encoding.ASCII.GetBytes("nice click!"));
}
}
void OnGUI() {
if (msgq != null && msgq.Count > 0)
{
if (lastMessage == null) {
lastMessage = (string)msgq.Dequeue();
}else{
lastMessage = (string)msgq.Dequeue();
lastMessage = null;
}
}
GUILayout.Label(lastMessage);
}
public void Connect()
{
// SSL使用時はtrue、CAを指定
client = new MqttClient4Unity(brokerHostname, brokerPort, false,
null);
// clientidを生成
string clientId = Guid.NewGuid().ToString();
client.Connect(clientId, userName, password);
}
public void Publish(string _topic, string msg)
{
client.Publish(
_topic, Encoding.UTF8.GetBytes(msg),
MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false); // retainがfalse
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment