Recent changes
Slingshot user guide
tag Guide, user
NFCLamp user guide
tag Guide, user
Homepage
MPL115A2
Compiler Error 42
From the mbed microcontroller Cookbook.  

Interfacing with JavaScript

The mbed HTTP Server makes it easy to get mbed up and running on a network. However a webserver on its own is only good for serving web pages, whereas mbed is great for interacting with the outside world through actuators and sensors. To make your web pages interactive you can make use of the RPC handler which allows you to use RPC to control the mbed using HTTP requests. This means you can use web pages to provide a GUI for your project which can be accessed from anywhere on your network. To make your webpages dynamic you could use Java or JavaScript. Here is a JavaScript library which makes it easy to send RPC requests over HTTP from your webpage and maps many of the mbed interface classes onto JavaScript classes. This means that for some projects you may not need to write any custom code for mbed.

HTTP Server

To use the JavaScript Library on this page your mbed needs to be running a HTTP Server program. A HTTP server program modified to fully support RPC can be found on the Interfacing Using RPC page. You can find more information about how to connect to a network here.

JavaScript mbedRPC Library

To use this library simply save it to mbed along side the bin and the HTML file which uses it.

Here is an example HTML file which flashes LED1, fades LED3 and prints the analog input at p20 to the screen once a second.

Code

<html>
	<head>
		<script src="mbedRPC.js" language="javascript"></script>
		<script type="text/javascript">
			mbed = new HTTPRPC();
			led1 = new DigitalOut(mbed, LED1);
			ain = new AnalogIn(mbed, p20);	
			led2 = new PwmOut(mbed, LED3);
			function print(str){
  				document.getElementById("t").innerHTML = str;
			}
		</script>
	</head>
	<body>
		<p>mbedRPC javascript example! Using the mbedRPC javascript library to control mbed over http;
		<a href="http://mbed.org/cookbook/Interfacing-using-JavaScript"> for more information goto the cookbook </a>
		<br>
		This script will flash LED1 and read the value of AnalogIn p20 every second
		</p>
		<div id="t"><br/>
		</div>
		<script language="javascript">
			var i = 1;
			var x = 0;
			function tick(){
				led1.write(i);
				if(i == 0){i = 1;
				}else{i = 0;}
				led2.write(x);
				x = x + 0.1;
				if(x >= 1) x = 0;
				f = ain.read();
				print(f);
			}
			setInterval("tick()",1000);			
		</script>
	</body>
</html>

To try this out extract the contents of this zip jsRPCdemo.zip (html file, .bin and javascript library) directly onto mbed, reset and then navigate to http://<address of mbed>/RPCdemo.htm. The example HTTP server programs print out the assigned address over the serial port.

Using the Library

To use the library in your html pages you must first load it in

Code

<script src="mbedRPC.js" language="javascript"></script>

You then need to create an mbed object. You can only create a HTTPRPC connection and only on the mbed that is hosting the javascript.

Code

<script type="text/javascript">
    mbed = new HTTPRPC();
</script>

You can now create objects or tie to existing objects on mbed.

Code

<script type="text/javascript">
    led1 = new DigitalOut(mbed, LED1);
    ain = new AnalogIn(mbed, p20);	
    led2 = new PwmOut(mbed, LED3);
    led3 = new DigitalOut(mbed, "myled");
</script>

Finally you can execute the methods for each of the objects

Code

    led1.write(i);
    f = ain.read();

If your project needs to use more than just Digital and Analog I/O then you can use the RPC Interface Library which is supported by this JavaScript library. This means you can use RPCFunctions or RPCVariables depending on which is most suitable for your application.

Code

RangeFinder = new RPCFunction(mbed, "RangeFinder");
Range = RangeFinder.run("  ");



calendar Page history
Last modified 20 Nov 2010, by   user Michael Walker   tag No tags | 15 comments  

15 comments on Interfacing with JavaScript:

23 Nov 2010

Hi Michael,

You can count me as a newbie for C++ and mbed and I would like to get your opinion how to use RPCVariable in a html code and consuming it in mbed code accordingly. I found some certain usages for RPCFunction but not for RPCVariable. This is the point I need your assistance.

According to my understanding, it must be so;

Javascript Code in a html file:

<<Code>>
<script src="mbedRPC.js" language="javascript"></script>

<script type="text/javascript">
    mbed = new HTTPRPC();
    myObj = new RPCVariable(mbed, "myObj");
    myObj.write("myInput");
</script>
<</Code>>

