DotCloud/Assets/ROS2TalkerExample.cs

81 lines
2.3 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 ROS2TalkerExample : MonoBehaviour
{
// Start is called before the first frame update
private ROS2UnityComponent ros2Unity;
private ROS2Node ros2Node;
private IPublisher<PointCloud2> chatter_pub;
private int i;
void Start()
{
ros2Unity = GetComponent<ROS2UnityComponent>();
}
void Update()
{
if (ros2Unity.Ok())
{
if (ros2Node == null)
{
ros2Node = ros2Unity.CreateNode("ROS2UnityTalkerNode");
chatter_pub = ros2Node.CreatePublisher<PointCloud2>("chatter_PointCloud2");
}
i++;
PointCloud2 msg = new PointCloud2();
msg.Point_step = 16;
msg.Data = new byte[150000 * msg.Point_step];
msg.Width = 1;
msg.Row_step = 16;
msg.Height = (uint)(150000);
unsafe
{
var ptr = UnsafeUtility.PinGCArrayAndGetDataAddress(msg.Data, out var handle);
try
{
var dateTime = (long*)ptr;
*dateTime = DateTime.Now.Ticks;
}
finally
{
UnsafeUtility.ReleaseGCObject(handle);
}
}
if (Time.frameCount % 60 == 0)
{
chatter_pub.Publish(msg);
Debug.Log($"[{DateTime.Now:HH:mm:ss.fff}]{Time.frameCount}");
}
}
}
}
} // namespace ROS2