Reading sensor values input to blockly

567 views
Skip to first unread message

pratika jain

unread,
Apr 10, 2019, 12:34:10 PM4/10/19
to Blockly
Hi ,

I am reading sensor values and if it is true , i want to execute a set of blocks.

I have created custom block to read value. please help where i am going wrong..I am new to blockly.

It reads value and even if condition is correct, it doesnot execute the next statements.

Blockly.defineBlocksWithJsonArray([   
{
  "type": "event_name",
  "message0": "%1",
  "args0": [
    {
      "type": "field_dropdown",
      "name": "logic",
      "options": [
        [
          "face obstacle",
          "true"
        ],
        [
          "faces no obstacle",
          "false"
        ]
]
    }
  ],
  "output": "Boolean",
  "colour": 230,
  "tooltip": "",
  "helpUrl": ""
}
]);

Blockly.JavaScript['event_name'] = function(block) {
var value1 = {valueV:0};
  value1.valueV = 'false';
  var dropdown_logic = block.getFieldValue('logic');
  value1.valueV = dropdown_logic;
  
  var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.particle.io/v1/devices/" + 'DEVICEID' + "/sensor_value/?access_token=ACCESSTOKEN",
"method": "GET",
"headers": {}
}
$.ajax(settings).done(function (response) {
var flag = {flagF:0};
flag.flagF = 0;
var inputY = response.result;
alert(inputY);
if (inputY == 1) {inputY ='false'}
else if(inputY == 0) {inputY='true'}
alert(inputY);
flag.flagF = inputY;
alert(flag.flagF);
if (value1.valueV == flag.flagF)
 {
alert("Equal to sensorrrr");
 
     value1.valueV = true;
 
}
 
else {
alert("in else")
value1.valueV = false;
}
});
  
 var code =value1.valueV;
 //alert(code);
  return code;
};


Blockly.png

Coda Highland

unread,
Apr 10, 2019, 2:49:46 PM4/10/19
to blo...@googlegroups.com
The core of your issue is that it's an async request and by default Blockly expects blocks to be synchronous.

There's a way around this but it depends on if you're using Blockly in interpreted mode, if you're using the JS sandbox, or if you're generating and running code directly. (And, if the last one, what environment you're targeting.)

/s/ Adam

--
You received this message because you are subscribed to the Google Groups "Blockly" group.
To unsubscribe from this group and stop receiving emails from it, send an email to blockly+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

pratika jain

unread,
Apr 10, 2019, 3:01:30 PM4/10/19
to Blockly
Hi Adam,
Thanks for your reply..

I am directly running code. Presently I am working
On Dev box only.
I have made a block on blockly developer tool. I am not sure if block config is correct to accept the output to if conditions.. And proceed to next statement in do. How can it be done.

Please give inputs.

Coda Highland

unread,
Apr 10, 2019, 3:22:21 PM4/10/19
to blo...@googlegroups.com
By environment, I meant if you're working in Node.JS or in the browser, and which browsers you need to support.

The absolute easiest way to do it would be to use the `await` JS keyword and stick the code from the code generator into an `async` function. This works in any browser released since mid-2017, and I think Node 10 supports it. In order to use `await`, though, you need to be using Promises.

The simplest way to do THAT is by using fetch() instead of $.ajax(), but that runs into CORS issues, so it might prove to be easier to wrap your code in a promise yourself.

/s/ Adam

pratika jain

unread,
Apr 10, 2019, 11:58:38 PM4/10/19
to blo...@googlegroups.com
Hi Adam,

I will try out the options suggested.
Will get back to you post trying.

It would be great, if you can share some code snippets. 

Thanks. 

Coda Highland

unread,
Apr 11, 2019, 11:29:11 AM4/11/19
to blo...@googlegroups.com
async function runProgram() {
  window.alert(await new Promise(resolve => {
    $.ajax({
      url: "whatever",
      success: resolve,
    })
  }))
}

runProgram().then(() => {
  /* if you need to know when it's done, do it here */
})

The stuff inside of `runProgram` is the generated Blockly code. The subsequent call is an example of how to call the function you created.  The `await new Promise` expression is what the code generator for your sensor block would return.

This example is just using the default "print" block and attaching your sensor block to it.

/s/ Adam

pratika jain

unread,
Apr 13, 2019, 8:53:41 AM4/13/19
to Blockly
Hi Adam,

Thanks a lot for code snippet.
I tried its not working for me, not sure where i am going wrong.

My block is this one:
I am getting sensor value and comparing it if true..i want to run next blocks stacked else no action.
I am using particle photon to read sensor value through api in blockly.
I created block in block factory .

Blockly.defineBlocksWithJsonArray([   
{
  "type": "event_name",
  "message0": "%1",
  "args0": [
    {
      "type": "field_dropdown",
      "name": "logic",
      "options": [
        [
          "face obstacle",
          "true"
        ],
        [
          "faces no obstacle",
          "false"
        ]
]
    }
  ],
  "inputsInline": true,
   "output": "Boolean",
  "colour": 230,
  "tooltip": "",
  "helpUrl": ""
}
]);
Blockly.JavaScript['event_name'] = function(block) {
var value1 = {valueV:0};
  value1.valueV = 'false';
  var dropdown_logic = block.getFieldValue('logic');
  value1.valueV = dropdown_logic;
  
 
  
  var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.particle.io/v1/devices/" + 'DEVICEID' + "/sensor_value/?access_token=ACCESS_TOKEN",
"method": "GET",
"headers": {}
}
$.ajax(settings).done(function (response) {
var flag = {flagF:0};
flag.flagF = 0;
var inputY = response.result;
alert(inputY);
if (inputY == 1) {inputY ='false'}
else if(inputY == 0) {inputY='true'}
alert(inputY);
flag.flagF = inputY;
alert(flag.flagF);
if (value1.valueV == flag.flagF){
  alert("Equal to sensorrrr");
alert(value1.valueV);
document.myForm.action = 'https://api.particle.io/v1/devices/' + 'DEVICEID' + '/led'
    document.all.mySend.value = document.myForm.action 
    alert("Actions");
    document.myForm.submit();
  }
 
else {
alert("in else")
value1.valueV = false;
var code =value1.valueV;
}
});
  
 var code =value1.valueV;
 return [code,Blockly.JavaScript.ORDER_NONE];
};

--------------It should be changed like this?

async function runProgram() {
  window.alert(await new Promise(resolve => {
    $.ajax({
      url: "https://api.particle.io/v1/devices/" + 'DEVICEID' + "/sensor_value/?access_token=ACCESS_TOKEN",
      success: resolve,
    })
  }))
}

runProgram().then(() => {

if (value1.valueV == flag.flagF){
   alert("Equal to sensorrrr");
 alert(value1.valueV);
document.myForm.action = 'https://api.particle.io/v1/devices/' + 'DEVICEID' + '/led'
    document.all.mySend.value = document.myForm.action 
    alert("Actions");
    document.myForm.submit();
     }
 
else {
alert("in else")
value1.valueV = false;
var code =value1.valueV;
}
});
  
 var code =value1.valueV;
 return [code,Blockly.JavaScript.ORDER_NONE];


  /* if you need to know when it's done, do it here */
})

Please correct me..!!











On Thursday, 11 April 2019 20:59:11 UTC+5:30, Coda Highland wrote:
async function runProgram() {
  window.alert(await new Promise(resolve => {
    $.ajax({
      url: "whatever",
      success: resolve,
    })
  }))
}

runProgram().then(() => {
  /* if you need to know when it's done, do it here */
})

The stuff inside of `runProgram` is the generated Blockly code. The subsequent call is an example of how to call the function you created.  The `await new Promise` expression is what the code generator for your sensor block would return.

This example is just using the default "print" block and attaching your sensor block to it.

/s/ Adam

On Wed, Apr 10, 2019 at 10:58 PM pratika jain <pratik...@gmail.com> wrote:
Hi Adam,

I will try out the options suggested.
Will get back to you post trying.

It would be great, if you can share some code snippets. 

Thanks. 

On Thu 11 Apr, 2019, 12:52 AM Coda Highland, <chig...@gmail.com> wrote:
By environment, I meant if you're working in Node.JS or in the browser, and which browsers you need to support.

The absolute easiest way to do it would be to use the `await` JS keyword and stick the code from the code generator into an `async` function. This works in any browser released since mid-2017, and I think Node 10 supports it. In order to use `await`, though, you need to be using Promises.

The simplest way to do THAT is by using fetch() instead of $.ajax(), but that runs into CORS issues, so it might prove to be easier to wrap your code in a promise yourself.

/s/ Adam

On Wed, Apr 10, 2019 at 2:01 PM pratika jain <pratik...@gmail.com> wrote:
Hi Adam,
Thanks for your reply..

I am directly running code. Presently I am working
On Dev box only.
I have made a block on blockly developer tool. I am not sure if block config is correct to accept the output to if conditions.. And proceed to next statement in do. How can it be done.

Please give inputs.

--
You received this message because you are subscribed to the Google Groups "Blockly" group.
To unsubscribe from this group and stop receiving emails from it, send an email to blo...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Blockly" group.
To unsubscribe from this group and stop receiving emails from it, send an email to blo...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Blockly" group.
To unsubscribe from this group and stop receiving emails from it, send an email to blo...@googlegroups.com.

Massimo CodemotionKIDS

unread,
Apr 13, 2019, 4:20:51 PM4/13/19
to Blockly
Hi Pratika,

I think you should use the JS Interpreter in order to achieve what you are looking for. It looks a bit complicated at the beginning but you'll gain much more control on execution of your code!


Your should be able to wait for results from your sensor function using, as Adam pointed out, an asynchronous function like in this example:


In the source code you'll find a wait_seconds block definition and there it is the solution:


Blockly.JavaScript.addReservedWords('waitForSeconds');


 
var wrapper = interpreter.createAsyncFunction(
   
function(timeInSeconds, callback) {
     
// Delay the call to the callback.
      setTimeout
(callback, timeInSeconds * 1000);
   
});
  interpreter
.setProperty(scope, 'waitForSeconds', wrapper);

As you can see instead of interpreter.createNativeFunction() it uses interpreter.createAsyncFunction() and that's the key!

I really think that if you are dealing with sensors and such things you must use the interpreter. I never tried using it when returning a value but probably you can call the callback function (the parameter passed to the function used to trigger the interpreter to go on in its running) when your ajax call is done.

I hope this help.

Happy Hacking,
Massimo

Coda Highland

unread,
Apr 13, 2019, 8:18:14 PM4/13/19
to blo...@googlegroups.com
Yes, switching to using JS Interpreter would definitely make this kind of thing more straightforward, but I don't have any firsthand experience with it while I DO have firsthand experience with async/await. I would advise going with that route because you'll have a lot more community support that way.

Regarding the async function, it appears you've misunderstood what I was saying: After you generate JS code from your Blockly code, that generated code needs to be wrapped inside of "async function runProgram", which you then invoke with the example call I put below it.

Another thing I would recommend, regardless of which technique you use, is to wrap all of this code in a function, so that the code generator can output a simple function call. After all, a block that returns a value needs to generate code in the form of a JS expression. Using async/await, this worker function would be called as "await getSensor()" or something, and its implementation would "return new Promise" as the sample i showed you before. Using JS Interpreter, the worker function would need to accept a callback parameter.

/s/ Adam


--
You received this message because you are subscribed to the Google Groups "Blockly" group.
To unsubscribe from this group and stop receiving emails from it, send an email to blockly+u...@googlegroups.com.

pratika jain

unread,
Apr 15, 2019, 1:03:57 PM4/15/19
to Blockly
Hi Adam and Massimo,

Thank you so much for your suggestions,

Now my concern is how to use the methods (blocks which were using eval ).since now its getting stuck for them.
The block gets highlighted and no processing after that.

The delay is working fine in js interpreter.
Is there a way so that i can incorporate both? if not how to make blocks made with eval work with js interpreter.

Thanks in advance!
Pratika





On Sunday, 14 April 2019 05:48:14 UTC+5:30, Coda Highland wrote:
Yes, switching to using JS Interpreter would definitely make this kind of thing more straightforward, but I don't have any firsthand experience with it while I DO have firsthand experience with async/await. I would advise going with that route because you'll have a lot more community support that way.

Regarding the async function, it appears you've misunderstood what I was saying: After you generate JS code from your Blockly code, that generated code needs to be wrapped inside of "async function runProgram", which you then invoke with the example call I put below it.

