1
0
Fork 0
baconscript/bacon/script.py

76 lines
2.4 KiB
Python

"""comment.py: Hog 4 comment macro interpreter and OSC bridge.
"""
import configparser
import logging
import sys
from antlr4 import CommonTokenStream, InputStream, ParseTreeWalker
from antlr4.error.ErrorListener import ErrorListener
from pythonosc import udp_client
from .commentmacro.CommentMacroLexer import CommentMacroLexer
from .commentmacro.CommentMacroParser import CommentMacroParser
from .OscListener import OscCommentMacroListener
# define an error listener that raises SyntaxError exceptions
class SyntaxErrorListener(ErrorListener):
def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
raise SyntaxError("line "+str(line)+":"+str(column)+" "+msg)
def loadConfig(file='server.cfg'):
# empty server dictionary
servers = {}
# open config file
config = configparser.ConfigParser(allow_no_value=True)
config.read(file)
# set up each hog device
for name in config.get('network', 'hogs').split(','):
try:
# move to config section
server = config[name.strip().strip('\"')]
# read settings
ip = server.get("ip", "10.0.0.100")
port = server.getint("port", 7001)
net = server.getint("net", 1)
# osc clients are added to the dictionary with the net # as the key
logging.info("Adding Hog device at net# " + str(net))
servers[net] = udp_client.SimpleUDPClient(ip, port)
except KeyError as e:
print('Error configuring net#', net, e)
continue
return servers
# init reusable walker and listener
walker = ParseTreeWalker()
listener = OscCommentMacroListener()
# main handler for processing input
def comment(text):
# force upper case
text = text.upper()
# generate text stream
input_stream = InputStream(text)
# lex the text stream
lexer = CommentMacroLexer(input_stream)
# get token stream from lexer
stream = CommonTokenStream(lexer)
# parse the token steam
parser = CommentMacroParser(stream)
# attach an error handler to the parser
parser._listeners.append(SyntaxErrorListener())
try:
# get tree from parser
tree = parser.prog()
# walk the tree
walker.walk(listener, tree)
except SyntaxError as e:
logging.debug(e) # antlr internal listener prints the error
# # log it to the debug logging anyway