Angular web bluetooth write and notify example - javascript

Currently i'm working with this module for angular: Angular web bluetooth
I can find an example how to read characteristics and got it working. But there are no samples to write (or notify). I am pretty sure that this module is capable of this tasks, see here, but my knowledge of Angular (or even JS?) isnt enough.
Did someone have any idea where to find examples or/and can provide them?
Snippet to read battery level:
getBatteryLevel() {
console.log('Getting Battery Service...');
try {
return this.ble
.discover$({
acceptAllDevices: true,
optionalServices: [BatteryLevelService.GATT_PRIMARY_SERVICE]
})
.mergeMap((gatt: BluetoothRemoteGATTServer) => {
return this.ble.getPrimaryService$(
gatt,
BatteryLevelService.GATT_PRIMARY_SERVICE
);
})
.mergeMap((primaryService: BluetoothRemoteGATTService) => {
return this.ble.getCharacteristic$(
primaryService,
BatteryLevelService.GATT_CHARACTERISTIC_BATTERY_LEVEL
);
})
.mergeMap((characteristic: BluetoothRemoteGATTCharacteristic) => {
return this.ble.readValue$(characteristic);
})
.map((value: DataView) => value.getUint8(0));
} catch (e) {
console.error('Oops! can not read value from %s');
}
}
Thank you.
Edit: thanks to the assistance of Aluan Haddad i was able to perform a write request, with the right Service and Characteristic UUID
.mergeMap((characteristic: BluetoothRemoteGATTCharacteristic) => {
let value = new Uint8Array(1);
value[0] = 2;
return this.ble.writeValue$(characteristic, value);
}).subscribe();

Related

Jest custom testing API, how to correct code frame

I'm looking to simplify my project's testing API where I am aiming for something like this:
testThing((t) => {
t(33);
t(44);
t(42);
})
Now I don't know how to get Jest to show the correct code frames for failed expect's. This is my current stab at an implementation:
const testThing = (callback: any) => {
callback((n: any) => {
test(n.toString(), () => {
expect(n).toBe(42);
});
});
};
Which results in the testThing definition to be shown for every failed test case. Here's a replit if you want to see it in action: https://replit.com/#grgr/jest-frame-issue#thing.test.js

How to insert data into mysql using angular and nodejs - getting (NULL, NULL) upon insert - Problem solved

Good day,
I've been trying to learn a bit of angular and nodejs. I found a tutorial on a realtime chat app and made some few adjustment to some function of the code. But the one aspect that I cannot seem to get right is the ability for the user to post to a feed. The login process works, the user is already logged in but the user can't post. I would also like to be able to get all they data i insert from all the user to show up like a normal feedview will. Please assist.
Here are my files:
FROM MY CONTROLLER HERE IS THE CODE WHEN THE BUTTON IS PRESSED
$scope.postDatatoDd = () => {
appService.httpCall({
url: '/posts',
params: {
'posts': $scope.data.info,
'from_user_id': $scope.data.username
}
})
.then((response) => {
// $scope.$apply();
})
.catch((error) => {
alert(error.message);
});
}
and here is my route file:
this.app.post('/posts', async(request,response) => {
const reqResponse = {}
const data = {
posts : request.body.postDatatoDd,
from_user_id: request.body.username
};
if (data.posts === ''){
reqResponse.error = true;
reqResponse.message = `error, input`;
response.status(412).json(reqResponse);
} else {
const result = await helper.insertFeed(data);
if (result === null) {
reqResponse.error = true;
reqResponse.message = `they was an error.`;
response.status(417).json(reqResponse);
} else {
reqResponse.error = false;
reqResponse.userId = result.insertId;
reqResponse.message = `posted succesfully`;
response.status(200).json(reqResponse);
}
}});
and in my helper file there is this function to insert data:
async insertFeed(params){
try {
return await this.db.query(
`INSERT INTO posts (from_user_id,posts) values (?,?)`,
[params.from_user_id,params.postDatatoDd]
);
} catch (error) {
console.warn(error);
return null;
}
}
On the client side here is the button with :
<label for="postDatatoDd">Post</label>
<input type="text" id="postDatatoDd"
ng-model="data.postDatatoDd"
class="feed form-control"
placeholder="post your data here?"
/>
<button ng-click="postDatatoDd()" class="btn btn-primary">Post</button>
</div>
--- EDIT 1---
Data is being inserted now, but it is receiving the values as (NULL, NULL).
--- EDIT 2 ---
After closely looking at the code and fixing some naming variables the code works fine, the data is being inserted in mysql as it should.
Other than a lot of typos when it comes to the variables reference. The code seem to be fine.
Assuming that you using appservice class somewhere in your code and its functioned, then everything else will work.
You are getting the (NULL, NULL) because you are parsing parameters that are not being properly parsed out to your helper file, please close attention to that.
appService
.httpCall({
url: "/posts",
params: {
posts: $scope.data.postbuzz,
from_user_id: $scope.data.username,
},
})
.then((response) => {
$scope.$apply();
})
.catch((error) => {
alert(error.message);
});
make sure that the data that you calling from this above function is similar to $scope parameter you passing in your route file that your requesting:
const data = {
posts : request.body.posts,
from_user_id: request.body.from_user_id}
and in your database helper class you running:
`INSERT INTO posts (from_user_id,post) values (?,?)`,
[params.from_user_id,params.posts]
Hope this was helpful
You seem to have an understand already. your question may help a lot more people in the future.
params should be as following, since the data object has properties from_user_id and posts
`INSERT INTO posts (from_user_id,posts) values (?, ?)`,
[params.from_user_id,params.posts]
Might be useful https://www.w3schools.com/nodejs/nodejs_mysql_insert.asp
--- EDIT 2 ---
After closely looking at the code and fixing some naming variables the code works fine, the data is being inserted in mysql as it should.
If you are new to Angular you can use the code as reference.

