master
marko 2022-03-15 21:56:02 -04:00
parent e43181da7d
commit 39e52dbfe4
21 changed files with 171 additions and 781 deletions

View File

@ -5,6 +5,13 @@ var characteristic;
const SETTINGS_FILE = 'cscsensor.json';
const storage = require('Storage');
const W = g.getWidth();
const H = g.getHeight();
const yStart = 48;
const rowHeight = (H-yStart)/6;
const yCol1 = W/2.7586;
const fontSizeLabel = W/12.632;
const fontSizeValue = W/9.2308;
class CSCSensor {
constructor() {
@ -20,7 +27,6 @@ class CSCSensor {
this.speed = 0;
this.maxSpeed = 0;
this.lastSpeed = 0;
this.qUpdateScreen = true;
this.lastRevsStart = -1;
this.qMetric = !require("locale").speed(1).toString().endsWith("mph");
this.speedUnit = this.qMetric ? "km/h" : "mph";
@ -28,6 +34,10 @@ class CSCSensor {
this.distFactor = this.qMetric ? 1.609344 : 1;
this.screenInit = true;
this.batteryLevel = -1;
this.lastCrankTime = 0;
this.lastCrankRevs = 0;
this.showCadence = false;
this.cadence = 0;
}
reset() {
@ -40,6 +50,12 @@ class CSCSensor {
this.screenInit = true;
}
toggleDisplayCadence() {
this.showCadence = !this.showCadence;
this.screenInit = true;
g.setBgColor(0, 0, 0);
}
setBatteryLevel(level) {
if (level!=this.batteryLevel) {
this.batteryLevel = level;
@ -52,17 +68,19 @@ class CSCSensor {
}
drawBatteryIcon() {
g.setColor(1, 1, 1).drawRect(6, 38, 16, 58).fillRect(10, 36, 12, 38).setColor(0).fillRect(7, 39, 15, 57);
g.setColor(1, 1, 1).drawRect(10*W/240, yStart+0.029167*H, 20*W/240, yStart+0.1125*H)
.fillRect(14*W/240, yStart+0.020833*H, 16*W/240, yStart+0.029167*H)
.setColor(0).fillRect(11*W/240, yStart+0.033333*H, 19*W/240, yStart+0.10833*H);
if (this.batteryLevel!=-1) {
if (this.batteryLevel<25) g.setColor(1, 0, 0);
else if (this.batteryLevel<50) g.setColor(1, 0.5, 0);
else g.setColor(0, 1, 0);
g.fillRect(7, 57-18*this.batteryLevel/100, 15, 57);
g.fillRect(11*W/240, (yStart+0.10833*H)-18*this.batteryLevel/100, 19*W/240, yStart+0.10833*H);
}
else g.setFontVector(14).setFontAlign(0, 0, 0).setColor(0xffff).drawString("?", 12, 49);
else g.setFontVector(W/17.143).setFontAlign(0, 0, 0).setColor(0xffff).drawString("?", 16*W/240, yStart+0.075*H);
}
updateScreen() {
updateScreenRevs() {
var dist = this.distFactor*(this.lastRevs-this.lastRevsStart)*this.wheelCirc/63360.0;
var ddist = Math.round(100*dist)/100;
var tdist = Math.round(this.distFactor*this.totaldist*10)/10;
@ -73,19 +91,87 @@ class CSCSensor {
if (dsecs.length<2) dsecs = "0"+dsecs;
var avespeed = (this.movingTime>3 ? Math.round(10*dist/(this.movingTime/3600))/10 : 0);
var maxspeed = Math.round(10*this.distFactor*this.maxSpeed)/10;
layout.vtime.label = dmins+":"+dsecs;
layout.vspeed.label = dspeed + "" + this.speedUnit;
layout.vaspeed.label = avespeed + "" + this.speedUnit;
layout.vmspeed.label = maxspeed + "" + this.speedUnit;
layout.vtrip.label = ddist + "" + this.distUnit;
layout.vtotal.label = tdist + "" + this.distUnit;
layout.render();
if (this.screenInit) {
for (var i=0; i<6; ++i) {
if ((i&1)==0) g.setColor(0, 0, 0);
else g.setColor(0x30cd);
g.fillRect(0, yStart+i*rowHeight, yCol1-1, yStart+(i+1)*rowHeight);
if ((i&1)==1) g.setColor(0);
else g.setColor(0x30cd);
g.fillRect(yCol1, yStart+i*rowHeight, H-1, yStart+(i+1)*rowHeight);
g.setColor(0.5, 0.5, 0.5).drawRect(yCol1, yStart+i*rowHeight, H-1, yStart+(i+1)*rowHeight).drawLine(0, H-1, W-1, H-1);
g.moveTo(0, yStart+0.13333*H).lineTo(30*W/240, yStart+0.13333*H).lineTo(30*W/240, yStart).lineTo(yCol1, yStart).lineTo(yCol1, H-1).lineTo(0, H-1).lineTo(0, yStart+0.13333*H);
}
g.setFontAlign(1, 0, 0).setFontVector(fontSizeLabel).setColor(1, 1, 0);
g.drawString("Time:", yCol1, yStart+rowHeight/2+0*rowHeight);
g.drawString("Speed:", yCol1, yStart+rowHeight/2+1*rowHeight);
g.drawString("Avg spd:", yCol1, yStart+rowHeight/2+2*rowHeight);
g.drawString("Max spd:", yCol1, yStart+rowHeight/2+3*rowHeight);
g.drawString("Trip:", yCol1, yStart+rowHeight/2+4*rowHeight);
g.drawString("Total:", yCol1, yStart+rowHeight/2+5*rowHeight);
this.drawBatteryIcon();
this.screenInit = false;
}
g.setFontAlign(-1, 0, 0).setFontVector(fontSizeValue);
g.setColor(0x30cd).fillRect(yCol1+1, 49+rowHeight*0, 238, 47+1*rowHeight);
g.setColor(0xffff).drawString(dmins+":"+dsecs, yCol1+5, 50+rowHeight/2+0*rowHeight);
g.setColor(0).fillRect(yCol1+1, 49+rowHeight*1, 238, 47+2*rowHeight);
g.setColor(0xffff).drawString(dspeed+" "+this.speedUnit, yCol1+5, 50+rowHeight/2+1*rowHeight);
g.setColor(0x30cd).fillRect(yCol1+1, 49+rowHeight*2, 238, 47+3*rowHeight);
g.setColor(0xffff).drawString(avespeed + " " + this.speedUnit, yCol1+5, 50+rowHeight/2+2*rowHeight);
g.setColor(0).fillRect(yCol1+1, 49+rowHeight*3, 238, 47+4*rowHeight);
g.setColor(0xffff).drawString(maxspeed + " " + this.speedUnit, yCol1+5, 50+rowHeight/2+3*rowHeight);
g.setColor(0x30cd).fillRect(yCol1+1, 49+rowHeight*4, 238, 47+5*rowHeight);
g.setColor(0xffff).drawString(ddist + " " + this.distUnit, yCol1+5, 50+rowHeight/2+4*rowHeight);
g.setColor(0).fillRect(yCol1+1, 49+rowHeight*5, 238, 47+6*rowHeight);
g.setColor(0xffff).drawString(tdist + " " + this.distUnit, yCol1+5, 50+rowHeight/2+5*rowHeight);
}
updateScreenCadence() {
if (this.screenInit) {
for (var i=0; i<2; ++i) {
if ((i&1)==0) g.setColor(0, 0, 0);
else g.setColor(0x30cd);
g.fillRect(0, yStart+i*rowHeight, yCol1-1, yStart+(i+1)*rowHeight);
if ((i&1)==1) g.setColor(0);
else g.setColor(0x30cd);
g.fillRect(yCol1, yStart+i*rowHeight, H-1, yStart+(i+1)*rowHeight);
g.setColor(0.5, 0.5, 0.5).drawRect(yCol1, yStart+i*rowHeight, H-1, yStart+(i+1)*rowHeight).drawLine(0, H-1, W-1, H-1);
g.moveTo(0, yStart+0.13333*H).lineTo(30*W/240, yStart+0.13333*H).lineTo(30*W/240, yStart).lineTo(yCol1, yStart).lineTo(yCol1, H-1).lineTo(0, H-1).lineTo(0, yStart+0.13333*H);
}
g.setFontAlign(1, 0, 0).setFontVector(fontSizeLabel).setColor(1, 1, 0);
g.drawString("Cadence:", yCol1, yStart+rowHeight/2+1*rowHeight);
this.drawBatteryIcon();
this.screenInit = false;
}
g.setFontAlign(-1, 0, 0).setFontVector(fontSizeValue);
g.setColor(0).fillRect(yCol1+1, 49+rowHeight*1, 238, 47+2*rowHeight);
g.setColor(0xffff).drawString(Math.round(this.cadence), yCol1+5, 50+rowHeight/2+1*rowHeight);
}
updateScreen() {
if (!this.showCadence) {
this.updateScreenRevs();
} else {
this.updateScreenCadence();
}
}
updateSensor(event) {
var qChanged = false;
if (event.target.uuid == "0x2a5b") {
if (event.target.value.getUint8(0, true) & 0x2) {
// crank revolution - if enabled
const crankRevs = event.target.value.getUint16(1, true);
const crankTime = event.target.value.getUint16(3, true);
if (crankTime > this.lastCrankTime) {
this.cadence = (crankRevs-this.lastCrankRevs)/(crankTime-this.lastCrankTime)*(60*1024);
qChanged = true;
}
this.lastCrankRevs = crankRevs;
this.lastCrankTime = crankTime;
} else {
// wheel revolution
var wheelRevs = event.target.value.getUint32(1, true);
var dRevs = (this.lastRevs>0 ? wheelRevs-this.lastRevs : 0);
if (dRevs>0) {
@ -110,8 +196,7 @@ class CSCSensor {
this.speed = (dRevs*this.wheelCirc/63360.0)*3600/dT;
this.speedFailed = 0;
this.movingTime += dT;
}
else {
} else if (!this.showCadence) {
this.speedFailed++;
qChanged = false;
if (this.speedFailed>3) {
@ -122,7 +207,8 @@ class CSCSensor {
this.lastSpeed = this.speed;
if (this.speed>this.maxSpeed && (this.movingTime>3 || this.speed<20) && this.speed<50) this.maxSpeed = this.speed;
}
if (qChanged && this.qUpdateScreen) this.updateScreen();
}
if (qChanged) this.updateScreen();
}
}
@ -137,100 +223,47 @@ function getSensorBatteryLevel(gatt) {
});
}
function parseDevice(d) {
function connection_setup() {
mySensor.screenInit = true;
E.showMessage("Scanning for CSC sensor...");
NRF.requestDevice({ filters: [{services:["1816"]}]}).then(function(d) {
device = d;
g.clearRect(0, 24, 239, 239).setFontAlign(0, 0, 0).setColor(0, 1, 0).drawString("Found device", 120, 120).flip();
device.gatt.connect().then(function(ga) {
E.showMessage("Found device");
return device.gatt.connect();
}).then(function(ga) {
gatt = ga;
g.clearRect(0, 24, 239, 239).setFontAlign(0, 0, 0).setColor(0, 1, 0).drawString("Connected", 120, 120).flip();
E.showMessage("Connected");
return gatt.getPrimaryService("1816");
}).then(function(s) {
}).then(function(s) {
service = s;
return service.getCharacteristic("2a5b");
}).then(function(c) {
}).then(function(c) {
characteristic = c;
characteristic.on('characteristicvaluechanged', (event)=>mySensor.updateSensor(event));
return characteristic.startNotifications();
}).then(function() {
}).then(function() {
console.log("Done!");
g.clearRect(0, 24, 239, 239).setColor(1, 1, 1).flip();
// setWatch(function() { mySensor.reset(); g.clearRect(0, 24, 239, 239); mySensor.updateScreen(); }, BTN1, {repeat:true, debounce:20});
E.on('kill',()=>{ if (gatt!=undefined) gatt.disconnect(); mySensor.settings.totaldist = mySensor.totaldist; storage.writeJSON(SETTINGS_FILE, mySensor.settings); });
// setWatch(function() { if (Date.now()-mySensor.lastBangleTime>10000) connection_setup(); }, BTN3, {repeat:true, debounce:20}); getSensorBatteryLevel(gatt);
g.reset().clearRect(Bangle.appRect).flip();
getSensorBatteryLevel(gatt);
mySensor.updateScreen();
}).catch(function(e) {
g.clear().setColor(1, 0, 0).setFontAlign(0, 0, 0).drawString("ERROR"+e, 120, 120).flip();
}).catch(function(e) {
E.showMessage(e.toString(), "ERROR");
console.log(e);
})}
function scan() {
menu = {
"": { "title": "Select sensor" },
"re-scan": () => scan()
};
waitMessage();
NRF.findDevices(devices => {
devices.forEach(device =>{
let deviceName = device.id.substring(0,17);
if (device.name) {
deviceName = device.name;
}
if (device.services!=undefined && device.services.find(e => e=="1816")) deviceName = "* "+deviceName;
menu[deviceName] = () => { E.showMenu(); parseDevice(device); }
});
E.showMenu(menu);
}, { active: true });
}
function waitMessage() {
E.showMenu();
E.showMessage("scanning");
}
function connection_setup() {
if (mySensor.settings.autoconnect) {
NRF.setScan();
mySensor.screenInit = true;
NRF.setScan(parseDevice, { filters: [{services:["1816"]}], timeout: 2000});
g.clearRect(0, 24, 239, 239).setFontVector(18).setFontAlign(0, 0, 0).setColor(0, 1, 0);
g.drawString("Scanning for CSC sensor...", 120, 120);
}
else scan();
}
var Layout = require("Layout");
var layout = new Layout( {
lazy: true,
type:"h", c: [
{type: "v", c: [
{type:"txt", font:"12%", label:"Time", id:"time", halign:1, bgCol:0x30cd, col:"#ffff00"},
{type:"txt", font:"12%", label:"Speed", id:"speed", halign:1, col:"#ffff00"},
{type:"txt", font:"12%", label:"AveSpd", id:"aspeed", halign:1, bgCol:0x30cd, col:"#ffff00"},
{type:"txt", font:"12%", label:"MaxSpd", id:"mspeed", halign:1, col:"#ffff00"},
{type:"txt", font:"12%", label:"Trip", id:"trip", halign:1, bgCol:0x30cd, col:"#ffff00"},
{type:"txt", font:"12%", label:"Total", id:"total", halign:1, col:"#ffff00"}]
},
{type: "v", c: [
{type:"txt", font:"12%", label:": ", id:"vtimes", halign:-1},
{type:"txt", font:"12%", label:": ", id:"vspeeds", halign:-1},
{type:"txt", font:"12%", label:": ", id:"vaspeeds", halign:-1},
{type:"txt", font:"12%", label:": ", id:"vmspeeds", halign:-1},
{type:"txt", font:"12%", label:": ", id:"vtrips", halign:-1},
{type:"txt", font:"12%", label:": ", id:"vtotals", halign:-1}]
},
{type: "v", fillx:1.2, c: [
{type:"txt", font:"12%", label:"0:00", id:"vtime", halign:-1},
{type:"txt", font:"12%", label:"0", id:"vspeed", halign:-1, bgCol:0x30cd},
{type:"txt", font:"12%", label:"0", id:"vaspeed", halign:-1},
{type:"txt", font:"12%", label:"0", id:"vmspeed", halign:-1, bgCol:0x30cd},
{type:"txt", font:"12%", label:"0", id:"vtrip", halign:-1},
{type:"txt", font:"12%", label:"0", id:"vtotal", halign:-1, bgCol:0x30cd}]
}
]
});
connection_setup();
NRF.on('disconnect', connection_setup);
E.on('kill',()=>{
if (gatt!=undefined) gatt.disconnect();
mySensor.settings.totaldist = mySensor.totaldist;
storage.writeJSON(SETTINGS_FILE, mySensor.settings);
});
NRF.on('disconnect', connection_setup); // restart if disconnected
Bangle.setUI("updown", d=>{
if (d<0) { mySensor.reset(); g.clearRect(0, yStart, W, H); mySensor.updateScreen(); }
else if (d>0) { if (Date.now()-mySensor.lastBangleTime>10000) connection_setup(); }
else { mySensor.toggleDisplayCadence(); g.clearRect(0, yStart, W, H); mySensor.updateScreen(); }
});
Bangle.loadWidgets();
Bangle.drawWidgets();

View File

@ -6,7 +6,6 @@
const SETTINGS_FILE = 'cscsensor.json'
// initialize with default settings...
let s = {
'autoconnect': true,
'wheelcirc': 2230,
}
// ...and overwrite them with any saved values
@ -33,11 +32,6 @@
step: 5,
onchange: save('wheelcirc'),
},
'Auto connect': {
value: s.autoconnect,
format: boolFormat,
onchange: save('autoconnect'),
},
'Reset total distance': function() {
E.showPrompt("Zero total distance?", {buttons: {"No":false, "Yes":true}}).then(function(v) {
if (v) {

View File

@ -1 +0,0 @@
0.01: New App!

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

View File

@ -1 +0,0 @@
require("heatshrink").decompress(atob("mEwxH+AAOxAAIFCABmrwwRP/2yBJAvCAAYZJ2Wr1eHAAYSLAAQwP1YYHF4xEGCQovT2IYGFwIwDCIWAq1cwIABrtWwAaETZIuFCgIVDA4QvEBoNcq2s6/X2ezCQIDBwIKB2QBBF5ulAYQvI2IvBEQQAD1gACGQVXwKQPLwQwERwmrwFXLAJTDGAoACxFWF55VCGYSqCXYKOBrqHCAAXXAIQyExABBrjAOFQKSDMYQIBw9W2a7CFYiUGw4wBwTwPSQhmCGAJ7BAB4wDqwvIcwTnFYggFBrrjDRonX2ZnCSImHAQMrF5IAFLQQ3DrgtCRoYvDAQLJDF4ZgJOpAvBFgLtBXoIvHLgQCBF4QuCMAeIF5otCLwIuCw2B1mzEwQBB2etAAouEFoJgBSAwtE2IBCRYQvCwGIE4wACGQI0DGAwvGLopaBMIQvDwztBFQopBMQRkEF47AFRoy8Ga4KOBGAgpCSBoABF5mxRous1eBR4jmCSpAvHR4qJBAAYtCAYIvCAgWBEYZDDF4+yFwuyF4gmBGA4zD1gvCrovHE4JeFF4gNCLwgwBLQYvFAoOsw+rwQvDDwQwHBQ2y69dF4wnCGIelAga+B1bwBSAYkGLQQHF2fX2a+FSAoEB0oDCDwQvDlbxCKo4AGFwPXq4uFeAwuCF4RNBR4OswUslYvPFoPXxAuHF4ruEbAgvBq8rlgvN6wuB1iNGSAwrBMAitCcQOIq0rGBgtC2YTB1gvIQQLpDd4esAoIfCFwUrAYOBRZWzrtdVAIvISA+lFwIEBwGk1YuCF4IABEQIvG2eBq2I1eHF5RfCAAeIMIOxrgqBGIMrmNWrlcwAhBrmBAAdWwAWBxAMB1ZfLFoWsxBkCFwQABv9/qweBwAwDagQABAwIACwIgBLxLkCAAKSDFwiMCwWr2SACLYQ2BHIQACHIKRBF5CiBVIguIldcxGsJwIPCLAYsCwwABF4OswIvJc4QuLq2BfIIwDCYaRBRwiaCqwvILoIWB2IDBFxGAWoOIZgIUDa4YtEMQQuJCoYdBqwuIcoWrxJgBCwaVCFgQBCAALuJPQYuLAARDBSIJdBaoYuDAAdcF5QYB1guJLgOlFwKKCGAaUCXwxeJL4ZdJwLhCLoQAD1jDBF4ZeFF5mHFxGHRghdCGAg3C1YuGF5SbCFw1cFwexwFWCYJnBGAgvCFgmGXpIAD0mrFworB1YsDAAr4CGAQDBJoIsNAAfP1QuCg8AlcGC51cHxIAN1Wjg4wBDSoAUldVF1gA/AH4A5A"))

View File

@ -1,90 +0,0 @@
var m = require("openseachart");
var HASWIDGETS = true;
var y1,y2;
var fix = {};
var last_course = -1;
var cur_course = -1;
var course_marker_len = g.getWidth()/4;
var settings = require("Storage").readJSON('openseacsettings.json', 1) || {};
function redraw() {
g.setClipRect(0,y1,g.getWidth()-1,y2);
m.draw();
drawMarker();
g.setClipRect(0,0,g.getWidth()-1,g.getHeight()-1);
if (settings.drawcourse && cur_course!=-1) drawCourseMarker(cur_course);
}
function drawMarker() {
if (!fix.fix) return;
var p = m.latLonToXY(fix.lat, fix.lon);
g.setColor(1,0,0);
g.fillRect(p.x-2, p.y-2, p.x+2, p.y+2);
}
function drawCourseMarker(c) {
var p = m.latLonToXY(fix.lat, fix.lon);
var dx = -Math.sin(Math.PI*(c+180)/180.0)*course_marker_len*m.map.dlonpx/m.map.dlatpx;
var dy = Math.cos(Math.PI*(c+180)/180.0)*course_marker_len;
g.setColor(1,0,0);
g.drawLine(p.x, p.y, p.x+dx, p.y+dy);
}
var fix;
Bangle.on('GPS',function(f) {
fix=f;
g.reset().clearRect(0,y1,g.getWidth()-1,y1+8).setFont("6x8").setFontAlign(0,0);
var txt = fix.satellites+" satellites";
if (!fix.fix)
txt += " - NO FIX";
else {
if (fix.satellites>3 && fix.speed>2) { // only uses fixes w/ more than 3 sats and speed > 2kph
cur_course = fix.course;
if (Math.abs(cur_course-last_course)>10 && Math.abs(cur_course-last_course)<350) {
last_course = cur_course;
redraw();
}
}
}
g.drawString(txt,g.getWidth()/2,y1 + 4);
drawMarker();
if (settings.autocenter) recenter();
});
Bangle.setGPSPower(1, "app");
if (HASWIDGETS) {
Bangle.loadWidgets();
Bangle.drawWidgets();
y1 = 24;
var hasBottomRow = Object.keys(WIDGETS).some(w=>WIDGETS[w].area[0]=="b");
y2 = g.getHeight() - (hasBottomRow ? 24 : 1);
} else {
y1=0;
y2=g.getHeight()-1;
}
redraw();
function recenter() {
if (!fix.fix) return;
m.lat = fix.lat;
m.lon = fix.lon;
redraw();
}
setWatch(recenter, global.BTN2?BTN2:BTN1, {repeat:true});
var hasScrolled = false;
Bangle.on('drag',e=>{
if (e.b) {
g.setClipRect(0,y1,g.getWidth()-1,y2);
g.scroll(e.dx,e.dy);
m.scroll(e.dx,e.dy);
g.setClipRect(0,0,g.getWidth()-1,g.getHeight()-1);
hasScrolled = true;
} else if (hasScrolled) {
hasScrolled = false;
redraw();
}
});

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

View File

@ -1,234 +0,0 @@
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
<link rel="stylesheet" href="../../css/spectre.min.css">
<link rel="stylesheet" href="https://unpkg.com/leaflet-geosearch@3.6.0/dist/geosearch.css"/>
</head>
<style>
body {
padding: 0;
margin: 0;
}
html, body, #map {
height: 100%;
width: 100%;
}
#map { z-index: 1; }
#controls {
padding: 10px;
margin: 10px;
border: 1px solid black;
position:absolute;
right:0px;top:0px;
background-color: rgb(255, 255, 255);
z-index: 100;
}
#maptiles {
width: 448px;
height: 448px;
}
</style>
</head>
<body>
<div id="map">
</div>
<div id="controls">
<div style="display:inline-block;text-align:center;vertical-align: top;"> <input type="checkbox" id="3bit"></input><br/><span>3 bit</span></div>
<button id="getmap" class="btn btn-primary">Get Map</button><br/>
<canvas id="maptiles" style="display:none"></canvas>
<div id="uploadbuttons" style="display:none"><button id="upload" class="btn btn-primary">Upload</button>
<button id="cancel" class="btn">Cancel</button></div>
</div>
<script src="../../core/lib/customize.js"></script>
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="../../core/lib/heatshrink.js"></script>
<script src="../../core/lib/imageconverter.js"></script>
<script src="https://unpkg.com/leaflet-geosearch@3.6.0/dist/bundle.min.js"></script>
<script>
/*
TODO:
* Allow a larger tilesize. Currently we use 'evaluate:true' which means we can only send 64x64x8 bit, but with some tweaking we could send 128x128 which would reduce the number of files and make things a bit snappier
* Could maybe use palettised output?
* Could potentially use a custom 16 color palette?
* Allow user to choose size of map area to be uploaded (small/med/large)
* What is faster? Storing as a compressed image and decompressing, or storing decompressed?
*/
var TILESIZE = 128;
var OSMTILESIZE = 256;
var OSMSUBTILES = OSMTILESIZE / TILESIZE;
/* Can see possible tiles on http://leaflet-extras.github.io/leaflet-providers/preview/
However some don't allow cross-origin use */
var TILELAYER = 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png'; // simple, high contrast
var PREVIEWTILELAYER = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
//var TILELAYER = 'http://a.tile.stamen.com/toner/{z}/{x}/{y}.png'; // black and white
// Create map and try and set the location to where the browser thinks we are
var map = L.map('map').locate({setView: true, maxZoom: 16, enableHighAccuracy:true});
// Tiles used for Bangle.js itself
var bangleTileLayer = L.tileLayer(TILELAYER, {
maxZoom: 18,
attribution: 'Map data &copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors</a>'
});
// Tiles used for the may the user sees (faster)
var previewTileLayer = L.tileLayer(PREVIEWTILELAYER, {
maxZoom: 18,
attribution: 'Map data &copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors</a>'
});
// Could optionally overlay trails: https://wiki.openstreetmap.org/wiki/Tiles
var mapFiles = [];
previewTileLayer.addTo(map);
function tilesLoaded(ctx, width, height) {
var options = { compression:false, mode:"web", output:"raw"};
if (document.getElementById("3bit").checked) {
options = {
compression:false, output:"raw",
mode:"3bit",
};
/* If in 3 bit mode, go through all the data beforehand and
turn the saturation up to maximum, so when thresholded it
works a lot better */
var imageData = ctx.getImageData(0,0,width,height);
var rgba = imageData.data;
var l = width*height*4;
for (var i=0;i<l;i+=4) {
var min = Math.min(rgba[i+0],rgba[i+1],rgba[i+2]);
var max = Math.max(rgba[i+0],rgba[i+1],rgba[i+2]);
var d = max-min;
if (max<120) { // black
rgba[i+0]=0;
rgba[i+1]=0;
rgba[i+2]=0;
} else if (min>240 || d<8) { // white or grey
rgba[i+0]=255;
rgba[i+1]=255;
rgba[i+2]=255;
} else { // another colour - use max saturation
rgba[i+0] = (rgba[i+0]-min) * 255 / d;
rgba[i+1] = (rgba[i+1]-min) * 255 / d;
rgba[i+2] = (rgba[i+2]-min) * 255 / d;
}
}
ctx.putImageData(imageData,0,0);
}
console.log("Compression options", options);
var w = Math.round(width / TILESIZE);
var h = Math.round(height / TILESIZE);
console.log("Width", width);
console.log("Height", height);
var tiles = [];
for (var y=0;y<h;y++) {
for (var x=0;x<w;x++) {
var imageData = ctx.getImageData(x*TILESIZE, y*TILESIZE, TILESIZE, TILESIZE);
var rgba = imageData.data;
options.rgbaOut = rgba;
options.width = TILESIZE;
options.height = TILESIZE;
var imgstr = imageconverter.RGBAtoString(rgba, options);
ctx.putImageData(imageData,x*TILESIZE, y*TILESIZE);
tiles.push({
name:"openseamap-"+x+"-"+y+".img",
content:imgstr,
});
}
}
return tiles;
}
document.getElementById("getmap").addEventListener("click", function() {
var zoom = map.getZoom();
var centerlatlon = map.getBounds().getCenter();
var center = map.project(centerlatlon, zoom).divideBy(OSMTILESIZE);
// Reason for 16px adjustment below not 100% known, but it seems to
// align everything perfectly: https://github.com/espruino/BangleApps/issues/984
var ox = Math.round((center.x - Math.floor(center.x)) * OSMTILESIZE) + 16;
var oy = Math.round((center.y - Math.floor(center.y)) * OSMTILESIZE) + 16;
center = center.floor(); // make sure we're in the middle of a tile
// JS version of Bangle.js's projection
function bproject(lat, lon) {
const degToRad = Math.PI / 180; // degree to radian conversion
const latMax = 85.0511287798; // clip latitude to sane values
const R = 6378137; // earth radius in m
if (lat > latMax) lat=latMax;
if (lat < -latMax) lat=-latMax;
var s = Math.sin(lat * degToRad);
return new L.Point(
(R * lon * degToRad),
(R * Math.log((1 + s) / (1 - s)) / 2)
);
}
// Work out scale factors (how much from Bangle.project does one pixel equate to?)
var pc = map.unproject(center.multiplyBy(OSMTILESIZE), zoom);
var pd = map.unproject(center.multiplyBy(OSMTILESIZE).add({x:1,y:0}), zoom);
var bc = bproject(pc.lat, pc.lng)
var bd = bproject(pd.lat, pd.lng)
var scale = bc.distanceTo(bd);
// test
/*var p = bproject(centerlatlon.lat, centerlatlon.lng);
var q = bproject(mylat, mylon);
var testPt = {
x : (q.x-p.x)/scale + (MAPSIZE/2),
y : (MAPSIZE/2) - (q.y-p.y)/scale
};*/
var tileGetters = [];
// Render everything to a canvas...
var canvas = document.getElementById("maptiles");
canvas.style.display="";
var ctx = canvas.getContext('2d');
canvas.width = 896;//OSMTILESIZE*2;
canvas.height = 896;//OSMTILESIZE*2;
for (var i = 0; i < 1; i++) {
for (var j = 0; j < 1; j++) {
(function(i,j){
var img = new Image();
img.crossOrigin = "Anonymous";
tileGetters.push(new Promise(function(resolve,reject) {
img.onload = function(){
ctx.drawImage(img, 0, 0);//i*OSMTILESIZE - ox, j*OSMTILESIZE - oy);
resolve();
};
}));
img.src = 'https://raw.githubusercontent.com/berkenbu/BangleApps/master/apps/openseachart/boca_ciega_cr.png';
})(i,j);
}
}
Promise.all(tileGetters).then(() => {
document.getElementById("uploadbuttons").style.display="";
mapFiles = tilesLoaded(ctx, canvas.width, canvas.height);
mapFiles.unshift({name:"openseachart.json",content:JSON.stringify({
imgx : canvas.width,
imgy : canvas.height,
tilesize : TILESIZE,
scale : scale, // how much of Bangle.project(latlon) does one pixel equate to?
lat : centerlatlon.lat,
lon : centerlatlon.lng
})});
console.log(mapFiles);
});
});
document.getElementById("upload").addEventListener("click", function() {
sendCustomizedApp({
storage:mapFiles
});
});
document.getElementById("cancel").addEventListener("click", function() {
document.getElementById("maptiles").style.display="none";
document.getElementById("uploadbuttons").style.display="none";
});
</script>
</body>
</html>

View File

@ -1,19 +0,0 @@
{
"id": "openseachart",
"name": "OpenSeaChart",
"shortName": "OpenSeaChart",
"version": "0.01",
"description": "Sea chart",
"icon": "app.png",
"tags": "outdoors,gps,osm",
"supports": ["BANGLEJS","BANGLEJS2"],
"screenshots": [{"url":"screenshot.png"}],
"custom": "custom.html",
"customConnect": true,
"storage": [
{"name":"openseachart","url":"openseachart.js"},
{"name":"openseachart.app.js","url":"app.js"},
{"name":"openseachart.settings.js", "url":"settings.js"},
{"name":"openseachart.img","url":"app-icon.js","evaluate":true}
]
}

View File

@ -1,67 +0,0 @@
/* OpenStreetMap plotting module.
Usage:
var m = require("openseachart");
// m.lat/lon are now the center of the loaded map
m.draw(); // draw centered on the middle of the loaded map
// plot gps position on map
Bangle.on('GPS',function(f) {
if (!f.fix) return;
var p = m.latLonToXY(fix.lat, fix.lon);
g.fillRect(p.x-2, p.y-2, p.x+2, p.y+2);
});
// recenter and redraw map!
function center() {
m.lat = fix.lat;
m.lon = fix.lon;
m.draw();
}
*/
var map = require("Storage").readJSON("openseachart.json");
map.center = {lat:map.lat, lon:map.lon}; // save original center
exports.map = map;
exports.lat = map.lat; // actual position of middle of screen
exports.lon = map.lon; // actual position of middle of screen
var m = exports;
exports.draw = function() {
var s = require("Storage");
var cx = g.getWidth()/2;
var cy = g.getHeight()/2;
var ix = (m.lon-map.center.lon)/map.dlonpx + (map.imgx/2) - cx;
var iy = (map.center.lat-m.lat)/map.dlatpx + (map.imgy/2) - cy;
//console.log(ix,iy);
var tx = 0|(ix/map.tilesize);
var ty = 0|(iy/map.tilesize);
var ox = (tx*map.tilesize)-ix;
var oy = (ty*map.tilesize)-iy;
for (var x=ox,ttx=tx;x<g.getWidth();x+=map.tilesize,ttx++) {
for (var y=oy,tty=ty;y<g.getHeight();y+=map.tilesize,tty++) {
var img = s.read("openseamap-"+ttx+"-"+tty+".img");
if (img) g.drawImage(img,x,y);
else g.clearRect(x,y,x+map.tilesize-1,y+map.tilesize-1).drawLine(x,y,x+map.tilesize-1,y+map.tilesize-1).drawLine(x,y+map.tilesize-1,x+map.tilesize-1,y);
}
}
};
/// Convert lat/lon to pixels on the screen
exports.latLonToXY = function(lat, lon) {
var cx = g.getWidth()/2;
var cy = g.getHeight()/2;
return {
x : cx + (lon-m.lon)/map.dlonpx,
y : cy - (lat-m.lat)/map.dlatpx
};
};
/// Given an amount to scroll in pixels on the screen, adjust the lat/lon of the map to match
exports.scroll = function(x,y) {
this.lon -= x * this.map.dlonpx;
this.lat += y * this.map.dlatpx;
// console.log(this.lon, this.lat);
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.6 KiB

View File

@ -1,41 +0,0 @@
// This file should contain exactly one function, which shows the app's settings
/**
* @param {function} back Use back() to return to settings menu
*/
(function(back) {
const SETTINGS_FILE = 'openseacsettings.json'
// initialize with default settings...
let s = {
'drawcourse': true,
'autocenter': false,
}
// ...and overwrite them with any saved values
// This way saved values are preserved if a new version adds more settings
const storage = require('Storage')
const saved = storage.readJSON(SETTINGS_FILE, 1) || {}
for (const key in saved) {
s[key] = saved[key];
}
// creates a function to safe a specific setting, e.g. save('color')(1)
function save(key) {
return function (value) {
s[key] = value;
storage.write(SETTINGS_FILE, s);
}
}
const menu = {
'': { 'title': 'OpenSeaChart' },
'< Back': back,
'Draw course': {
value: s.drawcourse,
format: boolFormat,
onchange: save('drawcourse'),
},
'Auto center': {
value: s.autocenter,
format: boolFormat,
onchange: save('autocenter'),
}
}
E.showMenu(menu);
})

View File

@ -1 +0,0 @@
0.01: New App!

View File

@ -1,25 +0,0 @@
# App Name
Describe the app...
Add screen shots (if possible) to the app folder and link then into this file with ![](<name>.png)
## Usage
Describe how to use it
## Features
Name the function
## Controls
Name the buttons and what they are used for
## Requests
Name who should be contacted for support/update requests
## Creator
Your name

View File

@ -1 +0,0 @@
require("heatshrink").decompress(atob("mEwxH+AH4A/AH4A/AH4A/AH4A/AH4AzhMJF94wtF+QwsF/4APnAACF54wZFoYxNF7guHGBQv0GCwuJGBIvFACov/AD4vvd6Yv/GCoumGIwtpAH4A/AH4A/AH4A/AH4A/AH4A/AH4A/AHoA=="))

View File

@ -1,108 +0,0 @@
OW_CHAR_UUID = '0000cc91-0000-1000-8000-00805f9b34fb';
require("Font7x11Numeric7Seg").add(Graphics);
gatt = {};
cx = g.getWidth()/2;
cy = 24+(g.getHeight()-24)/2;
w = (g.getWidth()-24)/2;
gps_course = {};
var settings = require("Storage").readJSON('openwindsettings.json', 1) || {};
i = 0;
hullpoly = [];
for (y=-1; y<=1; y+=0.1) {
hullpoly[i++] = cx - (y<0 ? 1+y*0.15 : (Math.sqrt(1-0.7*y*y)-Math.sqrt(0.3))/(1-Math.sqrt(0.3)))*w*0.3;
hullpoly[i++] = cy - y*w*0.7;
}
for (y=1; y>=-1; y-=0.1) {
hullpoly[i++] = cx + (y<0 ? 1+y*0.15 : (Math.sqrt(1-0.7*y*y)-Math.sqrt(0.3))/(1-Math.sqrt(0.3)))*w*0.3;
hullpoly[i++] = cy - y*w*0.7;
}
function wind_updated(ev) {
if (ev.target.uuid == "0xcc91") {
awa = 180-ev.target.value.getInt16(1, true)*0.1;
aws = ev.target.value.getInt16(3, true)*0.01;
// console.log(awa, aws);
if (gps_course.spd > 0) {
wv = { // wind vector
lon: Math.sin(Math.PI*awa/180)*aws,
lat: Math.cos(Math.PI*awa/180)*aws
};
twv = { lon: wv.lon+gps_course.lon, lat: wv.lat+gps_course.lat };
tws = Math.sqrt(Math.pow(twv.lon,2)+Math.pow(twv.lat, 2));
twa = Math.atan2(twv.lat, twv.lon)*180/Math.PI;
if (twa<0) twa += 360;
}
else {
tws = -1;
twa = 0;
}
draw_compass(awa,aws,twa,tws);
}
}
function draw_compass(awa, aws, twa, tws) {
g.clearRect(0, 24, g.getWidth()-1, g.getHeight()-1);
fh = w*0.15;
g.setColor(0, 0, 1).fillPoly(hullpoly);
g.setFontVector(fh).setColor(1, 1, 1);
g.setFontAlign(0, 0, 0).drawString("0", cx, 24+fh/2);
g.setFontAlign(0, 0, 1).drawString("90", g.getWidth()-12-fh, cy);
g.setFontAlign(0, 0, 2).drawString("180", cx, g.getHeight()-fh/2);
g.setFontAlign(0, 0, 3).drawString("270", 12+fh/2, cy);
for (i=0; i<4; ++i) {
a = i*Math.PI/2+Math.PI/4;
g.drawLineAA(cx+Math.cos(a)*w*0.85, cy+Math.sin(a)*w*0.85, cx+Math.cos(a)*w*0.99, cy+Math.sin(a)*w*0.99);
}
g.setColor(0, 1, 0).fillCircle(cx+Math.sin(Math.PI*awa/180)*w*0.9, cy+Math.cos(Math.PI*awa/180)*w*0.9, w*0.1);
if (tws>0) g.setColor(1, 0, 0).fillCircle(cx+Math.sin(Math.PI*twa/180)*w*0.9, cy+Math.cos(Math.PI*twa/180)*w*0.9, w*0.1);
g.setColor(0, 1, 0).setFont("7x11Numeric7Seg",w*0.06);
g.setFontAlign(0, 0, 0).drawString(aws.toFixed(1), cx, cy-0.32*w);
if (tws>0) g.setColor(1, 0, 0).drawString(tws.toFixed(1), cx, cy+0.32*w);
}
function parseDevice(d) {
device = d;
console.log("Found device");
device.gatt.connect().then(function(ga) {
console.log("Connected");
gatt = ga;
return ga.getPrimaryService("cc90");
}).then(function(s) {
return s.getCharacteristic("cc91");
}).then(function(c) {
c.on('characteristicvaluechanged', (event)=>wind_updated(event));
return c.startNotifications();
}).then(function() {
console.log("Done!");
}).catch(function(e) {
console.log("ERROR"+e);
});}
function connection_setup() {
NRF.setScan();
NRF.setScan(parseDevice, { filters: [{services:["cc90"]}], timeout: 2000});
console.log("Scanning for OW sensor");
}
if (settings.truewind) {
Bangle.on('GPS',function(fix) {
if (fix.fix && fix.satellites>3 && fix.speed>2) { // only uses fixes w/ more than 3 sats and speed > 2kph
gps_course =
{ lon: Math.sin(Math.PI*fix.course/180)*fix.speed/1.852,
lat: Math.cos(Math.PI*fix.course/180)*fix.speed/1.852,
spd: fix.speed,
crs: fix.course
};
}
else gps_course.spd = -1;
});
Bangle.setGPSPower(1, "app");
}
Bangle.loadWidgets();
Bangle.drawWidgets();
draw_compass(0, 0, 0, 0);
connection_setup();

Binary file not shown.

Before

Width:  |  Height:  |  Size: 497 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 497 B

View File

@ -1,14 +0,0 @@
{ "id": "openwind",
"name": "OpenWind",
"shortName":"OpenWind",
"version":"0.01",
"description": "OpenWind",
"icon": "app.png",
"tags": "",
"supports" : ["BANGLEJS2"],
"storage": [
{"name":"openwind.app.js","url":"app.js"},
{"name":"openwind.img","url":"app-icon.js","evaluate":true},
{"name":"openwind.settings.js", "url":"settings.js"}
]
}

View File

@ -1,35 +0,0 @@
// This file should contain exactly one function, which shows the app's settings
/**
* @param {function} back Use back() to return to settings menu
*/
(function(back) {
const SETTINGS_FILE = 'openwindsettings.json'
// initialize with default settings...
let s = {
'truewind': false,
}
// ...and overwrite them with any saved values
// This way saved values are preserved if a new version adds more settings
const storage = require('Storage')
const saved = storage.readJSON(SETTINGS_FILE, 1) || {}
for (const key in saved) {
s[key] = saved[key];
}
// creates a function to safe a specific setting, e.g. save('color')(1)
function save(key) {
return function (value) {
s[key] = value;
storage.write(SETTINGS_FILE, s);
}
}
const menu = {
'': { 'title': 'OpenWind' },
'< Back': back,
'True wind': {
value: s.truewind,
format: boolFormat,
onchange: save('truewind'),
},
}
E.showMenu(menu);
})