Example #1
0
    def __init__(self,  logname, wrapper = wrapMessage):
        """
        Initializes a new Logger.

        -logname - the name of the log to write to
        -wrapper - a method that takes a message as an argument and returns a
            formatted string to put in the log.
        """
        super(Logger,  self).__init__()
        self.logname = logname
        self.bplane = Backplane('LOG_' + logname)
        self.subscriber = SubscribeTo('LOG_' + logname)
        self.wrapper = wrapper

        #add the components as children
        self.addChildren(self.subscriber, self.bplane)
        self.link((self.subscriber,  'outbox'),  (self,  'inbox'))
        self.link((self, 'signal'), (self.bplane, 'control'))
Example #2
0
def PassThroughAudio(edlfile, tmpFilePath):
    """\
    Prefab.
    
    Goes through the specified edit decision list file and reads in the audio
    frames corresponding to the video frames referred to in the reframing
    instructions in sequence. Outputs the audio frames out of the "outbox"
    outbox.
    
    Arguments:
    
    - edlfile      -- full filepathname of the EDL xml file
    - tmpFilePath  -- temp directory into which video frames have been saved
    
    Inboxes:
    
    - "inbox"    -- NOT USED
    - "control"  -- Shutdown signalling
    
    Outboxes:
    
    - "outbox"  -- raw audio data, chunked by frames
    - "signal"  -- Shutdown signalling
    """
    backplane_name = "AUDIO_FORMAT"
    return Graphline( \
        GET_EDL = EditDecisionSource(edlfile),
        AUDIO = Carousel( lambda edit : PassThroughAudioSegment(tmpFilePath, edit, backplane_name),
                          make1stRequest=True),
        
        BACKPLANE = Backplane(backplane_name),
        AUDIOFORMAT = Pipeline( SubscribeTo(backplane_name), FirstOnly() ),
        
        linkages = {
            ("AUDIO", "requestNext") : ("GET_EDL", "inbox"),
            
            ("GET_EDL", "outbox") : ("AUDIO", "next"),
            
            ("AUDIO", "outbox") : ("", "outbox"),
            
            ("AUDIOFORMAT", "outbox") : ("", "audioformat"),
            
            ("GET_EDL", "signal") : ("AUDIO", "control"),
            ("AUDIO", "signal") : ("AUDIOFORMAT", "control"),
            ("AUDIOFORMAT", "signal") : ("BACKPLANE", "control"),
            ("BACKPLANE", "signal") : ("", "signal"),
        },
        )
Example #3
0
    Pipeline(
        SubscribeTo("WEBCAM"),
        TagAndFilterWrapperKeepingTag(camera),
        PublishTo("WEBCAM"),
    ).activate()

    rhost, rport, serveport = parseOptions()

    # setup a server, if requested
    if serveport:
        LocalEventServer("WHITEBOARD", "AUDIO", port=serveport).activate()
        LocalWebcamEventServer("WEBCAM", port=(serveport + 1)).activate()

    # connect to remote host & port, if requested
    if rhost and rport:
        EventServerClients(rhost, rport, "WHITEBOARD", "AUDIO").activate()
        WebcamEventServerClients(rhost, (rport + 1), "WEBCAM").activate()

#    sys.path.append("../Introspection")
#    from Profiling import FormattedProfiler
#
#    Pipeline(FormattedProfiler( 20.0, 1.0),
#             ConsoleEchoer()
#            ).activate()

    Backplane("WHITEBOARD").activate()

    Backplane("WEBCAM").activate()

    Backplane("AUDIO").run()
Example #4
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import Axon
from Kamaelia.Chassis.ConnectedServer import FastRestartServer
from Kamaelia.Chassis.Pipeline import Pipeline
from Kamaelia.Util.Backplane import Backplane, PublishTo, SubscribeTo
from Kamaelia.Util.PureTransformer import PureTransformer

Backplane("CHAT_ONE").activate()


def EchoEveryone(**kwargs):
    peer = str(kwargs.get("peer", "<>"))
    peerport = str(kwargs.get("peerport", "<>"))
    return Pipeline(
        PureTransformer(lambda x: "%s:%s says %s" % (peer, peerport, x)),
        PublishTo("CHAT_ONE"),
        # ------------
        SubscribeTo("CHAT_ONE"),
    )


