PICO w with pushbullet - micropython

Is there a way to use pushbullet with a pico w using micropython? I am using the thonny IDE. This is my code as of right now. I keep getting a osError:-2 when it is ran.
body = "Sensor Data"
title = "Fall Detected"
data_sent = {"type":"note","title":title,"body":body}
API_KEY = 'o.Ywi05DOBMqM3jdGJ5FdGEwd6STLclHuj'
pb_headers = {
'Authorization': 'Bearer ' + API_KEY,
'Content-Type': 'application/json',
'Host': 'api.pushbullet.com'
}
r = requests.post('https://api.pushbullet.com/v2/pushes',data=json.dumps(data_sent),headers=pb_headers)

Related

Failed to upload apk via Connect API

I am working on a python script to update the app on Huawei AppGallery via Connect API.
I successfully fetched the token and upload URL but not able to upload the APK/AAB.
Getting this error -
{'result': {'CException': {'errorCode': 70001405, 'errorDesc': 'get no file from request!'}, 'resultCode': '70001405'}}
Here's my python script
def uploadAAB(uploadUrl, authCode, accessToken, appId):
try:
fileName = 'latest_hms.apk'
headers = {
"Authorization": "Bearer " + accessToken,
"accept": "application/json",
"client_id": clientId,
"Content-Type": "multipart/form-data"
}
uploadBody = {
"authCode": authCode,
"fileCount": 1
}
with open(aabPath, 'rb') as f:
f.seek(0, os.SEEK_END)
print(f.tell()) # printing the correct size
first_phase = requests.post(
uploadUrl,
files={fileName: f},
data=uploadBody,
headers=headers)
if first_phase.status_code == 200:
print(first_phase.json())
body = {
'fileType': 5,
'files': [{
'fileName': fileName,
'fileDestUrl': first_phase.json()['result']['UploadFileRsp']['fileInfoList'][0]['fileDestUlr'],
'size': str(first_phase.json()['result']['UploadFileRsp']['fileInfoList'][0]['size'])
}]
}
fileHeader = {
'client_id': clientId,
'Authorization': 'Bearer ' + accessToken,
}
params = {
'appId': appId,
}
second_phase = requests.put(
BASE_URL + "/publish/v2/app-file-info",
headers=fileHeader,
json=body,
params=params)
print(second_phase.json())
except (requests.exceptions.RequestException, requests.exceptions.HTTPError, KeyError) as err:
stopOnError(repr(err))
Please help me out here.
{'result': {'CException': {'errorCode': 70001405, 'errorDesc': 'get no file from request!'}, 'resultCode': '70001405'}}
This error means there is no file in the request. the file is not include successfully in the request. Please make sure the file is achievable.
It seems Huawei made a change to the AppGallery API in February 2022. I don't know if this was intentional, but you must now specify a filename of "file" instead of your original filename (which worked before). See my pull request on Natgho's HMS-Publishing-API code.

SocketException: OS Error: Broken pipe on flutter

i've been having trouble with video upload.
I'm using Express JS/Node JS as a backend.
The thing is, the upload works when i upload a video of 2 seconds and it works 100% with postman.
but when i try to upload a big video from the app i get :
SocketException: OS Error: Broken pipe, errno = 32, address = 51.254.241.1, port = 47908
and this is my code :
var stream = new http.ByteStream(file.openRead())..cast();
var request = http.MultipartRequest(
"POST",
Uri.parse(sp.getString(SharedPreferencesManager
.LAST_SELECTED_ESTABLISHMENT_ENDPOINT) +
"api/group/uploadVideoFile"));
request.fields["email"] = sp.getString(SharedPreferencesManager.EMAIL);
request.fields["groupId"] = group.id;
request.files.add(http.MultipartFile("video", stream, await file.length(),
filename: file.absolute.path));
// request.files
// .add(http.MultipartFile.fromBytes("video", file.readAsBytesSync()));
// request.files
// .add(await http.MultipartFile.fromPath("video", file.absolute.path));
request.headers.addAll({
"Connection": "keep-alive",
"Accept-Encoding": "gzip,deflate,br",
"Accept": "application/json",
"Authorization": "Bearer " + sp.getString("TOKEN"),
"X-Auth-Token": FlutterConfig.get('X_AUTH_TOKEN')
});
request.send().then((value) => print("jawk behy $value"),
onError: (error) => print("error : $error"));
var response = await request.send();
return json.decode(await response.stream.bytesToString());

