def stop_task(self): from Axon.Ipc import shutdownMicroprocess from Kamaelia.Util.OneShot import OneShot o = OneShot(msg=shutdownMicroprocess()) o.link((o, 'outbox'), (self.p, 'control')) o.activate()
def createRequestHandler(request): if request.get("bad"): return OneShot( errorpages.getErrorPage(400, request.get("errormsg", ""))) else: for (prefix, handler) in URLHandlers: if request["raw-uri"][:len(prefix)] == prefix: request["uri-prefix-trigger"] = prefix request["uri-suffix"] = request["raw-uri"][len(prefix):] return handler(request) return OneShot( errorpages.getErrorPage( 404, "No resource handlers could be found for the requested URL"))
def test_302response(self): responses = {} oldpath = 'old.addr' oldbody = 'nothing to see here' newpath = 'new.addr' newbody = 'found me!' responses['/' + oldpath] = dict(body=oldbody, code=302, locationAddr='http://localhost:%i/%s' % (PORT, newpath)) responses['/' + newpath] = dict( body=newbody, code=200, ) self.fakeHttpServer.setResponses(responses) p = Pipeline(OneShot('http://localhost:%i/%s' % (PORT, oldpath)), SimpleHTTPClient()) self.initializeSystem(p) self.assertEquals(newbody, self.get('outbox', timeout=30)) signalMessage = self.get('signal') self.assertTrue(isinstance(signalMessage, producerFinished)) self.assertFinished() self.assertOutboxEmpty('outbox') self.assertOutboxEmpty('signal')
def start(self): httpMonitor = HTTPResourceMonitor(30.0) httpMonitor.activate() newProfileFeedReader = FeedReaderComponent() newProfileFeedReader.activate() newProfileHandler = NewProfileHandler(base_dir, self.atompub) newProfileHandler.link((newProfileFeedReader, 'outbox'), (newProfileHandler, 'inbox')) newProfileHandler.activate() from Kamaelia.Util.OneShot import OneShot shot = OneShot() httpMonitor.link((shot, 'outbox'), (httpMonitor, 'monitor')) shot.send(('http://localhost:8080/profile/new/feed', newProfileFeedReader)) profileFeedReader = FeedReaderComponent() profileFeedReader.activate() profileHandler = ProfileHandler(base_dir, self.atompub) profileFeedReader.link((profileFeedReader, 'outbox'), (profileHandler, 'inbox')) profileHandler.activate() from Kamaelia.Util.OneShot import OneShot shot = OneShot() httpMonitor.link((shot, 'outbox'), (httpMonitor, 'monitor')) shot.send(('http://localhost:8080/profile/feed', profileFeedReader)) self.running = True
def makeFeedParser(self, feedUrl): """ makeFeedParser(feedUrl) -> Pipeline It returns a pipeline which does not expect any input except for signals and sends the parsed data through the "outbox" outbox. """ started(feedUrl) return Pipeline( OneShot(feedUrl), SimpleHTTPClient( ), # TODO: SimpleHTTPClient doesn't seem to have proxy support )
def AudioSplitterByFrames(framerate, channels, sample_rate, sample_format, tmpFilePath, edlfile): """\ Prefab. Saves raw audio data in the specified (chanels,sample_rate,sample_format) format sent to the "inbox" inbox into the specified temp directory. Chunks the audio into frames, as per the specified frame-rate. Only saves those frames actually referenced in the EDL file. Frames are saved in individual files in WAV format. They are named sequentially "00000001.wav", "00000002.wav", "00000003.wav", etc - being assigned frame numbers as they arrive, starting at 1. Arguments: - frame_rate -- the frame rate to chunk the audio into for saving - channels -- number of channels in the audio data - sample_rate -- sample rate of the audio data - sample_format -- sample format of the audio data - tmpFilePath -- temp directory into which frames should be saved - edlfile -- full filepathname of the EDL xml file Inboxes: - "inbox" -- raw audio data - "control" -- Shutdown signalling Outboxes: - "outbox" -- NOT USED - "signal" -- Shutdown signalling """ from Kamaelia.Support.PyMedia.AudioFormats import format2BytesPerSample quantasize = format2BytesPerSample[sample_format] * channels audioByteRate = quantasize * sample_rate return Pipeline( 10, RateChunker(datarate=audioByteRate, quantasize=quantasize, chunkrate=framerate), 1, TagWithSequenceNumber(), 1, FilterForWantedFrameNumbers(edlfile), 1, InboxControlledCarousel( lambda (framenum, audiochunk) : \ Pipeline( 1, OneShot(audiochunk), 1, WAVWriter(channels,sample_format,sample_rate), 1, SimpleFileWriter(tmpFilePath+("%08d.wav" % framenum)), ), boxsize=1, ), )
def TunablePublisher(initial_publishto=None): def makePublisher(meta): return PublishTo(meta) structure = { "TUNER": Carousel(makePublisher), "linkages": { ("self", "inbox"): ("TUNER", "inbox"), # To publish! ("self", "next"): ("TUNER", "next"), } } if initial_publishto != None: structure["INITIAL"] = OneShot(initial_publishto) structure["linkages"]["INITIAL", "outbox"] = ("TUNER", "next") return Graphline(**structure)
def TunableSubscriber(initial_subscription=None): def makeSubscriber(meta): return SubscribeTo(meta) structure = { "TUNER": Carousel(makeSubscriber), "linkages": { ("self", "inbox"): ("TUNER", "next"), ("TUNER", "outbox"): ("self", "outbox"), } } if initial_subscription != None: structure["INITIAL"] = OneShot(initial_subscription) structure["linkages"]["INITIAL", "outbox"] = ("TUNER", "next") return Graphline(**structure)
def _test200response(self, body, timeout): responses = {} path = 'foo' responses['/' + path] = dict( body=body, contentType='text', code=200, ) self.fakeHttpServer.setResponses(responses) p = Pipeline(OneShot('http://localhost:%i/%s' % (PORT, path)), SimpleHTTPClient()) self.initializeSystem(p) self.assertEquals(body, self.get('outbox', timeout=timeout)) signalMessage = self.get('signal') self.assertTrue(isinstance(signalMessage, producerFinished)) self.assertFinished() self.assertOutboxEmpty('outbox') self.assertOutboxEmpty('signal')
def testNoAnswer(self): # This test fails because of a bug in # Kamaelia.Protocol.HTTP.HTTPParser.HTTPParser.getInitialLine # the self.shouldShutdown does not handle the fact that the # provider might have finished, sending a producerFinished # message self.fakeHttpServer.stop() self.fakeHttpServer.join() # Now there is no server path = 'server.was.shutdown' p = Pipeline(OneShot('http://localhost:%i/%s' % (PORT, path)), SimpleHTTPClient()) self.initializeSystem(p) signalMessage = self.get('signal', timeout=20) self.assertTrue(isinstance(signalMessage, producerFinished)) # Is this actually correct? message = self.get('outbox') self.assertEquals('', message) self.assertFinished() self.assertOutboxEmpty('outbox') self.assertOutboxEmpty('signal')
def SaveVideoFrames(tmpFilePath,edlfile): """\ Prefab. Saves video frames sent to the "inbox" inbox into the specified temp directory. Only saves those frames actually referenced in the EDL file. Frames are saved in individual files in YUV4MPEG2 format. They are named sequentially "00000001.yuv", "00000002.yuv", "00000003.yuv", etc - being assigned frame numbers as they arrive, starting at 1. Arguments: - tmpFilePath -- temp directory into which frames should be saved - edlfile -- full filepathname of the EDL xml file Inboxes: - "inbox" -- video frames to be saved - "control" -- Shutdown signalling Outboxes: - "outbox" -- NOT USED - "signal" -- Shutdown signalling """ return \ Pipeline( 1, TagWithSequenceNumber(), 1, FilterForWantedFrameNumbers(edlfile), 1, InboxControlledCarousel( lambda (framenum, frame) : \ Pipeline( OneShot(frame), 1, FrameToYUV4MPEG(), 1, SimpleFileWriter(tmpFilePath+("%08d.yuv" % framenum)), ), boxsize=1, ), )
def test200withoutLength(self): # This test fails because of a bug in # Kamaelia.Protocol.HTTP.HTTPParser.HTTPParser.getBodyDependingOnHalfClose responses = {} path = 'foo' body = 'whatever' path = 'without.length' responses['/' + path] = dict( body=body, contentType='text', code=200, dontProvideLength=True, ) self.fakeHttpServer.setResponses(responses) p = Pipeline(OneShot('http://localhost:%i/%s' % (PORT, path)), SimpleHTTPClient()) self.initializeSystem(p) self.assertEquals(body, self.get('outbox', timeout=30)) signalMessage = self.get('signal') self.assertTrue(isinstance(signalMessage, producerFinished)) self.assertFinished() self.assertOutboxEmpty('outbox') self.assertOutboxEmpty('signal')
# not this notice. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.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. from Kamaelia.Apps.Jam.Internet.UDP_ng import SimplePeer, UDPSender from Kamaelia.Util.Console import ConsoleEchoer from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Apps.Jam.Protocol.Osc import Osc, DeOsc from Kamaelia.Util.OneShot import OneShot Pipeline( OneShot(("/Jam/Connect", 2005)), Osc(), # UDPSender(receiver_addr="127.0.0.1", receiver_port=2001)).run() SimplePeer(localaddr="127.0.0.1", localport=2005, receiver_addr="127.0.0.1", receiver_port=2001), DeOsc(0), ConsoleEchoer()).run()
from Kamaelia.Internet.TCPClient import TCPClient from Kamaelia.Util.Console import ConsoleEchoer, ConsoleReader from Kamaelia.Util.OneShot import OneShot print if len(sys.argv)>1: testing = int(sys.argv[1]) else: testing = 10 if testing == 1: Graphline( MAKESSL = OneShot(" make ssl "), # The actual message here is not necessary CONSOLE = ConsoleReader(), ECHO = ConsoleEchoer(), CONNECTION = TCPClient("kamaelia.svn.sourceforge.net", 443), linkages = { ("MAKESSL", "outbox"): ("CONNECTION", "makessl"), ("CONSOLE", "outbox"): ("CONNECTION", "inbox"), ("CONSOLE", "signal"): ("CONNECTION", "control"), ("CONNECTION", "outbox"): ("ECHO", "inbox"), ("CONNECTION", "signal"): ("ECHO", "control"), } ).run() if testing == 2: print "Test 2 Disabled, was more of a sketch thinking 'what sort of API might we like?'"
self.send(msg, "signal") break if self.dataReady("inbox"): data = self.recv("inbox") if self.index is None: decoded = OSC.decodeOSC(data) # Send decoded data as (address, [arguments], timetag) tuple self.send((decoded[2][0], decoded[2][2:], decoded[1]), "outbox") else: decoded = OSC.decodeOSC(data[self.index]) data = list(data) data[self.index] = (decoded[2][0], decoded[2][2:], decoded[1]) self.send(data, "outbox") if not self.anyReady(): self.pause() yield 1 if __name__ == "__main__": from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Internet.UDP import SimplePeer from Kamaelia.Util.OneShot import OneShot from Kamaelia.Util.Console import ConsoleEchoer Pipeline(OneShot(("/TestMessage", (1, 2, 3))), Osc("/OscTest"), SimplePeer(receiver_addr="127.0.0.1", receiver_port=2000)).run() Pipeline(OneShot(("/TestMessage", (1, 2, 3))), Osc("/OscTest"), DeOsc(), ConsoleEchoer()).run()
if self.dataReady("inbox"): self.recv("inbox") for url, targetOutbox in self.urls: self.send(url, targetOutbox) if not self.anyReady(): self.pause() yield 1 if __name__ == '__main__': from Kamaelia.Util.Console import ConsoleEchoer from Kamaelia.Util.OneShot import OneShot from atomhandler import FeedReaderComponent shot = OneShot() monitor = HTTPResourceMonitor() monitor.link((shot, 'outbox'), (monitor, 'monitor')) feedreader = FeedReaderComponent() printer = ConsoleEchoer() feedreader.link((feedreader, 'outbox'), (printer, 'inbox')) shot.send(('http://localhost:8080/profile/feed', feedreader)) printer.activate() feedreader.activate() #shot.activate() monitor.run()
Unplugs any children that have terminated, and returns true if there are no running child components left (ie. their microproceses have finished) """ for child in self.childComponents(): if child._isStopped(): self.removeChild(child) # deregisters linkages for us return 0==len(self.childComponents()) __kamaelia_components__ = ( Seq, ) if __name__=="__main__": from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.OneShot import OneShot from Kamaelia.Util.Console import ConsoleEchoer Pipeline( Seq( "BEGIN SEQUENCE", OneShot("Hello\n"), OneShot("Doctor\n"), OneShot("Name\n"), OneShot("Continue\n"), OneShot("Yesterday\n"), OneShot("Tomorrow\n"), "END SEQUENCE", ), ConsoleEchoer(), ).run()
def ErrorPageHandler(statuscode, message): """ This is the default error page handler. It is essentially the above function getErrorPage mapped to a resource handler for the HTTPServer. """ return OneShot(getErrorPage(statuscode, message))
def HTTPDataStreamingClient(fullurl, method="GET", body=None, headers={}, username=None, password=None, proxy=None): headers = dict(headers) proto, url_host, url_port, path = parse_url(fullurl) if username is not None and password is not None: (header_field, header_value) = http_basic_auth_header(username, password) headers[header_field] = header_value if proxy != None: _, proxy_host, proxy_port, _ = parse_url(proxy) args = {} sequence = [] request_path = path if proxy: # print "Via Proxy..." connhost, connport = proxy_host, proxy_port else: # print "NOT Via Proxy..." connhost, connport = url_host, url_port if proto == "https": # print "Attempting SSL..." if proxy: # print "desthost=url_host, destport=url_port, connhost, connport", url_host, url_port, connhost, connport args["ProxyConnect"] = ConnectRequest(desthost=url_host, destport=url_port) args["ProxyResponse"] = HandleConnectRequest() sequence.append({ ("ProxyConnect", "outbox"): ("item", "inbox"), ("item", "outbox"): ("ProxyResponse", "inbox") }) args["makessl"] = OneShot(" make ssl ") sequence.append({("makessl", "outbox"): ("item", "makessl")}) if proto == "http": # print "Attempting Plain HTTP" if proxy: request_path = fullurl args["http_req"] = HTTPClientRequest(url=request_path, host=url_host, method=method, postbody=body, headers=headers) args["http_resp"] = HTTPClientResponseHandler(suppress_header=True) sequence.append({ ("http_req", "outbox"): ("item", "inbox"), ("item", "outbox"): ("http_resp", "inbox"), ("http_resp", "outbox"): ("self", "outbox") }) args["sequence"] = sequence return With(item=TCPClient(connhost, connport), **args)
from Kamaelia.Internet.TCPClient import TCPClient from Kamaelia.Util.Console import ConsoleEchoer, ConsoleReader from Kamaelia.Util.OneShot import OneShot import sys if len(sys.argv) != 3: print print "Format of usage wrong, it should be this:" print print " ", sys.argv[0], "host", "port" sys.exit(0) host = sys.argv[1] port = int(sys.argv[2]) if 1: Graphline( MAKESSL=OneShot( " make ssl "), # The actual message here is not necessary CONSOLE=ConsoleReader(), ECHO=ConsoleEchoer(), CONNECTION=TCPClient(host, port), linkages={ ("MAKESSL", "outbox"): ("CONNECTION", "makessl"), ("CONSOLE", "outbox"): ("CONNECTION", "inbox"), ("CONSOLE", "signal"): ("CONNECTION", "control"), ("CONNECTION", "outbox"): ("ECHO", "inbox"), ("CONNECTION", "signal"): ("ECHO", "control"), }).run()
import Axon from Axon.Ipc import producerFinished, shutdownMicroprocess class Midi(Axon.Component.component): def __init__(self, portNumber=0, **argd): super(Midi, self).__init__(**argd) self.output = rtmidi.RtMidiOut() self.output.openPort(portNumber) def main(self): while 1: if self.dataReady("inbox"): self.output.sendMessage(*self.recv("inbox")) if self.dataReady("control"): msg = self.recv("control") if (isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess)): self.output.closePort() self.send(msg, "signal") break if not self.anyReady(): self.pause() yield 1 if __name__ == "__main__": from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.OneShot import OneShot Pipeline(OneShot((0x90, 36, 127)), Midi(0)).run()
socketOptions=(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1), ).activate() if 0: # Server ServerCore( protocol=Echo, port=2345, socketOptions=(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1), ).run() if 0: # Client from Kamaelia.Chassis.Graphline import Graphline Graphline( CLIENT_PROTOCOL=Seq( # Pause(delay=0.1), OneShot("Hello1\r\n"), OneShot("Hello2\r\n"), OneShot("Hello3\r\n"), OneShot("Hello4\r\n"), OneShot("Hello5\r\n"), OneShot("Hello6\r\n"), OneShot("Hello7\r\n"), OneShot("Hello8\r\n"), ), CLIENT=TCPClient("127.0.0.1", 2345), SANITY_CHECK=ConsoleEchoer(), linkages={ ("CLIENT_PROTOCOL", "outbox"): ("CLIENT", "inbox"), ("CLIENT", "outbox"): ("SANITY_CHECK", "inbox"), }).run()