func BuildMessage()

in lib/ec2macossystemmonitor/relayd.go [33:80]


func BuildMessage(tag string, data string, compress bool) ([]byte, error) {
	payload := SerialPayload{
		Tag: tag,
		Compress: compress,
		Data: data,
	}

	// 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 nil, fmt.Errorf("ec2macossystemmonitor: couldn't get compression writer: %w", err)
		}
		_, err = w.Write([]byte(data))
		if err != nil {
			return nil, fmt.Errorf("ec2macossystemmonitor: couldn't copy compressed data: %w", err)
		}
		err = w.Close()
		if err != nil {
			return nil, fmt.Errorf("ec2macossystemmonitor: couldn't close compressor: %w", err)
		}

		payload.Data = base64.StdEncoding.EncodeToString(b.Bytes())
	}

	// Marshal the payload to wrap in the relay output message.
	payloadBytes, err := json.Marshal(payload)
	if err != nil {
		return nil, fmt.Errorf("ec2macossystemmonitor: %w", err)
	}

	messageBytes, err := json.Marshal(SerialMessage{
		Checksum: adler32.Checksum(payloadBytes),
		Payload:  string(payloadBytes),
	})
	if err != nil {
		return nil, fmt.Errorf("ec2macossystemmonitor: marshal: %w", err)
	}

	// FIXME: message shouldn't append the newline, that's up to clients to
	// decide (ie: flushing data as needed to clients/servers).
	messageBytes = append(messageBytes, "\n"...)

	return messageBytes, nil
}