FastRestartServer(protocol=EchoEveryone, port=1500).run()
Example #5
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Splitting server. This expects a single inbound connection on one port and spits it out to all recipients who connect on another port. This can be
used as an alternate server for the TCPRelayMulticast to connect to, and
it would expect to be fed using MulticastTCPClientRelay.

"""

from Kamaelia.Util.Backplane import Backplane, publishTo, subscribeTo
from Kamaelia.Util.PipelineComponent import pipeline
from Kamaelia.SimpleServerComponent import SimpleServer
from Kamaelia.SingleServer import SingleServer
from config import tcp_tcp_splitter_port, tcp_splitter_client_port

p = Backplane("Splitting").activate()

pipeline(
    SingleServer(tcp_tcp_splitter_port),
    publishTo("Splitting"),
).activate()


def SubscribeToSplitData():  # Protocol handler for each connected client
    return subscribeTo("Splitting")


SimpleServer(SubscribeToSplitData, tcp_splitter_client_port).run()
Example #6
0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This is a simple proxy to relay multicast data from a given multicast
group and port as a TCP Service on a given port. It's worth noting that
this is one way - any data from the TCP connection is discarded.
"""

from Kamaelia.Util.Backplane import Backplane, publishTo, subscribeTo
from Kamaelia.Internet.Multicast_transceiver import Multicast_transceiver
from Kamaelia.Util.PipelineComponent import pipeline
from config import mcast_group, mcast_port, mcast_tcp_splitter_port

p = Backplane("MulticastProxy").activate()

pipeline(
    Multicast_transceiver("0.0.0.0", mcast_port, mcast_group, 0),
    publishTo("MulticastProxy"),
).activate()


def RelayMulticastData():  # Protocol handler for each connected client
    return subscribeTo("MulticastProxy")


SimpleServer(RelayMulticastData, mcast_tcp_splitter_port).run()
Example #7
0
    )

mainsketcher = \
    Graphline( SKETCHER = makeBasicSketcher(width=1024,height=768),
               CONSOLE = Pipeline(ConsoleReader(),text_to_tokenlists(),parseCommands()),

               linkages = { ('self','inbox'):('SKETCHER','inbox'),
                            ('SKETCHER','outbox'):('self','outbox'),
                            ('CONSOLE','outbox'):('SKETCHER','inbox'),
                          }
                 )

# primary whiteboard
Pipeline(subscribeTo("WHITEBOARD"), TagAndFilterWrapper(mainsketcher),
         publishTo("WHITEBOARD")).activate()

if __name__ == "__main__":
    import sys, getopt, re

    rhost, rport, serveport = parseOptions()

    # setup a server, if requested
    if serveport:
        LocalEventServer("WHITEBOARD", port=serveport).activate()

    # connect to remote host & port, if requested
    if rhost and rport:
        EventServerClients(rhost, rport, "WHITEBOARD").activate()

    Backplane("WHITEBOARD").run()
