Skip to content

Commit

Permalink
Added react for the UI, got it to work well with npm scripts, made th…
Browse files Browse the repository at this point in the history
…e UI connect to the server using wss
  • Loading branch information
rakeshpai committed Sep 14, 2017
1 parent 746af3d commit 855e55b
Show file tree
Hide file tree
Showing 10 changed files with 9,624 additions and 884 deletions.
10,273 changes: 9,395 additions & 878 deletions package-lock.json

Large diffs are not rendered by default.

11 changes: 8 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,19 @@
"description": "An app to control the AlphaBot",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js # --inspect=0.0.0.0:9229"
"start": "concurrently \"nodemon index.js\" \"PORT=80 react-scripts start\""
},
"author": "",
"nodemonConfig": {
"ignore": [ "public", "build", "src" ]
},
"author": "rakeshpai",
"license": "MIT",
"dependencies": {
"alphabot-hal": "^1.0.1",
"concurrently": "^3.5.0",
"nodemon": "^1.12.0",
"react-scripts": "^1.0.13",
"reconnecting-websocket": "^3.2.1",
"through2-map": "^3.0.0",
"ws": "^3.1.0"
}
Expand Down
Binary file added public/favicon.ico
Binary file not shown.
40 changes: 40 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>AlphaBot</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
15 changes: 15 additions & 0 deletions public/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "192x192",
"type": "image/png"
}
],
"start_url": "./index.html",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
3 changes: 0 additions & 3 deletions sensors/odometry.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const config = require("../config");
const { log } = require("../ui-server");
const { bus, restrictAngle } = require("../utils");

const distanceTurnedByWheel = (wheel, ticks) => {
Expand Down Expand Up @@ -27,8 +26,6 @@ module.exports = sensors => {
previous.phi += (rightWheelDistance - leftWheelDistance) / config.wheelbase;
previous.phi = restrictAngle(previous.phi);

log("odometry", previous);

return previous;
};

Expand Down
10 changes: 10 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import React from 'react';
import store from './store';

export default props => {
return (
<pre>
{JSON.stringify(store, null, 2)}
</pre>
)
};
12 changes: 12 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import React from 'react';
import { render } from 'react-dom';
import App from './App';
import store from './store';
// import registerServiceWorker from './registerServiceWorker';

const renderApp = () => render(<App />, document.getElementById('root'));

renderApp();
store.onChange = renderApp;

// registerServiceWorker();
108 changes: 108 additions & 0 deletions src/registerServiceWorker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.

const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);

export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
return;
}

window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

if (!isLocalhost) {
// Is not local host. Just register service worker
registerValidSW(swUrl);
} else {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
}
});
}
}

function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}

function checkValidServiceWorker(swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}

export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
36 changes: 36 additions & 0 deletions src/store.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import WebSocket from 'reconnecting-websocket';

const wss = new WebSocket(`ws://${document.location.hostname}:8080/`, "protocolOne");

const sendCommand = (type, data) => {
wss.send(JSON.stringify({type, data}));
}

const store = {
connected: false,
sensed: null,
motors: null,

resetOdometry: () => sendCommand("resetOdo")
};

const render = () => { if(store.onChange) store.onChange() };

wss.addEventListener("open", () => { store.connected = true; render(); });
wss.addEventListener("close", () => { store.connected = false; render(); });

wss.onmessage = evt => {
const event = JSON.parse(evt.data);

if(event.type === 'log') {
if(event.logType === 'sensed') {
store.sensed = event.data;
} else if(event.logType === 'motors') {
store.motors = event.data;
}
}

render();
}

export default store;

0 comments on commit 855e55b

Please sign in to comment.