Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions examples/communication/ip/KnockKnockSample/ReadMe.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
Introduction
------------
This sample Java application shows how to connect an Internet radio module
to a web server to send and receive data using the XBee Java Library.

In this example, the server starts a Knock Knock joke and you have to respond
to its messages accordingly to continue the joke.

NOTE: This example uses the Wi-Fi device (WiFiDevice) class, but it can be
applied to other Internet capable XBee device classes such as
CellularDevice.


Files
-----
* com.digi.xbee.api.knockknock.MainApp.java:
Main application class. It starts the web server, instantiates a Wi-Fi
device and establishes a serial connection with it. Then, starts the
communication with the server by sending an empty message.

* com.digi.xbee.api.knockknock.WebServer.java:
Class that creates a web server and listens for incoming messages. It uses
the KnockKnockProtocol to parse the message and generate the response.

* com.digi.xbee.api.knockknock.KnockKnockProtocol.java:
Class that generates a response based on the input message following the
Knock Knock jokes.


Requirements
------------
To run this example you will need:

* One XBee Wi-Fi radio in API mode and its corresponding carrier board (XBIB
or equivalent).
* The XCTU application (available at www.digi.com/xctu).


Example setup
-------------
1) Plug the Wi-Fi radio into the XBee adapter and connect it to your
computer's USB or serial port.

2) Ensure that the module is in API mode and connected to the same network
as your computer.
For further information on how to perform this task, read the
'Configuring Your XBee Modules' topic of the Getting Started guide.

3) Set the port and baud rate of the XBee radio in the MainApp class.
If you configured the module in the previous step with the XCTU, you
will see the port number and baud rate in the 'Port' label of the device
on the left view.


Running the example
-------------------
First, build and launch the application. When the application starts, it
connects to the web server and sends an empty message to start the
communication. You will receive the following message through the standard
output:

Knock! Knock!

You have to respond typing the following text:

Who's there?

The server then responds with the clue:

Turnip

Now, repond with:

Turnip who?

Finally the server responds with the punch line. You can continue with more
jokes by sendind a 'y' or finishing the connection with 'n' and then 'Bye.'.
50 changes: 50 additions & 0 deletions examples/communication/ip/KnockKnockSample/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.digi.xbee</groupId>
<artifactId>xbjlib-parent</artifactId>
<version>1.1.1</version>
<relativePath>../../../pom.xml</relativePath>
</parent>
<artifactId>knock-knock-sample</artifactId>
<packaging>jar</packaging>

<name>Knock Knock Sample</name>

<properties>
<rxtx.native.libs.dir>rxtx-native-libs</rxtx.native.libs.dir>
</properties>

<build>
<sourceDirectory>src</sourceDirectory>
<directory>../../../target/examples/communication/ip/KnockKnockSample</directory>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec.maven.version}</version>
<configuration>
<executable>java</executable>
<arguments>
<argument>-Djava.library.path=${project.build.directory}/../../../${rxtx.native.libs.dir}</argument>
<argument>-classpath</argument>
<!-- automatically creates the classpath using all project dependencies,
also adding the project build directory -->
<classpath/>
<argument>com.digi.xbee.api.knockknock.MainApp</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>

<dependencies>
<dependency>
<groupId>com.digi.xbee</groupId>
<artifactId>xbjlib</artifactId>
<version>${project.version}</version>
<type>jar</type>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle or the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.digi.xbee.api.knockknock;

import java.net.*;
import java.io.*;