Another thing I would recommend, regardless of which technique you use, is to wrap all of this code in a function, so that the code generator can output a simple function call. After all, a block that returns a value needs to generate code in the form of a JS expression. Using async/await, this worker function would be called as "await getSensor()" or something, and its implementation would "return new Promise" as the sample i showed you before. Using JS Interpreter, the worker function would need to accept a callback parameter.

/s/ Adam


To unsubscribe from this group and stop receiving emails from it, send an email to blo...@googlegroups.com.

Erik Pasternak

unread,
Apr 15, 2019, 2:05:54 PM4/15/19
to Blockly
Hi Pratika,

I think you may be working from a misunderstanding of how generators are used. The generator is designed to be run once on the blocks and spit out a text program that can be run multiple times. It looks like instead you're doing async checks in the generator itself to decide if a branch is true or false and generating 'true'/'false'. This means if you ran the generated code more than once the value would never change.

Instead, you should generate a string of code that performs the sensor reading (but not run it) and return that string of code from the generator. That code can then be run in the JS Interpreter using an async wrapper.

If you haven't before, you should also go through the Blockly CodeLab which walks you through setting up Blockly for the first time and creating some custom blocks.

Cheers,
Erik

pratika jain

unread,
Apr 16, 2019, 2:37:50 AM4/16/19
to Blockly
Thanks Erik,

