leds/pattern.py

101 lines
2.3 KiB
Python
Raw Normal View History

2020-11-08 07:18:12 +00:00
import sys
2020-11-09 04:15:31 +00:00
import json
2020-11-09 06:09:47 +00:00
import random
2020-11-08 07:18:12 +00:00
2020-11-08 07:16:30 +00:00
this = sys.modules[__name__]
2020-11-09 05:33:07 +00:00
this.encoded = None
this.pattern = None
2020-11-09 04:15:31 +00:00
this.values = {
"stack": 0,
"r": 0,
"g": 0,
2020-11-09 06:09:47 +00:00
"b": 0,
"tick": 0,
"index": 0
2020-11-09 04:15:31 +00:00
}
def constant(target, arg):
return arg
def add(target, arg):
res = target + arg
if res > 255:
res = 255
elif res < 0:
res = 0
return res
def sub(target, arg):
res = target - arg
if res > 255:
res = 255
elif res < 0:
res = 0
return res
2020-11-09 06:09:47 +00:00
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])
2020-11-09 04:15:31 +00:00
def apply(targets, args, func):
for target in range(len(targets)):
2020-11-09 05:51:49 +00:00
if this.values[targets[target]['channel']] != None:
2020-11-09 06:09:47 +00:00
if target in 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)
2020-11-09 04:15:31 +00:00
this.instructions = {
"CONSTANT": constant,
"ADD": add,
2020-11-09 06:09:47 +00:00
"SUB": sub,
"RAND": rand
2020-11-09 04:15:31 +00:00
}
2020-11-08 07:16:30 +00:00
def default(index, tick):
return (((index + tick) * 5) % 255, (tick * 42) % 255, (tick * 50) % 255)
def pat(index, tick, previous_values):
2020-11-09 04:15:31 +00:00
if this.pattern != None:
for i in range(len(this.pattern)):
2020-11-09 05:50:37 +00:00
name = this.pattern[i]['instruction']['name']
targets = this.pattern[i]['instruction']['targets']
2020-11-09 06:09:47 +00:00
args = []
if 'args' in this.pattern[i]['instruction']:
args = this.pattern[i]['instruction']['args']
2020-11-09 04:15:31 +00:00
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
return (r, g, b)
else:
return default(index, tick)
2020-11-08 07:16:30 +00:00
def parse(str):
this.encoded = str
print(this.encoded)
2020-11-09 04:15:31 +00:00
this.pattern = json.loads(this.encoded)