How to make a proper http request?

I can't seem to make a proper http request with my code. Whenever I run the following code,
var url = Uri.https('datamall2.mytransport.sg', '/ltaodataservice/BusArrivalv2?BusStopCode=', {'BusStopCode': busStopCode});
final response = await http.get(
url,
headers: <String, String>{
'Content-Type': 'application/json',
'AccountKey': accountKey,
},
);
I get the following error
I/flutter (24816): SocketException: OS Error: Connection refused, errno = 111, address = datamall2.mytransport.sg
This is the http request I'm trying to make
http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2?BusStopCode=busStopCode (busStopCode is a 5 digit number)
The wrong protocol is being used.
You've requested httpS.
The server is only responding to http.
You could try something simpler:
String url = 'http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2?$busStopCode';
final response = await http.get(
url,
headers: <String, String>{
'Content-Type': 'application/json',
'AccountKey': accountKey,
},
);
You should change your url variable to:
var url = Uri.http('datamall2.mytransport.sg', '/ltaodataservice/BusArrivalv2', {'BusStopCode': busStopCode});

Api Authorization working in postman but not working in flutter

I created an api with authorization, It is working correctly in postman but but i am not able to use authorization in flutter, I am getting Statuscode: 401(unauthorized) in flutter but in postman i am getting statuscode: 200(success). Here is my Code:
sharedPreferences = await SharedPreferences.getInstance();
String Authorization = sharedPreferences.getString("token");
var data = await http.get("http://10.148.7.58/Election/api/TblDatas",
headers: <String, String>{'Authorization': '$Authorization',}
);
//Also tried these
//headers: {'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': '$Authorization',}
//headers: {HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.authorizationHeader: "$Authorization"}
print('status code is' + (data.statusCode).toString());
headers: <String, String>{
'Content-Type': 'application/json', //add context-type
'Accept': 'application/json',//add accept
'Authorization': 'Bearer $token',
}
Make sure that your server accepts lower case header names - in this case authorization, as Dart will lower case them. This fools some servers that aren't RFC compliant

RC-IamErrorResponse - Account context in the query param is different from the account context in the token

I'm trying to get resource groups via an api key.
First, I authenticate to IAM...
apikey = 'myapikeyvalue'
self.log.debug('Authenticating to IAM')
url = self.iam_endpoint + '/identity/token'
data = "apikey={}&grant_type=urn%3Aibm%3Aparams%3Aoauth%3Agrant-type%3Aapikey".format(apiKey)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic Yng6Yng="
}
response = requests.post(url, headers=headers, data=data)
token_type, access_token = # get token_type and access_token from response
Then I receive the account_id ...
url = self.iam_endpoint + '/v1/apikeys/details'
headers = {
"IAM-Apikey": apiKey,
'accept': 'application/json',
'authorization': '{} {}'.format(token_type, access_token),
'cache-control': 'no-cache',
'content-type': 'application/json'
}
response = self._request(url=url, http_method='get', description='_get_account_id', additional_headers=headers)
account_id = response.json()['account_id']
Next, I try to retrieve the resource_groups ...
url = self.region.rc_endpoint() + '/v1/resource_groups?account_id=' + account_id
response = self.client._request(url=url, http_method='get', description='get_resource_groups')
return response.json()
However, this results in:
{
"error_code":"RC-IamErrorResponse",
"message":"Account context in the query param is different from the account context in the token.",
"status_code":401,
"transaction_id":"7e89f6873e1bd4f92d57829e0f08f4ad"
}
Any ideas?
For some reason, returned value seems to be of the format: xxxxxxxxxxxY-YYYY and we only need the x's. This worked for me
return account_id.split('-')[0][:-1]