Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 32 additions & 7 deletions app/electron/apis.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { dialog } = require('electron');
const path = require('path');
const fs = require('fs');
const fs = require('fs-extra');
const drivelist = require('drivelist');

/* List of all APIS */
Expand All @@ -16,8 +16,8 @@ global.share.ipcMain.handle('open-file', handleOpenFile);
async function handleSaveCode(event, req) {
const appState = JSON.parse(fs.readFileSync(path.join(__dirname, "../state.json")));
if (appState.fullPath != "") {
let filePath = path.join(appState.fullPath, req.filename);
fs.writeFileSync(filePath, req.content);
let filePath = path.join(appState.fullPath, req.filename);
fs.writeFileSync(filePath, req.content);
return {
status: 200,
payload: path.basename(filePath, path.extname(filePath)),
Expand Down Expand Up @@ -61,15 +61,16 @@ async function handleSaveAsCode(event, req) {
};

// Uploads Code to robot
async function handleUploadCode (event, code) {
async function handleUploadCode(event, code) {
try {
let drives = await drivelist.list();

let first_bot = drives.find(x => x.description.includes('Maker Pi RP2040'));
let first_bot_drive = first_bot.mountpoints[0].path;
let output_filepath = path.join(first_bot_drive, 'code.py');
let initLib = initializeCodeLibrary(first_bot_drive)
fs.writeFileSync(output_filepath, code);

return {
status: 201,
message: "Code Uploaded"
Expand All @@ -80,8 +81,32 @@ async function handleUploadCode (event, code) {
message: `Internal Error: ${e}`
};
}

};


function initializeCodeLibrary(fpath) {
try {
const wpilibLoc = path.join(__dirname, "../lib/WPILib");
let output_filepath = path.join(fpath, 'WPILib');
fs.pathExists(output_filepath).then(exists => {
if (exists) {
return true
} else {
fs.copy(wpilibLoc, output_filepath).then(() => {
return true
})
.catch(err => {
console.error(err)
})
}
}
);
} catch (e) {
return false;
}
}

// Opens File
async function handleOpenFile(event, req) {
const filePath = dialog.showOpenDialogSync({
Expand All @@ -93,7 +118,7 @@ async function handleOpenFile(event, req) {

if (filePath) {
let inputFile = fs.readFileSync(filePath[0], { encoding: 'utf8' });

return {
status: 200,
payload: {
Expand Down
2 changes: 1 addition & 1 deletion app/electron/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs');
const fs = require('fs-extra');
const drivelist = require('drivelist');
const { SerialPort } = require('serialport');
var AsyncPolling = require('async-polling');
Expand Down
44 changes: 44 additions & 0 deletions app/lib/WPILib/WPILib.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import board as _board
from _drivetrain import Drivetrain
from _encoded_motor import EncodedMotor
from _ultrasonic_wrapper import Ultrasonic
from _reflectance_wrapper import Reflectance
from _servo import Servo
from _buttons import Buttons
from _led import RGBLED

import time

# hidden motor variables
"""
If you need to change the encoder counts, alter the ticksPerRev values in the following two constructors.
Most robots have either 144 or 288 ticks per revolution, depending on which motors are used.
"""
_leftMotor = EncodedMotor(
encoderPinA=_board.GP4,
encoderPinB=_board.GP5,
motorPin1=_board.GP8,
motorPin2=_board.GP9,
doFlip=True,
ticksPerRev=288)

_rightMotor = EncodedMotor(
encoderPinA=_board.GP2,
encoderPinB=_board.GP3,
motorPin1=_board.GP10,
motorPin2=_board.GP11,
doFlip=False,
ticksPerRev=288)

# Publicly-accessible objects
drivetrain = Drivetrain(_leftMotor, _rightMotor) # units in cm
reflectance = Reflectance()
sonar = Ultrasonic()
led = RGBLED(_board.GP18)
servo = Servo(_board.GP12, actuationRange = 135)
buttons = Buttons()

def set_legacy_mode(is_legacy: bool = True):
drivetrain.set_legacy_mode(is_legacy)
sonar.set_legacy_mode(is_legacy)
reflectance.set_legacy_mode(is_legacy)
Binary file not shown.
172 changes: 172 additions & 0 deletions app/lib/WPILib/_adafruit_hcsr04.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
# Write your code here :-)
# SPDX-FileCopyrightText: 2017 Mike Mabey
#
# SPDX-License-Identifier: MIT

"""
`adafruit_hcsr04`
====================================================

A CircuitPython library for the HC-SR04 ultrasonic range sensor.

The HC-SR04 functions by sending an ultrasonic signal, which is reflected by
many materials, and then sensing when the signal returns to the sensor. Knowing
that sound travels through dry air at `343.2 meters per second (at 20 °C)
<https://en.wikipedia.org/wiki/Speed_of_sound>`_, it's pretty straightforward
to calculate how far away the object is by timing how long the signal took to
go round-trip and do some simple arithmetic, which is handled for you by this
library.

.. warning::

The HC-SR04 uses 5V logic, so you will have to use a `level shifter
<https://www.adafruit.com/product/2653?q=level%20shifter&>`_ or simple
voltage divider between it and your CircuitPython board (which uses 3.3V logic)

* Authors:

- Mike Mabey
- Jerry Needell - modified to add timeout while waiting for echo (2/26/2018)
- ladyada - compatible with `distance` property standard, renaming, Pi compat
"""

import time
import math
from digitalio import DigitalInOut, Direction

_USE_PULSEIO = False
try:
from pulseio import PulseIn

_USE_PULSEIO = True
except ImportError:
pass # This is OK, we'll try to bitbang it!

__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_HCSR04.git"

class AdafruitUltrasonic:
"""Control a HC-SR04 ultrasonic range sensor.

Example use:

::

import time
import board

import adafruit_hcsr04

sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D2, echo_pin=board.D3)


while True:
try:
print((sonar.distance,))
except RuntimeError:
print("Retrying!")
pass
time.sleep(0.1)
"""

def __init__(self, trigger_pin, echo_pin, *, timeout=0.1):
"""
:param trigger_pin: The pin on the microcontroller that's connected to the
``Trig`` pin on the HC-SR04.
:type trig_pin: microcontroller.Pin
:param echo_pin: The pin on the microcontroller that's connected to the
``Echo`` pin on the HC-SR04.
:type echo_pin: microcontroller.Pin
:param float timeout: Max seconds to wait for a response from the
sensor before assuming it isn't going to answer. Should *not* be
set to less than 0.05 seconds!
"""
self.MAX_VALUE = 65535
self._timeout = timeout
self._trig = DigitalInOut(trigger_pin)
self._trig.direction = Direction.OUTPUT

if _USE_PULSEIO:
self._echo = PulseIn(echo_pin)
self._echo.pause()
self._echo.clear()
else:
self._echo = DigitalInOut(echo_pin)
self._echo.direction = Direction.INPUT

def __enter__(self):
"""Allows for use in context managers."""
return self

def __exit__(self, exc_type, exc_val, exc_tb):
"""Automatically de-initialize after a context manager."""
self.deinit()

def _deinit(self):
"""De-initialize the trigger and echo pins."""
self._trig.deinit()
self._echo.deinit()

def get_distance(self):
"""
Return the distance measured by the sensor in cm.

This is the function that will be called most often in user code. The
distance is calculated by timing a pulse from the sensor, indicating
how long between when the sensor sent out an ultrasonic signal and when
it bounced back and was received again.

If no signal is received, we'll throw a RuntimeError exception. This means
either the sensor was moving too fast to be pointing in the right
direction to pick up the ultrasonic signal when it bounced back (less
likely), or the object off of which the signal bounced is too far away
for the sensor to handle. In my experience, the sensor can detect
objects over 460 cm away.

:return: Distance in centimeters.
:rtype: float
"""
return self._dist_two_wire() # at this time we only support 2-wire meausre

def _dist_two_wire(self):
if _USE_PULSEIO:
self._echo.clear() # Discard any previous pulse values
self._trig.value = True # Set trig high
time.sleep(0.00001) # 10 micro seconds 10/1000/1000
self._trig.value = False # Set trig low

pulselen = None
timestamp = time.monotonic()
if _USE_PULSEIO:
self._echo.resume()
while not self._echo:
# Wait for a pulse
if (time.monotonic() - timestamp) > self._timeout:
self._echo.pause()
#raise RuntimeError("Timed out")
return self.MAX_VALUE
self._echo.pause()
pulselen = self._echo[0]
else:
# OK no hardware pulse support, we'll just do it by hand!
# hang out while the pin is low
while not self._echo.value:
if time.monotonic() - timestamp > self._timeout:
#raise RuntimeError("Timed out")
return self.MAX_VALUE
timestamp = time.monotonic()
# track how long pin is high
while self._echo.value:
if time.monotonic() - timestamp > self._timeout:
#raise RuntimeError("Timed out")
return self.MAX_VALUE
pulselen = time.monotonic() - timestamp
pulselen *= 1000000 # convert to us to match pulseio
if pulselen >= 65535:
#raise RuntimeError("Timed out")
return self.MAX_VALUE

# positive pulse time, in seconds, times 340 meters/sec, then
# divided by 2 gives meters. Multiply by 100 for cm
# 1/1000000 s/us * 340 m/s * 100 cm/m * 2 = 0.017
return pulselen * 0.017
34 changes: 34 additions & 0 deletions app/lib/WPILib/_analog_reflectance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from analogio import AnalogIn

class AnalogReflectance:

"""
Implements for the new reflectance sensor.
Reads from analog in and converts to a float from 0 (white) to 1 (black)
"""

def __init__(self, leftPin, rightPin):
self._leftReflectance = AnalogIn(leftPin)
self._rightReflectance = AnalogIn(rightPin)

def _get_value(self, sensor: AnalogIn) -> float:
MAX_ANALOG_VALUE: int = 65535
return sensor.value / MAX_ANALOG_VALUE

# Implements AbstractReflectance
def get_left(self) -> float:
"""
Gets the the reflectance of the left reflectance sensor
:return: The reflectance ranging from 0 (white) to 1 (black)
:rtype: float
"""
return self._get_value(self._leftReflectance)

# Implements AbstractReflectance
def get_right(self) -> float:
"""
Gets the the reflectance of the right reflectance sensor
:return: The reflectance ranging from 0 (white) to 1 (black)
:rtype: float
"""
return self._get_value(self._rightReflectance)
30 changes: 30 additions & 0 deletions app/lib/WPILib/_buttons.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import board
from digitalio import DigitalInOut, Direction, Pull

class Buttons:

def _createButton(self, buttonPin):
btn = DigitalInOut(buttonPin)
btn.direction = Direction.INPUT
btn.pull = Pull.UP
return btn

def __init__(self):
self._buttonGP20 = self._createButton(board.GP20)
self._buttonGP21 = self._createButton(board.GP21)

def is_GP20_pressed(self) -> bool:
"""
Get whether the GP20 button on the RP2040 microcontroller has been pressed
: return: if the GP20 button was pressed
: rtype: bool
"""
return not self._buttonGP20.value

def is_GP21_pressed(self) -> bool:
"""
Get whether the GP21 button on the RP2040 microcontroller has been pressed
: return: if the GP21 button was pressed
: rtype: bool
"""
return not self._buttonGP21.value
Loading