<repo_name>PSGXerus/volumio-plugins<file_sep>/plugins/miscellanea/ambx/index.js
'use strict';

var libQ = require('kew');
var fs=require('fs-extra');
var config = new (require('v-conf'))();
var exec = require('child_process').exec;
var execSync = require('child_process').execSync;


module.exports = ambx;
function ambx(context) {
	var self = this;
	this.context = context;
	this.commandRouter = this.context.coreCommand;
	this.logger = this.context.logger;
	this.configManager = this.context.configManager;
}

ambx.prototype.onVolumioStart = function()
{
	var self = this;
	var configFile=this.commandRouter.pluginManager.getConfigurationFile(this.context,'config.json');
	this.config = new (require('v-conf'))();
	this.config.loadFile(configFile);

    return libQ.resolve();
}

ambx.prototype.onStart = function() {
    var self = this;
    var defer=libQ.defer();
    var color = self.config.get('colorHex');
    if (typeof color === 'undefined') {
            color = "#000000";
    }
    color = color.match(/[A-Za-z0-9]{2}/g).map(function(v) { return parseInt(v, 16) });

    exec("ambx_set_color -r " + color[0] + " -g " + color[1] + " -b " + color[2], function (error, stdout, stderr) {
        if(error){
            self.logger.info('No control on AmbX');
            defer.reject(new Error());
        } else {
            // Once the Plugin has successfull started resolve the promise
            defer.resolve();
        }
    });

    return defer.promise;
};

ambx.prototype.onStop = function() {
    var self = this;
    var defer=libQ.defer();

    exec("ambx_set_color -o", function (error, stdout, stderr) {
        if(error){
            self.logger.info('No control on AmbX');
            defer.reject(new Error());
        } else {
            // Once the Plugin has successfull stopped resolve the promise
            defer.resolve();
        }
    });

    return defer.promise;
};

ambx.prototype.onRestart = function() {
    var self = this;
    // Optional, use if you need it
};


// Configuration Methods -----------------------------------------------------------------------------

ambx.prototype.getUIConfig = function() {
    var defer = libQ.defer();
    var self = this;

    var lang_code = this.commandRouter.sharedVars.get('language_code');

    self.commandRouter.i18nJson(__dirname+'/i18n/strings_'+lang_code+'.json',
        __dirname+'/i18n/strings_en.json',
        __dirname + '/UIConfig.json')
        .then(function(uiconf)
        {
            uiconf.sections[0].content[0].value = self.config.get('colorHex');
            defer.resolve(uiconf);
        })
        .fail(function()
        {
            defer.reject(new Error());
        });

    return defer.promise;
};

ambx.prototype.setColor = function(data) {
    var self = this;

    var defer = libQ.defer();
    var color = data['colorHex']
    self.config.set('colorHex', color);
    color = color.match(/[A-Za-z0-9]{2}/g).map(function(v) { return parseInt(v, 16) });

    exec("ambx_set_color -r " + color[0] + " -g " + color[1] + " -b " + color[2], function (error, stdout, stderr) {
        if(error){
            self.commandRouter.pushToastMessage('error', "Set Color", "No connection to AmbX");
            defer.reject(new Error());
        } else {
            self.commandRouter.pushToastMessage('success', "Set Color", "Set color was successful");
            defer.resolve({});
        }
    });

    return defer.promise;
}

ambx.prototype.getConfigurationFiles = function() {
	return ['config.json'];
}

ambx.prototype.setUIConfig = function(data) {
	var self = this;
	//Perform your installation tasks here
};

ambx.prototype.getConf = function(varName) {
	var self = this;
	//Perform your installation tasks here
};

ambx.prototype.setConf = function(varName, varValue) {
	var self = this;
	//Perform your installation tasks here
};
<file_sep>/plugins/miscellanea/ambx/uninstall.sh
#!/bin/bash

# Uninstall dependendencies
sudo rm /etc/udev/rules.d/10-ambx.rules
sudo rm -r /usr/lib/python2.7/dist-packages/ambx

echo "Done"
echo "pluginuninstallend"
<file_sep>/plugins/miscellanea/ambx/ambx_set_color
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from ambx.ambx import AMBX, Lights
import struct
import sys, getopt

lights = [Lights.LEFT, Lights.RIGHT, Lights.WWLEFT, Lights.WWCENTER, Lights.WWRIGHT]

def print_help():
    print 'ambx_set_color [ -h | -o | -r <red> -g <green> -b <blue>]'

def set_color(red, green, blue):
    dev = None
    try:
        dev = AMBX(0)

        for light in lights:
            try:
                dev.set_color_rgb8(light, [red, green, blue])
            except IOError:
                print 'USB Error'
                break

    except IndexError:
        if dev is None:
            print 'No AmbX found!'

if __name__ == '__main__':
    argv = sys.argv[1:]
    try:
        opts, args = getopt.getopt(argv,"hor:g:b:",["help", "red=","green=","blue=", "off"])
    except getopt.GetoptError:
        print_help()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print_help()
            sys.exit()
        elif opt in ("-r", "--red"):
            red = int(arg)
        elif opt in ("-g", "--green"):
            green = int(arg)
        elif opt in ("-b", "--blue"):
            blue = int(arg)
        elif opt in ("-o", "--off"):
            red = 0
            green = 0
            blue = 0
    set_color(red, green, blue)
<file_sep>/plugins/miscellanea/ambx/install.sh
#!/bin/bash

echo "Installing PyUSB"
sudo apt update
sudo apt -y install python-pip --no-install-recommends
sudo pip install pyusb

echo "Installing color change executable"
sudo sh -c 'curl -L https://raw.githubusercontent.com/PSGXerus/ambx-sound-light/master/10-ambx.rules > /etc/udev/rules.d/10-ambx.rules'
sudo cp ambx_set_color /usr/bin
sudo mkdir -p /usr/lib/python2.7/dist-packages/ambx
sudo touch /usr/lib/python2.7/dist-packages/ambx/__init__.py
sudo sh -c 'curl -L https://raw.githubusercontent.com/PSGXerus/ambx-sound-light/master/ambx/ambx.py > /usr/lib/python2.7/dist-packages/ambx/ambx.py'

echo "plugininstallend"