public class KnockKnockProtocol {
private static final int WAITING = 0;
private static final int SENTKNOCKKNOCK = 1;
private static final int SENTCLUE = 2;
private static final int ANOTHER = 3;

private static final int NUMJOKES = 5;

private int state = WAITING;
private int currentJoke = 0;

private String[] clues = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" };
private String[] answers = { "Turnip the heat, it's cold in here!",
"I didn't know you could yodel!",
"Bless you!",
"Is there an owl in here?",
"Is there an echo in here?" };

public String processInput(String theInput) {
String theOutput = null;

if (state == WAITING) {
theOutput = "Knock! Knock!";
state = SENTKNOCKKNOCK;
} else if (state == SENTKNOCKKNOCK) {
if (theInput.equalsIgnoreCase("Who's there?")) {
theOutput = clues[currentJoke];
state = SENTCLUE;
} else {
theOutput = "You're supposed to say \"Who's there?\"! " +
"Try again. Knock! Knock!";
}
} else if (state == SENTCLUE) {
if (theInput.equalsIgnoreCase(clues[currentJoke] + " who?")) {
theOutput = answers[currentJoke] + " Want another? (y/n)";
state = ANOTHER;
} else {
theOutput = "You're supposed to say \"" +
clues[currentJoke] +
" who?\"" +
"! Try again. Knock! Knock!";
state = SENTKNOCKKNOCK;
}
} else if (state == ANOTHER) {
if (theInput.equalsIgnoreCase("y")) {
theOutput = "Knock! Knock!";
if (currentJoke == (NUMJOKES - 1))
currentJoke = 0;
else
currentJoke++;
state = SENTKNOCKKNOCK;
} else {
theOutput = "Bye.";
state = WAITING;
}
}
return theOutput;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* Copyright (c) 2016 Digi International Inc.,
* All rights not expressly granted are reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343
* =======================================================================
*/
package com.digi.xbee.api.knockknock;

import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.Scanner;

import com.digi.xbee.api.WiFiDevice;
import com.digi.xbee.api.exceptions.XBeeException;
import com.digi.xbee.api.listeners.IIPDataReceiveListener;
import com.digi.xbee.api.models.IPMessage;
import com.digi.xbee.api.models.IPProtocol;

/**
* XBee Java Library Knock Knock sample application.
*
* <p>This example starts a simple web server and connects to it by sending a
* message to start a Knock Knock joke.</p>
*
* <p>For a complete description on the example, refer to the 'ReadMe.txt' file
* included in the root directory.</p>
*/
public class MainApp {

/* Constants */

// TODO Replace with the serial port where your module is connected to.
private static final String PORT = "COM1";
// TODO Replace with the baud rate of your module.
private static final int BAUD_RATE = 9600;

private static final int SERVER_PORT = 9750;

/**
* Application main method.
*
* @param args Command line arguments.
*/
public static void main(String[] args) {
System.out.println(" +----------------------------------------+");
System.out.println(" | XBee Java Library Knock Knock Sample |");
System.out.println(" +----------------------------------------+\n");

WebServer.start(SERVER_PORT);

Scanner scanner = new Scanner(System.in);

WiFiDevice myDevice = new WiFiDevice(PORT, BAUD_RATE);

try {
myDevice.open();

myDevice.addIPDataListener(new IIPDataReceiveListener() {
@Override
public void ipDataReceived(IPMessage ipMessage) {
System.out.println(ipMessage.getDataString());
}
});

myDevice.sendIPData((Inet4Address) Inet4Address.getLocalHost(),
SERVER_PORT, IPProtocol.TCP, ("\n").getBytes());

String line;
while (!(line = scanner.nextLine()).equalsIgnoreCase("bye.")) {
myDevice.sendIPData((Inet4Address) Inet4Address.getLocalHost(),
SERVER_PORT, IPProtocol.TCP, (line + "\n").getBytes());
}

} catch (XBeeException | UnknownHostException e) {
System.out.println("Error sending data to the web server");
e.printStackTrace();
myDevice.close();
System.exit(1);
} finally {
scanner.close();
myDevice.close();
System.exit(0);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* Copyright (c) 2016 Digi International Inc.,
* All rights not expressly granted are reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343
* =======================================================================
*/
package com.digi.xbee.api.knockknock;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
* Simple web server that responds to clients with a text message.
*/
public class WebServer {

/**
* Starts the web server in the given port.
*
* @param port The port number of the web server.
*/
public static void start(final int port) {
new Thread(new Runnable() {
@Override
public void run() {
ServerSocket serverSocket = null;
Socket client = null;
try {
serverSocket = new ServerSocket(port);
KnockKnockProtocol kkp = new KnockKnockProtocol();
while (true) {
client = serverSocket.accept();
PrintWriter out = new PrintWriter(client.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String inputLine, outputLine;
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.print(outputLine);
out.flush();
if (outputLine.equals("Bye."))
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null)
try {
serverSocket.close();
} catch (IOException e) {}
}
}
}).start();
}
}