Beispiel #1
0
 def start_osc_server(self):
     s = OSC.ThreadingOSCServer(('127.0.0.1', self.recv_port))
     s.addDefaultHandlers()
     s.addMsgHandler('/monome/grid/led/set', self.osc_dispatch)
     t = threading.Thread(target=s.serve_forever)
     t.start()
     self.osc_client = s.client
Beispiel #2
0
	def __init__(self, lpackHost, lpackPort, ledMap, oscHost, oscPort):
	""" установка начальных значений, создание OSC-сервера, назначение обработчиков, инициализация lightpack
		lpackHost, lpackPort - IP и порт хоста с Лайтпаком
		ledMap               - массив для переопределения порядка светодиодов Лайтпака
		oscHost, oscPort     - IP и порт на котором будет запущен OSC-сервер """ 

		self.r = 127
		self.g = 127
		self.b = 127
		self.smooth = 127
		self.brightness = 0.5
		self.ledMap = [[3,2,1],[4,-1,10],[5,-1,9],[6,7,8]]
		self.enabledLeds = Set([1,2,3,4,5,6,7,8,9,10])
		self.gamma = 2
	
		self.lpack = lightpack.lightpack(lpackHost, lpackPort, ledMap)
		self.lpack.connect()
		self.oscServer = OSC.ThreadingOSCServer((oscHost, oscPort))
		self.oscServer.addDefaultHandlers()
		
		self.oscClient = OSC.OSCClient()

		self.profiles = self.lpack.getProfiles()
		self.currentProfileIndex = 0

		self.mapControls()

		print "Registered Callback-functions are :"
		for addr in self.oscServer.getOSCAddressSpace():
			print addr
Beispiel #3
0
    def __init__(self, robotData):
        print "Create behavior manager with default behavior 'IdleState'"

        self.robotData = robotData
        self.lastTime = time.time()
        self.active = False
        self.thread = None

        self.currentState = BaseState()
        self.setState("IdleState")

        # setup server
        receive_address = '192.168.0.255', 8000
        self.server = OSC.ThreadingOSCServer(receive_address) 
        
        # setup handlers
        self.server.addMsgHandler("/IdleState", self.changeStateWithOSC)
        self.server.addMsgHandler("/BaseState", self.changeStateWithOSC)
        self.server.addMsgHandler("/ShakenState", self.changeStateWithOSC)
        self.server.addMsgHandler("/AngeredState", self.changeStateWithOSC)
        self.server.addMsgHandler("/BeingPetState", self.changeStateWithOSC)
        self.server.addMsgHandler("/ReturnToBaseState", self.changeStateWithOSC)
        self.server.addMsgHandler("/RemoveSnowState", self.changeStateWithOSC)
        self.server.addMsgHandler("/AttackBaseState", self.changeStateWithOSC)
        self.server.addMsgHandler("/DriveState", self.changeStateWithOSC)

        print "Serving on {}".format(self.server.server_address) 
        self.server_thread = Thread(target=self.server.serve_forever)
        self.server_thread.start()
        print "done" 
Beispiel #4
0
def main(args):
    addr = (args.addr, args.port)
    osc = OSC.ThreadingOSCServer(addr, bind_and_activate=False)

    # setup multicast
    osc.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
    osc.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
    osc.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    osc.server_bind()
    mcast_iface_aton = socket.inet_aton(args.iface)
    osc.socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF,
                          mcast_iface_aton)
    mreq = socket.inet_aton(args.addr) + mcast_iface_aton
    osc.socket.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    osc.timeout = 0.1

    if not args.no_curses:
        osc.handle_timeout = display_update
    else:
        global out_lock
        out_lock = threading.Lock()

    osc.server_activate()

    osc.addMsgHandler("default", handle_osc)

    osc.serve_forever()
