in lib/ec2macossystemmonitor/relayd.go [24:77]
func BuildMessage(tag string, data string, compress bool) ([]byte, error) {
var payload SerialPayload
// This determines if the data will be passed in as provided or zlib compressed and then base64 encoded
// Some payload will exceed the limit of what can be sent on the serial device, so compression allows more data
// to be sent. base64 encoding allows safe characters only to be passed on the device
if compress {
var b bytes.Buffer
w, err := zlib.NewWriterLevel(&b, 9)
if err != nil {
return []byte{}, fmt.Errorf("ec2macossystemmonitor: couldn't get compression writer: %s", err)
}
_, err = w.Write([]byte(data))
if err != nil {
return []byte{}, fmt.Errorf("ec2macossystemmonitor: couldn't copy compressed data: %s", err)
}
err = w.Close()
if err != nil {
return []byte{}, fmt.Errorf("ec2macossystemmonitor: couldn't close compressor: %s", err)
}
encodedData := base64.StdEncoding.EncodeToString(b.Bytes())
payload = SerialPayload{
Tag: tag,
Compress: compress,
Data: encodedData,
}
} else {
// No compression needed, simply create the SerialPayload
payload = SerialPayload{
Tag: tag,
Compress: compress,
Data: data,
}
}
// Once the payload is created, it's converted to json
payloadBytes, err := json.Marshal(payload)
if err != nil {
return []byte{}, fmt.Errorf("ec2macossystemmonitor: couldn't get %s into json", err)
}
// A checksum is computed on the json payload for the serial message
checkSum := adler32.Checksum(payloadBytes)
message := SerialMessage{
Csum: checkSum,
Payload: string(payloadBytes),
}
// Once the message is created, it's converted to json
messageBytes, err := json.Marshal(message)
if err != nil {
return []byte{}, fmt.Errorf("ec2macossystemmonitor: couldn't convert %s into json", err)
}
messageBytes = append(messageBytes, "\n"...)
return messageBytes, nil
}