DotCloud/Assets/ROS2ListenerExample.cs

69 lines
2.2 KiB
C#
Raw Normal View History

2024-12-09 16:51:45 +08:00
// Copyright 2019-2021 Robotec.ai.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using ROS2;
using sensor_msgs.msg;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
namespace ZC
{
/// <summary>
/// An example class provided for testing of basic ROS2 communication
/// </summary>
public class ROS2ListenerExample : MonoBehaviour
{
private ROS2UnityComponent ros2Unity;
private ROS2Node ros2Node;
private ISubscription<PointCloud2> chatter_sub;
void Start()
{
ros2Unity = GetComponent<ROS2UnityComponent>();
}
void Update()
{
if (ros2Node == null && ros2Unity.Ok())
{
ros2Node = ros2Unity.CreateNode("ROS2UnityListenerNode");
chatter_sub = ros2Node.CreateSubscription<PointCloud2>(
"chatter_PointCloud2", msg =>
{
unsafe
{
var objData = msg.Data;
var pinGCArrayAndGetDataAddress = UnsafeUtility.PinGCArrayAndGetDataAddress(objData, out var handle);
try
{
var gcArrayAndGetDataAddress = (long*)pinGCArrayAndGetDataAddress;
var ticks = *gcArrayAndGetDataAddress;
var dateTime = new DateTime(ticks);
Debug.Log($"re:{DateTime.Now:HH:mm:ss.fff}");
Debug.Log($"se:{dateTime:HH:mm:ss.fff}");
}
finally
{
UnsafeUtility.ReleaseGCObject(handle);
}
}
});
}
}
}
} // namespace ROS2