Beispiel #5
0
 def start_osc_server(self, port):
     s = OSC.ThreadingOSCServer(('localhost', port))
     s.addDefaultHandlers()
     s.addMsgHandler('/monome/enc/key', self.osc_dispatch)
     s.addMsgHandler('/monome/enc/delta', self.osc_dispatch)
     t = threading.Thread(target=s.serve_forever)
     t.start()
    def __init__(self, FAKE_CONNECTION=None):
        super(Anoto, self).__init__()

        if FAKE_CONNECTION is None:
            FAKE_CONNECTION = config.getboolean('Anoto Server',
                                                'fake_connection')
        self.speed = TraceSpeed()
        self.keep_serving = True

        if not FAKE_CONNECTION:
            receive_address = (config.get('Anoto Server', 'receive_ip'),
                               config.getint('Anoto Server', 'receive_port'))
            # self.osc_server = OSC.OSCServer(receive_address)  # basic
            self.osc_server = OSC.ThreadingOSCServer(receive_address)
        else:
            receive_address = (config.get('Anoto Server', 'fake_receive_ip'),
                               config.getint('Anoto Server', 'receive_port'))
            self.osc_server = OSC.ThreadingOSCServer(receive_address)
        # either way - print tracebacks
        self.osc_server.print_tracebacks = True
	def __init__(self, ip, port):
		self.receive_address = ip, port
		self.s = OSC.ThreadingOSCServer(self.receive_address)
		self.s.addDefaultHandlers() # this registers a 'default' handler (for unmatched messages)
		self.st = threading.Thread(target=self.s.serve_forever)
		self.st.start()

		#Initialize variables
		self.curAddr = "No OSC address"
		self.curMess = "No OSC message"

		print "Starting OSCServer"
    def __init__(self, ip, port):
        self.receive_address = (ip, port)
        self.s = OSC.ThreadingOSCServer(self.receive_address)
        self.s.addDefaultHandlers()  # this registers a 'default' handler (for unmatched messages)
        self.st = threading.Thread(target=self.s.serve_forever)
        self.st.start()

        # Initialize variables
        self.curAddr = "No OSC address"  # It can take the value of "movuino", "streamo", "gesture", "repetions"
        self.curMess = "No OSC message"

        print("Starting OSCServer")
Beispiel #9
0
 def startServer(self, addr, port):
     self.addr = (addr, port)  #home wifi
     #super(OSCInterface, self).__init__()
     self.threadedOSC = OSC.ThreadingOSCServer(self.addr)
     self.threadedOSC.addDefaultHandlers()
     self.threadedOSC.addMsgHandler("/1/play", self.play)
     self.threadedOSC.addMsgHandler("/1/record", self.record)
     self.threadedOSC.addMsgHandler("/1/skip", self.skip)
     self.threadedOSC.addMsgHandler("/1/keep", self.keep)
     self.threadedOSC.addMsgHandler("/1/delete", self.delete)
     self.threadedOSC.addMsgHandler("/1/threshold", self.threshold)
     self.threadedOSC.addMsgHandler("/1/stop", self.stop)
     self.st = threading.Thread(target=self.threadedOSC.serve_forever)
     self.st.start()
     print("Starting openOSC on addr and port: " + str(addr) + ":" +
           str(port))
Beispiel #10
0
    def setup_osc_server(self, port=9002, address='localhost'):
        """
        Sets OSC server to listening for messages from Pd.
        default port is 9002 on localhost.
        """

        if address == 'localhost':
            address = '127.0.0.1'
        self.osc_server = OSC.ThreadingOSCServer((address, port))
        self.osc_server.addDefaultHandlers()
        for ch in self.channel_list:
            self.osc_server.addMsgHandler('/%s' % ch, self._osc_server_handler)

        self.osc_thread = mp.Process(target=self.osc_server.serve_forever)
        # self.osc_thread = mp.Process(target = self._osc_server_serving)
        # self.osc_thread.setDaemon(True)
        self.osc_server_setup = True
Beispiel #11
0
def main():
    signal.signal(signal.SIGINT, signal_handler)

    s = OSC.ThreadingOSCServer(("localhost", 5444))  # threading
    print "Creating OSCServer on port 5444..."
    s.addMsgHandler("/OSC", osc_handler)  # adding our function
    st = Thread(target=s.serve_forever)
    st.start()

    tornado.options.parse_command_line()
    app = Application()
    app.listen(options.port)
    io_loop = tornado.ioloop.IOLoop.instance()
    tornado.ioloop.PeriodicCallback(OSCWebSocketHandler.update_coords,
                                    10.0,
                                    io_loop=io_loop).start()
    io_loop.start()
Beispiel #12
0
def create_osc_server(ip, port):
    receive_address = (ip, port)
    server = OSC.ThreadingOSCServer(receive_address)
    server.addDefaultHandlers() # 'default' handler for unmatched messages 
    server.addMsgHandler("/print", printing_handler) # useful for debugging
    return server
Beispiel #13
0
    print "with addr : %s" % addr
    print "addr[-1] : %s" % mesothelioma
    print "typetags :%s" % tags
    print "the actual data is : %s" % data
    print "---"


