MCPcopy Index your code
hub / github.com/cisco/senml / Encode

Function Encode

senml.go:228–364  ·  view source on GitHub ↗

Encode takes a SenML record, and encodes it using the given format.

(s SenML, format Format, options OutputOptions)

Source from the content-addressed store, hash-verified

226
227// Encode takes a SenML record, and encodes it using the given format.
228func Encode(s SenML, format Format, options OutputOptions) ([]byte, error) {
229 var data []byte
230 var err error
231
232 if options.Topic == "" {
233 options.Topic = "senml"
234 }
235
236 s.Xmlns = "urn:ietf:params:xml:ns:senml"
237
238 switch {
239
240 case format == JSON:
241 // ouput JSON version
242 if options.PrettyPrint {
243 // data, err = json.MarshalIndent(s.Records, "", " ")
244 var lines string
245 lines += fmt.Sprintf("[\n ")
246 for i, r := range s.Records {
247 if i != 0 {
248 lines += ",\n "
249 }
250 recData, err := json.Marshal(r)
251 if err != nil {
252 //fmt.Println("error encoding JSON SenML", err)
253 return nil, err
254 }
255 lines += fmt.Sprintf("%s", recData)
256 }
257 lines += fmt.Sprintf("\n]\n")
258 data = []byte(lines)
259 } else {
260 data, err = json.Marshal(s.Records)
261 }
262 if err != nil {
263 //fmt.Println("error encoding JSON SenML", err)
264 return nil, err
265 }
266
267 case format == XML:
268 // output a XML version
269 if options.PrettyPrint {
270 data, err = xml.MarshalIndent(s, "", " ")
271 } else {
272 data, err = xml.Marshal(s)
273 }
274 if err != nil {
275 //fmt.Println("error encoding XML SenML", err)
276 return nil, err
277 }
278
279 case format == CSV:
280 // output a CSV version
281 var lines string
282 for _, r := range s.Records {
283 if r.Value != nil {
284 // TODO - replace sprintf with bytes.Buffer
285 lines += fmt.Sprintf("%s,", r.Name)

Callers 7

ExampleEncode1Function · 0.92
ExampleEncode2Function · 0.92
TestEncodeFunction · 0.92
TestDecodeFunction · 0.92
TestNormalizeFunction · 0.92
processDataFunction · 0.92
processDataFunction · 0.92

Calls 1

toRecordsMethod · 0.80

Tested by 5

ExampleEncode1Function · 0.74
ExampleEncode2Function · 0.74
TestEncodeFunction · 0.74
TestDecodeFunction · 0.74
TestNormalizeFunction · 0.74