Skip to content

Instantly share code, notes, and snippets.

@fisherds
Created February 14, 2022 05:03
Show Gist options
  • Save fisherds/48e4563c98a2428d1af1ffebad98766f to your computer and use it in GitHub Desktop.
Save fisherds/48e4563c98a2428d1af1ffebad98766f to your computer and use it in GitHub Desktop.
// These methods could be added to your existing class.
/**
* Read button - Gets the state of the fake pushbutton (0 or 1)
* method: GET
* path: /api/readbutton
* expected request body: none
* side effects: none (the pushbutton is always random)
* response: {"button": 0} or {"button": 1}
*/
async readButton() {
const response = await fetch(`/api/readButton`);
const data = await response.json();
console.log("Read Button response:", data);
this.button = data["button"];
this.updateView();
}
/**
* Set LED - Sets the state of 1 LED
* method: PUT
* path: /api/setled/:color/:state
* expected request body: none
* side effects: saves the state for this LED into db.json
* prints to the console the LED states
* response: {"leds": {"red": 0, "yellow": 0, "green": 0}}
*/
async setLed(color, value) {
const options = {
method: "PUT"
}
const response = await fetch(`/api/setled/${color}/${value}`, options);
const data = await response.json();
console.log("Set LED response:", data);
this.leds = data["leds"];
this.updateView();
}
/**
* Set servos - Set all three servo angles using a POST, body is a JSON array with 3 numbers.
* method: POST
* path: /api/setservos
* expected request body: JSON object, for example [-90, 90, 0]
* side effects: saves the state of the servos into db.json
* prints to the console the servo states
* response: {"servos": [-90, 90, 0]}
*/
async setServos(angles) {
const options = {
method: "POST",
headers: {
"Content-Type": 'application/json'
},
body: JSON.stringify({
"angles": angles
})
}
const response = await fetch(`/api/setservos`, options);
const data = await response.json();
console.log("Set Servos response", data);
this.servos = data["servos"];
this.updateView();
}
/**
* Get Status - Get the state of all fake physical components.
* method: GET
* path: /api/getstatus
* expected request body: none
* side effects: none
* response: {"button": 0, "leds": {"red": 1, "yellow": 1, "green": 0},
* "servos": [0, 45, 0]}
*/
async getStatus() {
const response = await fetch(`/api/getstatus`);
const data = await response.json();
console.log("Get Status response:", data);
this.button = data["button"];
this.leds = data["leds"];
this.servos = data["servos"];
this.updateView();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment