public void Write(BridgeType message, Action completed) { var sb = new StringBuilder(4096); sb.Append('{'); { sb.Append("\"op\":\"publish\","); sb.Append("\"topic\":\""); sb.Append(Topic); sb.Append("\","); sb.Append("\"msg\":"); try { RosSerialization.Serialize(message, sb); } catch (Exception ex) { // explicit logging of exception because this method is often called // from background threads for which Unity does not log exceptions Debug.LogException(ex); throw; } } sb.Append('}'); var data = sb.ToString(); Instance.SendAsync(data, completed); }
void OnMessage(object sender, MessageEventArgs args) { var json = JSONNode.Parse(args.Data); string op = json["op"]; if (op == "publish") { string topic = json["topic"]; Action <JSONNode> callback; lock (Subscribers) { Subscribers.TryGetValue(topic, out callback); } if (callback == null) { Debug.LogWarning($"Received message on '{topic}' topic which nobody subscribed"); } else { callback(json["msg"]); } } else if (op == "call_service") { var topic = json["service"]; var id = json["id"]; Action <JSONNode, Action <object> > callback; lock (Services) { Services.TryGetValue(topic, out callback); } if (callback == null) { Debug.LogWarning($"Received service message on '{topic}' topic which nobody serves"); } else { callback(json["args"], res => { var sb = new StringBuilder(1024); sb.Append('{'); { sb.Append("\"op\":\"service_response\","); sb.Append("\"id\":"); sb.Append(id.ToString()); sb.Append(","); sb.Append("\"service\":\""); sb.Append(topic.Value); sb.Append("\","); sb.Append("\"values\":"); try { RosSerialization.Serialize(res, sb); } catch (Exception ex) { // explicit logging of exception because this method is often called // from background threads for which Unity does not log exceptions Debug.LogException(ex); throw; } sb.Append(","); sb.Append("\"result\":true"); } sb.Append('}'); var data = sb.ToString(); Socket.SendAsync(data, null); }); } } else if (op == "set_level") { // ignore these } else { Debug.LogWarning($"Unknown operation from rosbridge: {op}"); } }