def sendOSCMsg(address='/print', data=[]):
    m = OSC.OSCMessage()
    m.setAdress(address)
    for d in data:
        m.append(d)
    client.send(m)


serialOSC = OSC.ThreadingOSCServer(serReceive)
pdOSC = OSC.ThreadingOSCServer(pdReceive)

initOSCClient(localhost, sendSer)
initOSCClient(
    localhost,
    sendPD,
)

serialOSC.addMsgHandler("/test", printing_handler)
pdOSC.addMsgHandler("/test", printing_handler)

SOSC = threading.Thread(target=serialOSC.serve_forever)
POSC = threading.Thread(target=pdOSC.serve_forever)

SOSC.daemon = True
Beispiel #14
0
import OSC
import threading
import socket

#------OSC Server-------------------------------------#
# local maching running osc2udp.py script
receive_address = '192.168.129.160', 57121

#UDP
# windows machine running freepie and steamvr
import socket
UDP_IP = "192.168.129.201"
UDP_PORT = 9999

# OSC Server. there are three different types of server.
s = OSC.ThreadingOSCServer(receive_address)

# this registers a 'default' handler (for unmatched messages)
s.addDefaultHandlers()


# define a message-handler function for the server to call.
def printing_handler(addr, tags, value, source):
    if addr == '/muse/elements/theta_absolute':
        print "theta_absolute", '%.3f' % value[0]
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP
        sock.sendto('%.3f' % value[0], (UDP_IP, UDP_PORT))


s.addMsgHandler("/muse/elements/theta_absolute", printing_handler)
Beispiel #15
0
from time import sleep
from random import random
import math
import OSC
from OSC import OSCServer
import time, threading
import sys
sys.path.append("../")
from ax12 import ax12

server = OSC.ThreadingOSCServer(("meme00.local", 8888))


def _oscHandler(addr, tags, stuff, source):
    addrTokens = addr.lstrip('/').split('/')
    if (addrTokens[0].lower() == "angles"):
        angles = []
        for (i, v) in enumerate(stuff):
            ang = math.degrees(v)
            angInt = int(ang * 1024 / 300)
            angPos = 520 + angInt
            angPos = 820 if angPos > 820 else angPos
            angPos = 220 if angPos < 220 else angPos
            angles.append(angPos)
            angPos = angPos if (i + 1) % 2 == 0 else 1024 - angPos
            servos.moveSpeedRW(i + 1, angPos, 244)
            sleep(0.02)
        print angles
        servos.action()
        sleep(0.02)
    elif (addrTokens[0].lower() == "teste"):
Beispiel #16
0
def send_play():
    msg = OSC.OSCMessage()
    msg.setAddress("/play")
    if v_play.get() == "Play":
        msg.append(1)
        c.send(msg)
    if v_play.get() == "Stop":
        msg.append(0)
        c.send(msg)


# OSC SERVER
# ==========

s = OSC.ThreadingOSCServer(('localhost', 7111))
s.addDefaultHandlers()


def receive_OSC(addr, tags, stuff, source):
    print addr, stuff[0]
    if addr == "/tempo":
        v_tempo.set(stuff[0])
    if addr == "/density":
        v_density.set(stuff[0])
    if addr == "/legato":
        v_legato.set(stuff[0])
    if addr == "/saturation":
        v_saturation.set(stuff[0])
    if addr == "/substitution":
        v_substitution.set(stuff[0])
