Skip to end of metadata
Go to start of metadata

You are viewing an old version of this content. View the current version.

Compare with Current View Version History

« Previous Version 7 Next »

Now we will add a REST 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.

It's easy, just add the line below and start playing

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

You could use the "RaspberryPI" as Server

 

Complete source

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:

pom.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:

http://localhost:8181/device/1/value/1

http://localhost:8181/device/1/value/0

This will send the command to turn on/off the device 1 (the LED that is on port 13 of the arduino)

In OpenDevice commands are not tied directly to PIN but the Device ID, allowing you to control multiple Arduino at the same time.

 

To get the value of device:

http://localhost:8181/device/1/value

 

All options of the REST api  can be found at: Rest API

 

You can connect with more devices(like arduino), adding more outputs:

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: 

 

See next stepBluetooth Connection

 

  • No labels