error handling in observable or in observer?

I have this method (Angular 9, so Typescript) which is used to retrieve a brend new Json Web Token for authenticate the current user
getNewAccessToken(){
return this.httpClient.post<Token>(`${this.baseService.baseUrl}auth-token-refresh/`, { refresh: this.getRefreshToken() }, this.baseService.httpOptions).pipe(
tap((response:Token) => {
this.cookieService.set(environment.tokenAccessName, response.access, null, '/', null, null, 'Strict');
this.isLoggedIn.next(true);
}
}
When I subscribe to this method, I check for errors like so
this.authService.getNewAccessToken().subscribe(
res => { //do something with res... },
error => throw error //catch error
);
Could I move the error detection directly inside my observable code using pipe and catchError? The code would turn to this
getNewAccessToken(){
return this.httpClient.post<Token>(`${this.baseService.baseUrl}auth-token-refresh/`, { refresh: this.getRefreshToken() }, this.baseService.httpOptions).pipe(
tap((response:Token) => {
this.cookieService.set(environment.tokenAccessName, response.access, null, '/', null, null, 'Strict');
this.isLoggedIn.next(true);
},
catchError(error => {
throw error;
})
));
}
I think this is a sort of centralized way of managing errors in observable.
Generally, is error handling better on observables or on their observers?
What are the pros and cons of these two approaches? Is there any difference in terms of performance?
I think the same question can be raised for promises
Yeah, and it is the good practice to move error handling into pipe as it is separation of concern. It separates data retrieving from the presentation of the data.
An example of code of Angular 2 documentation:
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
catchError(this.handleError('getHeroes', []))
);

How to hit/consume post and get api in React Native with Ignite Bowser 2 Boilerplate. (Mobx state stree, type script)

I am new to React Native, please provide some Github link or your own code for reference. Consider me as a beginner in RN.
I found very less open support for RN, Mobx State tree, Ignite and all, so not just post and get API reference, if you find anything helpful related to these above-mentioned topics, Feel free to share.
Thanks in advance.
Mobx State Tree, With Ignite Bowler you would have api.ts file where you can specify API calls.
async getUser(userToken: string): Promise<Types.GetUserResult> {
// make the api call
const response: ApiResponse<any> = await this.apisauce.post(`api/v1/sales/login?authCode=${userToken}`)
if (!response.ok) {
const problem = getGeneralApiProblem(response)
if (problem) return problem
}
// transform the data into the format we are expecting
try {
try {
const rawUser = response.data
console.log('rawUser'+ rawUser)
const user: UserSnapshot = convertRawUserToUserStore(rawUser)
return { kind: "ok", user }
console.log({ user })
} catch (e) {
__DEV__ && console.tron.log(e.message)
return { kind: "bad-data" }
}
} catch {
return { kind: "bad-data" }
}
}
Consider, we will be getting user data from this API call,
you can notice that there is UserSnapshot which belongs to User Model, Snapshot will save the data automatically, you don't need Aysnc storage to save or retrieve data.

meteor collection fs forbid upload

i want to forbid the upload / storage of files under special circumstances.
I tried in the collectionfs before hook:
Attachments.files.before.insert((userId, doc) => {
if(!Meteor.isServer){
if (!isUploadAllowed()) {
throw new Meteor.Error('Upload not allowed');
}
}
}
Unfortunately this is not working.
Is there a better way to achieve this? Or can someone help me?
(An ugly solution would be to remove the uploaded document in the after.insert hook, i hope there is a better way)
You can set the deny for this collection for all client operations to false:
const Attachments.files = new Mongo.Collection('fs.files')
Attachments.files.deny({
insert () { return true },
update () { return true },
remove () { return true }
})
This defaults to deny any client operation to sync with the server.

Categories