jpan127 / APDS

Autonomous Postal Delivery System
0 stars 0 forks source link

app.js magic number cleanup and generalizing functions #20

Closed jpan127 closed 5 years ago

jpan127 commented 6 years ago

I think we can clean up the code by having a table.

Currently:

clientConnectSendState(0,0x1E,0);
clientConnectSendState(7,0x2,0);
clientConnectSendState(6,0x2,0);
clientConnectSendState(14,0x4B,0);

What do these numbers mean? How can we keep track of these numbers and manage them when the code gets more complex?

Proposal:

These names can be replaced with real names.
Not sure what the values are supposed to be though.
const var packet_types_enum = {
    "type0" : 0,
    "type1" : 1,
    ...
    "type14" : 14,
};
clientConnectSendState(packet_types_enum.type0, 0x1E, state["NAVIGATING_SIDEWALK"]);
clientConnectSendState(packet_types_enum.type7, 0x2, state["NAVIGATING_SIDEWALK"]);
clientConnectSendState(packet_types_enum.type6, 0x2, state["NAVIGATING_SIDEWALK"]);
clientConnectSendState(packet_types_enum.type14, 0x4B, state["NAVIGATING_SIDEWALK"]);

One generic function for the logging + client connect + transition. I'm sure this doesn't work because I don't understand Javascript that much but I think you can get the general idea of what I mean. Trying to generalize functions. Currently:

function looking_for_path() {
    current_state = state["LOOKING_FOR_PATH"];

    debug_log("Looking for path");
                //STOP
    clientConnectSendState(14,0x4,1); 
    setTimeout(found_path_to_house, 1000);                 

}

function found_path_to_house() {
    current_state = state["FOUND_PATH_TO_HOUSE"];

    debug_log("found path to house");
    clientConnectSendState(17,0x4,2);  
    setTimeout(navigating_path, 1000);      
    // Pivot 90 degrees and go down new path
}

Proposal:

function update_state(state, next_state) {
    state_num = state_table[state];
    debug_log(state);
    clientConnectSendState(PACKET_TYPE_STATE, SOME_VALUE, state_num);
    const var delay_until_next_state_ms = 1000;
    setTimeOut(update_state, delay_until_next_state_ms);
}

Example usage:
update_state("LOOKING_FOR_PATH", "FOUND_PATH_TO_HOUSE");
update_state("FOUND_PATH_TO_HOUSE", "NAVIGATING_PATH");