Example #8
0
class Logger(component):
    """
    This component is used to write messages to file.  Upon instantiation, the
    a backplane is registered with the name LOG_ + logname, so that a log named
    'foo.bar' would be registered under 'LOG_foo.bar'.

    Please note that the Logger will not be shut down automatically.  It must be
    sent a shutdown message via its control box.  Typically this component is to
    be used by a Chassis or some other Parent component to provide a log for its
    children.
    """
    Inboxes = { 'inbox' : 'Receive a tuple containing the filename and message to log',
                'control' : 'Receive shutdown messages',}
    Outboxes = {'outbox' : 'NOT USED',
                'signal' : 'Send shutdown messages',}

    def __init__(self,  logname, wrapper = wrapMessage):
        """
        Initializes a new Logger.

        -logname - the name of the log to write to
        -wrapper - a method that takes a message as an argument and returns a
            formatted string to put in the log.
        """
        super(Logger,  self).__init__()
        self.logname = logname
        self.bplane = Backplane('LOG_' + logname)
        self.subscriber = SubscribeTo('LOG_' + logname)
        self.wrapper = wrapper

        #add the components as children
        self.addChildren(self.subscriber, self.bplane)
        self.link((self.subscriber,  'outbox'),  (self,  'inbox'))
        self.link((self, 'signal'), (self.bplane, 'control'))


    def main(self):
        self.bplane.activate()
        self.subscriber.activate()
        self.first_run = False

        not_done = True
        while not_done:
            if self.dataReady('inbox'):
                file = open(self.logname, 'a')
                while self.dataReady('inbox'):
                    msg = self.recv('inbox')
                    file.write(self.wrapper(msg))
                file.close()

            while self.dataReady('control'):
                msg = self.recv('control')
                if isinstance(msg, (shutdownMicroprocess)):
                    not_done = False
                    self.shutdown(msg)
            if not_done:
                self.pause()
                yield 1

    def shutdown(self, msg):
        """
        Sends shutdown message to signal box and removes children.
        """
        self.send(msg, 'signal')
        self.removeChild(self.bplane)
        self.removeChild(self.subscriber)
Example #9
0
        from Kamaelia.UI.Pygame.Display import PygameDisplay
        from Kamaelia.UI.Pygame.VideoOverlay import VideoOverlay
        from Kamaelia.Util.Backplane import Backplane, PublishTo, SubscribeTo
        from Kamaelia.Util.RateFilter import MessageRateLimit

        PygameDisplay.setDisplayService(
            PygameDisplay(width=1024, height=500).activate())

        Pipeline(
            UnixProcess("ffmpeg -i " + infile +
                        " -f yuv4mpegpipe -y /dev/stdout"),
            2,
            YUV4MPEGToFrame(),
            50,
            MessageRateLimit(25, 25),
            PublishTo("VIDEO"),
            Backplane("VIDEO"),
            StopSelector(waitForTrigger=True),
        ).activate()

        Pipeline(
            SubscribeTo("VIDEO"),
            TagWithSequenceNumber(),
            DetectShotChanges(threshold),
            FormatOutput(),
            ConsoleEchoer(),
        ).activate()

        Pipeline(SubscribeTo("VIDEO"), VideoOverlay()).run()
Example #10
0
        linkages={
            ("CANVAS", "eventsOut"): ("PAINTER", "inbox"),

            #("PAINTER", "outbox")    : ("CANVAS", "inbox"),
            ("PAINTER", "outbox"): ("TWOWAY", "inbox"),
            #("CLEAR", "outbox")       : ("CANVAS", "inbox"),
            ("CALIBRATE", "outbox"): ("CANVAS", "inbox"),
            #("CANVAS", "toApp") : ("CALIBRATE", "coords"),
            ("TWOWAY", "outbox"): ("CALIBRATE", "coords"),
            ("TWOWAY", "outbox2"): ("CANVAS", "inbox"),
            ("CALIBBUTTON", "outbox"): ("CALIBRATE", "inbox"),
            ("CALIBRATE", "finaldata"): ("FILEWRITER", "inbox"),
            ("FILEWRITER", "outbox"): ("CALIBRATE", "inbox"),
        },
    )


if __name__ == "__main__":
    mainsketcher = \
        Graphline( SKETCHER = makeBasicSketcher(width=1024,height=768),
                   linkages = { ('','inbox'):('SKETCHER','inbox'),
                                ('SKETCHER','outbox'):('','outbox'),
                              }
                     )
    # primary calibrator
    Pipeline(SubscribeTo("CALIBRATOR"), TagAndFilterWrapper(mainsketcher),
             PublishTo("CALIBRATOR")).activate()

    print("Starting calibration...")
    Backplane("CALIBRATOR").run()
     {"PSI_Tables":"request"}
                ).activate()

# ------------------------------------------------------------------------------
# now and next data on a backplane

Pipeline(
    Subscribe("PSI_Tables", [EIT_PID]),
    ParseEventInformationTable_Subset(True, False, False, False),
    FilterOutNotCurrent(),
    SimplifyEIT(),
    NowNextProgrammeJunctionDetect(),
    PublishTo("nowEvents"),
).activate()

