0

I have a problem.

I have a page where I send commands to a sensor network.

When I click on this part of code

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

I call a js function, this:

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!");
       }
     }); 
   }

This function build a url that recall an handler in the Tornado web server written in python. The handler is this:

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(0, 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)

    mynet_type="ztc"

    print("\t\t " + packet + "\n")

    #TODO : -write command into db  
    ts = datetime.datetime.now().isoformat()
    mynet_type ="ztc" 
    self.lock_tables("write", ['confcommands'])
self.db.execute("INSERT INTO confcommands (network_id, ntype, timestamp, command) \
                              VALUES (%s,%s,%s,%s)", nid, mynet_type, ts, cmdjson)
    self.unlock_tables();

    # TODO: - open the /tmp/iztc file in append mode
    cmdfile = open('/tmp/iztc', 'a')
    #       - acquire a lock  "only for the DB case, it's easier"
    #       - write the packet 
    cmdfile.write(netid + "\t"+ mynet_type + "\t"+ ts + "\t"+  cmdjson +"\n");
    #       - release the lock "only for the DB case, it's easier"
    #       - close the file
    cmdfile.close()

    if command == 'RESTARTNWK':
        opcodegroupr = "A4"
        opcoder = "E0"      

    #Code for retrieving the MAC address of the node
    como_url = "".join(['http://options.como_address:', options.como_port,
                        '/', ztc_config, '?netid=', netid,
                        '&opcode_group=', opcodegroupr, 
                        '&opcode=', opcoder, '&start=-5m&end=-1s'])
    http_client = AsyncHTTPClient()
    response = yield tornado.gen.Task(http_client.fetch, como_url)

    ret = {}
    if response.error:
        ret['error'] = 'Error while retrieving unregistered sensors'
    else:
        for line in response.body.split("\n"):
            if line != "": 
                value = int(line.split(" ")[6])

    ret['response'] = value
    self.write(tornado.escape.json_encode(ret))
    self.finish()

    if value == "0":
        # TODO: handle Errors. It always return succesfully.
        #ret['error'] = "Error while sending the %s command!" % (command.upper())
        ret['success'] = "The %s command has been succesfully sent!" % (command.upper())
        self.write(tornado.escape.json_encode(ret))
    else:
    ret['error'] = "Error while sending the %s command!" % (command.upper())

The error I receive in the developer consolle is this:

Uncaught TypeError: Cannot read property 'error' of null

in the js function. Why the function doesn't know 'error' or 'success'? Where is the problem???? I think the program don't enter never in the handler, but is blocked after, just in the js function.

Thank you very much for the help.

sharkbait
  • 2,980
  • 16
  • 51
  • 89
  • FYI: The script after your `self.finish()` is never going to produce results. Because the request has finished and the data was send already. But can you please send your tornado application routes? To make sure your request is going to the right script. Thanks. – Steve Peak Jan 29 '13 at 21:43
  • Do you mean this? `(r"/networks/([0-9]+)/send/*", NetworkSendHandler)` – sharkbait Jan 30 '13 at 09:16

0 Answers0