JSON Formatting from Particle Photon Webhook to Azure - javascript

I have hooked up my Particle Photon to log my temperature and then publishing the events to eventhub at Microsoft Azure. Then i use Stream Analytics to output the JSON file into Azure Storage (Good idea? or not?).
When i try to open it with <script src="URL"></script> through HTML, i get " Uncaught Syntax error: Unexpected token : " in the browser console window.
I also tried to validate my JSON file with JSON formatter and got alot of errors.
Here is the JSON file: https://pptlbhstorage.blob.core.windows.net/temperature/0_d1e8a2b709b14461b5ac12265f33020b_1.json
From the stream analytics i created a job with this query:
CREATE TABLE pptlbhhub (
coreid nvarchar(max),
data nvarchar(max),
event nvarchar(max),
EventEnqueuedUtcTime datetime,
EventProcessedUtcTime datetime,
measurename nvarchar(max),
PartitionId bigint,
published_at datetime,
subject nvarchar(max),
timecreated datetime,
unitofmeasure nvarchar(max),
value float
);
SELECT
coreid
,event
,EventEnqueuedUtcTime
,EventProcessedUtcTime
,measurename
,PartitionId
,published_at
,subject
,timecreated
,unitofmeasure
,value
INTO
pptlbhstorage
FROM
pptlbhhub;

I mean your file should look like this to be JSON valid (like an array).
[{"coreid":"1e0041000c47343432313031","displayname":"IoT Assignment 3","event":"PublishToEventHub","eventenqueuedutctime":"2016-05-12T08:56:20.5300000Z","eventprocessedutctime":"2016-05-12T08:56:21.3068971Z","guid":"1e0041000c47343432313031","location":"Oslo","measurename":"Temperature","organization":"Westerdals ACT","partitionid":0,"published_at":"2016-05-12T08:56:21.0850000Z","subject":"Weather","timecreated":"2016-05-12T08:56:21.0850000Z","unitofmeasure":"F","value":21.0},
{"coreid":"1e0041000c47343432313031","displayname":"IoT Assignment 3","event":"PublishToEventHub","eventenqueuedutctime":"2016-05-12T08:56:20.5300000Z","eventprocessedutctime":"2016-05-12T08:56:21.3068971Z","guid":"1e0041000c47343432313031","location":"Oslo","measurename":"Temperature","organization":"Westerdals ACT","partitionid":0,"published_at":"2016-05-12T08:56:21.0850000Z","subject":"Weather","timecreated":"2016-05-12T08:56:21.0850000Z","unitofmeasure":"F","value":21.0}, ...]
Not like
{"coreid":"1e0041000c47343432313031","displayname":"IoT Assignment 3","event":"PublishToEventHub","eventenqueuedutctime":"2016-05-12T08:56:20.5300000Z","eventprocessedutctime":"2016-05-12T08:56:21.3068971Z","guid":"1e0041000c47343432313031","location":"Oslo","measurename":"Temperature","organization":"Westerdals ACT","partitionid":0,"published_at":"2016-05-12T08:56:21.0850000Z","subject":"Weather","timecreated":"2016-05-12T08:56:21.0850000Z","unitofmeasure":"F","value":21.0}
{"coreid":"1e0041000c47343432313031","displayname":"IoT Assignment 3","event":"PublishToEventHub","eventenqueuedutctime":"2016-05-12T08:56:20.5300000Z","eventprocessedutctime":"2016-05-12T08:56:21.3068971Z","guid":"1e0041000c47343432313031","location":"Oslo","measurename":"Temperature","organization":"Westerdals ACT","partitionid":0,"published_at":"2016-05-12T08:56:21.0850000Z","subject":"Weather","timecreated":"2016-05-12T08:56:21.0850000Z","unitofmeasure":"F","value":21.0}...
The difference is the "[]" at the beginning & the end of the stream and the "," between each element.

If you output the events as an array, your JSON file will be ok :
[{}, {}, ...]
instead of
{} {} {} ...

You might be interested Particle's 1st class integration with Azure IoT Hub to help you get Particle device data into Microsoft Azure. For more information on how to get this set up, check out:
https://docs.particle.io/tutorials/integrations/azure-iot-hub/

Related

How can I combine a WHERE and ORDERBY request in Firestore (Firebase 9)? ReactJs [duplicate]

