当前位置: 首页>>代码示例>>Python>>正文


Python umsgpack.unpackb函数代码示例

本文整理汇总了Python中umsgpack.unpackb函数的典型用法代码示例。如果您正苦于以下问题:Python unpackb函数的具体用法?Python unpackb怎么用?Python unpackb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了unpackb函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_unpack_exceptions

 def test_unpack_exceptions(self):
     for (name, data, exception) in unpack_exception_test_vectors:
         print("\tTesting %s" % name)
         try:
             umsgpack.unpackb(data)
         except Exception as e:
             self.assertTrue(isinstance(e, exception))
开发者ID:cforger,项目名称:u-msgpack-python,代码行数:7,代码来源:test_umsgpack.py

示例2: main

def main():
	# Switch to API Mode
	print ">> Configuring Xbee"
	time.sleep(1)
	ser_xbee.write("+++")				# enter command mode
	time.sleep(1)
	if (ser_xbee.read(3) == "OK\r"):
		print "AT  \tOK"
		ser_xbee.write("ATAP 1\r")					# switch to API mode
		print "ATAP\t%s" %ser_xbee.read(3)			# wait for reply
		ser_xbee.write("ATID %s\r" %XBEE_MESH_ID)	# mesh id
		print "ATID\t%s" %ser_xbee.read(3)			# wait for reply
		ser_xbee.write("ATCH %s\r" %XBEE_MESH_CH)	# mesh ch
		print "ATCH\t%s" %ser_xbee.read(3)			# wait for reply
		ser_xbee.write("ATWR\r")					# apply settings
		print "ATWR\t%s" %ser_xbee.read(3)			# wait for reply
		ser_xbee.write("ATAG %s\r" %XBEE_MESH_DL)	# apply settings
		print "ATAG\t%s" %ser_xbee.read(3)			# wait for reply
		ser_xbee.write("ATCN\r")					# exit command mode	
	else:
		print "AT  \tFAIL"

	# Configure Xbee
	#xbee.at(command="CE", parameter="0")			# router mode
	#xbee.at(command="ID", parameter=XBEE_MESH_ID)	# mesh id 
	#xbee.at(command="CH", parameter=XBEE_MESH_CH)	# mesh channel
	#xbee.at(command="WR")							# apply
	#xbee.at(command="AG", parameter=XBEE_MESH_DL)	# broadcast as master

	# Receive packets
	frames = {}							# buffer for storing unprocessed frames
	packet = ""							# buffer for placing string after processing
	packets = []						# all packets received
	while True:
		frame = xbee.wait_read_frame()		# wait for frames
		print frame["source_addr"]
		frame = unpackb(frame["data"])		# decode json
		pid   = frame["id"]					# get id
		pnum  = frame["pn"]					# get packet number
		pdata = frame["dt"]					# get data

		if not pid in frames:				# if new packet stream
			frames[pid] = {}				# initialize slot
		frames[pid][pnum] = pdata			# store data from frame
		#print frame

		if 0 in frames[pid]:				# if we already have the header
			if frames[pid][0] == len(frames[pid]):	# and we have all the frames
				for i in range(1, frames[pid][0]):	# join data from frames
					packet += frames[pid][i]
				frames[pid] = {}
				packet = unpackb(packet)
				timestamp = time.strftime("%H:%M:%S", time.localtime())
				print "Got packet from: %s at %s" %(packet["ant_mac"], timestamp)
				packets += (timestamp, packet)
				packet = ""
开发者ID:luisbc92,项目名称:antenna_listener,代码行数:56,代码来源:antenna_listener.py

示例3: aes_decrypt

def aes_decrypt(word, key=config.aes_key, iv=None):
    if iv is None:
        word, iv = umsgpack.unpackb(word)
    else:
        raise Exception('no iv error')

    aes = AES.new(key, AES.MODE_CBC, iv)
    word = aes.decrypt(word)

    return umsgpack.unpackb(word)
开发者ID:BulletTrain,项目名称:qiandao,代码行数:10,代码来源:mcrypto.py

示例4: aes_decrypt

