def __init__(self, schema_directory): search_path = [os.path.dirname(os.path.dirname(capnp.__file__))] if 'CONDA_PREFIX' in os.environ: search_path.append( os.path.join(os.environ['CONDA_PREFIX'], 'include')) if 'CAPNP_PATH' in os.environ: search_path.append(os.environ['CAPNP_PATH']) for path in ['/usr/local/include', '/usr/include']: if os.path.exists(path): search_path.append(path) self.references_schema = capnp.load(os.path.join( schema_directory, 'References.capnp'), imports=search_path) self.logical_netlist_schema = capnp.load(os.path.join( schema_directory, 'LogicalNetlist.capnp'), imports=search_path) self.physical_netlist_schema = capnp.load(os.path.join( schema_directory, 'PhysicalNetlist.capnp'), imports=search_path) self.device_resources_schema = capnp.load(os.path.join( schema_directory, 'DeviceResources.capnp'), imports=search_path)
def __init__(self, graph, root_attrib, capnp_schema_file_name, output_file_name, progressbar=None): if progressbar is None: progressbar = lambda x: x # noqa: E731 self.progressbar = progressbar self.input_file_name = None self.output_file_name = output_file_name self.graph = graph self.root_attrib = root_attrib # Handle multiple paths for the capnp library search_path = [os.path.dirname(os.path.dirname(capnp.__file__))] if 'CAPNP_PATH' in os.environ: search_path.append(os.environ['CAPNP_PATH']) for path in ['/usr/local/include', '/usr/include']: if os.path.exists(path): search_path.append(path) # Load the Cap'n'proto schema self.rr_graph_schema = capnp.load(capnp_schema_file_name, imports=search_path)
def load_schema(path=""): capnp.remove_import_hook() im_paths = get_include_paths(get_schema_files()) im_paths.append("/usr/include") im_paths.append("/usr/local/include") module = capnp.load(path, imports=im_paths) return module
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( '--schema_path', help='Path to override delta delay placement model schema', required=True) parser.add_argument('--place_delay_matrix', required=True) args = parser.parse_args() place_delay_model = capnp.load( os.path.join(args.schema_path, 'place_delay_model.capnp')) with open(args.place_delay_matrix, 'rb') as f: delay_model = place_delay_model.VprOverrideDelayModel.read(f) x_dim = delay_model.delays.dims[0] y_dim = delay_model.delays.dims[1] itr = iter(delay_model.delays.data) for x in range(x_dim): row = [] for y in range(y_dim): value = next(itr) row.append(str(value.value.value)) print(','.join(row))
def load_capnp_to_dicts(file_name='data.capnp'): import capnp capnp.remove_import_hook() schemas_path = str(DATA_ROOT / 'schemas.capnp') schemas = capnp.load(schemas_path) path = str(DATA_ROOT / file_name) with open(path, 'rb') as f: flight_book = schemas.FlightBook.read( f, traversal_limit_in_words=2**61, ) flights = flight_book.to_dict()['flights'] for flight in flights: for key in flight.keys(): value = flight.pop(key) if (value == -1) or (value == ""): value = None key = from_camel(key) flight[key] = value return flights
def decode(schema_file, struct_name, defaults): schema = capnp.load(schema_file) struct_schema = getattr(schema, struct_name) struct = struct_schema.read(sys.stdin) json.dump(struct.to_dict(defaults), sys.stdout)
def to_capnp(self): """ Load the class in capnp schema Cage.capnp :rtype bytes """ template = capnp.load("%s/Cage.capnp" % dir) return template.Cage.new_message(**self.as_dict()).to_bytes()
def get_pycapnpstuff(): "return capnp adapted message factories for StuffToTest schema" # loads the StuffToTest schema import capnp capnp.remove_import_hook() schmod = capnp.load(join(PROJECT_ROOT,'idl/StuffToTest.capnp')) # contruct schema schema = SchemaContainer('pycapnp', capnp.__version__) context = {} for message, fieldnames in FNIDX: # load capnp Struct class structClass = getattr(schmod,message) # contruct Struct proxy object structProxy = CapNpStructProxy(structClass, fieldnames, context) # add proxy to schema setattr(schema, message, structProxy) # update context for it to hold new structProxy reference context[message] = structProxy return schema
def __init__(self): ''' All subclasses must call the superclass constructor as the first line of their constructor. ''' # grab function information self.functions = { f.__name__ : f._rtype for f in _gen_funcs(self) } self.class_names = { f._rtype for f in _gen_funcs(self) } #setup FFI self.ffi = cffi.FFI() self.ffi.cdef(''' typedef struct { char* values; size_t len; } bytes_output; ''' + '\n'.join( 'bytes_output {}(char*, size_t);'.format(f) for f in self.functions.keys() )) self.lib = self.ffi.dlopen(self.lib_file) self.MessageType = capnp.load(self.capnp_file) #attach class names for cn in self.class_names: setattr(self, cn, lambda *args, **kwargs: self.make_new(cn, *args, **kwargs))
def to_capnp(self): """ Load the class in capnp schema PlainObject.capnp :rtype bytes """ template = capnp.load('%s/PlainObject.capnp' % dir) return template.PlainObject.new_message(**self.as_dict()).to_bytes()
def __init__(self, btrdb_host, btrdb_port, schema_filepath=os.path.join(os.path.dirname(__file__), 'interface.capnp')): """ Construct a new 'BTrDBConnection' object. :param btrdb_host: The hostname at which the BTrDB is located. :param btrdb_port: The port of the Cap'n Proto interface of the BTrDB. :param schema_filepath: The filepath of the Cap'n Proto schema file for BTrDB. The file can be found at https://github.com/SoftwareDefinedBuildings/btrdb/blob/master/cpinterface/interface.capnp. """ self.bs = capnp.load(schema_filepath) self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.connect((btrdb_host, btrdb_port)) self.seqno = 0 self.seqnolock = threading.Lock() self.seqmap = {} self.have = '' self.expecting = 0 self.hdrexpecting = 0 self.numsegs = 0 self.partmsg = {} self.alive = True rcvthread = threading.Thread(target=self._readall, args=()) rcvthread.daemon = True rcvthread.start()
def main(): parser = argparse.ArgumentParser("replayd") parser.add_argument("--dir", help="Directory to search for replays", default="/media/marcel/Games/Dataset/comma2k19/") parser.add_argument("--repeat", action="store_true") args = parser.parse_args() replayd_port = get_port("replayd") context = zmq.Context() sock = socket.create_push_sock(context, replayd_port) drivingframe_capnp = capnp.load( get_file_in_root_folder("daemons/schemas/Schemas.capnp")).DrivingFrame # Search for all subdirectories that contain replays replay_dirs = _get_all_logs_in_dir(args.dir) random.shuffle(replay_dirs) while True: for replay_dir in replay_dirs: _send_frames_from_dir(replay_dir, sock, drivingframe_capnp) if not args.repeat: break
def get_messages(filename): filen, ext = path.splitext(filename) if ext == ".bz2": sp.run(["bzip2", "-dk", filename]) filename = filen # Get message indexes from file indexes = index_capnp(filename) # Load capnp schema capnp_schema = get_file_in_root_folder("../data/log.capnp") msg_capnp = capnp.load(capnp_schema) # Read file with open(filename, "rb") as f: data = f.read() """ for i in range(len(indexes) - 1): print(data[ indexes[i]:indexes[i+1] ]) """ messages = [ msg_capnp.Event.from_bytes(data[indexes[i]:indexes[i + 1]]) for i in range(len(indexes) - 1) ] return messages
def to_capnp(self): """ Load the class in capnp schema NumberFormat.capnp :rtype bytes """ template = capnp.load('%s/NumberFormat.capnp' % dir) return template.NumberFormat.new_message(**self.as_dict()).to_bytes()
def to_capnp(self): """ Load the class in capnp schema Animal.capnp :rtype bytes """ template = capnp.load('%s/Animal.capnp' % dir) return template.Animal.new_message(**self.as_dict()).to_bytes()
def capnp_crunch(key, value): schema = key_to_capnpfile[key] schema_file = capnp.load(schemas + schema + '.capnp', imports=[os.environ['CAPNP_ROOT'] + '/c++/src']) Any.register_class(schema, getattr(schema_file, schema)) new_value = value.to_any().reader() return new_value
def main(): """ User security module example implementation. :return: -1 upon failure. """ try: sock = socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM, 31) sock.bind((0, 0)) send_initializaiton_message(sock) except Exception as e: print("Failure message: " + str(e)) exit(-1) print("Listening to messages from kernel") print("_" * COLS) capnp_scheme = capnp.load(PROC_SCHEME_PATH) while True: kernel_message = recv_messsage(sock) proc = capnp_scheme.Process.from_bytes(kernel_message) verdict = security_logic(proc) print() print("Message ID: {} |\t Executable path: {} |\t {}Verdict: {}{}". format(proc.id, proc.name, COLOR_START_DICT[verdict], VERDICTS[verdict], COLOR_END)) print("_" * COLS) send_messsage(sock, struct.pack("=II", proc.id, verdict))
def save_capnp(data, file_name='data.capnp', test=True): import capnp capnp.remove_import_hook() schemas_path = str(DATA_ROOT / 'schemas.capnp') schemas = capnp.load(schemas_path) flight_book = schemas.FlightBook.new_message() flights = flight_book.init('flights', len(data)) for i, item in enumerate(data): flight = flights[i] for key, value in item.items(): key = to_camel(key) if value is None: try: setattr(flight, key, -1) except capnp.lib.capnp.KjException: setattr(flight, key, "") else: setattr(flight, key, value) if test: file_name = "{}.{}".format(file_name, os.getpid()) path = str(DATA_ROOT / file_name) try: with open(path, 'wb') as f: flight_book.write(f) finally: if test: os.remove(path)
def create_ffi(capnp_file): GenericFFI = type('GenericFFI', (object,), {}) capnp_schema = capnp.load(capnp_file) for interface in dir(capnp_schema): interface = getattr(capnp_schema, interface) if not isinstance(interface, cpl._InterfaceModule): continue InterfaceType = type(interface, (interface.Server,), {}) #attach the implementations for the ffi functions, we know what they are for method_name, method in interface.schema.methods.items(): def ffi_method(self, **kwargs): for field_name, field in method.param_type.fields.items(): field=field.proto.slot if field.hasExplicitDefault: if field_name not in kwargs: kwargs[field_name] = field.defaultValue try: assert field in kwargs except Exception: raise KeyError('Missing required field "{}" to function "{}" with no default'.format(field_name, method_name)) # insert call to ffi library here and parse return type but what is it? ffi_method.__name__ = method_name setattr(InterfaceType, method_name, ffi_method) setattr(GenericFFI, interface, InterfaceType) return GenericFFI
def __init__(self, btrdb_host, btrdb_port, schema_filepath): """ Construct a new 'BTrDBConnection' object. :param btrdb_host: The hostname at which the BTrDB is located. :param btrdb_port: The port of the Cap'n Proto interface of the BTrDB. :param schema_filepath: The filepath of the Cap'n Proto schema file for BTrDB. The file can be found at https://github.com/SoftwareDefinedBuildings/btrdb/blob/master/cpinterface/interface.capnp. """ self.bs = capnp.load(schema_filepath) self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.connect((btrdb_host, btrdb_port)) self.seqno = 0 self.seqnolock = threading.Lock() self.seqmap = {} self.have = '' self.expecting = 0 self.hdrexpecting = 0 self.numsegs = 0 self.partmsg = {} self.alive = True rcvthread = threading.Thread(target = self._readall, args = ()) rcvthread.daemon = True rcvthread.start()
def session_capnp(): """Load out capnproto schema """ import capnp capnp.remove_import_hook() return capnp.load(os.path.join(capture.__path__[0], "session.capnp"))
def to_capnp(self): """ Load the class in capnp schema WithDateTime.capnp :rtype bytes """ template = capnp.load('%s/WithDateTime.capnp' % dir) return template.WithDateTime.new_message(**self.as_dict()).to_bytes()
def __init__( self, rr_graph_schema_fname, input_file_name, output_file_name=None, progressbar=None, build_pin_edges=True, rebase_nodes=True, filter_nodes=True, ): if progressbar is None: progressbar = lambda x: x # noqa: E731 self.input_file_name = input_file_name self.progressbar = progressbar self.output_file_name = output_file_name self.rr_graph_schema = capnp.load( rr_graph_schema_fname, imports=[os.path.dirname(os.path.dirname(capnp.__file__))]) graph_input = graph_from_capnp( rr_graph_schema=self.rr_graph_schema, input_file_name=input_file_name, progressbar=progressbar, filter_nodes=filter_nodes, rebase_nodes=rebase_nodes, ) graph_input['build_pin_edges'] = build_pin_edges self.root_attrib = graph_input["root_attrib"] del graph_input["root_attrib"] self.graph = graph2.Graph(**graph_input)
def to_capnp(self): """ Load the class in capnp schema MultipleInheritance.capnp :rtype bytes """ template = capnp.load('%s/MultipleInheritance.capnp' % dir) return template.MultipleInheritance.new_message( **self.as_dict()).to_bytes()
def rpc(self): self.dpi = capnp.load( os.path.join(cosimDir, "cosim_dpi_server", "esi_cosim_dpi.capnp")) hostname = os.uname()[1] self.rpc_client = capnp.TwoPartyClient(f"{hostname}:1111") self.cosim = self.rpc_client.bootstrap().cast_as( self.dpi.CosimDpiServer) return self.cosim
def encode(schema_file, struct_name, **kwargs): schema = capnp.load(schema_file) struct_schema = getattr(schema, struct_name) struct_dict = json.load(sys.stdin) struct = struct_schema.from_dict(struct_dict) struct.write(sys.stdout)
def new(binary=None): """ Load the binary of Cat.capnp into class Cat :type binary: bytes. If none creates an empty capnp object. rtype: Cat """ template = capnp.load('%s/Cat.capnp' % dir) struct = template.Cat.from_bytes(binary) if binary else template.Cat.new_message() return Cat(**struct.to_dict(verbose=True))
def new(binary=None): """ Load the binary of NumberFormat.capnp into class NumberFormat :type binary: bytes. If none creates an empty capnp object. rtype: NumberFormat """ template = capnp.load("%s/NumberFormat.capnp" % dir) struct = (template.NumberFormat.from_bytes(binary) if binary else template.NumberFormat.new_message()) return NumberFormat(**struct.to_dict(verbose=True))
def load_capnp_schema(): here = pathlib.Path(__file__).absolute().parent search_paths = [ here.parent / "share" / "kvak" / "schema.capnp", here.parent / "schema.capnp", ] for path in search_paths: if path.exists(): return capnp.load(str(path)) raise RuntimeError("Unable to find the schema.capnp file!")
def new(binary=None): """ Load the binary of EnumCity.capnp into class EnumCity :type binary: bytes. If none creates an empty capnp object. rtype: EnumCity """ template = capnp.load("%s/EnumCity.capnp" % dir) struct = (template.EnumCity.from_bytes(binary) if binary else template.EnumCity.new_message()) return EnumCity(**struct.to_dict(verbose=True))
def new(binary=None): """ Load the binary of Animal.capnp into class Animal :type binary: bytes. If none creates an empty capnp object. rtype: Animal """ template = capnp.load('%s/Animal.capnp' % dir) struct = template.Animal.from_bytes( binary) if binary else template.Animal.new_message() return Animal(**struct.to_dict(verbose=True))
def new(binary=None): """ Load the binary of WithDateTime.capnp into class WithDateTime :type binary: bytes. If none creates an empty capnp object. rtype: WithDateTime """ template = capnp.load('%s/WithDateTime.capnp' % dir) struct = template.WithDateTime.from_bytes( binary) if binary else template.WithDateTime.new_message() return WithDateTime(**struct.to_dict(verbose=True))
def new(binary=None): """ Load the binary of Petshop.capnp into class Petshop :type binary: bytes. If none creates an empty capnp object. rtype: Petshop """ template = capnp.load("%s/Petshop.capnp" % dir) struct = (template.Petshop.from_bytes(binary) if binary else template.Petshop.new_message()) return Petshop(**struct.to_dict(verbose=True))
def capnp_crunch(self, key, value): schema = value.to_any().tag() if not (key in DataReaderInterface.capnp_registered_schemas): schema_file = capnp.load(self.capnp_folder + '/' + schema + '.capnp', imports=[os.environ['CAPNP_ROOT'] + '/c++/src']) Any.register_class(schema, getattr(schema_file, schema)) DataReaderInterface.capnp_registered_schemas.add(key) new_value = value.to_any().reader() return new_value
def make_schemas_module(): """ small hack to make the schemas available in ``sys.modules`` """ import os import sys capnp.remove_import_hook() pkg_path = os.path.dirname(os.path.realpath(__file__)) schemas_path = os.path.join(pkg_path, 'schemas.capnp') sys.modules['schemas'] = capnp.load( encoding.ensure_native_str(schemas_path))
def get_serializer(branch, table_name): title = make_title_name(table_name) key = 'tables/%s/schema.json' % table_name schema_id = branch.tree.object_id(key) if schema_id not in PROTO_CACHE: table = json.loads(branch[key]) with tempfile.NamedTemporaryFile() as f: f.write(table['proto']) f.flush() module = capnp.load(f.name) cls = type(title + 'Proto', (Proto,), {}) proto = cls(table, getattr(module, title)) PROTO_CACHE[schema_id] = proto return PROTO_CACHE[schema_id]
def main(): dirMngr = Chdir() currPath = os.getcwd() wildcard = '*.capnp' chWildcard = 'Change schema wildcard' chDir = 'Change directory' while True: schemaFiles = [(x,'') for x in glob.glob(wildcard)] code, tag = d.menu('Schema selection', choices=schemaFiles+[ (chDir, '('+os.getcwd()+')'), (chWildcard, '('+wildcard+')')]) if code == Dialog.CANCEL: return if tag == chWildcard: code, tag = d.inputbox('Wildcard',init = wildcard) if code == Dialog.OK: wildcard = tag continue if tag == chDir: code, tag = d.dselect(os.getcwd()) if code == Dialog.OK: dirMngr.changeDir(tag) else: break userSchema = capnp.load(str(tag)) (code,rootStruct) = d.menu('Select root struct', choices = [(x.name,'') for x in userSchema.schema.node.nestedNodes]) msg = getattr(userSchema, rootStruct).new_message() handleStruct(msg) print msg.to_dict()
import stix.core.stix_package import capnp import time from lxml import etree capnp.remove_import_hook() stix_capnp = capnp.load('stix.capnp') with open('ma_report.bin', 'rb') as fh: start_time = time.time() for i in range(1000): fh.seek(0) stix_package = stix_capnp.STIXPackage.read(fh) stix_package.to_dict() print time.time() - start_time with open('maa.xml', 'r') as fh: start_time = time.time() for i in range(1000): fh.seek(0) doc = etree.parse(fh) parsed_package = stix.core.stix_package.STIXPackage.from_xml(doc) parsed_package.to_dict() print time.time() - start_time
tmp += int(sline[1]) ret['free'] = tmp ret['used'] = int(ret['total']) - int(ret['free']) return ret def getNetworkByteCount(dev_name): '''Return (no. received bytes, no transmitted bytes) for network device dev_name''' with open('/proc/net/dev') as fp: for line in fp: line = line.split() if line[0].startswith(dev_name): return int(line[1]), int(line[9]) return 0,0 data_capnp = capnp.load('data.capnp') mypid = os.getpid() client_uniq = "pubclient_"+str(mypid) mqttc = paho.Client(client_uniq, False) #connect to broker mqttc.connect(broker, port, CONNECT_TIMEOUT_S) #remain connected and publish mqttc.loop_start() while True: data = data_capnp.Data.new_message() macAddress = get_mac() data.systemIdHi = macAddress >> 32 & 0xffff
def addressbook(): return capnp.load(os.path.join(this_dir, 'addressbook.capnp'))
def bar(): return capnp.load(os.path.join(this_dir, 'bar.capnp'))
import socket, time import capnp from flask import Flask from config import socket_file, schema_file, poll_interval app = Flask(__name__) def listen(s): while True: try: # receive binary data binary_data = s.recv(4096) if binary_data: # parse as Reading object print schemas.Reading.from_bytes(binary_data) time.sleep(poll_interval) except KeyboardInterrupt: # close connection s.close() if __name__ == "__main__": schemas = capnp.load(schema_file) # create socket object s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect(socket_file) # begin listening for data emitted listen(s)
def test_basic_load(): capnp.load(os.path.join(this_dir, 'addressbook.capnp'))
# -*- coding: utf-8 -*- """ These objects are providing access to our :doc:`schema` in `Python's Cap'n Proto implementation <http://jparyani.github.io/pycapnp/>`_. """ import os import capnp capnp.remove_import_hook() _dirname = os.path.dirname(os.path.realpath(__file__)) bbb = capnp.load(os.path.join(_dirname, 'bb_binary_schema.capnp')) FrameContainer = bbb.FrameContainer """ FrameContainer are basically the root of our data container. They represent a video that in beesbook context usually consist of 5 minutes. Each FrameContainer only has the frames of **one** camera. .. literalinclude:: ../../bb_binary/bb_binary_schema.capnp :lines: 82-98 """ Frame = bbb.Frame """ A Frame holds all the information about a single image in a video. .. literalinclude:: ../../bb_binary/bb_binary_schema.capnp :lines: 62-74 """
#!/usr/bin/env python from __future__ import print_function import os import capnp this_dir = os.path.dirname(__file__) out_path = os.path.join(this_dir, "addressbook.bin") addressbook = capnp.load(os.path.join(this_dir, "addressbook.capnp")) def writeAddressBook(file): addresses = addressbook.AddressBook.newMessage() people = addresses.init("people", 2) alice = people[0] alice.id = 123 alice.name = "Alice" alice.email = "*****@*****.**" alicePhones = alice.init("phones", 1) alicePhones[0].number = "555-1212" alicePhones[0].type = "mobile" alice.employment.school = "MIT" bob = people[1] bob.id = 456 bob.name = "Bob" bob.email = "*****@*****.**" bobPhones = bob.init("phones", 2) bobPhones[0].number = "555-4567" bobPhones[0].type = "home" bobPhones[1].number = "555-7654"
def object(): return capnp.load(os.path.join(this_dir, 'object.capnp'))
def foo(): return capnp.load(os.path.join(this_dir, 'foo.capnp'))
import capnp import capnp.lib.capnp as cpl capnp.remove_import_hook() fs_capnp = capnp.load('schemas/fs.capnp') def create_ffi(capnp_file): GenericFFI = type('GenericFFI', (object,), {}) capnp_schema = capnp.load(capnp_file) for interface in dir(capnp_schema): interface = getattr(capnp_schema, interface) if not isinstance(interface, cpl._InterfaceModule): continue InterfaceType = type(interface, (interface.Server,), {}) #attach the implementations for the ffi functions, we know what they are for method_name, method in interface.schema.methods.items(): def ffi_method(self, **kwargs): for field_name, field in method.param_type.fields.items(): field=field.proto.slot if field.hasExplicitDefault: if field_name not in kwargs: kwargs[field_name] = field.defaultValue try: assert field in kwargs except Exception: raise KeyError('Missing required field "{}" to function "{}" with no default'.format(field_name, method_name)) # insert call to ffi library here and parse return type but what is it? ffi_method.__name__ = method_name setattr(InterfaceType, method_name, ffi_method) setattr(GenericFFI, interface, InterfaceType)
import bpy import math from math import * import bmesh from collections import deque from mathutils import * import capnp mscene = capnp.load('src/micropolis/mscene.capnp') def vsum(vs): s = Vector([0,0,0]) for v in vs: s += v return s def face_center(f): return vsum((v.co for v in f.verts)) / len(f.verts) def edge_center(e): return (e.verts[0].co + e.verts[1].co)/2
import capnp import os import os.path import socket import struct import uuid from twisted.internet import defer, protocol, reactor from twisted.internet.protocol import Factory, Protocol from twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocol scriptpath = os.path.dirname(os.path.realpath(__file__)) quasar_cpnp = capnp.load(os.path.join(scriptpath, "quasar.cpnp")) def connectToArchiver(addr, port=4410): ep = TCP4ClientEndpoint(reactor, addr, port) d = connectProtocol(ep, Quasar()) return d class QuasarFactory(Factory): def buildProtocol(self, addr): return Quasar() class Quasar(Protocol): LATEST = 0 def connectionMade(self): self.defmap = {} self.etag = 1
import pycapnqml from pycapnqml import Client, QtClient, ZmqChannel, create_context, ZmqAddress, ZmqProtocol from pycapnqml import MessageType, ErrorKind, Message, LocalChannel from os.path import abspath, dirname, join from random import randint import capnp from subprocess import Popen import sys curdir = dirname(abspath(__file__)) json_capnp = capnp.load(join(curdir, 'json.capnp')) error_capnp = capnp.load(join(curdir, 'error.capnp')) def pack_string(arg): ret = arg.encode('UTF-8') return ret def make_local(): server = Server() client = QtClient() cha = LocalChannel() chb = LocalChannel() cha.target = chb.loop chb.target = cha.loop server.channel = cha client.channel = chb server.run() client.run()
from urllib.parse import urlparse from flask import Flask from flask import request from flask import render_template from flask import make_response import capnp # Hack to make RPC work in Flask worker threads capnp.remove_event_loop() capnp.create_event_loop(threaded=True) # Load the relevant interface descriptors from the current sandstorm bundle. bridge = capnp.load("/opt/sandstorm/latest/usr/include/sandstorm/sandstorm-http-bridge.capnp", imports=[ "/opt/sandstorm/latest/usr/include", ] ) util = capnp.load("/opt/sandstorm/latest/usr/include/sandstorm/util.capnp", imports=[ "/opt/sandstorm/latest/usr/include", ] ) powerbox = capnp.load("/opt/sandstorm/latest/usr/include/sandstorm/powerbox.capnp", imports=[ "/opt/sandstorm/latest/usr/include", ] ) grain = capnp.load("/opt/sandstorm/latest/usr/include/sandstorm/grain.capnp",
#!/usr/bin/env python from __future__ import print_function import os import capnp this_dir = os.path.dirname(__file__) addressbook = capnp.load(os.path.join(this_dir, 'addressbook.capnp')) def writeAddressBook(file): addresses = addressbook.AddressBook.newMessage() people = addresses.init('people', 2) alice = people[0] alice.id = 123 alice.name = 'Alice' alice.email = '*****@*****.**' alicePhones = alice.init('phones', 1) alicePhones[0].number = "555-1212" alicePhones[0].type = 'mobile' alice.employment.school = "MIT" bob = people[1] bob.id = 456 bob.name = 'Bob' bob.email = '*****@*****.**' bobPhones = bob.init('phones', 2) bobPhones[0].number = "555-4567" bobPhones[0].type = 'home' bobPhones[1].number = "555-7654" bobPhones[1].type = 'work' bob.employment.unemployed = None
def capability(): return capnp.load(os.path.join(this_dir, 'test_capability.capnp'))
def test_capnp(): return capnp.load(os.path.join(this_dir, 'test_large_read.capnp'))
def all_types(): return capnp.load(os.path.join(this_dir, 'all_types.capnp'))
#!/usr/bin/env python2 import sys import os import capnp from madara.knowledge import * geo = capnp.load(os.environ["MADARA_ROOT"] + "/tests/capnfiles/Geo.capnp") Any.register_int32("i32"); Any.register_class("Point", geo.Point) Any.register_class("Pose", geo.Pose) a = Any("i32") a.assign(10); print(a.to_integer()) p = geo.Point.new_message() p.x = 2 p.y = 4 p.z = 6 b = Any(p) print(b.tag()) print(b) print(b.reader()) pose = geo.Pose.new_message() pose.x = 42