Beispiel #17
0
    def __init__(self, send_address, listen_address):
        super(OSCThread, self).__init__()
        self.stoprequest = threading.Event()
        self.s = OSC.ThreadingOSCServer(listen_address)

        self.objectID_lock = threading.Lock()
        self.activeObjects = set()

        self.new_object_listener = None
        self.removed_object_listener = None

        # Set Server to return errors as OSCMessages to "/error"
        self.s.setSrvErrorPrefix("/error")
        # Set Server to reply to server-info requests with OSCMessages to "/serverinfo"
        self.s.setSrvInfoPrefix("/serverinfo")

        # this registers a 'default' handler (for unmatched messages),
        # an /'error' handler, an '/info' handler.
        # And, if the client supports it, a '/subscribe' & '/unsubscribe' handler
        self.s.addDefaultHandlers()

        self.s.addMsgHandler("default", self.printing_handler)
        #s.addMsgHandler("/MM_Remote/Control/activeObjectsID", pallete_handler)
        self.s.addMsgHandler("/MM_Remote/Control/activeObjectsID",
                             self.objectID_handler)

        self.s.addMsgHandler("/MM_Remote/Control/activeObjectsPosition",
                             self.pallete_handler)
        self.s.addMsgHandler("/MM_Remote/Global/pairingAccepted",
                             self.pairing_handler)

        print "Registered Callback-functions:"
        for addr in self.s.getOSCAddressSpace():
            print addr

        print "\nStarting OSCServer. Use ctrl-C to quit."
        self.st = threading.Thread(target=self.s.serve_forever)
        self.st.start()

        self.c2 = OSC.OSCClient()
        self.c2.connect(send_address)
        #subreq = OSC.OSCMessage("/MashMachine/Control/getActiveObjectsPosition")

        tries = 10
        self.paired = 0

        try:
            while self.paired == 0 and tries > 0:
                try:

                    print "Pairing..."
                    subreq = OSC.OSCMessage("/MashMachine/Global/makePairing")
                    subreq.append(listen_address[0])
                    subreq.append(listen_address[1])
                    self.c2.send(subreq)

                except (OSC.OSCClientError):
                    print "Pairing or Subscribing failed.."
                time.sleep(1)
                tries -= 1
        except (KeyboardInterrupt):
            print "Continue without pairing.."
            self.paired = 2

        if (tries == 0):
            print "Continue without pairing.."
            self.paired = 2
Beispiel #18
0
def quitpd(addr, tags, data, source):
	sendOSCPD("/quitpd",1)


def enc(addr, tags, data, source):
	return 0
def encbutton(addr, tags, data, source):
	return 0

#serial can be sent: /hello, /enablemux, disablemux, /getknobs,  /led

#pd server needs to listen to: /oled/line/X, /oled, /led
#pd needs to be sent: /key, /knobs, /quitpd, 

#server stuff below
serialListener = OSC.ThreadingOSCServer( receiveSer )
pdListener  = OSC.ThreadingOSCServer( receivePD )

#serial listener needs to listen to: /key, /knobs, /enc, /encbut, /hello
serialListener.addMsgHandler("/key", keys) #forward key messages to pd
serialListener.addMsgHandler("/knobs", knobs) #forward knob messages to pd
###############################################################################
serialListener.addMsgHandler("/enc", enc)
serialListener.addMsgHandler("/encbut", encbutton) 
###############################################################################


pdListener.addMsgHandler("/led", led) # handles LED pd -> stm32
for x in range(1,15):
	pdListener.addMsgHandler("/oled/line/"+str(x), screenLine)
pdListener.addMsgHandler("/oled/vumeter", vuMeter) #draws vu meter on line 0
print 'Reading text'
with open('old/texts_all.txt') as file:
    text = file.read()
markovGenerator = markovify.Text(text)

# --- JSON (actually slower)
# with open('punkMarkov.json') as file:
#     text = file.read()
# markovGenerator = markovify.Text.from_json( text )

# ----------------
print 'Init OSC'
oscSender_HostPort = ('127.0.0.1', 6000)  # to OpenFrameworks
oscReciever_HostPort = ('127.0.0.1', 5000)  # python
oscSender = OSC.OSCClient()
oscReceiver = OSC.ThreadingOSCServer(oscReciever_HostPort)
oscSender.connect(oscSender_HostPort)

adressCreate = "/create"
adressText = "/text"

print 'Init done'


def recieveMessage(addr, tags, stuff, source):
    inputLength = int(stuff[0])
    print "Received message:", inputLength
    text = str(markovGenerator.make_short_sentence(inputLength))
    print "sending message: " + text

    messageToSend = OSC.OSCMessage()
Beispiel #20
0
#print("Serving on {}".format(server.server_address))
#server.serve_forever()


###########################
# EXPERIMENT

listen_address = ('localhost', 54321)
send_address = ('localhost', 12345)



try:
    #c = OSC.OSCClient()
    #c.connect(listen_address)
    s = OSC.ThreadingOSCServer(listen_address)#, c)#, return_port=54321)

    print s
            
    # Set Server to return errors as OSCMessages to "/error"
    s.setSrvErrorPrefix("/error")
    # Set Server to reply to server-info requests with OSCMessages to "/serverinfo"
    s.setSrvInfoPrefix("/serverinfo")

    # this registers a 'default' handler (for unmatched messages),
    # an /'error' handler, an '/info' handler.
    # And, if the client supports it, a '/subscribe' & '/unsubscribe' handler
    s.addDefaultHandlers()

    #s.addMsgHandler("/print", printing_handler)
    s.addMsgHandler("default", printing_handler)