def aes_decrypt(word, key=config.aes_key, iv=None):
    if iv is None:
        word, iv = umsgpack.unpackb(word)
    else:
        raise Exception('no iv error')

    aes = AES.new(key, AES.MODE_CBC, iv)
    word = aes.decrypt(word)

    while word:
        try:
            return umsgpack.unpackb(word)
        except umsgpack.ExtraData:
            word = word[:-1]
开发者ID:Crooky,项目名称:qiandao,代码行数:14,代码来源:mcrypto.py

示例5: keep_alive

    async def keep_alive(self):
        """
        This method is used to keep the server up and running when not connected to Scratch
        :return:
        """
        while True:

            # check for reporter messages
            try:
                [address, contents] = self.router_socket.recv_multipart(zmq.NOBLOCK)
                payload = umsgpack.unpackb(contents)
                # print("[%s] %s" % (address, payload))
                board_num = address.decode()
                board_num = board_num[1]
                command = payload['command']
                if command == 'problem':
                    data_string = command + '/' + board_num + ' ' + payload['problem']
                else:
                    pin = payload['pin']
                    value = payload['value']
                    data_string = command + '/' + board_num + '/' + pin + ' ' + value + '\n'
                # print(data_string)
                self.poll_reply += data_string

            except zmq.error.Again:
                pass
            await asyncio.sleep(.001)
开发者ID:MrYsLab,项目名称:xideco,代码行数:27,代码来源:xihbt.py

示例6: test_invalid_name

    def test_invalid_name(self):
        created = signal.create(self.btctxstore, self.wif, "test")

        # repack to eliminate namedtuples and simulate io
        repacked = umsgpack.unpackb(umsgpack.packb(created))

        self.assertIsNone(signal.read(self.btctxstore, repacked, "wrongname"))
开发者ID:bookchin,项目名称:storjnode,代码行数:7,代码来源:signal.py

示例7: receive_loop

 def receive_loop(self):
     """
     This is the receive loop for zmq messages
     It is assumed that this method may be overwritten to meet the needs of the application
     It returns payload via user provided callback method
     :return:
     """
     while True:
         try:
             data = self.subscriber.recv_multipart(zmq.NOBLOCK)
             self.incoming_message_processing(data[0].decode(), umsgpack.unpackb(data[1]))
             time.sleep(.001)
         except zmq.error.Again:
             try:
                 time.sleep(.001)
                 self.root.update()
             except KeyboardInterrupt:
                 self.root.destroy()
                 self.publisher.close()
                 self.subscriber.close()
                 self.context.term()
                 sys.exit(0)
         except KeyboardInterrupt:
             self.root.destroy()
             self.publisher.close()
             self.subscriber.close()
             self.context.term()
             sys.exit(0)
开发者ID:MrYsLab,项目名称:xideco,代码行数:28,代码来源:gui2.py

示例8: keep_alive

    async def keep_alive(self):
        """
        This method is used to keep the server up and running when not connected to Scratch
        :return:
        """
        while True:

            # check for reporter messages
            try:
                [address, contents] = self.subscriber.recv_multipart(zmq.NOBLOCK)
                payload = umsgpack.unpackb(contents)
                # print("[%s] %s" % (address, payload))
                board_num = address.decode()
                board_num = board_num[1]
                command = payload['command']
                # we will ignore any i2c_replies
                if command == 'i2c_reply' or command == 'i2c_request':
                    continue
                elif command == 'problem':
                    data_string = command + '/' + board_num + ' ' + payload['problem']
                else:
                    # noinspection PyPep8
                    if not 'pin' in payload:
                        continue
                    else:
                        pin = payload['pin']
                        value = payload['value']
                        data_string = command + '/' + board_num + '/' + pin + ' ' + value + '\n'
                    # print(data_string)
                self.poll_reply += data_string

            except zmq.error.Again:
                await asyncio.sleep(.001)
开发者ID:MrYsLab,项目名称:xideco,代码行数:33,代码来源:xihb.py

