func play() (err error) { w3 := w3u.New() u, err := unit.NewUnit("hpea", "h001") if err != nil { return err } err = u.AddField("una1", 1) if err != nil { return err } w3.AddUnit(u) w3.PrintUnits() w3.Write("a.w3u") w3 = w3u.New() w3, err = w3u.Open("a.w3u") if err != nil { return err } fmt.Printf("%#v\n", w3) return nil }
func TestWrite(t *testing.T) { wu := w3u.New() unit, err := unit.NewUnit("hpea", "h001") if err != nil { t.Fail() } err = unit.AddField("una1", 1) if err != nil { t.Fail() } wu.AddUnit(unit) err = wu.Write("/tmp/a.w3u") if err != nil { t.Fail() } }
func Open(fileName string) (w3 *W3u, err error) { w3 = New() // Read w3u file file, err := os.Open(fileName) if err != nil { return nil, err } // Read all bytes from the file pointer buf, err := ioutil.ReadAll(file) if err != nil { return nil, err } // Make the bytes into a Buffer buffer := bytes.NewBuffer(buf) // Check header w3.Header = buffer.Next(8) if !w3.IsHeader() { return nil, errorsutil.Errorf("Invalid w3u header! Correct header: % X, your header: % X", Header, w3.Header) } // Number of units numUnits := uint(buffer.Next(1)[0]) if numUnits < 0 { return nil, errorsutil.Errorf("Invalid number of units: %d\n", numUnits) } // Skip seperator buffer.Next(3) for i := 0; i < int(numUnits); i++ { // Base unit rawcode baseUnit, err := GetRawCode(buffer) if err != nil { return nil, err } // Custom unit rawcode customUnit, err := GetRawCode(buffer) if err != nil { return nil, err } u, err := unit.NewUnit(baseUnit, customUnit) if err != nil { return nil, err } // Number of fields numFields := uint(buffer.Next(1)[0]) if numFields < 0 { return nil, errorsutil.Errorf("Invalid number of fields: %d\n", numFields) } // Skip seperator buffer.Next(3) for j := 0; j < int(numFields); j++ { f := new(field.Field) // Field name in raw data fieldName, err := GetRawCode(buffer) if err != nil { return nil, err } f.Name = fieldName // Type of field, 0:int(and bool), 1:fixed decimal point, 2:float, 3:string fieldType := int(buffer.Next(1)[0]) // 0, 1, 2, 3 are valid field types if fieldType < 0 || fieldType > 3 { return nil, errorsutil.Errorf("Invalid field type: %d\n", fieldType) } // Skip seperator buffer.Next(3) // ###Add fixed switch fieldType { case 0: f.Value, err = temp.FromBuf(buffer.Next(3)) if err != nil { return nil, err } // f.Value = temp.BigToLittle(buffer.Next(3)) case 2: // Float value f.Value = buffer.Next(3) case 3: // Get next seperator, that's were the string ends strLen := bytes.Index(buffer.Bytes(), []byte{00, 00, 00}) // String value f.Value = string(buffer.Next(strLen)) } // Skip field seperator buffer.Next(5) u.Fields = append(u.Fields, *f) } w3.Units = append(w3.Units, *u) } return w3, nil }