How to access a JSON object? #1172
Replies: 19 comments
-
Posted at 2016-11-10 by @allObjects
This code (see second line)
fixes your issue, but there is not point to first build a JSON string from Plain assignment gets you there - because it is the same:
Therefore, you can drop
It is a different story though when you want to write you readings onto a SD memory card, or transmit to wherever. For that you would A) for initialization
B) for update that readings on the storage, you
|
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-10 by @allObjects ...with that said - and to come full circle - your initial code is missing only two (2) single quotes in the first line...
Note: JSON is always a String (object)... JS Object Notated (as a string). It is the literal representation of an object, like the literal representation of a simple string is always in "DoubleQuotes" or 'SingleQuotes', or like literal number, for example 6, is just the 'naked' number, or like the literal booleans true and false ('naked' symbols / reserved words), or the null and undefined object null and undefined (also 'naked' symbols / reserved words)... versus the variable referencing - or value holder - of an object, string, boolean, number, null and undefined respectively. |
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-10 by d0773d @allObjects.. Ok, i think I get it. How do I access sensorObject to gather the values when using code:
Nevermind... I read over your posts again.. I was just a bit confused, before. Thanks for the informative response. |
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-11 by @allObjects Properties - value (state) and function (behavior) properties - of a JavaScript object ("object" === typeof objVariable) can be accessed in two ways: static and dynamic. Example to access a value property - read and 'write' (assign):
Same static (hard coded) and dynamic (by variable for property name) access goes for functions (behavior). The example below uses the SensorReading prototype based object-oriented approach to have multiple (maxNumOfLastReadings) sensorReading s (objects / instances of SensorReading prototype / class) stored in sensorReadings singleton object (singleton - only one instance exists). Two sensorObjects read values, create a reading with the read values and store it in the readings in different intervals.
Interval settings produce readings at 15, 30, 45, 50, 60, 75, 90, 95, 105, 120, 135, 140,... seconds (italics are LOC1 readings, bold are LOC2 readings). Complete above code with sensor specifics, upload / run it, and then ask
PS:
|
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-11 by d0773d @allObjects Thanks for that. I get it :-) I really like the flow of your code example/explaination. |
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-11 by d0773d For what it's worth here is my code that I hacked together before you responded a second time to my my original post. Its rather messy and I could probably do this a different way especially change the nested setTimeouts. The reason why I used setTimouts is to wait before I gather the other sensor data. On average, it takes 300ms to process a "read command" then I can issue a a "readFrom". On some occasions, depending on the sensor, it can take 1300ms to process a "read command" before I can issue an I2C "readFrom". The nested timeouts allows me to: First, send a read command to the temp sensor then take the temp Second, send a temp compensation update command to both the ph and Third, send a ph read command and wait 300ms to execute an i2c Fourth, send an ec read command and wait 1300ms to execute an i2c After all that I send the JSON object via serial to another device. Another reason for my nested timeouts was, well atleast I thought, If I send a read command to both the ph and ec sensors at the the same time(after their temp compensations was updated), thought the i2c would crash or timeout... I'll have to read through your post and attempt to implement the information into my code.
|
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-12 by @allObjects Great description and coding. To recap - in a nutshell:
Now, there are some pertinent specifics, such as that:
So far so good. - sounds abstract... but most likely not to you sick you touched on all these items in the code (if I'm close). 2 cents object-oriented analysis and design... For each 'thing' (object) in the description we will distill an interface (class, protocol) out of the description. A good techniques is the CRC (index) card analysis, design and validation 'game' to get every thing ready to punch out robust, requirements covering implementation / code (some of that you already have in one form or the other). CRC card means to have a card for each 'thing' that names the Class it belongs (the type it is), identifies what all it has to know about itself and what all it has to be able to do - Responsibilities - and whit whom - Collaborators - it needs to work with in order to be able to to fullfill the responsibilities: CRC = Class - Responsabilites - Colaborators For example, for a 'thing' like me and you, which we call aPerson, because we are an instant (or member) of the Class Person, (basic) Responsibilities are to know first an last name, date of birth (dob), to provide full name - which is first with last name, formal name - which is first's initial and last name, and last but not least, for example, provide / calculate the age in years. For the first four (5) responsibilities we need no other 'thing' - *** Collaborators*** to work with, for the last one though, we need another 'thing', namely aDate thing that knows today's date / year, and that 'thing' is an instance of the Class Date. Noteworthy is that he 'things' we have to know about are already as well instances of Classes, such as aString of String for the name business, and aDate of Date for dob, which both come with responsibilities that come in handy. The above text does 'just fine'... but is quite exhausting and not easy to work with on the green table with the business user... therefore the structured CRC index cards, of which we have at least two: one for Class Person and one for Class Date, and for the sake of the game we can also have on for the String class. Luckily, only for the Person class we have to implement, because JavaScript comes with the other two built in - and many more.
In an analysis session you sit around the table with empty cards or stand around a flip chart stickies and build together these CRC cards. To verify, run the business use cases / scenarios and each participant holding the card makes sure that responsibilities a fulfillable and collaborators are complete. CRC is not really new - actually in IT terms - stony old, but therefore and rock solid AND actual again: agile and CRC. Above cards include already some IT formal notions, such as data types / classes for the state and function parenthesis for behavioral responsibilities, but this can all be done with plain text... The Person Class code looks like this:
Notice the upercase beginning of class names vs. state (variables) and behavior (function) and instances (variable) are - almost - always lower case... This casing makes it very clear from what's a class from which you can make instances with When you add just one more line to the code above
then it is already a complete module - that holds a class definition - and
To save memory and speed up execution, got to google's closure and minifier compiler Web site, paste the code in the left pane, click Compile button, copy-paste the compiled/compressed code from the right pane into a new file which you store in the modules folder in the sandbox named
With his simple piece of code, source code memory saving is about 21%... for complex things the savings are more significant... For now, lets just paste the first code block into the source editor / right hand pane of the Espruino Web IDE, add the following lines to crate 'aPerson', upload it and then have some fun with it in the console / left hand pane of the Espruino Web IDE.
Work/validate expected behavior of the
This is very simple example, where the 'nestedness' of the objects is minimal. For your application it will be much higher, and individual static / value responsibilities of an complex object can be another complex object, such as your commands are already now (but a bit more memory saving and reuse oriented). ...this was a lot beating around the bush for 2 cents... next post goes to sensor work. |
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-13 by d0773d @allObjects thanks again for your write up. I especially like the explanation you gave about CRC. Your explanations gave me some insights about what I can and should do differently. |
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-14 by @allObjects @d0773d, I got side tracked / delayed in talking about some of the things had in mind when elaborating on the CRC analysis and design technique. I had already some lines, when I tried to better understand what you want to achieve. Of course, I could just badmouth your code to everyones frustration... including mine... so I did not want to say anything before better understanding what the challenges actually are across all the layers of your application, hardware and software. Therefore I'd ask you to provide a bit more detail about the whole system. Even without that detail, I conclude, there is something in place - such as a central control / monitor node - that will receive the serialized object as string in JSON and then do something with it. Of course, the first part is the easy part: making an object out of JSON with ```var readings = JSON.parse(receivedByteArrayOrString);'''. To give some hints how to decouple the systems, I would let the sensor node (or agent) to its job and read from some place (queue) your high level commands sent by the central control/monitor node, such as: '''takeAllReadings()'''. Since this takes a while, you best end up with an asynchronous coupling of your sensor and central nodes. Since readings are the most important things to you - I assume - you could let that happen with an initiating command that sets up an interval on the particular sensor node. When a reading - including time and all the other things - is complete, you just store it in a variable replacing the previous reading. When the central node is interested in a reading from a particular sensor node, it just asks and gets the most recent. Many of the sensor chips actually work this way, because having to sequence and wait for things all the way up through all layers of an application is a nightmare... indicated already in the amount of code you had to write for your sensor class. Split the it up into more classes / objects covering just a reasonable amount of functionality on a particular level and let lover levels be handled by collaborators... that's why I brought up the CRC stuff in the first place. Looking at the challenges here are timing, sequencing, which are purely technically and have 'basically' nothing to with your overall application architecture. This simplistic statement is though not completely truthful and does not good justice to the cause. Underlaying details - and in particular restrictions - have an impact on the UEberlaying (sorry for the word creation) overall architecture. For example: do not design something in an upper layer that expects a real time value within 100 ms... it will just not go-n-a happen... EXCEPT you say: is getting values within 100ms that are may be 5 seconds old? I guess you see where I'm heading for. Therefore, in your agent has a property Furthermore, your sensor object looks like a 3 in one (or even more) object. If you can split these out, it could be of help. On the other hand, it looks that only the command sequences and their timings are different... Dividing up the knowledge into separate things that know just about sequencing micro commands singleton as a helper to a more generic sensor object, and similar sequencing of the agent to sequence the the sensors with macro commands. The separation simplifies the understanding and increases grokking by everyone else - including you - especially after you have left the working code alone for some time and need not to go in and make some changes, enhancements, extensions,... or just some simple version maintenance triggered by component version changes. In particular, the sonsor object does a lot of repeated things - including eating up memory - even though after being created as a particular sensor, it is never even need. For example you command sequences you can keep outside of your generic sensor code as singleton and pass them in as reference on construction. Furthermore, you can add a reference to a result processing function to get rid of the case-logic in lines 118..138 (I may though be mistaken, since I do not know with what hardware you are dealing...). Since these sensors could be looked at as just being a bunch of static declarations - such as your commands already are, you could go even further and make a complete declaration for each individual sensor that also includes the type. As dynamic part of the application you write a visitor that takes some parameter and then works itself through the declarations with the collaboration of some helpers, such as a queue, a time sequencer, etc... The problem that you already solved - the solution - of managing timing is not go-n-away, you just express (specify) it in a little bit different way and the so implement the processing - visiting - code. Lookup the visitor pattern... Combined with some timing - which you already do - you will get to the point where you comfortably collect data and stick it into complete / consistent readings that can be picked up anytime - with no delay - by a command from the central. |
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-15 by @allObjects @d0773d, fyi: ...https://www.linkedin.com/groups/73311/73311-6196619773833506817 just 'sailed' through my linkedin (marketing/advertisment) entangling... (iternet of things)-group... somehow sounded familiar with terms in this thread. - No offense to Python, but I like the JS version more - especially with the frugal resources - no-resources - Espruino can live on. PS: have to peek a bit into IEEE 802.15.4 protocol... |
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-19 by d0773d @allObjects I read through your posts(a few times). I'm definitely needing to split my code up more. In case you are interested... I posted links to the sensors. I would of liked to upload the datasheets, but every time I tried to upload a file I keep getting: "Internal Server Error". Temp Sensor PH Sensor EC Sensor |
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-20 by @allObjects ...lot of datasheet... The main thing having skimmed through the datasheets is what you already tackled: timed commands. Each command has its deferred, particularly to interpret response. Common to the responses is that they are of variable length and their end is detected by receiving a null character. These protocols can be implemented as technical functions/objects working on descriptive data to implement them in a generic way and can be easily reused on a higher level of implementation, for example on the sensor. The dynamic nature of JavaScript comes handy to achieve that. You can start with each command and related response interpretations as own object. After a few implementations you then factor out repeated/shared function oriented things into service object(s) and specific data/control oriented things into descriptor/specification objects. Factoring out specifics is though not limited to data/control oriented things, a function can be part of it as well, passed as reference to the shared function objects and invoked there. When you 'feel' that things get too complicated or too obscure, you may revert some of the steps and adjust course, or stop all together. Your design should after all reflect the things that you encounter in real and thought world. Abstraction is not always simplifying complexity, but can make it manageable by creating manageable, robust code. Sounds plausible... but a lot of aspects fold into the term 'manageable'. Each aspects and its weight is derived from the requirements found top down, bottom up, outside in, inside out,... |
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-20 by d0773d @allObjects again thank you. Most of what you wrote went WAY over my head; however, It didn't go to waste. You have given me valuable information that I can google to learn more. |
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-21 by @allObjects Give this code a try... I used emulation code to emulate the i2c / sensor and embedded it all into an html. You can run it right off the link of the uploaded/download file. If opened in Chrome and inspected, you should get about the the same view as attached when clicking the buttons init(), logStatus(), and readTemp(). The AtlasSensor code is based on your initial code that extracts the commands into command specifications. I used longer variable names than usual for documentation purposes and added also some comments.
Executed as part of the test code in Espruino html emulation, the delay of 0.300 seconds in the response is clearly noticeable. The emulation code (embedded into html to run in browser):
Now it is your turn to add the calibration command implementation... You may have noticed that all requests go into a queue to make sure the writes and reads are nicely paired. This queuing allows to place multiple requests in a row without having to worry about timings. For cascading and combination with other sensors that need values from other sensors, callback implementation gets cumbersome; a promise implementation would look much cleaner.Attachments: |
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-26 by d0773d @allObjects I haven't forgotten the help you have given me so far. My day time job is consuming most of my time ATM - it's that time for the holiday season :-/ I'm hoping in the next few days I will give your example code a try on the Espruino. I will for sure respond back. |
Beta Was this translation helpful? Give feedback.
-
Posted at 2016-11-27 by @allObjects @d0773d, np, the sample code was just to fly a bit lower than WAY over the head. Enjoy your day time job (a year ago we worked in shifts to make sure that the 'colored days' went well... and they did: scaling almost 30-fold without a hick up - with same hardware but different delivering and caching strategies - all switchable at runtime. Begin started in the East with a wave all the way thru the West and beyond. It was fascinating to see the architectural work bearing fruit... - Anyway, looking forward to your experience with the code. Take you time - forum will not go away... nor does Espruino. ;<)> |
Beta Was this translation helpful? Give feedback.
-
Posted at 2018-07-08 by d0773d @allObjects howdy. It has been awhile since I updated my status on this project/your code. Turns out, the PH sensor that I am using from atlas-scientific is a bit older and buggy which in turn doesn't give me proper readings so I resorted to checking my water ph using the old fashioned method i.e. using the General Hydroponics Test Kit solution. I guess doing things the "old fashioned" way gets the job done :-) Now, I'm looking for another project for the espruino. |
Beta Was this translation helpful? Give feedback.
-
Posted at 2018-07-08 by @allObjects @d0773d , nice to hear back from you. Sad for all the efforts you did put in and the hope to get something done a great way... Sometimes we get things sold that do not exactly what they should and support / updates are just not available. What I can ensure you though is, that Espruino is a very bright light in the darkness of all the (s)crap sold on the internet and otherwise. May be a different, newer version or even a different product for ph sensing could have helped over the hump and over the finish line. I'm glad you go for another project with Espruino. I'm curious what it is all about... if not in public forum post, then in a personal forum message. |
Beta Was this translation helpful? Give feedback.
-
Posted at 2018-07-16 by d0773d @allObjects greetings, I sent you a pm.. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Posted at 2016-11-10 by d0773d
My goal is to calculate sensor readings and then save them to a JSON object then console.log output a specific value. I'm not sure why I'm not able to access my json value. I keep getting error:
code:
Beta Was this translation helpful? Give feedback.
All reactions