示例9: _load_cache_settings

    def _load_cache_settings(self):
        """Load settings from cache to self.cached_settings."""

        successful = _ensure_file(self.cache_file)

        if not successful:
            LOG.debug("Unable to load cache.")
            return

        with open(self.cache_file, "rb") as stream:
            LOG.debug("Opening subscription cache to retrieve subscriptions.")
            data = stream.read()

        if data == b"":
            LOG.debug("Received empty string from cache.")
            return False

        for encoded_sub in umsgpack.unpackb(data):
            try:
                decoded_sub = Subscription.Subscription.decode_subscription(encoded_sub)

            except Error.MalformedSubscriptionError as exception:
                LOG.debug("Encountered error in subscription decoding:")
                LOG.debug(exception)
                LOG.debug("Skipping this sub.")
                continue

            self.cache_map["by_name"][decoded_sub.name] = decoded_sub
            self.cache_map["by_url"][decoded_sub.original_url] = decoded_sub

        return True
开发者ID:andrewmichaud,项目名称:puckfetcher,代码行数:31,代码来源:config.py

示例10: get_current_user

 def get_current_user(self):
     ret = self.get_secure_cookie('user', max_age_days=config.cookie_days)
     if not ret:
         return ret
     user = umsgpack.unpackb(ret)
     user['isadmin'] = 'admin' in user['role'] if user['role'] else False
     return user
开发者ID:BulletTrain,项目名称:qiandao,代码行数:7,代码来源:base.py

示例11: test_invalid_peer_type

    def test_invalid_peer_type(self):
        created = base.create(self.btctxstore, self.wif, "peers", None)

        # repack to eliminate namedtuples and simulate io
        repacked = umsgpack.unpackb(umsgpack.packb(created))

        self.assertIsNone(peers.read(self.btctxstore, repacked))
开发者ID:bookchin,项目名称:storjnode,代码行数:7,代码来源:peers.py

示例12: process

 def process(self, message):
     datagram, host, port =  umsgpack.unpackb(message[0])
     reply = self.processAuth(datagram, host, port)
     logger.info("[Radiusd] :: Send radius response: %s" % repr(reply))
     if self.config.system.debug:
         logger.debug(reply.format_str())
     self.pusher.push(umsgpack.packb([reply.ReplyPacket(),host,port]))
开发者ID:niebaopeng,项目名称:ToughRADIUS,代码行数:7,代码来源:radiusd.py

示例13: get_next_message

    async def get_next_message(self):
        """
        This method uses an async future to retrieve the next message from the network.
        :return: If not message is available, None is returned, else the message is returned as a list containing
        the topic and payload.
        """
        # create an asyncio Future
        future = asyncio.Future()

        try:
            # get the next available message
            data = self.subscriber.recv_multipart(zmq.NOBLOCK)

            # get the topic and unpack the payload
            topic = data[0].decode()
            payload = umsgpack.unpackb(data[1])

            # place them into a list
            message = [topic, payload]

            # place the message in the future result
            future.set_result(message)

            # wait until the future reports that it is complete and then return the topic, payload list
            while not future.done():
                await asyncio.sleep(.01)
            return future.result()
        except zmq.error.Again:
            # if no message is available, zmq throws the Again exception, so just return None
            return None
开发者ID:MrYsLab,项目名称:xibot,代码行数:30,代码来源:xirb.py

示例14: test_40_with_rpc

 def test_40_with_rpc(self):
     data = dict(self.sample_task_http)
     data["url"] = "data:,hello"
     result = umsgpack.unpackb(self.rpc.fetch(data).data)
     self.assertEqual(result["status_code"], 200)
     self.assertIn("content", result)
     self.assertEqual(result["content"], "hello")
开发者ID:hemengsi123,项目名称:pyspider,代码行数:7,代码来源:test_fetcher.py

示例15: test_invalid_info_len

    def test_invalid_info_len(self):
        created = base.create(self.btctxstore, self.wif, "info", [])

        # repack to eliminate namedtuples and simulate io
        repacked = umsgpack.unpackb(umsgpack.packb(created))

        self.assertIsNone(info.read(self.btctxstore, repacked))
开发者ID:welfeng2016,项目名称:storjnode,代码行数:7,代码来源:info.py


注:本文中的umsgpack.unpackb函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。