Backplane("nowEvents").activate()

# ------------------------------------------------------------------------------
# A service to map textual channel names to service_id's

RegisterService( \
    Graphline( TABLE_SOURCE = Subscribe("PSI_Tables", [SDT_PID]),
               PARSING = ParseServiceDescriptionTable_ActualTS(),
               LOOKUP = ChannelNameLookupService(),
               linkages = {
                   ("","inbox")               : ("LOOKUP", "request"),
                   ("TABLE_SOURCE", "outbox") : ("PARSING", "inbox"),
                   ("PARSING", "outbox")      : ("LOOKUP", "inbox"),
               }
             ),
    {"LookupChannelName" : "inbox"}
Example #12
0
                            
                if event[0] == "MAKELINKTO":
                   mode = "LINK"
                   print "MAKING LINK from", selected
                   source = selected
                   try:
                       if '#' not in source:
                            source = source+"#next"
                   except TypeError,e:
                           mode = None
                           source = None
                           sink = None
                           priorselected = None
                           selected = None

Backplane("VIS").activate()
Backplane("UI_Events").activate()

X = Pipeline(
    SubscribeTo("VIS"),
    chunks_to_lines(),
    lines_to_tokenlists(),
    AxonVisualiser(position=(0,0)),
    ConsoleEchoer(forwarder=True),
    PublishTo("UI_Events"),
).activate()


Graphline(
    EXAMPLE = example,
    ADDASSET =  Button(caption="ADD ASSET", position=(800, 20), msg='add'),
Example #13
0
				data = self.recv("inbox")
				n += 1
				print "Received: %s" % data
				yield 1

			if self.dataReady("control"):
				data = self.recv("control")
				print "Control: %s" % data
				self.send(producerFinished(self), "signal")
				return

			#if not self.anyReady():
			#	self.pause()
			yield 1

backplane = Backplane("SAMPLE")
backplane.activate()

producer  = Producer()
consumer  = Consumer()
published = PublishTo("SAMPLE")
subscribe = SubscribeTo("SAMPLE")

pipe1 = Pipeline( 
	producer,
	published,
)
pipe1.activate()

pipe2 = Pipeline(
	subscribe,
Example #14
0
    def setup(self):
        # Backplanes are like a global entry points that
        # can be accessible both for publishing and
        # recieving data. 
        # In other words, a component interested
        # in advertising to many other components that
        # something happened may link one of its outbox
        # to a PublishTo component's inbox.
        # A component wishing to receive that piece of
        # information will link one of its inbox
        # to the SubscribeTo component's outbox.
        # This helps greatly to make components more
        # loosely connected but also allows for some data
        # to be dispatched at once to many (such as when
        # the server returns the per-session JID that
        # is of interest for most other components).
        Backplane("CONSOLE").activate()
        Backplane("JID").activate()
        # Used to inform components that the session is now active
        Backplane("BOUND").activate()
        # Used to inform components of the supported features
        Backplane("DISCO_FEAT").activate()
        

        sub = SubscribeTo("JID")
        self.link((sub, 'outbox'), (self, 'jid'))
        self.addChildren(sub)
        sub.activate()
        
        log = Logger(path=None, stdout=True, name='XmppLogger')
        Backplane('LOG_' + self.log_location).activate()
        Pipeline(SubscribeTo('LOG_' + self.log_location), log).activate()
        log_writable = WsgiLogWritable(self.log_location)
        log.activate()
        log_writable.activate()   
        
        # We pipe everything typed into the console
        # directly to the console backplane so that
        # every components subscribed to the console
        # backplane inbox will get the typed data and
        # will decide it it's of concern or not.
        Pipeline(ConsoleReader(), PublishTo('CONSOLE')).activate()

        # Add two outboxes ro the ClientSteam to support specific extensions.
        ClientStream.Outboxes["%s.query" % XMPP_IBR_NS] = "Registration"
        ClientStream.Outboxes["%s.query" % XMPP_LAST_NS] = "Activity"
        ClientStream.Outboxes["%s.query" % XMPP_DISCO_INFO_NS] = "Discovery"

        self.client = ClientStream(self.jid, self.passwordLookup, use_tls=self.usetls)
        
        WsgiConfig ={
        'server_software' : "Example WSGI Web Server",
        'server_admin' : "Jason Baker",
        'wsgi_ver' : (1,0),
        }
        routing = [ ["/", SimpleWsgiFactory(log_writable, WsgiConfig, simple_app, '/simple')], ]
        #routing = [ ['/', Echoer]]

        self.graph = Graphline(client = self,
                               console = SubscribeTo('CONSOLE'),
                               logger = PublishTo('LOG_' + self.log_location),
                               tcp = TCPClient(self.server, self.port),
                               xmlparser = XMLIncrParser(),
                               xmpp = self.client,
                               streamerr = StreamError(),
                               saslerr = SaslError(),
                               discohandler = DiscoHandler(self.jid, self.domain),
                               activityhandler = ActivityHandler(),
                               rosterhandler = RosterHandler(self.jid),
                               registerhandler = RegistrationHandler(self.username, self.password),
                               msgdummyhandler = WebMessageHandler(),
                               presencehandler = PresenceHandler(),
                               presencedisp = PresenceDispatcher(),
                               rosterdisp = RosterDispatcher(),
                               msgdisp = MessageDispatcher(),
                               discodisp = DiscoveryDispatcher(),
                               activitydisp = ActivityDispatcher(),
                               registerdisp = RegisterDispatcher(),
                               pjid = PublishTo("JID"),
                               pbound = PublishTo("BOUND"),
                               proto_man = ProtocolManager(Protocol=HTTPProtocol(routing)),

                               linkages = {('xmpp', 'terminated'): ('client', 'inbox'),
                                           ('console', 'outbox'): ('client', 'control'),
                                           ('client', 'forward'): ('xmpp', 'forward'),
                                           ('client', 'outbox'): ('tcp', 'inbox'),
                                           ('client', 'signal'): ('tcp', 'control'),
                                           ("tcp", "outbox") : ("xmlparser", "inbox"),
                                           ("xmpp", "starttls") : ("tcp", "makessl"),
                                           ("tcp", "sslready") : ("xmpp", "tlssuccess"), 
                                           ("xmlparser", "outbox") : ("xmpp" , "inbox"),
                                           ("xmpp", "outbox") : ("tcp" , "inbox"),
                                           ("xmpp", "reset"): ("xmlparser", "reset"),
                                           ("client", "log"): ("logger", "inbox"),
                                           ("xmpp", "log"): ("logger", "inbox"),
                                           ("xmpp", "jid"): ("pjid", "inbox"),
                                           ("xmpp", "bound"): ("pbound", "inbox"),
                                           ("xmpp", "features"): ("client", "streamfeat"),
                                           ("client", "doauth"): ("xmpp", "auth"),
                                           
                                           # Registration
                                           ("xmpp", "%s.query" % XMPP_IBR_NS): ("registerdisp", "inbox"),
                                           ("registerdisp", "log"): ('logger', "inbox"),
                                           ("registerdisp", "xmpp.error"): ("registerhandler", "error"),
                                           ("registerdisp", "xmpp.result"): ("registerhandler", "inbox"),
                                           ("registerhandler", "outbox"): ("registerdisp", "forward"),
                                           ("client", "doregistration"): ("registerdisp", "forward"),
                                           ("registerdisp", "outbox"): ("xmpp", "forward"),
                                           
                                           # Presence 
                                           ("xmpp", "%s.presence" % XMPP_CLIENT_NS): ("presencedisp", "inbox"),
                                           ("presencedisp", "log"): ('logger', "inbox"),
                                           ("presencedisp", "xmpp.subscribe"): ("presencehandler", "subscribe"),
                                           ("presencedisp", "xmpp.unsubscribe"): ("presencehandler", "unsubscribe"),
                                           ("presencehandler", "outbox"): ("presencedisp", "forward"),
                                           ("presencehandler", "roster"): ("rosterdisp", "forward"),
                                           ("presencedisp", "outbox"): ("xmpp", "forward"),

                                           # Roster
                                           ("xmpp", "%s.query" % XMPP_ROSTER_NS): ("rosterdisp", "inbox"),
                                           ("rosterdisp", "log"): ('logger', "inbox"),
                                           ('rosterdisp', 'xmpp.set'): ('rosterhandler', 'pushed'),
                                           ('rosterdisp', 'xmpp.result'): ('rosterhandler', 'inbox'),
                                           ('rosterhandler', 'result'): ('rosterdisp', 'forward'),
                                           ("rosterdisp", "outbox"): ("xmpp", "forward"),

                                           # Discovery
                                           ("xmpp", "%s.query" % XMPP_DISCO_INFO_NS): ("discodisp", "features.inbox"),
                                           ("discodisp", "log"): ('logger', "inbox"),
                                           ("discohandler", "features-disco"): ('discodisp', "features.forward"),
                                           ("discodisp", "out.features.result"): ('discohandler', "features.result"),
                                           ("discodisp", "outbox"): ("xmpp", "forward"),

                                           # Message
                                           ("xmpp", "%s.message" % XMPP_CLIENT_NS): ("msgdisp", "inbox"),
                                           ("msgdisp", "log"): ('logger', "inbox"),
                                           ("msgdisp", "xmpp.chat"): ('msgdummyhandler', 'inbox'),
                                           ("msgdummyhandler", "outbox"): ('msgdisp', 'forward'),
                                           ("msgdisp", "outbox"): ("xmpp", "forward"),
                                           ('msgdummyhandler', 'proto') : ('proto_man' , 'inbox'),
                                           ('proto_man', 'outbox') : ('msgdummyhandler', 'inbox'),

                                           # Activity
                                           ("xmpp", "%s.query" % XMPP_LAST_NS): ("activitydisp", "inbox"),
                                           ("activitydisp", "log"): ('logger', "inbox"),
                                           ("activitydisp", "outbox"): ("xmpp", "forward"),
                                           ("activityhandler", 'activity-supported'): ('rosterhandler', 'ask-activity'),
                                           ("rosterhandler", 'activity'): ('activitydisp', 'forward'),
                                           }
                               )
        self.addChildren(self.graph)
        self.graph.activate()

        return 1
Example #15
0
#!/usr/bin/python

from Kamaelia.Util.Backplane import Backplane, PublishTo, SubscribeTo
from Kamaelia.Chassis.ConnectedServer import ServerCore
from Kamaelia.Chassis.Pipeline import Pipeline
from Kamaelia.Util.PureTransformer import PureTransformer

Backplane(
    "CHAT").activate()  # This handles the sharing of data between clients


def ChatClient(*argc, **argd):
    peer = argd["peer"]
    peerport = argd["peerport"]
    return Pipeline(
        PureTransformer(lambda x: " %s:%s says %s" %
                        (str(peer), str(peerport), str(x))),
        PublishTo("CHAT"),  # Take data from client and publish to all clients
        # ----------------------
        SubscribeTo("CHAT"
                    ),  # Take data from other clients and send to our client
        PureTransformer(lambda x: "Chat:" + str(x).strip() + "\n"),
    )


class ChatServer(ServerCore):
    protocol = ChatClient


print "Chat server running on port 1501"
Example #16
0
"""
import Axon
import time
from Axon.Ipc import WaitComplete
from Kamaelia.Chassis.Graphline import Graphline
from Kamaelia.Chassis.Pipeline import Pipeline
from Kamaelia.Util.Backplane import Backplane, SubscribeTo
from Kamaelia.Util.TwoWaySplitter import TwoWaySplitter
from Kamaelia.Util.Console import ConsoleEchoer
from Kamaelia.Util.PureTransformer import PureTransformer
from BackplaneTuner import TunableSubscriber, TunablePublisher

locations = "holiday", "santasworkshop", "deliveringtoys", "study", "elfworkshop"

for locale in locations:
    Backplane(locale).activate()

debugging = 1


def tagger(tag):
    print "creating tag", tag
    return PureTransformer(lambda x: str((tag, x)) + "\n")


def tagger2(tag):
    print "creating tag2", tag
    return PureTransformer(lambda x: (tag, x))


if debugging: