Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Now we will add a REST Server interface, allowing you to control any device via the LAN using HTTP.
This will allow us to use other programming languages such as HTML5 / JS to control the devices.

...

addInput(Connections.in.rest(8181));

 

Now your computer will become a server, allowing other computers on the local network send commands to the arduino / similar

Tip

You could use the "RaspberryPI" as Server

 

Complete source

Code Block
import br.com.criativasoft.opendevice.core.SimpleDeviceManager;
import br.com.criativasoft.opendevice.core.connection.Connections;
import br.com.criativasoft.opendevice.core.model.Device;
import br.com.criativasoft.opendevice.core.model.DeviceListener;
import br.com.criativasoft.opendevice.core.model.DeviceType;

public class RestControlDemo extends SimpleDeviceManager implements DeviceListener {
    public static void main(String[] args) throws Exception {
        new RestControlDemo();
    }
    public RestControlDemo() throws Exception {
        Device led = new Device(1, DeviceType.DIGITAL);
        // setup connection with arduino/hardware
        addOutput(Connections.out.usb()); // Connect to first USB port available
        // Configure a Rest interface for receiving commands over HTTP
        addInput(Connections.in.rest(8181));
        addListener(this); // monitor changes on devices
        connect();
        addDevice(led);
    }
    // ------------- DeviceListener Impl --------------------------
    // ------------------------------------------------------------
    @Override
    public void onDeviceChanged(Device device) {
        System.out.println("DeviceChanged = " + device);
    }

}

 

Add Dependency:

Code Block
languagexml
titlepom.xml
		<dependency>
			<groupId>br.com.criativasoft.opendevice</groupId>
			<artifactId>opendevice-rest-ws-server</artifactId>
			<version>${opendevice-version}</version>
		</dependency>		

 

 

Run the class and and open your browser in:

...

addOutput(Connections.out.usb("/dev/ttyACM0"));
addOutput(Connections.out.usb("/dev/ttyACM1"));
addOutput(Connections.out.bluetooth("001303141907"));
addOutput(Connections.out.tcp("192.168.0.204:8081")); 

 

Here's an example of how to use JQuery to control devices: 

 

The REST connection has a simple http server for static pages, you can add the directories that will be available from this server.

 

Info
The examples and code used in this tutorial can be found here:
https://github.com/OpenDevice/OpenDevice/tree/master/examples/opendevice-tutorial

 

 

See next stepBluetooth Connection