Python中的十六进制转换错误

时间:2013-02-19 16:06:07

标签: python json tornado hex

我有一个问题。

我有一个页面,我将命令发送到传感器网络。

当我点击这部分代码时

<a href='javascript:void(send_command_to_network("{{net.id}}", "restartnwk"));'>Restart Network <i class="icon-repeat"></i> </a>

我调用js函数,这个:

function send_command_to_network(net, command) {
    $.ajax({url: "/networks/" + net + "/send?command=" + command,
    type: "GET",
    async: true,
    dataType: "json",
    success: function(json_response) { 
         var err = json_response['error'];
     if (err) {
       show_alert('error', err);
       return;
     }
     var success = json_response['success'];
     if (success) {
       show_alert('success', success);
       return;
     }
     show_alert('alert', "This should not happen!");
       }
     }); 
    }

此函数构建一个url,用于调用用python编写的Tornado Web服务器中的处理程序。处理程序是这样的:

class NetworkSendHandler(BaseHandler):
    # Requires authentication 
    @tornado.web.authenticated
    def get(self, nid):
        # Get the command 
        command = self.get_argument('command').upper(); 

        # The dictionary to return
        ret = {}

        #Check if the command is available
        if command not in ['RESTARTNWK']:
            raise tornado.web.HTTPError(404, "Unknown command: " + str(command))


        #Command ZDP-RestartNwk.Request
        if command == 'RESTARTNWK':
            op_group = "A3"
            op_code = "E0"
            packet_meta = "*%s;%s;%s;#"
            pkt_len = hextransform(16, 2)

            packet = packet_meta % (op_group, op_code, pkt_len)
            packet = packet.upper()

            op_group_hex=0xA3
            op_code_hex=0xE0

            cmdjson = packet2json(op_group_hex,op_code_hex, packet)

        self.finish()

我在Tornado调试consolle中收到此错误:

Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/tornado/web.py", line 988, in _execute
    getattr(self, self.request.method.lower())(*args, **kwargs)
  File "/usr/lib/python2.6/site-packages/tornado/web.py", line 1739, in wrapper
    return method(self, *args, **kwargs)
  File "./wsn.py", line 859, in get
    cmdjson = packet2json(op_group_hex,op_code_hex, packet)
  File "./wsn.py", line 188, in packet2json
    fcs = fcs ^ int('0x' + payload[(i - 1):(i + 1)], 16)
ValueError: invalid literal for int() with base 16: '0x*A'

我认为错误发生在调用packet2json之后。我认为错误是在函数内部进行转换,因为错误表明'0x * A'不是有效的int。我认为'*'是错误的....我该如何解决这个问题?

修改

抱歉,我忘记了这些功能:

# Transform an integer into a string with HEX symbols in the format that is
# understandable by Quantaservd
def hextransform(data, length):
    data = hex(data).lstrip('0x').rstrip('L')
    assert(len(data) <= length)
    # zero-padding
    data = ('0' * (length - len(data))) + data
    print data
    # Swap 'bytes' in the network ID
    data = list(data)
    for i in range(0, length, 2):
        tmp = data[i]
        data[i] = data[i + 1]
        data[i + 1] = tmp
    # Reverse the whole string (TODO: CHECK) 
    data.reverse()
    data = "".join(data)
    return data


def packet2json(op_group, op_code, payload): 
    #op_group =
    #op_code =
    #payload=""    # stringa ascii 2 char per byte, senza checksum 
    lun = len(payload) / 2
    fcs = op_group ^ op_code ^ lun #fcs = XOR of op_groip, op_code, lenght and  payload
    for i in range(len(payload)):
    if ((i % 2) == 1):
        fcs = fcs ^ int('0x' + payload[(i - 1):(i + 1)], 16)
        print int('0x' + payload[(i - 1):(i + 1)], 16)
    s=cmd_payload(op_group,op_code, lun, payload, fcs)
    #p = r '{"data": "' + s + r '"}'
    p=r'{"data": "'+s+r'"}'
    return p

1 个答案:

答案 0 :(得分:0)

问题在于packet2json()功能:

for i in range(len(payload)):
    if ((i % 2) == 1):
        fcs = fcs ^ int('0x' + payload[(i - 1):(i + 1)], 16)

在你的程序中,你可以这样调用这个函数:

packet2json(0xa3, 0xe0, '*A3;E0;10;#')

现在上面的循环将从第一个字符(索引0)开始,忽略它,因为它的索引不是奇数,然后转到索引为奇数的第二个字符(索引1)(1%2 == 1)。 if语句的正文使用int('0x' + payload[(i-1):(i+1)], 16),即int('0x' + payload[0:2], 16),即int('0x*A',16),这将永远崩溃......

您应该重写此packet2json()函数以使用正确的字符串索引,或者在有效负载中没有前导*的情况下正确调用它。