rosbag_write_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package test
  2. import (
  3. "cicv-data-closedloop/pjisuv_msgs"
  4. "fmt"
  5. "log"
  6. "os"
  7. "testing"
  8. "time"
  9. "github.com/bluenviron/goroslib/v2"
  10. "github.com/foxglove/go-rosbag"
  11. )
  12. func TestWriteRosBag(t *testing.T) {
  13. // 指定文件路径
  14. filePath := "C:\\Users\\mlxengingin\\Desktop\\1118\\my-bag.bag"
  15. // 以读写模式打开(或创建并清空)文件
  16. f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
  17. if err != nil {
  18. // 打开(或创建并清空)文件时出错
  19. panic(fmt.Errorf("无法打开或创建文件: %v", err))
  20. }
  21. defer f.Close() // 确保文件在函数结束时被关闭
  22. // 后续的文件写入操作...
  23. t.Log("文件已成功打开(或创建并清空)。")
  24. writer, err := rosbag.NewWriter(f)
  25. if err != nil {
  26. panic(err)
  27. }
  28. err = writer.WriteConnection(&rosbag.Connection{
  29. Conn: 1,
  30. Topic: "/cicv_location",
  31. Data: rosbag.ConnectionHeader{
  32. Topic: "/cicv_location",
  33. Type: "perception_msgs/PerceptionLocalization",
  34. MD5Sum: "b871ae769d4b537baab00d1c75ff3891",
  35. MessageDefinition: []byte("定位信息"),
  36. //// optional fields
  37. //CallerID: &callerID,
  38. //Latching: &latching,
  39. },
  40. })
  41. if err != nil {
  42. panic(err)
  43. }
  44. // -------------------------------------------------------------------------------------
  45. // create a node and connect to the master
  46. n, err := goroslib.NewNode(goroslib.NodeConf{
  47. Name: "goroslib_sub",
  48. MasterAddress: "127.0.0.1:11311",
  49. })
  50. if err != nil {
  51. panic(err)
  52. }
  53. defer n.Close()
  54. // create a subscriber
  55. sub, err := goroslib.NewSubscriber(goroslib.SubscriberConf{
  56. Node: n,
  57. Topic: "/cicv_location",
  58. Callback: func(msg *pjisuv_msgs.PerceptionLocalization) {
  59. log.Printf("Incoming: %+v\n", msg)
  60. nowInt := time.Now().Unix()
  61. data := pjisuv_msgs.PerceptionLocalization{}
  62. err = writer.WriteMessage(&rosbag.Message{
  63. Conn: 1,
  64. Time: uint64(nowInt),
  65. Data: []byte(msg),
  66. })
  67. if err != nil {
  68. panic(err)
  69. }
  70. t.Log("当前时间", uint64(nowInt))
  71. t.Log("保存数据", data)
  72. },
  73. })
  74. if err != nil {
  75. panic(err)
  76. }
  77. defer sub.Close()
  78. // // wait for CTRL-C
  79. // c := make(chan os.Signal, 1)
  80. // signal.Notify(c, os.Interrupt)
  81. // <-c
  82. // ------------------------------------------------------------------------------------
  83. }