import sys import json import random import logger this = sys.modules[__name__] this.encoded = None this.pattern = None this.values = { "stack": 0, "r": 0, "g": 0, "b": 0, "tick": 0, "index": 0 } def constant(target, arg): return arg def add(target, arg): return target + arg def sub(target, arg): return target - arg def mult(target, arg): return target * arg def div(target, arg): return target / arg def mod(target, arg): if arg <= 0: return target return target % arg def rand(target, arg): return random.randrange(0, 255) def _apply(target, arg, func): if type(arg is int): return func(target, arg) elif type(arg is str) and arg in this.values: return func(target, this.values[arg]) def apply(targets, args, func): for target in range(len(targets)): if this.values[targets[target]['channel']] != None: if target <= len(args): this.values[targets[target]['channel']] = _apply( this.values[targets[target]['channel']], args[target], func) else: this.values[targets[target]['channel']] = _apply( this.values[targets[target]['channel']], 0, func) logger.debug("{} : {}".format( targets[target]['channel'], this.values[targets[target]['channel']] )) this.instructions = { "CONSTANT": constant, "ADD": add, "SUBTRACT": sub, "MULTIPLY": mult, "DIVIDE": div, "MODULO": mod, "RANDOM": rand } def default(index, tick): return (((index + tick) * 5) % 255, (tick * 42) % 255, (tick * 50) % 255) def pat(index, tick, previous_values): this.values['tick'] = tick this.values['index'] = index if this.pattern != None: for i in range(len(this.pattern)): name = this.pattern[i]['instruction']['name'] targets = this.pattern[i]['instruction']['targets'] args = [] if 'args' in this.pattern[i]['instruction']: args = this.pattern[i]['instruction']['args'] if this.instructions[name] != None: apply(targets, args, this.instructions[name]) r = this.values["r"] g = this.values["g"] b = this.values["b"] this.values["r"] = 0 this.values["g"] = 0 this.values["b"] = 0 this.values["stack"] = 0 if r > 255: r = 255 elif r < 0: r = 0 if g > 255: g = 255 elif g < 0: g = 0 if b > 255: b = 255 elif b < 0: b = 0 return (r, g, b) else: return default(index, tick) def parse(str): this.encoded = str logger.debug(this.encoded) this.pattern = json.loads(this.encoded)