I want to query my Workout Collection for the latest workout from a routine. Meaning I query with whereEqualTo my routineKey, order it by the Started TimeStamp in descending order and then limit to 1 and then take the this 1st Key/Id of the Workout.
However this does not work. whereEqualTo and orderBy work separately but not combined. What am I doing wrong?
fm.getColRefWorkout().whereEqualTo("routineKey", routineKey).orderBy("startTimeStamp", Query.Direction.DESCENDING).limit(1).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
workoutKey = documentSnapshots.getDocuments().get(0).getId();
//To stuff with this workoutKey
}
});
This query will not work unless you create an index for it. This can be done, by creating it manually in your Firebase Console or if you are using Android Studio, you'll find in your logcat a message that sounds like this:
FAILED_PRECONDITION: The query requires an index. You can create it here: ...
You can simply click on that link or copy and paste the URL into a web browser and your index will be created automatically.

Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': cannot convert to dictionary

I am building a webrtc system and currently trying to have the session description sent back to the local connection. Below is the code block I am using to have the session description reinserted on the local side, but I am getting the error below. The "lc.setRemoteDescription()" line works when I manually type the description into lc.setRemoteDescription() in the devtool console. Any ideas what this could be due to?
Javascript code
...
console.log("broadcastlist");
broadcastlist.push(data.message);
console.log(data.message);
connectcounter ++;
console.log(connectcounter)
var user = data.user
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
lc.setRemoteDescription(data.message)
...
Output on browser dev tools console. ("lc.setRemoteDescription(data.message)" corresponds to the error displayed in the picture below.
That error happens when you attempt to pass a string to setRemoteDescription:
const pc = new RTCPeerConnection();
pc.setRemoteDescription("")
Assuming that your data.message is a JSON-serialized object you need to convert it to an object with JSON.parse first.

Cardano-wallet malformed tx payload from Submit External Transaction

I’m trying to submit an already signed tx from cardano-cli using the cardano-wallet endpoint: https://localhost:8090/v2/proxy/transactions
the signed transaction look like this:
txBody = {
"type": "Tx MaryEra",
"description": "",
"cborHex": "83a400818258202d7928a59fcba5bf71c40fe6428a301ffda4d2fa681e5357051970436462b89400018282583900c0e88694ab569f42453eb950fb4ec14cb50f4d5d26ac83fdec2c505d818bcebf1df51c84239805b8a330d68fdbc3c047c12bb4c3172cb9391a002b335f825839003d2d9ceb1a47bc1b62b7498ca496b16a7b4bbcc6d97ede81ba8621ebd6d947875fcf4845ef3a5f08dd5522581cf6de7b9c065379cbb3754d1a001e8480021a00029361031a01672b7ea1008182582073dd733cc50d594cb89d3ac67287b02dae00982fc800e9c9c9d1bb282b56122558404d0cb4e4f1cc415ddcf546871f075d0ca6e0c2620cd784b06c21c9b86e4403cb7a115038487576dcb20e7820e9d0dc93ab2a737ed9d0a71a77bc1e12f7c4dd0ef6"
}
I just don’t know how to pass it to the endpoint using Content-Type application/octet-stream. The API doc says the payload should be:
string <binary>
Signed transaction message binary blob.
I’m using javascript for this and have tried passing the cborHex directly, using Buffer.from(txBody.cborHex).toString('base64') and the whole json Buffer.from(JSON.stringify(txBody)).toString('base64') but always got the same response:
{
"code": "malformed_tx_payload",
"message": "I couldn't verify that the payload has the c…node. Please check the format and try again."
}
Also I’ve noticed from the swagger specification that the endpoint support a JSON payload and taking a look to the cardano-wallet's source code here:
newtype PostExternalTransactionData = PostExternalTransactionData
{ payload :: ByteString
} deriving (Eq, Generic, Show)
I thought the structure should be some like this:
{
"payload": ?// some binary blob here that I can't find. I've tried with:
// Buffer.from(txBody.cborHex).toString('base64') and
// Buffer.from(JSON.stringify(txBody)).toString('base64')
}
Any idea how to construct the payload and pass the signed tx?
This code tells me that when decoding external (sealed) transaction the wallet tries Base 16 encoding first and if that fails then it tries Base 64:
instance FromJSON (ApiT SealedTx) where
parseJSON v = do
tx <- parseSealedTxBytes #'Base16 v <|> parseSealedTxBytes #'Base64 v
pure $ ApiT tx
After that BytesString is passed to this function https://github.com/input-output-hk/cardano-node/blob/5faa1d2bb85ae806ec51fa4c576dec2670c67c7a/cardano-api/src/Cardano/Api/SerialiseCBOR.hs#L32 together with the currentNodeEra that node is running.
(Each era has a different way of decoding)
It could be (I am not sure) that node is running say Alonzo but you're submitting a Mary-encoded Tx. In which case the decoding might fail.
I hope this helps.

Display power usage as temperature with Node-Red in Apple HomeKit

I would like to display the power usage in HomeKit. Unfortunately there is no category to do that in HomeKit. That's why I had the idea to display this not as a power usage but as temperature in HomeKit. The idea is to control HomeKit scenes with the fake temperature sensor.
Unfortunately I have no experience in node-red and it is new for me.
I got the following string from the electricity meter:
success: "true"
response: string
{
"power": 3.040480,
"relay": true
}
I link this to the HomeKit Node which then returns the following error:
Characteristic response cannot be written.
Try one of these: Name, CurrentTemperature, StatusActive, StatusFault, StatusLowBattery, StatusTampered, Name
After various functions and other adjustments I unfortunately don't get the "temperature" displayed in HomeKit.
I use this:
https://flows.nodered.org/node/#plasma2450/node-red-contrib-homekit-bridged
I think you cannot directly link up the 2 nodes. From the error message it suggests that you have passed the payload from meter output to HomeKit node. While the meter output contains response property and it is not supported by HomeKit, your error would occur.
Make sure your payload only consists of the supported Characteristics. You can use a change node to modify the payload, or simply with a a function node
const msg.meterOutput = msg.payload;
// Just a prototype, type checking is required
msg.payload = {
currentTemperature: msg.meterOutput.response.power
}
return msg;

Meteor CityForks Demo Assistance

With reference to Josh Owens' Cityforks demo, I've gotten the get current location to work correctly and my app is not crashing but when I check Robomongo, the places collection is not populating the database.
I've copied the code exactly though:
Places = new Mongo.Collection('places');
Meteor.methods({
'fetchNearbyLocations': function(coords) {
if (Meteor.isServer) {
results = HTTP.get("https://maps.googleapis.com/maps/api/place/nearbysearch/json? location=" + coords.latitude + "," + coords.longitude + "&radius=500&types=food&key=AIzaSyCtfoCAldCEf8hXUlkVUd4UljqKR6W_aF4")
console.log(results)
_(results.data.results).each(function(loc) {
_.extend(loc, {loc: {type: "Point", coordinates: [loc.geometry.location.lng, loc.geometry.location.lat]}})
Places.upsert({id: loc.id}, {$set: loc})
});
}
}
});
Regarding the API key that I would of course change, is it the Key for server apps (with IP locking) or the Key for browser apps (with referers) that one should use?
I did remove autopublish, not sure if that makes a difference?
Also, would one have to add something like the below to a JS file somewhere within the project?
<script type="text/javascript" src="http://maps.google.com/maps/api/js? sensor=false"> </script>
Any assistance would be greatly appreciated.
About the API Key
It's the key for browser apps. https://developers.google.com/maps/documentation/javascript/tutorial#api_key
Finding the collection in Robomongo
The collection should show up in Robomongo if you simply follow Josh's code.
Are you running on localhost?
If you're on port 3000 for example, your database is on port 3001, and you have to enter this into your new Robomongo connection.
Then look in your New Connection>Meteor>Collections> and you should see places. Click on it and you should see 50 entries for db.places.find (or however many places you've opted to return in your code).
To check otherwise, just go into your browser's console (option+command+j in Chrome on OS X) and type Places.find().fetch() and you should get 50 objects returned.
Or in terminal, in your app's directory type meteor mongo to enter the mongo shell, and there type db.places.find().pretty() to see if your collection is properly populated.
If these work, then I think it means that you just aren't looking at Robomongo correctly, but you'll see that it's really easy.
Adding a script
The http call to google maps is already in the fetchNearbyLocations method, so that's enough as far as I understand.
The sensor parameter is no longer required by Google Maps. source
Hope that helps!

Categories