rosbag_write_test.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package test
  2. import (
  3. "fmt"
  4. "os"
  5. "testing"
  6. "github.com/foxglove/go-rosbag"
  7. )
  8. func TestWriteRosBag(t *testing.T) {
  9. // Check if the file exists, if not create it
  10. f, err := os.OpenFile("my-bag.bag", os.O_RDWR|os.O_CREATE, 0644)
  11. if err != nil {
  12. panic(err)
  13. }
  14. defer func(f *os.File) {
  15. err := f.Close()
  16. if err != nil {
  17. fmt.Printf("Error closing file: %s\n", err)
  18. }
  19. }(f)
  20. writer, err := rosbag.NewWriter(f)
  21. if err != nil {
  22. panic(err)
  23. }
  24. err = writer.WriteConnection(&rosbag.Connection{
  25. Conn: 1,
  26. Topic: "/foo",
  27. Data: rosbag.ConnectionHeader{
  28. Topic: "/foo",
  29. Type: "Foo",
  30. MD5Sum: "abc",
  31. MessageDefinition: []byte{0x01, 0x02, 0x03},
  32. //// optional fields
  33. //CallerID: &callerID,
  34. //Latching: &latching,
  35. },
  36. })
  37. if err != nil {
  38. panic(err)
  39. }
  40. for i := 0; i < 100; i++ {
  41. data := "hello"
  42. err = writer.WriteMessage(&rosbag.Message{
  43. Conn: 0,
  44. Time: uint64(i),
  45. Data: []byte(data),
  46. })
  47. if err != nil {
  48. panic(err)
  49. }
  50. fmt.Println("保存数据", data)
  51. }
  52. }