rosbag_write_test.go 2.2 KB

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