I am building a Flutter app that uses bluetooth to detect bluetooth beacons. I want to monitor the distance (RSSI) of the beacons continuously but I am not too sure how to approach this.
I am currently using flutter_blue. I am open to any new packages.
At the moment I am just scanning for devices.
_flutterBlue.scan(scanMode: ScanMode.balanced).listen((scanResult) {
// scanResult.device.
print("${scanResult.device.id} :: ${scanResult.device.name}");
// check if uuid can be assigned to a gate
if (!_gateOpening && !_preparingToOpenGate) {
_userGates.forEach((manualGate) {
manualGate.gates.forEach((gate) {
gate.beacons.forEach((beacon) {
if (beacon.uuid == scanResult.device.id.id) {
print("found a uiid");
if (gate.detectedBeacons.containsKey(scanResult.device.id.id)) {
gate.detectedBeacons[scanResult.device.id.id]
.insert(0, scanResult.rssi);
} else {
gate.detectedBeacons[scanResult.device.id.id] = [
scanResult.rssi
];
}
if (gate.detectedBeacons[scanResult.device.id.id].length >=
_config.minBLEDetections) {
gate.detectedBeacons[scanResult.device.id.id].removeLast();
}
}
});
});
});
//// only take readings further if gps is struggling
if (_gpsAccuracy > _config.maxFineAccuracyLevel) {
approachingBeacons();
}
}
});
Related
I have a bluetooth printer, this model: SEWOO LK-P400
I'm trying to develop inside my Ionic application this plugin: Ionic Native - BLE
How is the right way to develop that? seeams to have a SDK, how to start? I never develop with a custom SDK, I tryed to use the plugin, the connect and disconnect function it's ok, but the write function don't return any erros, the display of the printer turns ON but don't print anything.
the button print function:
async printTest() {
try {
let value = this.stringToBytes('Hello World');
await this.bluetoothProvider.print(this.deviceId.toUpperCase(), this.serviceUUID, this.characteristicUUID, value)
.then(response => {
console.log(retorno);
})
} catch (error) {
console.log(error);
}
}
stringToBytes(string) {
var array = new Uint8Array(string.length);
for (var i = 0, l = string.length; i < l; i++) {
array[i] = string.charCodeAt(i);
}
return array.buffer;
}
the provider function:
print(
deviceId: string,
serviceUUID: string,
characteristicUUID: string,
value: ArrayBuffer): any
{
return this.ble.write(deviceId, serviceUUID, characteristicUUID, value);
}
I am using Flutter WebRTC for creating P2P video calling.
I have encountered a problem which is related to networking: I have completeled the application but it only works with Mobile Data.
When changing the network to WiFi, it is not working and connection state hangs on Checking
I used Google Community STUN/TURN Servers and Node JS socket.io for signalling purposes. It also works when the mobile is not on same network but only with Mobile Data.
_createPeer() async {
try {
if (_peerConnection != null) return;
navigator.getUserMedia(mediaConstraints).then((stream) {
_localStream = stream;
_localRenderer.srcObject = stream;
});
_peerConnection = await createPeerConnection(configuration, constraints);
_peerConnection.onSignalingState = _onSignalingState;
_peerConnection.onIceGatheringState = _onIceGatheringState;
_peerConnection.onIceConnectionState = _onIceConnectionState;
_peerConnection.onAddStream = _onAddStream;
_peerConnection.onRemoveStream = _onRemoveStream;
_peerConnection.onIceCandidate = _onCandidate;
_peerConnection.onRenegotiationNeeded = _onRenegotiationNeeded;
_peerConnection.addStream(_localStream);
RTCSessionDescription offer =
await _peerConnection.createOffer(_offer_constraints);
_peerConnection.setLocalDescription(offer);
socket.emit('add-student', [
{'room': room, 'offer': offer.sdp}
]);
} catch (e) {
_snackBar(e.toString());
}
}
_onSignalingState(RTCSignalingState state) {
// _snackBar(state.toString());
}
_onIceGatheringState(RTCIceGatheringState state) {
// _snackBar(state.toString());
}
_onIceConnectionState(RTCIceConnectionState state) {
_snackBar(state.toString());
}
_onAddStream(MediaStream stream) {
if (stream == null) {
_snackBar('null');
return;
}
_progressVisible = false;
_buttonsVisible = true;
_remoteRenderer.srcObject = stream;
setState(() {});
}
_onRemoveStream(MediaStream stream) {
_snackBar('remove');
}
_onCandidate(RTCIceCandidate candidate) {
socket.emit('studentCandidate', [
{
'room': room,
'candidate': {
'candidate': candidate.candidate,
'sdpMid': candidate.sdpMid,
'sdpMLineIndex': candidate.sdpMlineIndex
}
}
]);
}
_onRenegotiationNeeded() {
_snackBar('reneg');
}
I am trying to build a progressive web app that utilizes the device camera to take pictures but want it to save to their Photos gallery without being prompted to download like the native camera app does..Is this even possible..I haven't discovered a way yet and not much info on google about it would it be different if it was uploaded to the cloud?
Thanks
The link at https://whatwebcando.today/photos.html suggests that this may be possible.
capturer = ImageCapture(streamVideoTrack)
Creates an image capturer out of the Media Stream Video Track.
capturer.takePhoto()
Returns a Promise resolved with the photo taken with the current settings.
capturer.setOptions(photoSettings)
Configures the photoSettings for subsequent captures; if visible, the effects of the configuration can be seen in the Track used as input.
This is the example code:
function getUserMedia(options, successCallback, failureCallback) {
var api = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (api) {
return api.bind(navigator)(options, successCallback, failureCallback);
}
}
var theStream;
function getStream() {
if (!navigator.getUserMedia && !navigator.webkitGetUserMedia &&
!navigator.mozGetUserMedia && !navigator.msGetUserMedia) {
alert('User Media API not supported.');
return;
}
var constraints = {
video: true
};
getUserMedia(constraints, function (stream) {
var mediaControl = document.querySelector('video');
if ('srcObject' in mediaControl) {
mediaControl.srcObject = stream;
mediaControl.src = (window.URL || window.webkitURL).createObjectURL(stream);
} else if (navigator.mozGetUserMedia) {
mediaControl.mozSrcObject = stream;
}
theStream = stream;
}, function (err) {
alert('Error: ' + err);
});
}
function takePhoto() {
if (!('ImageCapture' in window)) {
alert('ImageCapture is not available');
return;
}
if (!theStream) {
alert('Grab the video stream first!');
return;
}
var theImageCapturer = new ImageCapture(theStream.getVideoTracks()[0]);
theImageCapturer.takePhoto()
.then(blob => {
var theImageTag = document.getElementById("imageTag");
theImageTag.src = URL.createObjectURL(blob);
})
.catch(err => alert('Error: ' + err));
}
So it seems like you can take a photo... I can't see anywhere to indicate that you can then persist this photo in the users storage though. I'd love to be wrong.
I'm using Ionic3 to build an android videochat application.
The videochat works perfectly between two tabs on my browser, but only shows the local video on my android device (the remote video being blank).
I'm using PeerJS for the peer-to-peer connection in my index.html:
I'm using the stunServer {url: "stun:stun.l.google.com:19302"} for the connection.
I'm using the functions shown on the home page: http://peerjs.com/
My config service:
import {Injectable} from '#angular/core';
#Injectable()
export class WebRTCConfig {
peerServerPort: number = 9000;
key:string = '<my peer id>';
stun: string = 'stun.l.google.com:19302';
stunServer = {
url: 'stun:' + this.stun
};
getPeerJSOption() {
return {
// Set API key for cloud server (you don't need this if you're running your own.
key: this.key,
// Set highest debug level (log everything!).
debug: 3,
// Set it to false because of:
// > PeerJS: ERROR Error: The cloud server currently does not support HTTPS.
// > Please run your own PeerServer to use HTTPS.
secure: false,
config: {
iceServers: [
this.stunServer/*,
this.turnServer*/
]
}
};
}
/**********************/
audio: boolean = true;
video: boolean = false;
getMediaStreamConstraints(): MediaStreamConstraints {
return <MediaStreamConstraints> {
audio: this.audio,
video: this.video
}
}
}
Snippet of my Peer WebRTC service:
createPeer(userId: string = '') {
// Create the Peer object where we create and receive connections.
this._peer = new Peer(/*userId,*/ this.config.getPeerJSOption());
setTimeout(()=> {
console.log(this._peer.id);
this.myid = this._peer.id;
}, 3000)
}
myCallId() {
return this.myid;
}
answer(call) {
call.answer(this._localStream);
this._step2(call);
}
init(myEl: HTMLMediaElement, otherEl: HTMLMediaElement, onCalling: Function) {
this.myEl = myEl;
this.otherEl = otherEl;
this.onCalling = onCalling;
// Receiving a call
this._peer.on('call', (call) => {
// Answer the call automatically (instead of prompting user) for demo purposes
this.answer(call);
});
this._peer.on('error', (err) => {
console.log(err.message);
// Return to step 2 if error occurs
if (this.onCalling) {
this.onCalling();
}
// this._step2();
});
this._step1();
}
call(otherUserId: string) {
// Initiate a call!
var call = this._peer.call(otherUserId, this._localStream);
this._step2(call);
}
endCall() {
this._existingCall.close();
// this._step2();
if (this.onCalling) {
this.onCalling();
}
}
private _step1() {
// Get audio/video stream
navigator.getUserMedia({ audio: true, video: true }, (stream) => {
// Set your video displays
this.myEl.src = URL.createObjectURL(stream);
this._localStream = stream;
// this._step2();
if (this.onCalling) {
this.onCalling();
}
}, (error) => {
console.log(error);
});
}
private _step2(call) {
// Hang up on an existing call if present
if (this._existingCall) {
this._existingCall.close();
}
// Wait for stream on the call, then set peer video display
call.on('stream', (stream) => {
this.otherEl.src = URL.createObjectURL(stream);
});
// UI stuff
this._existingCall = call;
// $('#their-id').text(call.peer);
call.on('close', () => {
// this._step2();
if (this.onCalling) {
this.onCalling();
}
});
}
In my chat.ts, I use this to call the function from the peer webrtc service:
call() {
this.webRTCService.call(this.calleeId);
}
It's likely to be a permission problem. You need to grant it permission to use the camera.
Camera Permission - Your application must request permission to use a
device camera.
<uses-permission android:name="android.permission.CAMERA" />
See
https://developer.android.com/guide/topics/media/camera.html
I'm working out on the ionic project. I need to get the items based on current district. To get the current district I tried the below.
cordova.plugins.diagnostic.isLocationEnabled(function(enabled) {
alert("Location is " + (enabled ? "enabled" : "disabled"));
if(!enabled)
cordova.plugins.diagnostic.switchToLocationSettings();
var geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
}
function errorFunction(){
$ionicPopup.alert({
title:"Alert",
content:"Geocoder failed"
});
}
function codeLatLng(lat, lng) {
geocoder.geocode({'latLng': new google.maps.LatLng(lat, lng)}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
district= results[0].address_components[i];
}
}
}
alert(distrcit.long_name);
}
else {
alert("No results");
}
}
else {
alert("Geocoder Failed");
}
});
}
}, function(error) {
});
This code is working fine if the GPS is enabled after switching to location settings. I'm getting the problem when the GPS is not enabled and getting back into the app. How can I detect whether it is enabled or not after moving to location settings and getting back to the app? Even though I referred many posts in StackOverflow, I didn't get the solution what I needed actually. So please help me out in solving it.
How can I detect whether it is enabled or not after moving to location settings and getting back to the app?
You can detect when your app is returned to the foreground using the resume event.
function onResume() {
cordova.plugins.diagnostic.isLocationEnabled(function(enabled) {
console.log("Location is " + (enabled ? "enabled" : "disabled"));
// etc.
}, function(error) {});
}
document.addEventListener("resume", onResume, false);