// Decode an uplink message from a buffer
// payload - array of bytes
// metadata - key/value object

/** Decoder **/

// decode payload to string
//var payloadStr = decodeToString(payload);

// decode payload to JSON
var mapping = {
    "b8:27:eb:26:55:c0:01:99": {
        "deviceName": "Fee BM",
        "customer": "Faskens",
        "latitude": 32.1418251,
        "longitude": -102.2530966
    },
    "b8:27:eb:3d:e9:11:01:99": {
        "deviceName": "AW Battery",
        "customer": "Faskens",
        "latitude": 32.090579,
        "longitude": -102.244011
    }
};
var data = decodeToJson(payload);
var channel = metadata.topic.split("/").slice(-1)[0];
var devicetype = metadata.topic.split("/").slice(4)[0];
var mac = metadata.topic.split("/").slice(5)[0];
var deviceName = mapping[mac].deviceName;
var deviceType = devicetype;
var customerName = mapping[mac].customer;
//var groupName = 'All';

// use assetName and assetType instead of deviceName and deviceType
// to automatically create assets instead of devices.
// var assetName = 'Asset A';
// var assetType = 'building';

// Result object with device/asset attributes/telemetry data
var result = {
    // Use deviceName and deviceType or assetName and assetType, but not both.
    deviceName: deviceName,
    deviceType: deviceType,
    // assetName: assetName,
    // assetType: assetType,
    customerName: customerName,
    //   groupName: groupName,
    attributes: {
        latitude: mapping[mac].latitude,
        longitude: mapping[mac].longitude,
        Type: "colorpin"
    },
    telemetry: {

    }
};
result.telemetry[channel] = data[0].value;

/** Helper functions **/

function decodeToString(payload) {
    return String.fromCharCode.apply(String, payload);
}

function decodeToJson(payload) {
    // covert payload to string.
    var str = decodeToString(payload);

    // parse string to JSON
    var data = JSON.parse(str);
    return data;
}

return result;