Skip to content

fixed state.json creation and added Pestolink support #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 26 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
39ad8d1
Add XRP Library at 476a0bb
phonymacoroni Mar 27, 2023
a178ee8
Close #16
phonymacoroni Mar 27, 2023
d65360a
Merge branch 'bug/15' into feature/16
phonymacoroni Mar 27, 2023
827a43b
v0.0.6
phonymacoroni Mar 27, 2023
97c02a8
updated gitignore and packages
Advay17 May 24, 2024
885b321
uncompressed file for further modification
Advay17 May 26, 2024
c970da0
if state.json is not created, it becomes created.
Advay17 May 26, 2024
46f0fce
implemented pestolink
Advay17 May 27, 2024
114fabf
Merge remote-tracking branch 'upstream/feature/16'
Advay17 May 27, 2024
a1ab684
recompressed python stuff and fixed triggers
Advay17 May 27, 2024
5a5e7c5
update to electron
Advay17 May 27, 2024
67add84
fixed for building exe
314PiGuy May 27, 2024
d314056
fixed imports
314PiGuy May 27, 2024
a60c838
readded workflows
Advay17 May 27, 2024
24849e2
tried removing publish=never because that breaks stuff?
Advay17 May 27, 2024
d8bd901
updated stuff?
Advay17 May 27, 2024
05d5f41
maybe this works?
Advay17 May 27, 2024
8b65bf8
Updated node version for workflow
Advay17 May 28, 2024
319a276
installed setuptools to make mac work
Advay17 May 28, 2024
250593e
Uses older version of python
Advay17 May 28, 2024
f80414a
Update main.yml
Advay17 May 28, 2024
47edc81
Update main.yml
Advay17 May 28, 2024
b43847b
Update main.yml
Advay17 May 28, 2024
e5e88db
Fixed Workflow
Advay17 May 29, 2024
3b4b7c5
Merge branch 'main' of https://github.com/Advay17/xrp-blockly
Advay17 May 29, 2024
ddce262
Create README.md
Advay17 May 31, 2024
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
12 changes: 9 additions & 3 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,16 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- name: Use Node.js 14
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.10'
- name: Use Node.js 21
uses: actions/setup-node@v3
with:
node-version: 16
node-version: 21
- name: Install setuptools
run: pip install setuptools
- name: Install Packages
run: npm install
- name: Build
Expand All @@ -47,4 +53,4 @@ jobs:
run: |
gh release upload --clobber "${GITHUB_REF#refs/tags/}" dist/*/*
env:
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ build/Release
# Dependency directories
node_modules/
jspm_packages/
.vs/
.vscode/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
This is an app for XRP Blockly stuff that has been modified by Team 5338 RoboLoco to actually work and support saving.
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
14 changes: 12 additions & 2 deletions 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 Expand Up @@ -34,7 +34,8 @@ createWindow = () => {
});

// and load the index.html of the app.
mainWindow.loadFile('index.html')
// mainWindow.loadFile('../../index.html')
mainWindow.loadFile('../app/index.html')
mainWindow.setMenu(null);

// Open the DevTools.
Expand All @@ -48,6 +49,15 @@ var stoppingPorts = false;
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
fs.access(path.join(__dirname, "../state.json"), err => {
if (err) {
console.log('The file does not exist.');
fs.writeFile(path.join(__dirname, "../state.json"), JSON.stringify({"fullPath":""}), test);
}
});
function test(){
console.log("File Created");
}
app.whenReady().then(() => {
ipcMain.handle('load-appstate', () => {
return {
Expand Down
206 changes: 103 additions & 103 deletions app/js/python-compressed.js

Large diffs are not rendered by default.

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
Loading