I am trying as per your suggestion.
can you please guide me, regarding this block in screenshot as why the function name is not getting inside the if condition. :(

The Block defination is this:

Blockly.defineBlocksWithJsonArray([   
{
  "type": "event_name",
  "message0": "%1",
  "args0": [
    {
      "type": "field_dropdown",
      "name": "logic",
      "options": [
        [
          "face obstacle",
          "true"
        ],
        [
          "faces no obstacle",
          "false"
        ]
]
    }
  ],
  "inputsInline": true,
  "nextStatement": null,
  "output": "Boolean",
   "colour": 230,
  "tooltip": "",
  "helpUrl": ""
}
]);

which parameter is incorrect in this?

Thanks,
Pratika
Block.png

Erik Pasternak

unread,
Apr 16, 2019, 12:37:49 PM4/16/19
to Blockly
Hi Pratika,

It's your generator, not your block definition that is the problem.

The generator should be returning a string like 'getSensorValue()' where getSensorValue is declared as a function that makes the request to the sensor and returns the result. Here's a rough example that you'll need to modify to fit your use case.

Blockly.JavaScript['get_sensor_value'] = function(block) {
  var value1 = {valueV:0};
  var dropdown_logic = block.getFieldValue('logic');
  var code;

  if (dropdown_logic == 'NO_OBJECT') {
    code = 'getSensorValue() == 0';
  } else if (dropdown_logic == 'SENSOR_VALUE') {
    code = 'getSensorValue()';
  }
  
 return [code,Blockly.JavaScript.ORDER_NONE];
};

It can then be wrapped as an async function (as below) for use in the JS Interpreter or you can return 'await getSensorValue()' instead if you want to run it synchronously using eval().

    var wrapper = function(callback) {
      new Promise(function(callback) {
        $.ajax({
          url: "https://api.particle.io/v1/devices/" + 'DEVICEID' + "/sensor_value/?access_token=ACCESS_TOKEN",
          success: callback,
        });
    };
    interpreter.setProperty(scope, 'getSensorValue',
        interpreter.createAsyncFunction(wrapper));

pratika jain

unread,
Apr 17, 2019, 2:40:45 PM4/17/19
to Blockly
Hi Erik,

Thank you so much, for explanation in detail.
I tried the way you suggested. Troubling you again :(

..............I changed it like :

Blockly.JavaScript['event_name'] = function(block) {
  var dropdown_logic = block.getFieldValue('logic');
 
  
  if (dropdown_logic == 'false') {
    var code = 'getSensorValue() == 1';
  } else if (dropdown_logic == 'true') {
    var code = 'getSensorValue()==0';
  }
  
 return [code,Blockly.JavaScript.ORDER_NONE];
};

...............Created getSensorValue function:

function getSensorValue(){
window.alert("IN");

var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.particle.io/v1/devices/" + "DEVICEID" + "/sensor_value/?access_token=ACCESS_TOKEN",
"method": "GET",
"headers": {}
}
$.ajax(settings).done(function (response) {
var inputY = response.result;
alert("IN setting");
alert(inputY);
flag.flagF=inputY;
});
alert(flag.flagF);
return flag.flagF;
};

......................Changes in wrapper function
 alert(interpreter.value);
var wrapper = function(callback) {
      new Promise(function(callback) {
        $.ajax({
          url: "https://api.particle.io/v1/devices/" + 'DEVICEID' + "/sensor_value/?access_token=ACCESS_TOKEN",
          success: callback,
        });
    };
    interpreter.setProperty(scope, 'getSensorValue',
        interpreter.createAsyncFunction(wrapper));
    
}

but its not working .

It should be inside this function ,correct?
function initApi(interpreter, scope)

The wrapper not working ,i added the code where other wrapper functions are placed, but the toolbox is getting removed.

Also the getSensorValue is not getting calculated, Ideally it should calculate here ..correct?
var code = 'getSensorValue() == 1';

I created a button to get value from this function, But there i get result. 
Please see screenshot once..I have attached 2 screenshots.

Thanks in advance
Pratika
sensor.png
error.png

Erik Pasternak

unread,
Apr 17, 2019, 3:30:28 PM4/17/19
to Blockly
So the JS-interpreter is going to call the wrapper function, not the other function you created. At this point you'll need to debug the wrapper function until it does what you want. You can try calling it with a callback and logging the result directly:

var callback = function(result) {
  console.log(result);
}

wrapper(callback);

Or you can add console logs into the wrapper function directly. When you're using the interpreter the wrapper function is being mapped to the name you passed to interpreter.setProperty and any other functions outside the interpreter's scope won't exist.

You received this message because you are subscribed to a topic in the Google Groups "Blockly" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/blockly/W8r5p5qcqKM/unsubscribe.
To unsubscribe from this group and all its topics, send an email to blockly+u...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.


--
Erik Pasternak | Unblocker | epas...@google.com     

pratika jain

unread,
Apr 18, 2019, 1:14:57 PM4/18/19
to Blockly
Hi Erik,

Can you please help me with one complete sample of block , generated code and interpreter code for calling external api. (https request)

I am basically enabling a led of photon , if a sensor faces an obstacle. 
Using eval i was doing it this way.

if (myValue == 'green'){
document.all.myParameter.value='green'
document.myForm.action = 'https://api.particle.io/v1/devices/' + deviceID + '/led'
    document.all.mySend.value = document.myForm.action 
          alert("Show green");
document.myForm.submit();
alert("Showing green");
}

It a POST method.
I had to do both actions.GET and POST in my project.

Thanks in advance!!
Pratika



On Thursday, 18 April 2019 01:00:28 UTC+5:30, Erik Pasternak wrote:
So the JS-interpreter is going to call the wrapper function, not the other function you created. At this point you'll need to debug the wrapper function until it does what you want. You can try calling it with a callback and logging the result directly:

var callback = function(result) {
  console.log(result);
}

wrapper(callback);

Or you can add console logs into the wrapper function directly. When you're using the interpreter the wrapper function is being mapped to the name you passed to interpreter.setProperty and any other functions outside the interpreter's scope won't exist.

To unsubscribe from this group and all its topics, send an email to blo...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.


--
Erik Pasternak | Unblocker | epas...@google.com     

Erik Pasternak

unread,
Apr 18, 2019, 1:20:09 PM4/18/19
to Blockly
Hi Pratika,

The Async demo from the JS-Interpreter is a complete demo showing all of those things. I'm sorry, but we're not able to provide you complete working code for your specific case. 

To unsubscribe from this group and all its topics, send an email to blockly+u...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

pratika jain

unread,
Apr 25, 2019, 11:52:18 AM4/25/19
to Blockly
Hi Erik,

I understand that.

I have created a async method as you suggested.

async function fetchSensorValue() {

  const data = await res.json();
  const sensor_value = data.result;
  
}

i have mentioned it initApimethod for js  interpreter:

var wrapper = function() {
        //myValue = myValue ? myValue.toString() : '';
        return interpreter.createPrimitive(fetchSensorValue());
      };
      interpreter.setProperty(scope, 'fetchSensorValue',
          interpreter.createPrimitive(wrapper));

and block defination is this:

Blockly.JavaScript['event_name'] = function(block) {
 
 
  if (dropdown_logic =='0') {

   var code = "fetchUsers() == 0";
  
  } else if (dropdown_logic == '1'){
  
  var code = "fetchUsers() == 1";
  
  }
  

 return [code,Blockly.JavaScript.ORDER_NONE];
};

Can you please correct me.

how to get fetchSensorValue  value in a variable, outside its method defination, can you plz guide.

On Thursday, 18 April 2019 22:50:09 UTC+5:30, Erik Pasternak wrote:
Hi Pratika,

The Async demo from the JS-Interpreter is a complete demo showing all of those things. I'm sorry, but we're not able to provide you complete working code for your specific case. 

pratika jain

unread,
Apr 25, 2019, 11:57:32 AM4/25/19
to Blockly
Hi Erik,

I understand that.

I have created a async method as you suggested.

async function fetchSensorValue() {

  const data = await res.json();
  const sensor_value = data.result;
  
}

i have mentioned it initApimethod for js  interpreter:

var wrapper = function() {
        //myValue = myValue ? myValue.toString() : '';
        return interpreter.createPrimitive(fetchSensorValue());
      };
      interpreter.setProperty(scope, 'fetchSensorValue',
          interpreter.createPrimitive(wrapper));

and block defination is this:

Blockly.JavaScript['event_name'] = function(block) {
 
 
  if (dropdown_logic =='0') {

   var code = "fetchSensorValue() == 0";
  
  } else if (dropdown_logic == '1'){
  
  var code = "fetchSensorValue() == 1";
  
  }
  

 return [code,Blockly.JavaScript.ORDER_NONE];
};

Can you please correct me.

how to get fetchSensorValue  value in a variable, outside its method defination, can you plz guide.

Correction :in block defination made just now.


On Thursday, 18 April 2019 22:50:09 UTC+5:30, Erik Pasternak wrote:
Hi Pratika,

The Async demo from the JS-Interpreter is a complete demo showing all of those things. I'm sorry, but we're not able to provide you complete working code for your specific case. 

Erik Pasternak

unread,
Apr 25, 2019, 12:19:01 PM4/25/19
to Blockly
Alright, let's walk through your code and describe what each part is doing. =)

// This declares the function fetchSensorValue and tells JS that it is async, so it returns a Promise immediately, but not a final result.
async function fetchSensorValue() {
  // This waits until the fetch completes and returns a value, which is assigned to res
  // This gets the json blob from the result and assigns it to data, which is a synchronous call so await isn't necessary.
  const data = await res.json();
  // This gets the result field from the json data and assigns it to sensor value
  const sensor_value = data.result;
  // Nothing is returned via the implicit Promise.
}

// This creates a wrapper function that can be used by the JS interpreter.
var wrapper = function() {
        //myValue = myValue ? myValue.toString() : '';
        // This says, return a new primitive which is the result of calling fetchSensorValue().
        // fetchSensorValue() returns a Promise, so this returns a wrapped Promise that never gets a value.
        // interpreter.createPrimitive is used to create functions for the Interpreter that just returns the object, so this is returning a function that if called returns a Promise that is never given a value.
        return interpreter.createPrimitive(fetchSensorValue());
      };

// This is creating a function in the interpreter's scope called 'fetchSensorValue' that when called will return the wrapper function.
// Again, createPrimitive(x) returns a function that just returns x when called.
// So when the interpreter tries to call fetchSensorValue() it will get back the wrapper function.
interpreter.setProperty(scope, 'fetchSensorValue',
          interpreter.createPrimitive(wrapper));


What you want to do instead is
  • Create a wrapper that does the fetch and returns the data.result.
  • Create an asycnFunction from the wrapper using interpreter.createAsyncFunction and add it as a property with the name 'fetchSensorValue' to the interpreter.

Erik Pasternak

unread,
Apr 25, 2019, 12:22:22 PM4/25/19
to Blockly
Correction, the wrapper function shouldn't return the result, it should take a callback and call the callback with the result when it's ready: eg. 'callback(data.result)'

pratika jain

unread,
Apr 25, 2019, 1:12:22 PM4/25/19
to blo...@googlegroups.com
Thanks for explaination Erik,
I am totally new to interpretor.. Can you give lil more elaboration where I should have used callback for js interpretor. 

One clarification.. FetchSensorValue method should 

Return sensor_value ;

Thanks & Regards
Pratika

To unsubscribe from this group and stop receiving emails from it, send an email to blockly+u...@googlegroups.com.

Erik Pasternak

unread,
Apr 25, 2019, 1:23:53 PM4/25/19
to Blockly
Anytime you're wrapping a function that takes more than a few ms you should use a callback and wrap it as an AsyncFunction.

To unsubscribe from this group and all its topics, send an email to blockly+u...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

pratika jain

unread,
Apr 30, 2019, 1:14:15 PM4/30/19
to Blockly
Hi Erik,

Thanks you so much for your continuous support...
 
I am struggling a lot with this now. :(:(
please tell me what can be done here. 
code:

async function getSensorValue(myValue){
window.alert("IN");
try{
  
   

  const data = await res.json();
  var sensor_value = data.result;
  window.alert(myValue);
window.alert(data.result);
 callback(data.result);
var answer = data.result;
var abc = myValue;
var zero = '0';
var one = '1';
  
if((abc === zero) && (answer === zero)){
return 1;
}
else if((abc === one) && (answer === one)){
 return 0;
}
} catch (err) {
       console.log(err);
alert(err);
     }
}


Or this function:


  //add an API funtion for async
   var wrapper = function(href, callback) {
        var req = new XMLHttpRequest();
req.timeout = 5000;
        req.onreadystatechange = function() {
          if (req.readyState == 4 && req.status == 200) {
alert(req.responseText[50]);
            callback(req.responseText);
          }
          };
        req.send();
      };
      interpreter.setProperty(scope, 'getXhr',
          interpreter.createAsyncFunction(wrapper));

I want to compare sensor value to dropdown value , then if they are equal i want to run below blocks...else no...

With of them i am not able to get the return value in generator function , and irrespective of sensor values..its running below blocks.

Blockly.defineBlocksWithJsonArray([   
{
  "type": "event_name",
  "message0": "%1",
  "args0": [
    {
      "type": "field_dropdown",
      "name": "logic",
      "options": [
        [
          "face obstacle",
          "0"
        ],
        [
          "faces no obstacle",
          "1"
        ]
]
    }
  ],
  "inputsInline": true,
   "output": "Boolean",
  "colour": 230,
  "tooltip": "",
  "helpUrl": ""
}
]);

Blockly.JavaScript['event_name'] = function(block) {
  var dropdown_logic = block.getFieldValue('logic');
  
 
  if (dropdown_logic == '0') {
  //var abc = getSensorValue();
  
   var code = 'getSensorValue('+dropdown_logic+')';
   
  } else if (dropdown_logic == '1'){
  
  var code = 'getSensorValue('+dropdown_logic+')';
  
  }
  

 return [code,Blockly.JavaScript.ORDER_NONE];
};

Please help me correcting code..

Thanks a lott in advance.
Pratika.


On Thursday, 25 April 2019 22:53:53 UTC+5:30, Erik Pasternak wrote:
Anytime you're wrapping a function that takes more than a few ms you should use a callback and wrap it as an AsyncFunction.

Erik Pasternak

unread,
Apr 30, 2019, 1:21:58 PM4/30/19
to Blockly
Hi Pratika,

I think we're reaching the limit of how much I can help over email. If possible, I'd really recommend finding a friend or someone else who is comfortable with code that can sit down and talk it through with you.

Good luck and sorry I can't be of more help.

-Erik

To unsubscribe from this group and all its topics, send an email to blockly+u...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

pratika jain

unread,
Apr 30, 2019, 1:35:36 PM4/30/19
to blo...@googlegroups.com
Hi Erik,

Yes.. I think you are right... 
Can you please guide me some online course. 
Where I can understand topics in depth. 

Thanks in advance. 
Pratika


To unsubscribe from this group and stop receiving emails from it, send an email to blockly+u...@googlegroups.com.

Erik Pasternak

unread,
Apr 30, 2019, 2:44:03 PM4/30/19
to Blockly
Khan Academy has some good CS courses. It's also a non-profit so they provide all of their courses for free.
Reply all
Reply to author
Forward
0 new messages