Mbed Code:

<<Code>>
char myObj;
RPCVariable<char> rpc_myObj(&myObj, "myObj");

printf("My Data: %c\n", myObj)
<</Code>>

You may see in the lines above, I expect to print the "myData" value on the screen using printf.

Can you review my code snippet and tell me why I can't get it working?

Note that: all codings above are compiling succesfully. But no catch for the variable.

23 Nov 2010

Hi

There are a few things that I can see from the snippets you've posted. Firstly char myObj, defines a character, in c++ a string is an array of characters ie char myString[28]. Working with character arrays in C++ can be a bit odd so I suggest you find a tutorial about Strings in C. So the first point is that the RPCVariable won't be able to write "myInput" into a char, myObj can only take values such as 'a'.

The second point is that from your snippet I'm not sure how your program works. Is the printf(...) in a loop of some form. The RPCVariable won't trigger anything when you send to it, it will just change the value of the variable it is attached to in memory. You need to actually call the printf from the code. The RPCFunction on the other hand will actually allow you to exectute code when you call its run method over RPC.

Finally the way the RPC handler on mbed delimits the messages it recevies can make it very difficult to send strings as arguments over RPC, any space or puncutation mark will be interpreted as the end of the argument. However the RPCFunction gets around this as it uses a custom method caller which can only except one argument as a string but will accept spaces and punctuation marks. Perhaps a better approach would be for you to create an RPCFunction and within that function copy the string received (the input value) into your myObj variable (note you'll need to use strcpy) that way you'll be able to send any string.

This page has examples of both the RPCFunction and the RPCVariable in use. http://mbed.org/cookbook/RPC-Interface-Library

23 Nov 2010

Hi Michael,

It is now more clear than ever before. I appreciate your reaction, thank you.

27 Nov 2010

Hi Micheal,

I'm a novice having fun with the mbed. Thank you for your RPC libraries and examples.

I am having difficulty using RPCVariables with Javascript. The screen capture below shows some simple code to read a temperature, and make that temperature availble thru RPC. I am getting compile error 70, "Incomplete type is not allowed", at line 80 of the RPCVariable library.

Any suggestions you may have would be welcome. Thanks!

/media/uploads/RStonebrood/rpc_screen.jpg

27 Nov 2010

Hi

Update the library (in the compiler right click on the library and select update). You might notice all my examples used #include "SerialRPCInterface.h", I'd therefore neglected to include some files actually in RPCVarible.h but I've fixed it now. Sorry about that and thanks for finding that one. Hope it works for you now.

Michael

27 Nov 2010

Michael,

Thanks for updating the library. My code compiled, and RPCVariables are working as expected. I am able to read mbed variables from a browser via HTTP.

This is real quite a powerful tool you developed. Your efforts are greatly appreciated.

Russ

28 Dec 2010

Hi

The last function in "mbedrpc.js" is wrong:

Code

RPCVariable.prototype.run = function(value) { 
   ...

this must be:

Code

RPCFunction.prototype.run = function(value) {
   ...
16 Jan 2011

Michael: when I try ain2 = new AnalogIn(mbed, p21); pinmap issue . Pl.suggest p22,p23...same problem.

16 Jan 2011

Hi Joby,

Remember, AnalogIn can only be used on pins p15-p20. See:

Simon

16 Jan 2011

Thanks simon. That was a stupid mistake though I used analog inputs earlier.

Anyway what I have been trying is as follows. just tried to read two analog inputs and display it on a browser. I dont know what is wrong, when I read any one it displays together it doesnt. I know it is my work to find out. still you may be quicker. The code is as follows RPCdemo.htm

<html> <head>

<script src="mbedRPC.js" language="javascript"></script> <script type="text/javascript">

mbed = new HTTPRPC(); led1 = new DigitalOut(mbed, LED1);

ain1 = new AnalogIn(mbed, p15); ain2 = new AnalogIn(mbed, p16);

led2 = new PwmOut(mbed, LED3);

function print1(str1){ document.getElementById("adc1id").innerHTML = "1="+str1;

}

function print2(str2){

document.getElementById("adc2id").innerHTML = "2="+str2;

}

</script>

</head> <body>

<div id="adc1id" STYLE="font-family: Arial Black; font-size: 24px; color: red">adc1idtext<br/> <div id="adc2id" STYLE="font-family: Arial Black; font-size: 24px; color: red">adc2idtext<br/>

<script language="javascript"> var i = 1; var x = 0; var f1; var f2;

function tick(){ led1.write(i);

if(i == 0){ i = 1; }else{ i = 0; } led2.write(x); x = x + 0.1; if(x >= 1) x = 0;

f1 = ain1.read(); f2 = ain2.read();

print1(f1);

print2(f2);

}

setInterval("tick()",1000); </script> </body> </html>

02 Feb 2011

Hi, I have been trying to repeatedly call an RPCFunction from javascript using a 1s tick. I find that this will run for a few minutes but then my MBED server will lock up, requiring a reset. If I read the analog input instead it will run indefinitely. Has anybody else tried repeatedly calling RPCFunctions ??

Thanks, Pete.

MBED Code as follows:-

Code

#include "mbed.h"
#include "EthernetNetIf.h"
#include "HTTPServer.h"
#include "RPCFunction.h"

EthernetNetIf eth;

HTTPServer svr;

LocalFileSystem fs("webfs");

//Create a function of the required format
void testFunc(char * input, char * output);
//Attach it to an RPC object
RPCFunction rpcTestFunc(&testFunc, "testFunc");

int main() {

  Base::add_rpc_class<DigitalOut>();
  Base::add_rpc_class<PwmOut>();
  Base::add_rpc_class<AnalogIn>();
  
  
  printf("Setting up...\r\n");
  EthernetErr ethErr = eth.setup();
  if(ethErr)
  {
    printf("Error %d in setup.\r\n", ethErr);
    return -1;
  }
  printf("Setup OK\r\n");
  
  FSHandler::mount("/webfs", "/"); //Mount /webfs path on web root path

  svr.addHandler<SimpleHandler>("/hello"); //Default handler
  svr.addHandler<RPCHandler>("/rpc");
  svr.addHandler<FSHandler>("/"); //Default handler

  svr.bind(80);
  
  printf("Listening...\r\n");
    
  Timer tm;
  tm.start();
  //Listen indefinitely
  while(true)
  {
    Net::poll();
    if(tm.read()>.5)
    {
      tm.start();
      printf("alive!\r\n");
    }
  }
  
  return 0;
}

void testFunc(char * input, char * output){
    
    static int toggle=0;
    
    if (toggle != 0)
    {
        sprintf(output, "Hello");
        toggle = 0;
    }
    else
    {
        sprintf(output, "Bye !");
        toggle = 1;
    }
}

Web page as follows:-

Code

<html>
	<head>
		<script src="mbedRPC.js" language="javascript"></script>
		<script type="text/javascript">
			mbed = new HTTPRPC();
			led1 = new DigitalOut(mbed, LED1);
			ain = new AnalogIn(mbed, p20);	
			led2 = new PwmOut(mbed, LED3);
			rpcfunc = new RPCFunction(mbed, "testFunc");
			function print(str){
  				document.getElementById("t").innerHTML = str;
			}
		
		</script>
	</head>
	<body>
		<p>mbedRPC javascript example! 
		<p>Using the mbedRPC javascript library to control mbed over http;
		<a href="http://mbed.org/cookbook/Interfacing-using-JavaScript"> for more information goto the cookbook </a>
		<br>
		This script will flash LED1 and read the value of AnalogIn p20 every second
		</p>
		<div id="t"><br/>
		</div>

		<script language="javascript">
			var i = 1;
			var x = 0;
			function tick(){
				led1.write(i);
				
				if(i == 0){
					i = 1;
				}else{
					i = 0;
				}
				led2.write(x);
				x = x + 0.1;
				if(x >= 1) x = 0;
				// f = ain.read();
				f = rpcfunc.run("  ");
				print(f);
			}

			setInterval("tick()",1000);			
		</script>
	</body>
</html>
28 Feb 2011

hi all, i want to use serial over IP. my data is coming from another microcontroller via serial. can i use RPC's serial function for that ? what should be the procedure ?

11 May 2011

Is it possible to use this library to get values remotely.

EG. I have a web server running my website and would like it to show the values of a remote mbed running the http service.

Is this possible?

24 Nov 2011

Hi there how do i read a variable from a java program e.g. processing over usb to my mbed. I cant seem to find a simple example.

24 Nov 2011

Hi John,

This is the JavaScript page. The Interfacing with Java page should have all the information you need. Theres an example of using the RPC libraries with Processing and an example of using RPC Functions from the RPC Interface Library to interface with a Java Applet (Remote Sensing and Control Demo). The "Communicating with Custom Code" section demonstrates how to use RPCVariables and RPCFunctions.

Please login to post comments.